file_id
int64 1
215k
| content
stringlengths 7
454k
| repo
stringlengths 6
113
| path
stringlengths 6
251
|
---|---|---|---|
617 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import java.io.IOException;
import okhttp3.Request;
import okio.Timeout;
/**
* An invocation of a Retrofit method that sends a request to a webserver and returns a response.
* Each call yields its own HTTP request and response pair. Use {@link #clone} to make multiple
* calls with the same parameters to the same webserver; this may be used to implement polling or to
* retry a failed call.
*
* <p>Calls may be executed synchronously with {@link #execute}, or asynchronously with {@link
* #enqueue}. In either case the call can be canceled at any time with {@link #cancel}. A call that
* is busy writing its request or reading its response may receive a {@link IOException}; this is
* working as designed.
*
* @param <T> Successful response body type.
*/
public interface Call<T> extends Cloneable {
/**
* Synchronously send the request and return its response.
*
* @throws IOException if a problem occurred talking to the server.
* @throws RuntimeException (and subclasses) if an unexpected error occurs creating the request or
* decoding the response.
*/
Response<T> execute() throws IOException;
/**
* Asynchronously send the request and notify {@code callback} of its response or if an error
* occurred talking to the server, creating the request, or processing the response.
*/
void enqueue(Callback<T> callback);
/**
* Returns true if this call has been either {@linkplain #execute() executed} or {@linkplain
* #enqueue(Callback) enqueued}. It is an error to execute or enqueue a call more than once.
*/
boolean isExecuted();
/**
* Cancel this call. An attempt will be made to cancel in-flight calls, and if the call has not
* yet been executed it never will be.
*/
void cancel();
/** True if {@link #cancel()} was called. */
boolean isCanceled();
/**
* Create a new, identical call to this one which can be enqueued or executed even if this call
* has already been.
*/
Call<T> clone();
/** The original HTTP request. */
Request request();
/**
* Returns a timeout that spans the entire call: resolving DNS, connecting, writing the request
* body, server processing, and reading the response body. If the call requires redirects or
* retries all must complete within one timeout period.
*/
Timeout timeout();
}
| square/retrofit | retrofit/src/main/java/retrofit2/Call.java |
619 | // Companion Code to the paper "Generative Forests" by R. Nock and M. Guillame-Bert.
import java.io.*;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.*;
public class Dataset implements Debuggable{
public static String KEY_NODES = "@NODES";
public static String KEY_ARCS = "@ARCS";
public static String PATH_GENERATIVE_MODELS = "generators";
public static String KEY_SEPARATION_STRING[] = {"\t", ","};
public static int SEPARATION_INDEX = 1;
public static int SEPARATION_GNUPLOT = 0;
public static String DEFAULT_DIR = "Datasets", SEP = "/", KEY_COMMENT = "//";
public static String START_KEYWORD = "@";
public static String SUFFIX_FEATURES = "features";
public static String SUFFIX_OBSERVATIONS = "data";
int number_features_total, number_observations_total_from_file, number_observations_total_generated;
Vector <Feature> features;
Hashtable <String, Integer> name_of_feature_to_feature;
// keys = names, returns the Integer index of the feature with that name in features
Vector <Observation> observations_from_file;
// observations_from_file is the stored / read data
Domain myDomain;
String [] features_names_from_file;
public static void perror(String error_text){
System.out.println("\n" + error_text);
System.out.println("\nExiting to system\n");
System.exit(1);
}
public static void warning(String warning_text){
System.out.print(" * WARNING * " + warning_text);
}
Dataset(Domain d){
myDomain = d;
number_observations_total_generated = -1;
features_names_from_file = null;
name_of_feature_to_feature = null;
}
public Feature domain_feature(int f_index){
return features.elementAt(f_index);
}
public int number_domain_features(){
return features.size();
}
public int indexOfFeature(String n){
if (!name_of_feature_to_feature.containsKey(n))
Dataset.perror("Dataset.class :: no feature named " + n);
return (name_of_feature_to_feature.get(n).intValue());
}
public void printFeatures(){
int i;
System.out.println(features.size() + " features : ");
for (i=0;i<features.size();i++)
System.out.println((Feature) features.elementAt(i));
}
public Support domain_support(){
Support s = new Support(features, this);
if (s.weight_uniform_distribution != 1.0)
Dataset.perror(
"Dataset.class :: domain support has uniform measure "
+ s.weight_uniform_distribution
+ " != 1.0");
return s;
}
public void load_features_and_observations(){
if (myDomain.myW == null)
Dataset.perror("Dataset.class :: use not authorised without Wrapper");
FileReader e;
BufferedReader br;
StringTokenizer t;
Vector <Vector<String>> observations_read = new Vector<>();
Vector <String> current_observation;
String [] features_types = null;
String dum, n, ty;
int i, j;
boolean feature_names_ok = false;
Vector <Vector<String>> observations_test = null;
// features
features = new Vector<>();
name_of_feature_to_feature = new Hashtable <>();
System.out.print("\nLoading features & observations data... ");
number_features_total = -1;
try{
e = new FileReader(myDomain.myW.path_and_name_of_domain_dataset);
br = new BufferedReader(e);
while ( (dum=br.readLine()) != null){
if ( (dum.length()>1) && (!dum.substring(0,KEY_COMMENT.length()).equals(KEY_COMMENT)) ){
if (!feature_names_ok){
// the first usable line must be feature names
t = new StringTokenizer(dum,KEY_SEPARATION_STRING[SEPARATION_INDEX]);
features_names_from_file = new String[t.countTokens()];
i = 0;
while(t.hasMoreTokens()){
n = t.nextToken();
// must be String
if (is_number(n))
Dataset.perror(
"Dataset.class :: String "
+ n
+ " identified as Number; should not be the case for feature names");
features_names_from_file[i] = n;
i++;
}
number_features_total = features_names_from_file.length;
feature_names_ok = true;
}else{
// records all following values; checks sizes comply
current_observation = new Vector<>();
t = new StringTokenizer(dum,KEY_SEPARATION_STRING[SEPARATION_INDEX]);
if (t.countTokens() != number_features_total)
Dataset.perror(
"Dataset.class :: Observation string + "
+ dum
+ " does not have "
+ number_features_total
+ " features");
while(t.hasMoreTokens())
current_observation.addElement(t.nextToken());
observations_read.addElement(current_observation);
}
}
}
}catch(IOException eee){
System.out.println(
"Problem loading "
+ myDomain.myW.path_and_name_of_domain_dataset
+ " file --- Check the access to file");
System.exit(0);
}
if (myDomain.myW.density_estimation){
boolean feature_names_line_test = false;
observations_test = new Vector<>(); // used to complete the features domains if we are to do density estimation
try{
e = new FileReader(myDomain.myW.path_and_name_of_test_dataset);
br = new BufferedReader(e);
while ( (dum=br.readLine()) != null){
if ( (dum.length()>1) && (!dum.substring(0,Dataset.KEY_COMMENT.length()).equals(Dataset.KEY_COMMENT)) ){
if (!feature_names_line_test)
feature_names_line_test = true; // first line must also be features
else{
// records all following values; checks sizes comply
current_observation = new Vector<>();
t = new StringTokenizer(dum,Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]);
if (t.countTokens() != number_features_total)
Dataset.perror(
"Wrapper.class :: Observation string + "
+ dum
+ " does not have "
+ number_features_total
+ " features in *test file*");
while(t.hasMoreTokens())
current_observation.addElement(t.nextToken());
observations_test.addElement(current_observation);
}
}
}
}catch(IOException eee){
System.out.println(
"Problem loading "
+ myDomain.myW.path_and_name_of_test_dataset
+ " file --- Check the access to file");
System.exit(0);
}
}
// checking, if density plot requested, that names are found in columns and computes myW.index_x_name , index_y_name
if (myDomain.myW.plot_labels_names != null){
i = j = 0;
boolean found;
myDomain.myW.plot_labels_indexes = new int[myDomain.myW.plot_labels_names.length];
for (i=0;i<myDomain.myW.plot_labels_names.length;i++){
found = false;
j=0;
do{
if (features_names_from_file[j].equals(myDomain.myW.plot_labels_names[i]))
found = true;
else
j++;
}while( (!found) && (j<features_names_from_file.length) );
if (!found)
Dataset.perror(
"Dataset.class :: feature name "
+ myDomain.myW.plot_labels_names[i]
+ " not found in domain features");
myDomain.myW.plot_labels_indexes[i] = j;
}
}
System.out.print(
"ok (#"
+ number_features_total
+ " features total, #"
+ observations_read.size()
+ " observations total)... Computing features... ");
features_types = new String[number_features_total];
boolean not_a_number, not_an_integer, not_a_binary;
int idum, nvalf;
double ddum;
double miv, mav;
Vector <String> vs;
Vector <Double> vd;
Vector <Integer> vi;
// compute types
for (i=0;i<number_features_total;i++){
// String = nominal ? 1: text
not_a_number = false;
j = 0;
do{
n = observations_read.elementAt(j).elementAt(i);
if (!n.equals(FeatureValue.S_UNKNOWN)){
if (!is_number(n)){
not_a_number = true;
}else
j++;
}else
j++;
}while( (!not_a_number) && (j<observations_read.size()) );
// String = nominal ? 2: binary
if ( (!not_a_number) && (myDomain.myW.force_binary_coding) ){
j = 0;
not_a_binary = false;
do{
n = observations_read.elementAt(j).elementAt(i);
if (!n.equals(FeatureValue.S_UNKNOWN)){
not_an_integer = false;
idum = -1;
try{
idum = Integer.parseInt(n);
}catch(NumberFormatException nfe){
not_an_integer = true;
}
if ( (not_an_integer) || ( (idum != 0) && (idum != 1) ) ){
not_a_binary = true;
}else
j++;
}else
j++;
}while( (!not_a_binary) && (j<observations_read.size()) );
if (!not_a_binary)
not_a_number = true;
}
if (not_a_number)
features_types[i] = Feature.NOMINAL;
else if (!myDomain.myW.force_integer_coding)
features_types[i] = Feature.CONTINUOUS;
else{
// makes distinction integer / real
not_an_integer = false;
j = 0;
do{
n = observations_read.elementAt(j).elementAt(i);
if (!n.equals(FeatureValue.S_UNKNOWN)){
try{
idum = Integer.parseInt(n);
}catch(NumberFormatException nfe){
not_an_integer = true;
}
if (!not_an_integer)
j++;
}else
j++;
}while( (!not_an_integer) && (j<observations_read.size()) );
if (not_an_integer)
features_types[i] = Feature.CONTINUOUS;
else
features_types[i] = Feature.INTEGER;
}
}
System.out.print("Types found: [");
for (i=0;i<number_features_total;i++){
System.out.print(features_types[i]);
if (i<number_features_total-1)
System.out.print(",");
}
System.out.print("] ");
// compute features
boolean value_seen;
for (i=0;i<number_features_total;i++){
value_seen = false;
miv = mav = -1.0;
vs = null;
vd = null;
vi = null;
if (Feature.IS_NOMINAL(features_types[i])){
vs = new Vector<>();
for (j=0;j<observations_read.size();j++)
if ( (!observations_read.elementAt(j).elementAt(i).equals(FeatureValue.S_UNKNOWN)) && (!vs.contains(observations_read.elementAt(j).elementAt(i))) )
vs.addElement(observations_read.elementAt(j).elementAt(i));
if (myDomain.myW.density_estimation)
for (j=0;j<observations_test.size();j++)
if ( (!observations_test.elementAt(j).elementAt(i).equals(FeatureValue.S_UNKNOWN)) && (!vs.contains(observations_test.elementAt(j).elementAt(i))) )
vs.addElement(observations_test.elementAt(j).elementAt(i));
features.addElement(Feature.DOMAIN_FEATURE(features_names_from_file[i], features_types[i], vs, vd, vi, miv, mav));
}else{
if (Feature.IS_CONTINUOUS(features_types[i]))
vd = new Vector<>();
else if (Feature.IS_INTEGER(features_types[i]))
vi = new Vector<>();
Vector <String> dummyv = new Vector <>();
for (j=0;j<observations_read.size();j++)
if ( (!observations_read.elementAt(j).elementAt(i).equals(FeatureValue.S_UNKNOWN)) && (!dummyv.contains(observations_read.elementAt(j).elementAt(i))) )
dummyv.addElement(observations_read.elementAt(j).elementAt(i));
if (myDomain.myW.density_estimation)
for (j=0;j<observations_test.size();j++)
if ( (!observations_test.elementAt(j).elementAt(i).equals(FeatureValue.S_UNKNOWN)) && (!dummyv.contains(observations_test.elementAt(j).elementAt(i))) )
dummyv.addElement(observations_test.elementAt(j).elementAt(i));
nvalf = 0;
for (j=0;j<observations_read.size();j++){
n = observations_read.elementAt(j).elementAt(i);
if (!n.equals(FeatureValue.S_UNKNOWN)){
nvalf++;
ddum = Double.parseDouble(n);
if (!value_seen){
miv = mav = ddum;
value_seen = true;
}else{
if (ddum < miv)
miv = ddum;
if (ddum > mav)
mav = ddum;
}
}
}
if (myDomain.myW.density_estimation)
for (j=0;j<observations_test.size();j++){
n = observations_test.elementAt(j).elementAt(i);
if (!n.equals(FeatureValue.S_UNKNOWN)){
nvalf++;
ddum = Double.parseDouble(n);
if (!value_seen){
miv = mav = ddum;
value_seen = true;
}else{
if (ddum < miv)
miv = ddum;
if (ddum > mav)
mav = ddum;
}
}
}
for (j=0;j<dummyv.size();j++){
if (Feature.IS_CONTINUOUS(features_types[i]))
vd.addElement(new Double(Double.parseDouble(dummyv.elementAt(j))));
else if (Feature.IS_CONTINUOUS(features_types[i]))
vi.addElement(new Integer(Integer.parseInt(dummyv.elementAt(j))));
}
if (nvalf == 0)
Dataset.perror(
"Dataset.class :: feature "
+ features_names_from_file[i]
+ " has only unknown values");
features.addElement(Feature.DOMAIN_FEATURE(features_names_from_file[i], features_types[i], vs, vd, vi, miv, mav));
}
}
for (i=0;i<number_features_total;i++)
name_of_feature_to_feature.put(features.elementAt(i).name, new Integer(i));
System.out.print("ok... Computing observations... ");
observations_from_file = new Vector<>();
Observation ee;
number_observations_total_from_file = observations_read.size();
for (j=0;j<observations_read.size();j++){
ee = new Observation(j, observations_read.elementAt(j), features, 1.0 / (double) observations_read.size());
observations_from_file.addElement(ee);
if (ee.contains_unknown_values())
myDomain.myW.has_missing_values = true;
}
int errfound = 0;
for (i=0;i<number_observations_total_from_file;i++){
ee = (Observation) observations_from_file.elementAt(i);
errfound += ee.checkAndCompleteFeatures(features);
}
if (errfound > 0)
Dataset.perror(
"Dataset.class :: found "
+ errfound
+ " errs for feature domains in observations. Please correct domains in .features"
+ " file. ");
compute_feature_statistics();
System.out.println("ok... ");
}
public boolean is_number(String n){
double test;
boolean is_double = true;
try{
test = Double.parseDouble(n);
}catch(NumberFormatException nfe){
is_double = false;
}
if (is_double)
return true;
ParsePosition p = new ParsePosition(0);
NumberFormat.getNumberInstance().parse(n, p);
return (n.length() == p.getIndex());
}
public void compute_feature_statistics(){
int i, j;
double [] probab = null;
double expect_X2 = 0.0, expect_squared = 0.0, vex = -1.0, tot;
double nfeat = 0.0, nnonz = 0.0;
for (i=0;i<features.size();i++){
nfeat = 0.0;
if (Feature.IS_NOMINAL(((Feature) features.elementAt(i)).type))
probab = new double[((Feature) features.elementAt(i)).modalities.size()];
else{
expect_X2 = expect_squared = 0.0;
}
for (j=0;j<number_observations_total_from_file;j++)
if (!Observation.FEATURE_IS_UNKNOWN((Observation) observations_from_file.elementAt(j), i))
if (Feature.IS_NOMINAL(((Feature) features.elementAt(i)).type))
probab [((Feature) features.elementAt(i)).modalities.indexOf(observations_from_file.elementAt(j).typed_features.elementAt(i).sv)] += 1.0;
else{
if (Feature.IS_INTEGER(((Feature) features.elementAt(i)).type))
vex = (double) observations_from_file.elementAt(j).typed_features.elementAt(i).iv;
else if (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))
vex = observations_from_file.elementAt(j).typed_features.elementAt(i).dv;
else
Dataset.perror(
"Dataset.class :: no feature type " + ((Feature) features.elementAt(i)).type);
expect_squared += vex;
expect_X2 += (vex * vex);
nnonz += 1.0;
}
if (Feature.IS_NOMINAL(((Feature) features.elementAt(i)).type)){
tot = 0.0;
for (j=0;j<probab.length;j++)
tot += probab[j];
for (j=0;j<probab.length;j++)
probab[j] /= tot;
((Feature) features.elementAt(i)).dispertion_statistic_value = Statistics.SHANNON_ENTROPY(probab);
}else{
if (nnonz == 0.0)
Dataset.perror("Dataset.class :: feature " + i + " has only unknown values");
expect_X2 /= nnonz;
expect_squared /= nnonz;
expect_squared *= expect_squared;
((Feature) features.elementAt(i)).dispertion_statistic_value = expect_X2 - expect_squared;
}
}
}
public String toString(){
int i, nm = observations_from_file.size();
if (observations_from_file.size() > 10)
nm = 10;
String v = "\n* Features (Unknown value coded as " + FeatureValue.S_UNKNOWN + ") --\n";
for (i=0;i<features.size();i++)
v += ((Feature) features.elementAt(i)).toString() + "\n";
v += "\n* First observations --\n";
for (i=0;i<nm;i++)
v += ((Observation) observations_from_file.elementAt(i)).toString();
return v;
}
public void sample_check(){
if (observations_from_file == null)
Dataset.perror("Dataset.class :: no sample available");
}
public int [] all_indexes(int exception){
int [] v;
int i, ind = 0;
if (exception == -1)
v = new int [observations_from_file.size()];
else
v = new int [observations_from_file.size()-1];
for (i=0;i<observations_from_file.size();i++){
if ( (exception == -1) || (i != exception) ){
v[ind] = i;
ind++;
}
}
return v;
}
public int size(){
if (observations_from_file == null)
Dataset.perror("Dataset.class :: no observations");
return observations_from_file.size();
}
}
| google-research/google-research | generative_forests/src/Dataset.java |
621 | /**************************************************************************/
/* GodotLib.java */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
package org.godotengine.godot;
import org.godotengine.godot.gl.GodotRenderer;
import org.godotengine.godot.io.directory.DirectoryAccessHandler;
import org.godotengine.godot.io.file.FileAccessHandler;
import org.godotengine.godot.tts.GodotTTS;
import org.godotengine.godot.utils.GodotNetUtils;
import android.app.Activity;
import android.content.res.AssetManager;
import android.hardware.SensorEvent;
import android.view.Surface;
import javax.microedition.khronos.opengles.GL10;
/**
* Wrapper for native library
*/
public class GodotLib {
static {
System.loadLibrary("godot_android");
}
/**
* Invoked on the main thread to initialize Godot native layer.
*/
public static native boolean initialize(Activity activity,
Godot p_instance,
AssetManager p_asset_manager,
GodotIO godotIO,
GodotNetUtils netUtils,
DirectoryAccessHandler directoryAccessHandler,
FileAccessHandler fileAccessHandler,
boolean use_apk_expansion);
/**
* Invoked on the main thread to clean up Godot native layer.
* @see androidx.fragment.app.Fragment#onDestroy()
*/
public static native void ondestroy();
/**
* Invoked on the GL thread to complete setup for the Godot native layer logic.
* @param p_cmdline Command line arguments used to configure Godot native layer components.
*/
public static native boolean setup(String[] p_cmdline, GodotTTS tts);
/**
* Invoked on the GL thread when the underlying Android surface has changed size.
* @param p_surface
* @param p_width
* @param p_height
* @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int)
*/
public static native void resize(Surface p_surface, int p_width, int p_height);
/**
* Invoked on the render thread when the underlying Android surface is created or recreated.
* @param p_surface
*/
public static native void newcontext(Surface p_surface);
/**
* Forward {@link Activity#onBackPressed()} event.
*/
public static native void back();
/**
* Invoked on the GL thread to draw the current frame.
* @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onDrawFrame(GL10)
*/
public static native boolean step();
/**
* TTS callback.
*/
public static native void ttsCallback(int event, int id, int pos);
/**
* Forward touch events.
*/
public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions, boolean doubleTap);
/**
* Dispatch mouse events
*/
public static native void dispatchMouseEvent(int event, int buttonMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative, float pressure, float tiltX, float tiltY);
public static native void magnify(float x, float y, float factor);
public static native void pan(float x, float y, float deltaX, float deltaY);
/**
* Forward accelerometer sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void accelerometer(float x, float y, float z);
/**
* Forward gravity sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void gravity(float x, float y, float z);
/**
* Forward magnetometer sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void magnetometer(float x, float y, float z);
/**
* Forward gyroscope sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void gyroscope(float x, float y, float z);
/**
* Forward regular key events.
*/
public static native void key(int p_physical_keycode, int p_unicode, int p_key_label, boolean p_pressed, boolean p_echo);
/**
* Forward game device's key events.
*/
public static native void joybutton(int p_device, int p_but, boolean p_pressed);
/**
* Forward joystick devices axis motion events.
*/
public static native void joyaxis(int p_device, int p_axis, float p_value);
/**
* Forward joystick devices hat motion events.
*/
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
/**
* Fires when a joystick device is added or removed.
*/
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
/**
* Invoked when the Android app resumes.
* @see androidx.fragment.app.Fragment#onResume()
*/
public static native void focusin();
/**
* Invoked when the Android app pauses.
* @see androidx.fragment.app.Fragment#onPause()
*/
public static native void focusout();
/**
* Used to access Godot global properties.
* @param p_key Property key
* @return String value of the property
*/
public static native String getGlobal(String p_key);
/**
* Used to access Godot's editor settings.
* @param settingKey Setting key
* @return String value of the setting
*/
public static native String getEditorSetting(String settingKey);
/**
* Invoke method |p_method| on the Godot object specified by |p_id|
* @param p_id Id of the Godot object to invoke
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
public static native void callobject(long p_id, String p_method, Object[] p_params);
/**
* Invoke method |p_method| on the Godot object specified by |p_id| during idle time.
* @param p_id Id of the Godot object to invoke
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
public static native void calldeferred(long p_id, String p_method, Object[] p_params);
/**
* Forward the results from a permission request.
* @see Activity#onRequestPermissionsResult(int, String[], int[])
* @param p_permission Request permission
* @param p_result True if the permission was granted, false otherwise
*/
public static native void requestPermissionResult(String p_permission, boolean p_result);
/**
* Invoked on the theme light/dark mode change.
*/
public static native void onNightModeChanged();
/**
* Invoked on the GL thread to configure the height of the virtual keyboard.
*/
public static native void setVirtualKeyboardHeight(int p_height);
/**
* Invoked on the GL thread when the {@link GodotRenderer} has been resumed.
* @see GodotRenderer#onActivityResumed()
*/
public static native void onRendererResumed();
/**
* Invoked on the GL thread when the {@link GodotRenderer} has been paused.
* @see GodotRenderer#onActivityPaused()
*/
public static native void onRendererPaused();
}
| godotengine/godot | platform/android/java/lib/src/org/godotengine/godot/GodotLib.java |
622 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.script;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Objects;
/**
* Record object that holds stats information for the different script contexts in a node.
*
* @param context Context name.
* @param compilations Total number of compilations.
* @param compilationsHistory Historical information of the compilations of scripts in timeseries format.
* @param cacheEvictions Total of evictions.
* @param cacheEvictionsHistory Historical information of the evictions of scripts in timeseries format.
* @param compilationLimitTriggered Total times that a limit of compilations that have reached the limit.
*/
public record ScriptContextStats(
String context,
long compilations,
TimeSeries compilationsHistory,
long cacheEvictions,
TimeSeries cacheEvictionsHistory,
long compilationLimitTriggered
) implements Writeable, ToXContentFragment, Comparable<ScriptContextStats> {
public ScriptContextStats(
String context,
long compilationLimitTriggered,
TimeSeries compilationsHistory,
TimeSeries cacheEvictionsHistory
) {
this(
Objects.requireNonNull(context),
compilationsHistory.total,
compilationsHistory,
cacheEvictionsHistory.total,
cacheEvictionsHistory,
compilationLimitTriggered
);
}
public static ScriptContextStats read(StreamInput in) throws IOException {
var context = in.readString();
var compilations = in.readVLong();
var cacheEvictions = in.readVLong();
var compilationLimitTriggered = in.readVLong();
TimeSeries compilationsHistory;
TimeSeries cacheEvictionsHistory;
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) {
compilationsHistory = new TimeSeries(in);
cacheEvictionsHistory = new TimeSeries(in);
} else if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_0_0)) {
compilationsHistory = new TimeSeries(in).withTotal(compilations);
cacheEvictionsHistory = new TimeSeries(in).withTotal(cacheEvictions);
} else {
compilationsHistory = new TimeSeries(compilations);
cacheEvictionsHistory = new TimeSeries(cacheEvictions);
}
return new ScriptContextStats(
context,
compilations,
compilationsHistory,
cacheEvictions,
cacheEvictionsHistory,
compilationLimitTriggered
);
}
public static ScriptContextStats merge(ScriptContextStats first, ScriptContextStats second) {
assert first.context.equals(second.context) : "To merge 2 ScriptContextStats both of them must have the same context.";
return new ScriptContextStats(
first.context,
first.compilations + second.compilations,
TimeSeries.merge(first.compilationsHistory, second.compilationsHistory),
first.cacheEvictions + second.cacheEvictions,
TimeSeries.merge(first.cacheEvictionsHistory, second.cacheEvictionsHistory),
first.compilationLimitTriggered + second.compilationLimitTriggered
);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(context);
out.writeVLong(compilations);
out.writeVLong(cacheEvictions);
out.writeVLong(compilationLimitTriggered);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_0_0)) {
compilationsHistory.writeTo(out);
cacheEvictionsHistory.writeTo(out);
}
}
public String getContext() {
return context;
}
public long getCompilations() {
return compilations;
}
public TimeSeries getCompilationsHistory() {
return compilationsHistory;
}
public long getCacheEvictions() {
return cacheEvictions;
}
public TimeSeries getCacheEvictionsHistory() {
return cacheEvictionsHistory;
}
public long getCompilationLimitTriggered() {
return compilationLimitTriggered;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Fields.CONTEXT, getContext());
builder.field(Fields.COMPILATIONS, getCompilations());
TimeSeries series = getCompilationsHistory();
if (series != null && series.areTimingsEmpty() == false) {
builder.startObject(Fields.COMPILATIONS_HISTORY);
series.toXContent(builder, params);
builder.endObject();
}
builder.field(Fields.CACHE_EVICTIONS, getCacheEvictions());
series = getCacheEvictionsHistory();
if (series != null && series.areTimingsEmpty() == false) {
builder.startObject(Fields.CACHE_EVICTIONS_HISTORY);
series.toXContent(builder, params);
builder.endObject();
}
builder.field(Fields.COMPILATION_LIMIT_TRIGGERED, getCompilationLimitTriggered());
builder.endObject();
return builder;
}
@Override
public int compareTo(ScriptContextStats o) {
return this.context.compareTo(o.context);
}
static final class Fields {
static final String CONTEXT = "context";
static final String COMPILATIONS = "compilations";
static final String COMPILATIONS_HISTORY = "compilations_history";
static final String CACHE_EVICTIONS = "cache_evictions";
static final String CACHE_EVICTIONS_HISTORY = "cache_evictions_history";
static final String COMPILATION_LIMIT_TRIGGERED = "compilation_limit_triggered";
static final String FIVE_MINUTES = "5m";
static final String FIFTEEN_MINUTES = "15m";
static final String TWENTY_FOUR_HOURS = "24h";
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/script/ScriptContextStats.java |
623 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx;
import com.badlogic.gdx.utils.Clipboard;
/**
* <p>
* An <code>Application</code> is the main entry point of your project. It sets up a window and rendering surface and manages the
* different aspects of your application, namely {@link Graphics}, {@link Audio}, {@link Input} and {@link Files}. Think of an
* Application being equivalent to Swing's <code>JFrame</code> or Android's <code>Activity</code>.
* </p>
*
* <p>
* An application can be an instance of any of the following:
* <ul>
* <li>a desktop application (see <code>JglfwApplication</code> found in gdx-backends-jglfw.jar)</li>
* <li>an Android application (see <code>AndroidApplication</code> found in gdx-backends-android.jar)</li>
* <li>a HTML5 application (see <code>GwtApplication</code> found in gdx-backends-gwt.jar)</li>
* <li>an iOS application (see <code>IOSApplication</code> found in gdx-backends-robovm.jar)</li>
* </ul>
* Each application class has it's own startup and initialization methods. Please refer to their documentation for more
* information.
* </p>
*
* <p>
* While game programmers are used to having a main loop, libGDX employs a different concept to accommodate the event based nature
* of Android applications a little more. You application logic must be implemented in a {@link ApplicationListener} which has
* methods that get called by the Application when the application is created, resumed, paused, disposed or rendered. As a
* developer you will simply implement the ApplicationListener interface and fill in the functionality accordingly. The
* ApplicationListener is provided to a concrete Application instance as a parameter to the constructor or another initialization
* method. Please refer to the documentation of the Application implementations for more information. Note that the
* ApplicationListener can be provided to any Application implementation. This means that you only need to write your program
* logic once and have it run on different platforms by passing it to a concrete Application implementation.
* </p>
*
* <p>
* The Application interface provides you with a set of modules for graphics, audio, input and file i/o.
* </p>
*
* <p>
* {@link Graphics} offers you various methods to output visuals to the screen. This is achieved via OpenGL ES 2.0 or 3.0
* depending on what's available an the platform. On the desktop the features of OpenGL ES 2.0 and 3.0 are emulated via desktop
* OpenGL. On Android the functionality of the Java OpenGL ES bindings is used.
* </p>
*
* <p>
* {@link Audio} offers you various methods to output and record sound and music. This is achieved via the Java Sound API on the
* desktop. On Android the Android media framework is used.
* </p>
*
* <p>
* {@link Input} offers you various methods to poll user input from the keyboard, touch screen, mouse and accelerometer.
* Additionally you can implement an {@link InputProcessor} and use it with {@link Input#setInputProcessor(InputProcessor)} to
* receive input events.
* </p>
*
* <p>
* {@link Files} offers you various methods to access internal and external files. An internal file is a file that is stored near
* your application. On Android internal files are equivalent to assets. On the desktop the classpath is first scanned for the
* specified file. If that fails then the root directory of your application is used for a look up. External files are resources
* you create in your application and write to an external storage. On Android external files reside on the SD-card, on the
* desktop external files are written to a users home directory. If you know what you are doing you can also specify absolute file
* names. Absolute filenames are not portable, so take great care when using this feature.
* </p>
*
* <p>
* {@link Net} offers you various methods to perform network operations, such as performing HTTP requests, or creating server and
* client sockets for more elaborate network programming.
* </p>
*
* <p>
* The <code>Application</code> also has a set of methods that you can use to query specific information such as the operating
* system the application is currently running on and so forth. This allows you to have operating system dependent code paths. It
* is however not recommended to use these facilities.
* </p>
*
* <p>
* The <code>Application</code> also has a simple logging method which will print to standard out on the desktop and to logcat on
* Android.
* </p>
*
* @author mzechner */
public interface Application {
/** Enumeration of possible {@link Application} types
*
* @author mzechner */
public enum ApplicationType {
Android, Desktop, HeadlessDesktop, Applet, WebGL, iOS
}
public static final int LOG_NONE = 0;
public static final int LOG_DEBUG = 3;
public static final int LOG_INFO = 2;
public static final int LOG_ERROR = 1;
/** @return the {@link ApplicationListener} instance */
public ApplicationListener getApplicationListener ();
/** @return the {@link Graphics} instance */
public Graphics getGraphics ();
/** @return the {@link Audio} instance */
public Audio getAudio ();
/** @return the {@link Input} instance */
public Input getInput ();
/** @return the {@link Files} instance */
public Files getFiles ();
/** @return the {@link Net} instance */
public Net getNet ();
/** Logs a message to the console or logcat */
public void log (String tag, String message);
/** Logs a message to the console or logcat */
public void log (String tag, String message, Throwable exception);
/** Logs an error message to the console or logcat */
public void error (String tag, String message);
/** Logs an error message to the console or logcat */
public void error (String tag, String message, Throwable exception);
/** Logs a debug message to the console or logcat */
public void debug (String tag, String message);
/** Logs a debug message to the console or logcat */
public void debug (String tag, String message, Throwable exception);
/** Sets the log level. {@link #LOG_NONE} will mute all log output. {@link #LOG_ERROR} will only let error messages through.
* {@link #LOG_INFO} will let all non-debug messages through, and {@link #LOG_DEBUG} will let all messages through.
* @param logLevel {@link #LOG_NONE}, {@link #LOG_ERROR}, {@link #LOG_INFO}, {@link #LOG_DEBUG}. */
public void setLogLevel (int logLevel);
/** Gets the log level. */
public int getLogLevel ();
/** Sets the current Application logger. Calls to {@link #log(String, String)} are delegated to this
* {@link ApplicationLogger} */
public void setApplicationLogger (ApplicationLogger applicationLogger);
/** @return the current {@link ApplicationLogger} */
public ApplicationLogger getApplicationLogger ();
/** @return what {@link ApplicationType} this application has, e.g. Android or Desktop */
public ApplicationType getType ();
/** @return the Android API level on Android, the major OS version on iOS (5, 6, 7, ..), or 0 on the desktop. */
public int getVersion ();
/** @return the Java heap memory use in bytes */
public long getJavaHeap ();
/** @return the Native heap memory use in bytes */
public long getNativeHeap ();
/** Returns the {@link Preferences} instance of this Application. It can be used to store application settings across runs.
* @param name the name of the preferences, must be useable as a file name.
* @return the preferences. */
public Preferences getPreferences (String name);
public Clipboard getClipboard ();
/** Posts a {@link Runnable} on the main loop thread.
*
* In a multi-window application, the {@linkplain Gdx#graphics} and {@linkplain Gdx#input} values may be unpredictable at the
* time the Runnable is executed. If graphics or input are needed, they can be copied to a variable to be used in the Runnable.
* For example:
* <p>
* <code> final Graphics graphics = Gdx.graphics;
*
* @param runnable the runnable. */
public void postRunnable (Runnable runnable);
/** Schedule an exit from the application. On android, this will cause a call to pause() and dispose() some time in the future,
* it will not immediately finish your application. On iOS this should be avoided in production as it breaks Apples
* guidelines */
public void exit ();
/** Adds a new {@link LifecycleListener} to the application. This can be used by extensions to hook into the lifecycle more
* easily. The {@link ApplicationListener} methods are sufficient for application level development.
* @param listener */
public void addLifecycleListener (LifecycleListener listener);
/** Removes the {@link LifecycleListener}.
* @param listener */
public void removeLifecycleListener (LifecycleListener listener);
}
| libgdx/libgdx | gdx/src/com/badlogic/gdx/Application.java |
625 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx;
import com.badlogic.gdx.utils.Disposable;
/**
* <p>
* Represents one of many application screens, such as a main menu, a settings menu, the game screen and so on.
* </p>
* <p>
* Note that {@link #dispose()} is not called automatically.
* </p>
* @see Game */
public interface Screen extends Disposable {
/** Called when this screen becomes the current screen for a {@link Game}. */
public void show ();
/** Called when the screen should render itself.
* @param delta The time in seconds since the last render. */
public void render (float delta);
/** @see ApplicationListener#resize(int, int) */
public void resize (int width, int height);
/** @see ApplicationListener#pause() */
public void pause ();
/** @see ApplicationListener#resume() */
public void resume ();
/** Called when this screen is no longer the current screen for a {@link Game}. */
public void hide ();
/** Called when this screen should release all resources. */
public void dispose ();
}
| tommyettinger/libgdx | gdx/src/com/badlogic/gdx/Screen.java |
626 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium;
/**
* Indicates a driver or an HTML element that can capture a screenshot and store it in different
* ways.
*
* <p>Example usage:
*
* <pre>
* File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
* String screenshotBase64 = ((TakesScreenshot) element).getScreenshotAs(OutputType.BASE64);
* </pre>
*
* @see OutputType
*/
public interface TakesScreenshot {
/**
* Capture the screenshot and store it in the specified location.
*
* <p>For a W3C-conformant WebDriver or WebElement, this behaves as stated in <a
* href="https://w3c.github.io/webdriver/#screen-capture">W3C WebDriver specification</a>.
*
* <p>For a non-W3C-conformant WebDriver, this makes a best effort depending on the browser to
* return the following in order of preference:
*
* <ul>
* <li>Entire page
* <li>Current window
* <li>Visible portion of the current frame
* <li>The screenshot of the entire display containing the browser
* </ul>
*
* For a non-W3C-conformant WebElement extending TakesScreenshot, this makes a best effort
* depending on the browser to return the following in order of preference:
*
* <ul>
* <li>The entire content of the HTML element
* <li>The visible portion of the HTML element
* </ul>
*
* @param <X> Return type for getScreenshotAs.
* @param target target type, @see OutputType
* @return Object in which is stored information about the screenshot.
* @throws WebDriverException on failure.
* @throws UnsupportedOperationException if the underlying implementation does not support
* screenshot capturing.
*/
<X> X getScreenshotAs(OutputType<X> target) throws WebDriverException;
}
| SeleniumHQ/selenium | java/src/org/openqa/selenium/TakesScreenshot.java |
627 | /*
* Copyright (C) 2015 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.hash;
import com.google.common.primitives.Longs;
import java.lang.reflect.Field;
import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import sun.misc.Unsafe;
/**
* Utility functions for loading and storing values from a byte array.
*
* @author Kevin Damm
* @author Kyle Maddison
*/
@ElementTypesAreNonnullByDefault
final class LittleEndianByteArray {
/** The instance that actually does the work; delegates to Unsafe or a pure-Java fallback. */
private static final LittleEndianBytes byteArray;
/**
* Load 8 bytes into long in a little endian manner, from the substring between position and
* position + 8. The array must have at least 8 bytes from offset (inclusive).
*
* @param input the input bytes
* @param offset the offset into the array at which to start
* @return a long of a concatenated 8 bytes
*/
static long load64(byte[] input, int offset) {
// We don't want this in production code as this is the most critical part of the loop.
assert input.length >= offset + 8;
// Delegates to the fast (unsafe) version or the fallback.
return byteArray.getLongLittleEndian(input, offset);
}
/**
* Similar to load64, but allows offset + 8 > input.length, padding the result with zeroes. This
* has to explicitly reverse the order of the bytes as it packs them into the result which makes
* it slower than the native version.
*
* @param input the input bytes
* @param offset the offset into the array at which to start reading
* @param length the number of bytes from the input to read
* @return a long of a concatenated 8 bytes
*/
static long load64Safely(byte[] input, int offset, int length) {
long result = 0;
// Due to the way we shift, we can stop iterating once we've run out of data, the rest
// of the result already being filled with zeros.
// This loop is critical to performance, so please check HashBenchmark if altering it.
int limit = Math.min(length, 8);
for (int i = 0; i < limit; i++) {
// Shift value left while iterating logically through the array.
result |= (input[offset + i] & 0xFFL) << (i * 8);
}
return result;
}
/**
* Store 8 bytes into the provided array at the indicated offset, using the value provided.
*
* @param sink the output byte array
* @param offset the offset into the array at which to start writing
* @param value the value to write
*/
static void store64(byte[] sink, int offset, long value) {
// We don't want to assert in production code.
assert offset >= 0 && offset + 8 <= sink.length;
// Delegates to the fast (unsafe)version or the fallback.
byteArray.putLongLittleEndian(sink, offset, value);
}
/**
* Load 4 bytes from the provided array at the indicated offset.
*
* @param source the input bytes
* @param offset the offset into the array at which to start
* @return the value found in the array in the form of a long
*/
static int load32(byte[] source, int offset) {
// TODO(user): Measure the benefit of delegating this to LittleEndianBytes also.
return (source[offset] & 0xFF)
| ((source[offset + 1] & 0xFF) << 8)
| ((source[offset + 2] & 0xFF) << 16)
| ((source[offset + 3] & 0xFF) << 24);
}
/**
* Indicates that the loading of Unsafe was successful and the load and store operations will be
* very efficient. May be useful for calling code to fall back on an alternative implementation
* that is slower than Unsafe.get/store but faster than the pure-Java mask-and-shift.
*/
static boolean usingUnsafe() {
return (byteArray instanceof UnsafeByteArray);
}
/**
* Common interface for retrieving a 64-bit long from a little-endian byte array.
*
* <p>This abstraction allows us to use single-instruction load and put when available, or fall
* back on the slower approach of using Longs.fromBytes(byte...).
*/
private interface LittleEndianBytes {
long getLongLittleEndian(byte[] array, int offset);
void putLongLittleEndian(byte[] array, int offset, long value);
}
/**
* The only reference to Unsafe is in this nested class. We set things up so that if
* Unsafe.theUnsafe is inaccessible, the attempt to load the nested class fails, and the outer
* class's static initializer can fall back on a non-Unsafe version.
*/
private enum UnsafeByteArray implements LittleEndianBytes {
// Do *not* change the order of these constants!
UNSAFE_LITTLE_ENDIAN {
@Override
public long getLongLittleEndian(byte[] array, int offset) {
return theUnsafe.getLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET);
}
@Override
public void putLongLittleEndian(byte[] array, int offset, long value) {
theUnsafe.putLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET, value);
}
},
UNSAFE_BIG_ENDIAN {
@Override
public long getLongLittleEndian(byte[] array, int offset) {
long bigEndian = theUnsafe.getLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET);
// The hardware is big-endian, so we need to reverse the order of the bytes.
return Long.reverseBytes(bigEndian);
}
@Override
public void putLongLittleEndian(byte[] array, int offset, long value) {
// Reverse the order of the bytes before storing, since we're on big-endian hardware.
long littleEndianValue = Long.reverseBytes(value);
theUnsafe.putLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET, littleEndianValue);
}
};
// Provides load and store operations that use native instructions to get better performance.
private static final Unsafe theUnsafe;
// The offset to the first element in a byte array.
private static final int BYTE_ARRAY_BASE_OFFSET;
/**
* Returns an Unsafe. Suitable for use in a 3rd party package. Replace with a simple call to
* Unsafe.getUnsafe when integrating into a JDK.
*
* @return an Unsafe instance if successful
*/
@SuppressWarnings("removal") // b/318391980
private static Unsafe getUnsafe() {
try {
return Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {
// We'll try reflection instead.
}
try {
return AccessController.doPrivileged(
(PrivilegedExceptionAction<Unsafe>)
() -> {
Class<Unsafe> k = Unsafe.class;
for (Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x)) {
return k.cast(x);
}
}
throw new NoSuchFieldError("the Unsafe");
});
} catch (PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics", e.getCause());
}
}
static {
theUnsafe = getUnsafe();
BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
// sanity check - this should never fail
if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
throw new AssertionError();
}
}
}
/** Fallback implementation for when Unsafe is not available in our current environment. */
private enum JavaLittleEndianBytes implements LittleEndianBytes {
INSTANCE {
@Override
public long getLongLittleEndian(byte[] source, int offset) {
return Longs.fromBytes(
source[offset + 7],
source[offset + 6],
source[offset + 5],
source[offset + 4],
source[offset + 3],
source[offset + 2],
source[offset + 1],
source[offset]);
}
@Override
public void putLongLittleEndian(byte[] sink, int offset, long value) {
long mask = 0xFFL;
for (int i = 0; i < 8; mask <<= 8, i++) {
sink[offset + i] = (byte) ((value & mask) >> (i * 8));
}
}
}
}
static {
LittleEndianBytes theGetter = JavaLittleEndianBytes.INSTANCE;
try {
/*
* UnsafeByteArray uses Unsafe.getLong() in an unsupported way, which is known to cause
* crashes on Android when running in 32-bit mode. For maximum safety, we shouldn't use
* Unsafe.getLong() at all, but the performance benefit on x86_64 is too great to ignore, so
* as a compromise, we enable the optimization only on platforms that we specifically know to
* work.
*
* In the future, the use of Unsafe.getLong() should be replaced by ByteBuffer.getLong(),
* which will have an efficient native implementation in JDK 9.
*
*/
String arch = System.getProperty("os.arch");
if ("amd64".equals(arch)) {
theGetter =
ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)
? UnsafeByteArray.UNSAFE_LITTLE_ENDIAN
: UnsafeByteArray.UNSAFE_BIG_ENDIAN;
}
} catch (Throwable t) {
// ensure we really catch *everything*
}
byteArray = theGetter;
}
/** Deter instantiation of this class. */
private LittleEndianByteArray() {}
}
| google/guava | android/guava/src/com/google/common/hash/LittleEndianByteArray.java |
628 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.script;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Objects;
/**
* A response class representing a snapshot of a {@link org.elasticsearch.script.TimeSeriesCounter} at a point in time.
*/
public class TimeSeries implements Writeable, ToXContentFragment {
public final long fiveMinutes;
public final long fifteenMinutes;
public final long twentyFourHours;
public final long total;
public TimeSeries(long total) {
this.fiveMinutes = 0;
this.fifteenMinutes = 0;
this.twentyFourHours = 0;
this.total = total;
}
public TimeSeries(long fiveMinutes, long fifteenMinutes, long twentyFourHours, long total) {
this.fiveMinutes = fiveMinutes;
this.fifteenMinutes = fifteenMinutes;
this.twentyFourHours = twentyFourHours;
this.total = total;
}
TimeSeries withTotal(long total) {
return new TimeSeries(fiveMinutes, fifteenMinutes, twentyFourHours, total);
}
public static TimeSeries merge(TimeSeries first, TimeSeries second) {
return new TimeSeries(
first.fiveMinutes + second.fiveMinutes,
first.fifteenMinutes + second.fifteenMinutes,
first.twentyFourHours + second.twentyFourHours,
first.total + second.total
);
}
public TimeSeries(StreamInput in) throws IOException {
fiveMinutes = in.readVLong();
fifteenMinutes = in.readVLong();
twentyFourHours = in.readVLong();
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) {
total = in.readVLong();
} else {
total = 0;
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// total is omitted from toXContent as it's written at a higher level by ScriptContextStats
builder.field(ScriptContextStats.Fields.FIVE_MINUTES, fiveMinutes);
builder.field(ScriptContextStats.Fields.FIFTEEN_MINUTES, fifteenMinutes);
builder.field(ScriptContextStats.Fields.TWENTY_FOUR_HOURS, twentyFourHours);
return builder;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(fiveMinutes);
out.writeVLong(fifteenMinutes);
out.writeVLong(twentyFourHours);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) {
out.writeVLong(total);
}
}
public boolean areTimingsEmpty() {
return fiveMinutes == 0 && fifteenMinutes == 0 && twentyFourHours == 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TimeSeries that = (TimeSeries) o;
return fiveMinutes == that.fiveMinutes
&& fifteenMinutes == that.fifteenMinutes
&& twentyFourHours == that.twentyFourHours
&& total == that.total;
}
@Override
public int hashCode() {
return Objects.hash(fiveMinutes, fifteenMinutes, twentyFourHours, total);
}
@Override
public String toString() {
return "TimeSeries{"
+ "fiveMinutes="
+ fiveMinutes
+ ", fifteenMinutes="
+ fifteenMinutes
+ ", twentyFourHours="
+ twentyFourHours
+ ", total="
+ total
+ '}';
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/script/TimeSeries.java |
629 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.bootstrap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.common.settings.SecureSettings;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.env.Environment;
import org.elasticsearch.node.NodeValidationException;
import java.io.PrintStream;
/**
* A container for transient state during bootstrap of the Elasticsearch process.
*/
class Bootstrap {
// original stdout stream
private final PrintStream out;
// original stderr stream
private final PrintStream err;
// arguments from the CLI process
private final ServerArgs args;
// controller for spawning component subprocesses
private final Spawner spawner = new Spawner();
// the loaded keystore, not valid until after phase 2 of initialization
private final SetOnce<SecureSettings> secureSettings = new SetOnce<>();
// the loaded settings for the node, not valid until after phase 2 of initialization
private final SetOnce<Environment> nodeEnv = new SetOnce<>();
Bootstrap(PrintStream out, PrintStream err, ServerArgs args) {
this.out = out;
this.err = err;
this.args = args;
}
ServerArgs args() {
return args;
}
Spawner spawner() {
return spawner;
}
void setSecureSettings(SecureSettings secureSettings) {
this.secureSettings.set(secureSettings);
}
SecureSettings secureSettings() {
return secureSettings.get();
}
void setEnvironment(Environment environment) {
this.nodeEnv.set(environment);
}
Environment environment() {
return nodeEnv.get();
}
void exitWithNodeValidationException(NodeValidationException e) {
Logger logger = LogManager.getLogger(Elasticsearch.class);
logger.error("node validation exception\n{}", e.getMessage());
gracefullyExit(ExitCodes.CONFIG);
}
void exitWithUnknownException(Throwable e) {
Logger logger = LogManager.getLogger(Elasticsearch.class);
logger.error("fatal exception while booting Elasticsearch", e);
gracefullyExit(1); // mimic JDK exit code on exception
}
private void gracefullyExit(int exitCode) {
printLogsSuggestion();
err.flush();
exit(exitCode);
}
@SuppressForbidden(reason = "main exit path")
static void exit(int exitCode) {
System.exit(exitCode);
}
/**
* Prints a message directing the user to look at the logs. A message is only printed if
* logging has been configured.
*/
private void printLogsSuggestion() {
final String basePath = System.getProperty("es.logs.base_path");
assert basePath != null : "logging wasn't initialized";
err.println(
"ERROR: Elasticsearch did not exit normally - check the logs at "
+ basePath
+ System.getProperty("file.separator")
+ System.getProperty("es.logs.cluster_name")
+ ".log"
);
}
void sendCliMarker(char marker) {
err.println(marker);
err.flush();
}
void closeStreams() {
out.close();
err.close();
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java |
630 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.engine;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.LiveIndexWriterConfig;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.SegmentCommitInfo;
import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.index.SoftDeletesRetentionMergePolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ReferenceManager;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.Weight;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.InfoStream;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.SubscribableListener;
import org.elasticsearch.cluster.metadata.DataStream;
import org.elasticsearch.cluster.service.ClusterApplierService;
import org.elasticsearch.common.lucene.LoggerInfoStream;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver;
import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndSeqNo;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.metrics.MeanMetric;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.Maps;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.util.concurrent.AsyncIOProcessor;
import org.elasticsearch.common.util.concurrent.KeyedLock;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.core.Assertions;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.IOUtils;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Releasable;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexMode;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.IndexVersion;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.cache.query.TrivialQueryCachingPolicy;
import org.elasticsearch.index.mapper.DocumentParser;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.LuceneDocument;
import org.elasticsearch.index.mapper.MappingLookup;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SeqNoFieldMapper;
import org.elasticsearch.index.mapper.SourceFieldMapper;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.merge.MergeStats;
import org.elasticsearch.index.merge.OnGoingMerge;
import org.elasticsearch.index.seqno.LocalCheckpointTracker;
import org.elasticsearch.index.seqno.SeqNoStats;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardLongFieldRange;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogConfig;
import org.elasticsearch.index.translog.TranslogCorruptedException;
import org.elasticsearch.index.translog.TranslogDeletionPolicy;
import org.elasticsearch.index.translog.TranslogStats;
import org.elasticsearch.search.suggest.completion.CompletionStats;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.elasticsearch.core.Strings.format;
public class InternalEngine extends Engine {
/**
* When we last pruned expired tombstones from versionMap.deletes:
*/
private volatile long lastDeleteVersionPruneTimeMSec;
private final Translog translog;
private final ElasticsearchConcurrentMergeScheduler mergeScheduler;
private final IndexWriter indexWriter;
private final ExternalReaderManager externalReaderManager;
private final ElasticsearchReaderManager internalReaderManager;
private final ReentrantLock flushLock = new ReentrantLock();
private final ReentrantLock optimizeLock = new ReentrantLock();
// A uid (in the form of BytesRef) to the version map
// we use the hashed variant since we iterate over it and check removal and additions on existing keys
private final LiveVersionMap versionMap;
private final LiveVersionMapArchive liveVersionMapArchive;
// Records the last known generation during which LiveVersionMap was in unsafe mode. This indicates that only after this
// generation it is safe to rely on the LiveVersionMap for a real-time get.
// TODO: move the following two to the stateless plugin
private final AtomicLong lastUnsafeSegmentGenerationForGets;
// Records the segment generation for the currently ongoing commit if any, or the last finished commit otherwise.
private final AtomicLong preCommitSegmentGeneration = new AtomicLong(-1);
private volatile SegmentInfos lastCommittedSegmentInfos;
private final IndexThrottle throttle;
private final LocalCheckpointTracker localCheckpointTracker;
private final CombinedDeletionPolicy combinedDeletionPolicy;
// How many callers are currently requesting index throttling. Currently there are only two situations where we do this: when merges
// are falling behind and when writing indexing buffer to disk is too slow. When this is 0, there is no throttling, else we throttling
// incoming indexing ops to a single thread:
private final AtomicInteger throttleRequestCount = new AtomicInteger();
private final AtomicBoolean pendingTranslogRecovery = new AtomicBoolean(false);
private final AtomicLong maxUnsafeAutoIdTimestamp = new AtomicLong(-1);
private final AtomicLong maxSeenAutoIdTimestamp = new AtomicLong(-1);
// max_seq_no_of_updates_or_deletes tracks the max seq_no of update or delete operations that have been processed in this engine.
// An index request is considered as an update if it overwrites existing documents with the same docId in the Lucene index.
// The value of this marker never goes backwards, and is tracked/updated differently on primary and replica.
private final AtomicLong maxSeqNoOfUpdatesOrDeletes;
private final CounterMetric numVersionLookups = new CounterMetric();
private final CounterMetric numIndexVersionsLookups = new CounterMetric();
// Lucene operations since this engine was opened - not include operations from existing segments.
private final CounterMetric numDocDeletes = new CounterMetric();
private final CounterMetric numDocAppends = new CounterMetric();
private final CounterMetric numDocUpdates = new CounterMetric();
private final MeanMetric totalFlushTimeExcludingWaitingOnLock = new MeanMetric();
private final NumericDocValuesField softDeletesField = Lucene.newSoftDeletesField();
private final SoftDeletesPolicy softDeletesPolicy;
private final LastRefreshedCheckpointListener lastRefreshedCheckpointListener;
private final FlushListeners flushListener;
private final AsyncIOProcessor<Tuple<Long, Translog.Location>> translogSyncProcessor;
private final CompletionStatsCache completionStatsCache;
private final AtomicBoolean trackTranslogLocation = new AtomicBoolean(false);
private final KeyedLock<Long> noOpKeyedLock = new KeyedLock<>();
private final AtomicBoolean shouldPeriodicallyFlushAfterBigMerge = new AtomicBoolean(false);
/**
* If multiple writes passed {@link InternalEngine#tryAcquireInFlightDocs(Operation, int)} but they haven't adjusted
* {@link IndexWriter#getPendingNumDocs()} yet, then IndexWriter can fail with too many documents. In this case, we have to fail
* the engine because we already generated sequence numbers for write operations; otherwise we will have gaps in sequence numbers.
* To avoid this, we keep track the number of documents that are being added to IndexWriter, and account it in
* {@link InternalEngine#tryAcquireInFlightDocs(Operation, int)}. Although we can double count some inFlight documents in IW and Engine,
* this shouldn't be an issue because it happens for a short window and we adjust the inFlightDocCount once an indexing is completed.
*/
private final AtomicLong inFlightDocCount = new AtomicLong();
private final int maxDocs;
@Nullable
private final String historyUUID;
/**
* UUID value that is updated every time the engine is force merged.
*/
@Nullable
private volatile String forceMergeUUID;
private final LongSupplier relativeTimeInNanosSupplier;
private volatile long lastFlushTimestamp;
private final ByteSizeValue totalDiskSpace;
protected static final String REAL_TIME_GET_REFRESH_SOURCE = "realtime_get";
protected static final String UNSAFE_VERSION_MAP_REFRESH_SOURCE = "unsafe_version_map";
@SuppressWarnings("this-escape")
public InternalEngine(EngineConfig engineConfig) {
this(engineConfig, IndexWriter.MAX_DOCS, LocalCheckpointTracker::new);
}
@SuppressWarnings("this-escape")
InternalEngine(EngineConfig engineConfig, int maxDocs, BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier) {
super(engineConfig);
this.maxDocs = maxDocs;
this.relativeTimeInNanosSupplier = config().getRelativeTimeInNanosSupplier();
this.lastFlushTimestamp = relativeTimeInNanosSupplier.getAsLong(); // default to creation timestamp
this.liveVersionMapArchive = createLiveVersionMapArchive();
this.versionMap = new LiveVersionMap(liveVersionMapArchive);
final TranslogDeletionPolicy translogDeletionPolicy = new TranslogDeletionPolicy();
store.incRef();
IndexWriter writer = null;
Translog translog = null;
ExternalReaderManager externalReaderManager = null;
ElasticsearchReaderManager internalReaderManager = null;
EngineMergeScheduler scheduler = null;
boolean success = false;
try {
this.lastDeleteVersionPruneTimeMSec = engineConfig.getThreadPool().relativeTimeInMillis();
mergeScheduler = scheduler = new EngineMergeScheduler(engineConfig.getShardId(), engineConfig.getIndexSettings());
throttle = new IndexThrottle();
try {
store.trimUnsafeCommits(config().getTranslogConfig().getTranslogPath());
translog = openTranslog(
engineConfig,
translogDeletionPolicy,
engineConfig.getGlobalCheckpointSupplier(),
translogPersistedSeqNoConsumer()
);
assert translog.getGeneration() != null;
this.translog = translog;
this.totalDiskSpace = new ByteSizeValue(Environment.getFileStore(translog.location()).getTotalSpace(), ByteSizeUnit.BYTES);
this.softDeletesPolicy = newSoftDeletesPolicy();
this.combinedDeletionPolicy = new CombinedDeletionPolicy(
logger,
translogDeletionPolicy,
softDeletesPolicy,
translog::getLastSyncedGlobalCheckpoint,
newCommitsListener()
);
this.localCheckpointTracker = createLocalCheckpointTracker(localCheckpointTrackerSupplier);
writer = createWriter();
bootstrapAppendOnlyInfoFromWriter(writer);
final Map<String, String> commitData = commitDataAsMap(writer);
historyUUID = loadHistoryUUID(commitData);
forceMergeUUID = commitData.get(FORCE_MERGE_UUID_KEY);
indexWriter = writer;
} catch (IOException | TranslogCorruptedException e) {
throw new EngineCreationFailureException(shardId, "failed to create engine", e);
} catch (AssertionError e) {
// IndexWriter throws AssertionError on init, if asserts are enabled, if any files don't exist, but tests that
// randomly throw FNFE/NSFE can also hit this:
if (ExceptionsHelper.stackTrace(e).contains("org.apache.lucene.index.IndexWriter.filesExist")) {
throw new EngineCreationFailureException(shardId, "failed to create engine", e);
} else {
throw e;
}
}
externalReaderManager = createReaderManager(new RefreshWarmerListener(logger, isClosed, engineConfig));
internalReaderManager = externalReaderManager.internalReaderManager;
this.internalReaderManager = internalReaderManager;
this.externalReaderManager = externalReaderManager;
internalReaderManager.addListener(versionMap);
this.lastUnsafeSegmentGenerationForGets = new AtomicLong(lastCommittedSegmentInfos.getGeneration());
assert pendingTranslogRecovery.get() == false : "translog recovery can't be pending before we set it";
// don't allow commits until we are done with recovering
pendingTranslogRecovery.set(true);
for (ReferenceManager.RefreshListener listener : engineConfig.getExternalRefreshListener()) {
this.externalReaderManager.addListener(listener);
}
for (ReferenceManager.RefreshListener listener : engineConfig.getInternalRefreshListener()) {
this.internalReaderManager.addListener(listener);
}
this.lastRefreshedCheckpointListener = new LastRefreshedCheckpointListener(localCheckpointTracker.getProcessedCheckpoint());
this.internalReaderManager.addListener(lastRefreshedCheckpointListener);
maxSeqNoOfUpdatesOrDeletes = new AtomicLong(SequenceNumbers.max(localCheckpointTracker.getMaxSeqNo(), translog.getMaxSeqNo()));
if (localCheckpointTracker.getPersistedCheckpoint() < localCheckpointTracker.getMaxSeqNo()) {
try (Searcher searcher = acquireSearcher("restore_version_map_and_checkpoint_tracker", SearcherScope.INTERNAL)) {
restoreVersionMapAndCheckpointTracker(
Lucene.wrapAllDocsLive(searcher.getDirectoryReader()),
engineConfig.getIndexSettings().getIndexVersionCreated()
);
} catch (IOException e) {
throw new EngineCreationFailureException(
config().getShardId(),
"failed to restore version map and local checkpoint tracker",
e
);
}
}
completionStatsCache = new CompletionStatsCache(() -> acquireSearcher("completion_stats"));
this.externalReaderManager.addListener(completionStatsCache);
this.flushListener = new FlushListeners(logger, engineConfig.getThreadPool().getThreadContext());
this.translogSyncProcessor = createTranslogSyncProcessor(logger, engineConfig.getThreadPool().getThreadContext());
success = true;
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(writer, translog, internalReaderManager, externalReaderManager, scheduler);
if (isClosed.get() == false) {
// failure we need to dec the store reference
store.decRef();
}
}
}
logger.trace("created new InternalEngine");
}
private LocalCheckpointTracker createLocalCheckpointTracker(
BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier
) throws IOException {
final long maxSeqNo;
final long localCheckpoint;
final SequenceNumbers.CommitInfo seqNoStats = SequenceNumbers.loadSeqNoInfoFromLuceneCommit(
store.readLastCommittedSegmentsInfo().userData.entrySet()
);
maxSeqNo = seqNoStats.maxSeqNo;
localCheckpoint = seqNoStats.localCheckpoint;
logger.trace("recovered maximum sequence number [{}] and local checkpoint [{}]", maxSeqNo, localCheckpoint);
return localCheckpointTrackerSupplier.apply(maxSeqNo, localCheckpoint);
}
protected LongConsumer translogPersistedSeqNoConsumer() {
return seqNo -> {
final LocalCheckpointTracker tracker = getLocalCheckpointTracker();
assert tracker != null || getTranslog().isOpen() == false;
if (tracker != null) {
tracker.markSeqNoAsPersisted(seqNo);
}
};
}
private SoftDeletesPolicy newSoftDeletesPolicy() throws IOException {
final Map<String, String> commitUserData = store.readLastCommittedSegmentsInfo().userData;
final long lastMinRetainedSeqNo;
if (commitUserData.containsKey(Engine.MIN_RETAINED_SEQNO)) {
lastMinRetainedSeqNo = Long.parseLong(commitUserData.get(Engine.MIN_RETAINED_SEQNO));
} else {
lastMinRetainedSeqNo = Long.parseLong(commitUserData.get(SequenceNumbers.MAX_SEQ_NO)) + 1;
}
return new SoftDeletesPolicy(
translog::getLastSyncedGlobalCheckpoint,
lastMinRetainedSeqNo,
engineConfig.getIndexSettings().getSoftDeleteRetentionOperations(),
engineConfig.retentionLeasesSupplier()
);
}
@Nullable
private CombinedDeletionPolicy.CommitsListener newCommitsListener() {
Engine.IndexCommitListener listener = engineConfig.getIndexCommitListener();
if (listener != null) {
final IndexCommitListener wrappedListener = Assertions.ENABLED ? assertingCommitsOrderListener(listener) : listener;
return new CombinedDeletionPolicy.CommitsListener() {
@Override
public void onNewAcquiredCommit(final IndexCommit commit, final Set<String> additionalFiles) {
final IndexCommitRef indexCommitRef = acquireIndexCommitRef(() -> commit);
var primaryTerm = config().getPrimaryTermSupplier().getAsLong();
assert indexCommitRef.getIndexCommit() == commit;
wrappedListener.onNewCommit(shardId, store, primaryTerm, indexCommitRef, additionalFiles);
}
@Override
public void onDeletedCommit(IndexCommit commit) {
wrappedListener.onIndexCommitDelete(shardId, commit);
}
};
}
return null;
}
private IndexCommitListener assertingCommitsOrderListener(final IndexCommitListener listener) {
final AtomicLong generation = new AtomicLong(0L);
return new IndexCommitListener() {
@Override
public void onNewCommit(
ShardId shardId,
Store store,
long primaryTerm,
IndexCommitRef indexCommitRef,
Set<String> additionalFiles
) {
final long nextGen = indexCommitRef.getIndexCommit().getGeneration();
final long prevGen = generation.getAndSet(nextGen);
assert prevGen < nextGen
: "Expect new commit generation "
+ nextGen
+ " to be greater than previous commit generation "
+ prevGen
+ " for shard "
+ shardId;
listener.onNewCommit(shardId, store, primaryTerm, indexCommitRef, additionalFiles);
}
@Override
public void onIndexCommitDelete(ShardId shardId, IndexCommit deletedCommit) {
listener.onIndexCommitDelete(shardId, deletedCommit);
}
};
}
@Override
public CompletionStats completionStats(String... fieldNamePatterns) {
return completionStatsCache.get(fieldNamePatterns);
}
/**
* This reference manager delegates all it's refresh calls to another (internal) ReaderManager
* The main purpose for this is that if we have external refreshes happening we don't issue extra
* refreshes to clear version map memory etc. this can cause excessive segment creation if heavy indexing
* is happening and the refresh interval is low (ie. 1 sec)
*
* This also prevents segment starvation where an internal reader holds on to old segments literally forever
* since no indexing is happening and refreshes are only happening to the external reader manager, while with
* this specialized implementation an external refresh will immediately be reflected on the internal reader
* and old segments can be released in the same way previous version did this (as a side-effect of _refresh)
*/
@SuppressForbidden(reason = "reference counting is required here")
private static final class ExternalReaderManager extends ReferenceManager<ElasticsearchDirectoryReader> {
private final BiConsumer<ElasticsearchDirectoryReader, ElasticsearchDirectoryReader> refreshListener;
private final ElasticsearchReaderManager internalReaderManager;
private boolean isWarmedUp; // guarded by refreshLock
ExternalReaderManager(
ElasticsearchReaderManager internalReaderManager,
BiConsumer<ElasticsearchDirectoryReader, ElasticsearchDirectoryReader> refreshListener
) throws IOException {
this.refreshListener = refreshListener;
this.internalReaderManager = internalReaderManager;
this.current = internalReaderManager.acquire(); // steal the reference without warming up
}
@Override
protected ElasticsearchDirectoryReader refreshIfNeeded(ElasticsearchDirectoryReader referenceToRefresh) throws IOException {
// we simply run a blocking refresh on the internal reference manager and then steal it's reader
// it's a save operation since we acquire the reader which incs it's reference but then down the road
// steal it by calling incRef on the "stolen" reader
internalReaderManager.maybeRefreshBlocking();
final ElasticsearchDirectoryReader newReader = internalReaderManager.acquire();
if (isWarmedUp == false || newReader != referenceToRefresh) {
boolean success = false;
try {
refreshListener.accept(newReader, isWarmedUp ? referenceToRefresh : null);
isWarmedUp = true;
success = true;
} finally {
if (success == false) {
internalReaderManager.release(newReader);
}
}
}
// nothing has changed - both ref managers share the same instance so we can use reference equality
if (referenceToRefresh == newReader) {
internalReaderManager.release(newReader);
return null;
} else {
return newReader; // steal the reference
}
}
@Override
protected boolean tryIncRef(ElasticsearchDirectoryReader reference) {
return reference.tryIncRef();
}
@Override
protected int getRefCount(ElasticsearchDirectoryReader reference) {
return reference.getRefCount();
}
@Override
protected void decRef(ElasticsearchDirectoryReader reference) throws IOException {
reference.decRef();
}
}
@Override
final boolean assertSearcherIsWarmedUp(String source, SearcherScope scope) {
if (scope == SearcherScope.EXTERNAL) {
switch (source) {
// we can access segment_stats while a shard is still in the recovering state.
case "segments":
case "segments_stats":
break;
default:
assert externalReaderManager.isWarmedUp : "searcher was not warmed up yet for source[" + source + "]";
}
}
return true;
}
@Override
public int restoreLocalHistoryFromTranslog(TranslogRecoveryRunner translogRecoveryRunner) throws IOException {
try (var ignored = acquireEnsureOpenRef()) {
final long localCheckpoint = localCheckpointTracker.getProcessedCheckpoint();
try (Translog.Snapshot snapshot = getTranslog().newSnapshot(localCheckpoint + 1, Long.MAX_VALUE)) {
return translogRecoveryRunner.run(this, snapshot);
}
}
}
@Override
public int fillSeqNoGaps(long primaryTerm) throws IOException {
try (var ignored = acquireEnsureOpenRef()) {
final long localCheckpoint = localCheckpointTracker.getProcessedCheckpoint();
final long maxSeqNo = localCheckpointTracker.getMaxSeqNo();
int numNoOpsAdded = 0;
for (long seqNo = localCheckpoint + 1; seqNo <= maxSeqNo; seqNo = localCheckpointTracker.getProcessedCheckpoint()
+ 1 /* leap-frog the local checkpoint */) {
innerNoOp(new NoOp(seqNo, primaryTerm, Operation.Origin.PRIMARY, System.nanoTime(), "filling gaps"));
numNoOpsAdded++;
assert seqNo <= localCheckpointTracker.getProcessedCheckpoint()
: "local checkpoint did not advance; was ["
+ seqNo
+ "], now ["
+ localCheckpointTracker.getProcessedCheckpoint()
+ "]";
}
syncTranslog(); // to persist noops associated with the advancement of the local checkpoint
assert localCheckpointTracker.getPersistedCheckpoint() == maxSeqNo
: "persisted local checkpoint did not advance to max seq no; is ["
+ localCheckpointTracker.getPersistedCheckpoint()
+ "], max seq no ["
+ maxSeqNo
+ "]";
return numNoOpsAdded;
}
}
private void bootstrapAppendOnlyInfoFromWriter(IndexWriter writer) {
for (Map.Entry<String, String> entry : writer.getLiveCommitData()) {
if (MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID.equals(entry.getKey())) {
assert maxUnsafeAutoIdTimestamp.get() == -1
: "max unsafe timestamp was assigned already [" + maxUnsafeAutoIdTimestamp.get() + "]";
updateAutoIdTimestamp(Long.parseLong(entry.getValue()), true);
}
}
}
@Override
public void recoverFromTranslog(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo, ActionListener<Void> listener) {
ActionListener.runWithResource(listener, this::acquireEnsureOpenRef, (l, ignoredRef) -> {
if (pendingTranslogRecovery.get() == false) {
throw new IllegalStateException("Engine has already been recovered");
}
recoverFromTranslogInternal(translogRecoveryRunner, recoverUpToSeqNo, l.delegateResponse((ll, e) -> {
try {
pendingTranslogRecovery.set(true); // just play safe and never allow commits on this see #ensureCanFlush
failEngine("failed to recover from translog", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
ll.onFailure(e);
}));
});
}
@Override
public void skipTranslogRecovery() {
assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be";
pendingTranslogRecovery.set(false); // we are good - now we can commit
}
private void recoverFromTranslogInternal(
TranslogRecoveryRunner translogRecoveryRunner,
long recoverUpToSeqNo,
ActionListener<Void> listener
) {
ActionListener.run(listener, l -> {
final int opsRecovered;
final long localCheckpoint = getProcessedLocalCheckpoint();
if (localCheckpoint < recoverUpToSeqNo) {
try (Translog.Snapshot snapshot = newTranslogSnapshot(localCheckpoint + 1, recoverUpToSeqNo)) {
opsRecovered = translogRecoveryRunner.run(this, snapshot);
} catch (Exception e) {
throw new EngineException(shardId, "failed to recover from translog", e);
}
} else {
opsRecovered = 0;
}
// flush if we recovered something or if we have references to older translogs
// note: if opsRecovered == 0 and we have older translogs it means they are corrupted or 0 length.
assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be";
pendingTranslogRecovery.set(false); // we are good - now we can commit
logger.trace(
() -> format(
"flushing post recovery from translog: ops recovered [%s], current translog generation [%s]",
opsRecovered,
translog.currentFileGeneration()
)
);
// flush might do something async and complete the listener on a different thread, from which we must fork back to a generic
// thread to continue with recovery, but if it doesn't do anything async then there's no need to fork, hence why we use a
// SubscribableListener here
final var flushListener = new SubscribableListener<FlushResult>();
flush(false, true, flushListener);
flushListener.addListener(l.delegateFailureAndWrap((ll, r) -> {
translog.trimUnreferencedReaders();
ll.onResponse(null);
}), engineConfig.getThreadPool().generic(), null);
});
}
protected Translog.Snapshot newTranslogSnapshot(long fromSeqNo, long toSeqNo) throws IOException {
return translog.newSnapshot(fromSeqNo, toSeqNo);
}
private Translog openTranslog(
EngineConfig engineConfig,
TranslogDeletionPolicy translogDeletionPolicy,
LongSupplier globalCheckpointSupplier,
LongConsumer persistedSequenceNumberConsumer
) throws IOException {
final TranslogConfig translogConfig = engineConfig.getTranslogConfig();
final Map<String, String> userData = store.readLastCommittedSegmentsInfo().getUserData();
final String translogUUID = Objects.requireNonNull(userData.get(Translog.TRANSLOG_UUID_KEY));
// We expect that this shard already exists, so it must already have an existing translog else something is badly wrong!
return new Translog(
translogConfig,
translogUUID,
translogDeletionPolicy,
globalCheckpointSupplier,
engineConfig.getPrimaryTermSupplier(),
persistedSequenceNumberConsumer
);
}
// Package private for testing purposes only
Translog getTranslog() {
ensureOpen();
return translog;
}
// Package private for testing purposes only
boolean hasAcquiredIndexCommits() {
return combinedDeletionPolicy.hasAcquiredIndexCommits();
}
@Override
public boolean isTranslogSyncNeeded() {
return getTranslog().syncNeeded();
}
private AsyncIOProcessor<Tuple<Long, Translog.Location>> createTranslogSyncProcessor(Logger logger, ThreadContext threadContext) {
return new AsyncIOProcessor<>(logger, 1024, threadContext) {
@Override
protected void write(List<Tuple<Tuple<Long, Translog.Location>, Consumer<Exception>>> candidates) throws IOException {
try {
Translog.Location location = Translog.Location.EMPTY;
long processGlobalCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO;
for (Tuple<Tuple<Long, Translog.Location>, Consumer<Exception>> syncMarkers : candidates) {
Tuple<Long, Translog.Location> marker = syncMarkers.v1();
long globalCheckpointToSync = marker.v1();
if (globalCheckpointToSync != SequenceNumbers.UNASSIGNED_SEQ_NO) {
processGlobalCheckpoint = SequenceNumbers.max(processGlobalCheckpoint, globalCheckpointToSync);
}
location = location.compareTo(marker.v2()) >= 0 ? location : marker.v2();
}
final boolean synced = translog.ensureSynced(location, processGlobalCheckpoint);
if (synced) {
revisitIndexDeletionPolicyOnTranslogSynced();
}
} catch (AlreadyClosedException ex) {
// that's fine since we already synced everything on engine close - this also is conform with the methods
// documentation
} catch (IOException ex) { // if this fails we are in deep shit - fail the request
logger.debug("failed to sync translog", ex);
throw ex;
}
}
};
}
@Override
public void asyncEnsureTranslogSynced(Translog.Location location, Consumer<Exception> listener) {
translogSyncProcessor.put(new Tuple<>(SequenceNumbers.NO_OPS_PERFORMED, location), listener);
}
@Override
public void asyncEnsureGlobalCheckpointSynced(long globalCheckpoint, Consumer<Exception> listener) {
translogSyncProcessor.put(new Tuple<>(globalCheckpoint, Translog.Location.EMPTY), listener);
}
@Override
public void syncTranslog() throws IOException {
translog.sync();
revisitIndexDeletionPolicyOnTranslogSynced();
}
@Override
public TranslogStats getTranslogStats() {
return getTranslog().stats();
}
@Override
public Translog.Location getTranslogLastWriteLocation() {
return getTranslog().getLastWriteLocation();
}
private void revisitIndexDeletionPolicyOnTranslogSynced() throws IOException {
if (combinedDeletionPolicy.hasUnreferencedCommits()) {
indexWriter.deleteUnusedFiles();
}
translog.trimUnreferencedReaders();
}
@Override
public String getHistoryUUID() {
return historyUUID;
}
/** returns the force merge uuid for the engine */
@Nullable
public String getForceMergeUUID() {
return forceMergeUUID;
}
/** Returns how many bytes we are currently moving from indexing buffer to segments on disk */
@Override
public long getWritingBytes() {
return indexWriter.getFlushingBytes() + versionMap.getRefreshingBytes();
}
/**
* Reads the current stored history ID from the IW commit data.
*/
private static String loadHistoryUUID(Map<String, String> commitData) {
final String uuid = commitData.get(HISTORY_UUID_KEY);
if (uuid == null) {
throw new IllegalStateException("commit doesn't contain history uuid");
}
return uuid;
}
private ExternalReaderManager createReaderManager(RefreshWarmerListener externalRefreshListener) throws EngineException {
boolean success = false;
ElasticsearchDirectoryReader directoryReader = null;
ElasticsearchReaderManager internalReaderManager = null;
try {
try {
directoryReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(indexWriter), shardId);
lastCommittedSegmentInfos = store.readLastCommittedSegmentsInfo();
internalReaderManager = createInternalReaderManager(directoryReader);
ExternalReaderManager externalReaderManager = new ExternalReaderManager(internalReaderManager, externalRefreshListener);
success = true;
return externalReaderManager;
} catch (IOException e) {
maybeFailEngine("start", e);
try {
indexWriter.rollback();
} catch (IOException inner) { // iw is closed below
e.addSuppressed(inner);
}
throw new EngineCreationFailureException(shardId, "failed to open reader on writer", e);
}
} finally {
if (success == false) { // release everything we created on a failure
// make sure that we close the directory reader even if the internal reader manager has failed to initialize
var reader = internalReaderManager == null ? directoryReader : internalReaderManager;
IOUtils.closeWhileHandlingException(reader, indexWriter);
}
}
}
protected ElasticsearchReaderManager createInternalReaderManager(ElasticsearchDirectoryReader directoryReader) {
return new ElasticsearchReaderManager(directoryReader);
}
public final AtomicLong translogGetCount = new AtomicLong(); // number of times realtime get was done on translog
public final AtomicLong translogInMemorySegmentsCount = new AtomicLong(); // number of times in-memory index needed to be created
private GetResult getFromTranslog(
Get get,
Translog.Index index,
MappingLookup mappingLookup,
DocumentParser documentParser,
Function<Searcher, Searcher> searcherWrapper
) throws IOException {
assert get.isReadFromTranslog();
translogGetCount.incrementAndGet();
final TranslogDirectoryReader inMemoryReader = new TranslogDirectoryReader(
shardId,
index,
mappingLookup,
documentParser,
config(),
translogInMemorySegmentsCount::incrementAndGet
);
final Engine.Searcher searcher = new Engine.Searcher(
"realtime_get",
ElasticsearchDirectoryReader.wrap(inMemoryReader, shardId),
config().getSimilarity(),
null /*query cache disabled*/,
TrivialQueryCachingPolicy.NEVER,
inMemoryReader
);
final Searcher wrappedSearcher = searcherWrapper.apply(searcher);
return getFromSearcher(get, wrappedSearcher, true);
}
@Override
public GetResult get(
Get get,
MappingLookup mappingLookup,
DocumentParser documentParser,
Function<Engine.Searcher, Engine.Searcher> searcherWrapper
) {
assert assertGetUsesIdField(get);
try (var ignored = acquireEnsureOpenRef()) {
if (get.realtime()) {
var result = realtimeGetUnderLock(get, mappingLookup, documentParser, searcherWrapper, true);
assert result != null : "real-time get result must not be null";
return result;
} else {
// we expose what has been externally expose in a point in time snapshot via an explicit refresh
return getFromSearcher(get, acquireSearcher("get", SearcherScope.EXTERNAL, searcherWrapper), false);
}
}
}
@Override
public GetResult getFromTranslog(
Get get,
MappingLookup mappingLookup,
DocumentParser documentParser,
Function<Searcher, Searcher> searcherWrapper
) {
assert assertGetUsesIdField(get);
try (var ignored = acquireEnsureOpenRef()) {
return realtimeGetUnderLock(get, mappingLookup, documentParser, searcherWrapper, false);
}
}
/**
* @param getFromSearcher indicates whether we also try the internal searcher if not found in translog. In the case where
* we just started tracking locations in the translog, we always use the internal searcher.
*/
protected GetResult realtimeGetUnderLock(
Get get,
MappingLookup mappingLookup,
DocumentParser documentParser,
Function<Engine.Searcher, Engine.Searcher> searcherWrapper,
boolean getFromSearcher
) {
assert isDrainedForClose() == false;
assert get.realtime();
final VersionValue versionValue;
try (Releasable ignore = versionMap.acquireLock(get.uid().bytes())) {
// we need to lock here to access the version map to do this truly in RT
versionValue = getVersionFromMap(get.uid().bytes());
}
try {
boolean getFromSearcherIfNotInTranslog = getFromSearcher;
if (versionValue != null) {
/*
* Once we've seen the ID in the live version map, in two cases it is still possible not to
* be able to follow up with serving the get from the translog:
* 1. It is possible that once attempt handling the get, we won't see the doc in the translog
* since it might have been moved out.
* TODO: ideally we should keep around translog entries long enough to cover this case
* 2. We might not be tracking translog locations in the live version map (see @link{trackTranslogLocation})
*
* In these cases, we should always fall back to get the doc from the internal searcher.
*/
getFromSearcherIfNotInTranslog = true;
if (versionValue.isDelete()) {
return GetResult.NOT_EXISTS;
}
if (get.versionType().isVersionConflictForReads(versionValue.version, get.version())) {
throw new VersionConflictEngineException(
shardId,
"[" + get.id() + "]",
get.versionType().explainConflictForReads(versionValue.version, get.version())
);
}
if (get.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO
&& (get.getIfSeqNo() != versionValue.seqNo || get.getIfPrimaryTerm() != versionValue.term)) {
throw new VersionConflictEngineException(
shardId,
get.id(),
get.getIfSeqNo(),
get.getIfPrimaryTerm(),
versionValue.seqNo,
versionValue.term
);
}
if (get.isReadFromTranslog()) {
if (versionValue.getLocation() != null) {
try {
final Translog.Operation operation = translog.readOperation(versionValue.getLocation());
if (operation != null) {
return getFromTranslog(get, (Translog.Index) operation, mappingLookup, documentParser, searcherWrapper);
}
} catch (IOException e) {
maybeFailEngine("realtime_get", e); // lets check if the translog has failed with a tragic event
throw new EngineException(shardId, "failed to read operation from translog", e);
}
} else {
// We need to start tracking translog locations in the live version map.
trackTranslogLocation.set(true);
}
}
assert versionValue.seqNo >= 0 : versionValue;
refreshIfNeeded(REAL_TIME_GET_REFRESH_SOURCE, versionValue.seqNo);
}
if (getFromSearcherIfNotInTranslog) {
return getFromSearcher(get, acquireSearcher("realtime_get", SearcherScope.INTERNAL, searcherWrapper), false);
}
return null;
} finally {
assert isDrainedForClose() == false;
}
}
/**
* the status of the current doc version in lucene, compared to the version in an incoming
* operation
*/
enum OpVsLuceneDocStatus {
/** the op is more recent than the one that last modified the doc found in lucene*/
OP_NEWER,
/** the op is older or the same as the one that last modified the doc found in lucene*/
OP_STALE_OR_EQUAL,
/** no doc was found in lucene */
LUCENE_DOC_NOT_FOUND
}
private static OpVsLuceneDocStatus compareOpToVersionMapOnSeqNo(String id, long seqNo, long primaryTerm, VersionValue versionValue) {
Objects.requireNonNull(versionValue);
if (seqNo > versionValue.seqNo) {
return OpVsLuceneDocStatus.OP_NEWER;
} else if (seqNo == versionValue.seqNo) {
assert versionValue.term == primaryTerm
: "primary term not matched; id="
+ id
+ " seq_no="
+ seqNo
+ " op_term="
+ primaryTerm
+ " existing_term="
+ versionValue.term;
return OpVsLuceneDocStatus.OP_STALE_OR_EQUAL;
} else {
return OpVsLuceneDocStatus.OP_STALE_OR_EQUAL;
}
}
private OpVsLuceneDocStatus compareOpToLuceneDocBasedOnSeqNo(final Operation op) throws IOException {
assert op.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO : "resolving ops based on seq# but no seqNo is found";
final OpVsLuceneDocStatus status;
VersionValue versionValue = getVersionFromMap(op.uid().bytes());
assert incrementVersionLookup();
if (versionValue != null) {
status = compareOpToVersionMapOnSeqNo(op.id(), op.seqNo(), op.primaryTerm(), versionValue);
} else {
// load from index
assert incrementIndexVersionLookup();
try (Searcher searcher = acquireSearcher("load_seq_no", SearcherScope.INTERNAL)) {
final DocIdAndSeqNo docAndSeqNo = VersionsAndSeqNoResolver.loadDocIdAndSeqNo(searcher.getIndexReader(), op.uid());
if (docAndSeqNo == null) {
status = OpVsLuceneDocStatus.LUCENE_DOC_NOT_FOUND;
} else if (op.seqNo() > docAndSeqNo.seqNo) {
status = OpVsLuceneDocStatus.OP_NEWER;
} else if (op.seqNo() == docAndSeqNo.seqNo) {
assert localCheckpointTracker.hasProcessed(op.seqNo())
: "local checkpoint tracker is not updated seq_no=" + op.seqNo() + " id=" + op.id();
status = OpVsLuceneDocStatus.OP_STALE_OR_EQUAL;
} else {
status = OpVsLuceneDocStatus.OP_STALE_OR_EQUAL;
}
}
}
return status;
}
/** resolves the current version of the document, returning null if not found */
private VersionValue resolveDocVersion(final Operation op, boolean loadSeqNo) throws IOException {
assert incrementVersionLookup(); // used for asserting in tests
VersionValue versionValue = getVersionFromMap(op.uid().bytes());
if (versionValue == null) {
assert incrementIndexVersionLookup(); // used for asserting in tests
final VersionsAndSeqNoResolver.DocIdAndVersion docIdAndVersion;
try (Searcher searcher = acquireSearcher("load_version", SearcherScope.INTERNAL)) {
if (engineConfig.getIndexSettings().getMode() == IndexMode.TIME_SERIES) {
assert engineConfig.getLeafSorter() == DataStream.TIMESERIES_LEAF_READERS_SORTER;
docIdAndVersion = VersionsAndSeqNoResolver.timeSeriesLoadDocIdAndVersion(
searcher.getIndexReader(),
op.uid(),
op.id(),
loadSeqNo
);
} else {
docIdAndVersion = VersionsAndSeqNoResolver.timeSeriesLoadDocIdAndVersion(
searcher.getIndexReader(),
op.uid(),
loadSeqNo
);
}
}
if (docIdAndVersion != null) {
versionValue = new IndexVersionValue(null, docIdAndVersion.version, docIdAndVersion.seqNo, docIdAndVersion.primaryTerm);
}
} else if (engineConfig.isEnableGcDeletes()
&& versionValue.isDelete()
&& (engineConfig.getThreadPool().relativeTimeInMillis() - ((DeleteVersionValue) versionValue).time) > getGcDeletesInMillis()) {
versionValue = null;
}
return versionValue;
}
private VersionValue getVersionFromMap(BytesRef id) {
if (versionMap.isUnsafe()) {
synchronized (versionMap) {
// we are switching from an unsafe map to a safe map. This might happen concurrently
// but we only need to do this once since the last operation per ID is to add to the version
// map so once we pass this point we can safely lookup from the version map.
if (versionMap.isUnsafe()) {
refreshInternalSearcher(UNSAFE_VERSION_MAP_REFRESH_SOURCE, true);
// After the refresh, the doc that triggered it must now be part of the last commit.
// In rare cases, there could be other flush cycles completed in between the above line
// and the line below which push the last commit generation further. But that's OK.
// The invariant here is that doc is available within the generations of commits upto
// lastUnsafeSegmentGenerationForGets (inclusive). Therefore it is ok for it be larger
// which means the search shard needs to wait for extra generations and these generations
// are guaranteed to happen since they are all committed.
lastUnsafeSegmentGenerationForGets.set(lastCommittedSegmentInfos.getGeneration());
}
versionMap.enforceSafeAccess();
}
// The versionMap can still be unsafe at this point due to archive being unsafe
}
return versionMap.getUnderLock(id);
}
private boolean canOptimizeAddDocument(Index index) {
if (index.getAutoGeneratedIdTimestamp() != IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP) {
assert index.getAutoGeneratedIdTimestamp() >= 0
: "autoGeneratedIdTimestamp must be positive but was: " + index.getAutoGeneratedIdTimestamp();
return switch (index.origin()) {
case PRIMARY -> {
assert assertPrimaryCanOptimizeAddDocument(index);
yield true;
}
case PEER_RECOVERY, REPLICA -> {
assert index.version() == 1 && index.versionType() == null
: "version: " + index.version() + " type: " + index.versionType();
yield true;
}
case LOCAL_TRANSLOG_RECOVERY, LOCAL_RESET -> {
assert index.isRetry();
yield true; // allow to optimize in order to update the max safe time stamp
}
};
}
return false;
}
protected boolean assertPrimaryCanOptimizeAddDocument(final Index index) {
assert (index.version() == Versions.MATCH_DELETED || index.version() == Versions.MATCH_ANY)
&& index.versionType() == VersionType.INTERNAL : "version: " + index.version() + " type: " + index.versionType();
return true;
}
private boolean assertIncomingSequenceNumber(final Engine.Operation.Origin origin, final long seqNo) {
if (origin == Operation.Origin.PRIMARY) {
assert assertPrimaryIncomingSequenceNumber(origin, seqNo);
} else {
// sequence number should be set when operation origin is not primary
assert seqNo >= 0 : "recovery or replica ops should have an assigned seq no.; origin: " + origin;
}
return true;
}
protected boolean assertPrimaryIncomingSequenceNumber(final Engine.Operation.Origin origin, final long seqNo) {
// sequence number should not be set when operation origin is primary
assert seqNo == SequenceNumbers.UNASSIGNED_SEQ_NO
: "primary operations must never have an assigned sequence number but was [" + seqNo + "]";
return true;
}
protected long generateSeqNoForOperationOnPrimary(final Operation operation) {
assert operation.origin() == Operation.Origin.PRIMARY;
assert operation.seqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO
: "ops should not have an assigned seq no. but was: " + operation.seqNo();
return doGenerateSeqNoForOperation(operation);
}
protected void advanceMaxSeqNoOfUpdatesOnPrimary(long seqNo) {
advanceMaxSeqNoOfUpdatesOrDeletes(seqNo);
}
protected void advanceMaxSeqNoOfDeletesOnPrimary(long seqNo) {
advanceMaxSeqNoOfUpdatesOrDeletes(seqNo);
}
/**
* Generate the sequence number for the specified operation.
*
* @param operation the operation
* @return the sequence number
*/
long doGenerateSeqNoForOperation(final Operation operation) {
return localCheckpointTracker.generateSeqNo();
}
@Override
public IndexResult index(Index index) throws IOException {
assert Objects.equals(index.uid().field(), IdFieldMapper.NAME) : index.uid().field();
final boolean doThrottle = index.origin().isRecovery() == false;
try (var ignored1 = acquireEnsureOpenRef()) {
assert assertIncomingSequenceNumber(index.origin(), index.seqNo());
int reservedDocs = 0;
try (
Releasable ignored = versionMap.acquireLock(index.uid().bytes());
Releasable indexThrottle = doThrottle ? throttle.acquireThrottle() : () -> {}
) {
lastWriteNanos = index.startTime();
/* A NOTE ABOUT APPEND ONLY OPTIMIZATIONS:
* if we have an autoGeneratedID that comes into the engine we can potentially optimize
* and just use addDocument instead of updateDocument and skip the entire version and index lookupVersion across the board.
* Yet, we have to deal with multiple document delivery, for this we use a property of the document that is added
* to detect if it has potentially been added before. We use the documents timestamp for this since it's something
* that:
* - doesn't change per document
* - is preserved in the transaction log
* - and is assigned before we start to index / replicate
* NOTE: it's not important for this timestamp to be consistent across nodes etc. it's just a number that is in the common
* case increasing and can be used in the failure case when we retry and resent documents to establish a happens before
* relationship. For instance:
* - doc A has autoGeneratedIdTimestamp = 10, isRetry = false
* - doc B has autoGeneratedIdTimestamp = 9, isRetry = false
*
* while both docs are in flight, we disconnect on one node, reconnect and send doc A again
* - now doc A' has autoGeneratedIdTimestamp = 10, isRetry = true
*
* if A' arrives on the shard first we update maxUnsafeAutoIdTimestamp to 10 and use update document. All subsequent
* documents that arrive (A and B) will also use updateDocument since their timestamps are less than
* maxUnsafeAutoIdTimestamp. While this is not strictly needed for doc B it is just much simpler to implement since it
* will just de-optimize some doc in the worst case.
*
* if A arrives on the shard first we use addDocument since maxUnsafeAutoIdTimestamp is < 10. A` will then just be skipped
* or calls updateDocument.
*/
final IndexingStrategy plan = indexingStrategyForOperation(index);
reservedDocs = plan.reservedDocs;
final IndexResult indexResult;
if (plan.earlyResultOnPreFlightError.isPresent()) {
assert index.origin() == Operation.Origin.PRIMARY : index.origin();
indexResult = plan.earlyResultOnPreFlightError.get();
assert indexResult.getResultType() == Result.Type.FAILURE : indexResult.getResultType();
} else {
// generate or register sequence number
if (index.origin() == Operation.Origin.PRIMARY) {
index = new Index(
index.uid(),
index.parsedDoc(),
generateSeqNoForOperationOnPrimary(index),
index.primaryTerm(),
index.version(),
index.versionType(),
index.origin(),
index.startTime(),
index.getAutoGeneratedIdTimestamp(),
index.isRetry(),
index.getIfSeqNo(),
index.getIfPrimaryTerm()
);
final boolean toAppend = plan.indexIntoLucene && plan.useLuceneUpdateDocument == false;
if (toAppend == false) {
advanceMaxSeqNoOfUpdatesOnPrimary(index.seqNo());
}
} else {
markSeqNoAsSeen(index.seqNo());
}
assert index.seqNo() >= 0 : "ops should have an assigned seq no.; origin: " + index.origin();
if (plan.indexIntoLucene || plan.addStaleOpToLucene) {
indexResult = indexIntoLucene(index, plan);
} else {
indexResult = new IndexResult(
plan.versionForIndexing,
index.primaryTerm(),
index.seqNo(),
plan.currentNotFoundOrDeleted,
index.id()
);
}
}
if (index.origin().isFromTranslog() == false) {
final Translog.Location location;
if (indexResult.getResultType() == Result.Type.SUCCESS) {
location = translog.add(new Translog.Index(index, indexResult));
} else if (indexResult.getSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) {
// if we have document failure, record it as a no-op in the translog and Lucene with the generated seq_no
final NoOp noOp = new NoOp(
indexResult.getSeqNo(),
index.primaryTerm(),
index.origin(),
index.startTime(),
indexResult.getFailure().toString()
);
location = innerNoOp(noOp).getTranslogLocation();
} else {
location = null;
}
indexResult.setTranslogLocation(location);
}
if (plan.indexIntoLucene && indexResult.getResultType() == Result.Type.SUCCESS) {
final Translog.Location translogLocation = trackTranslogLocation.get() ? indexResult.getTranslogLocation() : null;
versionMap.maybePutIndexUnderLock(
index.uid().bytes(),
new IndexVersionValue(translogLocation, plan.versionForIndexing, index.seqNo(), index.primaryTerm())
);
}
localCheckpointTracker.markSeqNoAsProcessed(indexResult.getSeqNo());
if (indexResult.getTranslogLocation() == null) {
// the op is coming from the translog (and is hence persisted already) or it does not have a sequence number
assert index.origin().isFromTranslog() || indexResult.getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO;
localCheckpointTracker.markSeqNoAsPersisted(indexResult.getSeqNo());
}
indexResult.setTook(relativeTimeInNanosSupplier.getAsLong() - index.startTime());
indexResult.freeze();
return indexResult;
} finally {
releaseInFlightDocs(reservedDocs);
}
} catch (RuntimeException | IOException e) {
try {
if (e instanceof AlreadyClosedException == false && treatDocumentFailureAsTragicError(index)) {
failEngine("index id[" + index.id() + "] origin[" + index.origin() + "] seq#[" + index.seqNo() + "]", e);
} else {
maybeFailEngine("index id[" + index.id() + "] origin[" + index.origin() + "] seq#[" + index.seqNo() + "]", e);
}
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw e;
}
}
protected final IndexingStrategy planIndexingAsNonPrimary(Index index) throws IOException {
assert assertNonPrimaryOrigin(index);
// needs to maintain the auto_id timestamp in case this replica becomes primary
if (canOptimizeAddDocument(index)) {
mayHaveBeenIndexedBefore(index);
}
final IndexingStrategy plan;
// unlike the primary, replicas don't really care to about creation status of documents
// this allows to ignore the case where a document was found in the live version maps in
// a delete state and return false for the created flag in favor of code simplicity
final long maxSeqNoOfUpdatesOrDeletes = getMaxSeqNoOfUpdatesOrDeletes();
if (hasBeenProcessedBefore(index)) {
// the operation seq# was processed and thus the same operation was already put into lucene
// this can happen during recovery where older operations are sent from the translog that are already
// part of the lucene commit (either from a peer recovery or a local translog)
// or due to concurrent indexing & recovery. For the former it is important to skip lucene as the operation in
// question may have been deleted in an out of order op that is not replayed.
// See testRecoverFromStoreWithOutOfOrderDelete for an example of local recovery
// See testRecoveryWithOutOfOrderDelete for an example of peer recovery
plan = IndexingStrategy.processButSkipLucene(false, index.version());
} else if (maxSeqNoOfUpdatesOrDeletes <= localCheckpointTracker.getProcessedCheckpoint()) {
// see Engine#getMaxSeqNoOfUpdatesOrDeletes for the explanation of the optimization using sequence numbers
assert maxSeqNoOfUpdatesOrDeletes < index.seqNo() : index.seqNo() + ">=" + maxSeqNoOfUpdatesOrDeletes;
plan = IndexingStrategy.optimizedAppendOnly(index.version(), 0);
} else {
versionMap.enforceSafeAccess();
final OpVsLuceneDocStatus opVsLucene = compareOpToLuceneDocBasedOnSeqNo(index);
if (opVsLucene == OpVsLuceneDocStatus.OP_STALE_OR_EQUAL) {
plan = IndexingStrategy.processAsStaleOp(index.version(), 0);
} else {
plan = IndexingStrategy.processNormally(opVsLucene == OpVsLuceneDocStatus.LUCENE_DOC_NOT_FOUND, index.version(), 0);
}
}
return plan;
}
protected IndexingStrategy indexingStrategyForOperation(final Index index) throws IOException {
if (index.origin() == Operation.Origin.PRIMARY) {
return planIndexingAsPrimary(index);
} else {
// non-primary mode (i.e., replica or recovery)
return planIndexingAsNonPrimary(index);
}
}
private IndexingStrategy planIndexingAsPrimary(Index index) throws IOException {
assert index.origin() == Operation.Origin.PRIMARY : "planing as primary but origin isn't. got " + index.origin();
final int reservingDocs = index.parsedDoc().docs().size();
final IndexingStrategy plan;
// resolve an external operation into an internal one which is safe to replay
final boolean canOptimizeAddDocument = canOptimizeAddDocument(index);
if (canOptimizeAddDocument && mayHaveBeenIndexedBefore(index) == false) {
final Exception reserveError = tryAcquireInFlightDocs(index, reservingDocs);
if (reserveError != null) {
plan = IndexingStrategy.failAsTooManyDocs(reserveError, index.id());
} else {
plan = IndexingStrategy.optimizedAppendOnly(1L, reservingDocs);
}
} else {
versionMap.enforceSafeAccess();
// resolves incoming version
final VersionValue versionValue = resolveDocVersion(index, index.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO);
final long currentVersion;
final boolean currentNotFoundOrDeleted;
if (versionValue == null) {
currentVersion = Versions.NOT_FOUND;
currentNotFoundOrDeleted = true;
} else {
currentVersion = versionValue.version;
currentNotFoundOrDeleted = versionValue.isDelete();
}
if (index.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && currentNotFoundOrDeleted) {
final VersionConflictEngineException e = new VersionConflictEngineException(
shardId,
index.id(),
index.getIfSeqNo(),
index.getIfPrimaryTerm(),
SequenceNumbers.UNASSIGNED_SEQ_NO,
SequenceNumbers.UNASSIGNED_PRIMARY_TERM
);
plan = IndexingStrategy.skipDueToVersionConflict(e, true, currentVersion, index.id());
} else if (index.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO
&& (versionValue.seqNo != index.getIfSeqNo() || versionValue.term != index.getIfPrimaryTerm())) {
final VersionConflictEngineException e = new VersionConflictEngineException(
shardId,
index.id(),
index.getIfSeqNo(),
index.getIfPrimaryTerm(),
versionValue.seqNo,
versionValue.term
);
plan = IndexingStrategy.skipDueToVersionConflict(e, currentNotFoundOrDeleted, currentVersion, index.id());
} else if (index.versionType().isVersionConflictForWrites(currentVersion, index.version(), currentNotFoundOrDeleted)) {
final VersionConflictEngineException e = new VersionConflictEngineException(
shardId,
index.parsedDoc().documentDescription(),
index.versionType().explainConflictForWrites(currentVersion, index.version(), true)
);
plan = IndexingStrategy.skipDueToVersionConflict(e, currentNotFoundOrDeleted, currentVersion, index.id());
} else {
final Exception reserveError = tryAcquireInFlightDocs(index, reservingDocs);
if (reserveError != null) {
plan = IndexingStrategy.failAsTooManyDocs(reserveError, index.id());
} else {
plan = IndexingStrategy.processNormally(
currentNotFoundOrDeleted,
canOptimizeAddDocument ? 1L : index.versionType().updateVersion(currentVersion, index.version()),
reservingDocs
);
}
}
}
return plan;
}
private IndexResult indexIntoLucene(Index index, IndexingStrategy plan) throws IOException {
assert index.seqNo() >= 0 : "ops should have an assigned seq no.; origin: " + index.origin();
assert plan.versionForIndexing >= 0 : "version must be set. got " + plan.versionForIndexing;
assert plan.indexIntoLucene || plan.addStaleOpToLucene;
/* Update the document's sequence number and primary term; the sequence number here is derived here from either the sequence
* number service if this is on the primary, or the existing document's sequence number if this is on the replica. The
* primary term here has already been set, see IndexShard#prepareIndex where the Engine$Index operation is created.
*/
index.parsedDoc().updateSeqID(index.seqNo(), index.primaryTerm());
index.parsedDoc().version().setLongValue(plan.versionForIndexing);
try {
if (plan.addStaleOpToLucene) {
addStaleDocs(index.docs(), indexWriter);
} else if (plan.useLuceneUpdateDocument) {
assert assertMaxSeqNoOfUpdatesIsAdvanced(index.uid(), index.seqNo(), true, true);
updateDocs(index.uid(), index.docs(), indexWriter);
} else {
// document does not exists, we can optimize for create, but double check if assertions are running
assert assertDocDoesNotExist(index, canOptimizeAddDocument(index) == false);
addDocs(index.docs(), indexWriter);
}
return new IndexResult(plan.versionForIndexing, index.primaryTerm(), index.seqNo(), plan.currentNotFoundOrDeleted, index.id());
} catch (Exception ex) {
if (ex instanceof AlreadyClosedException == false
&& indexWriter.getTragicException() == null
&& treatDocumentFailureAsTragicError(index) == false) {
/* There is no tragic event recorded so this must be a document failure.
*
* The handling inside IW doesn't guarantee that an tragic / aborting exception
* will be used as THE tragicEventException since if there are multiple exceptions causing an abort in IW
* only one wins. Yet, only the one that wins will also close the IW and in turn fail the engine such that
* we can potentially handle the exception before the engine is failed.
* Bottom line is that we can only rely on the fact that if it's a document failure then
* `indexWriter.getTragicException()` will be null otherwise we have to rethrow and treat it as fatal or rather
* non-document failure
*
* we return a `MATCH_ANY` version to indicate no document was index. The value is
* not used anyway
*/
return new IndexResult(ex, Versions.MATCH_ANY, index.primaryTerm(), index.seqNo(), index.id());
} else {
throw ex;
}
}
}
/**
* Whether we should treat any document failure as tragic error.
* If we hit any failure while processing an indexing on a replica, we should treat that error as tragic and fail the engine.
* However, we prefer to fail a request individually (instead of a shard) if we hit a document failure on the primary.
*/
private static boolean treatDocumentFailureAsTragicError(Index index) {
// TODO: can we enable this check for all origins except primary on the leader?
return index.origin() == Operation.Origin.REPLICA
|| index.origin() == Operation.Origin.PEER_RECOVERY
|| index.origin() == Operation.Origin.LOCAL_RESET;
}
/**
* returns true if the indexing operation may have already be processed by this engine.
* Note that it is OK to rarely return true even if this is not the case. However a `false`
* return value must always be correct.
*
*/
private boolean mayHaveBeenIndexedBefore(Index index) {
assert canOptimizeAddDocument(index);
final boolean mayHaveBeenIndexBefore;
if (index.isRetry()) {
mayHaveBeenIndexBefore = true;
updateAutoIdTimestamp(index.getAutoGeneratedIdTimestamp(), true);
assert maxUnsafeAutoIdTimestamp.get() >= index.getAutoGeneratedIdTimestamp();
} else {
// in this case we force
mayHaveBeenIndexBefore = maxUnsafeAutoIdTimestamp.get() >= index.getAutoGeneratedIdTimestamp();
updateAutoIdTimestamp(index.getAutoGeneratedIdTimestamp(), false);
}
return mayHaveBeenIndexBefore;
}
private void addDocs(final List<LuceneDocument> docs, final IndexWriter indexWriter) throws IOException {
if (docs.size() > 1) {
indexWriter.addDocuments(docs);
} else {
indexWriter.addDocument(docs.get(0));
}
numDocAppends.inc(docs.size());
}
private void addStaleDocs(final List<LuceneDocument> docs, final IndexWriter indexWriter) throws IOException {
for (LuceneDocument doc : docs) {
doc.add(softDeletesField); // soft-deleted every document before adding to Lucene
}
if (docs.size() > 1) {
indexWriter.addDocuments(docs);
} else {
indexWriter.addDocument(docs.get(0));
}
}
protected static final class IndexingStrategy {
final boolean currentNotFoundOrDeleted;
final boolean useLuceneUpdateDocument;
final long versionForIndexing;
final boolean indexIntoLucene;
final boolean addStaleOpToLucene;
final int reservedDocs;
final Optional<IndexResult> earlyResultOnPreFlightError;
private IndexingStrategy(
boolean currentNotFoundOrDeleted,
boolean useLuceneUpdateDocument,
boolean indexIntoLucene,
boolean addStaleOpToLucene,
long versionForIndexing,
int reservedDocs,
IndexResult earlyResultOnPreFlightError
) {
assert useLuceneUpdateDocument == false || indexIntoLucene
: "use lucene update is set to true, but we're not indexing into lucene";
assert (indexIntoLucene && earlyResultOnPreFlightError != null) == false
: "can only index into lucene or have a preflight result but not both."
+ "indexIntoLucene: "
+ indexIntoLucene
+ " earlyResultOnPreFlightError:"
+ earlyResultOnPreFlightError;
assert reservedDocs == 0 || indexIntoLucene || addStaleOpToLucene : reservedDocs;
this.currentNotFoundOrDeleted = currentNotFoundOrDeleted;
this.useLuceneUpdateDocument = useLuceneUpdateDocument;
this.versionForIndexing = versionForIndexing;
this.indexIntoLucene = indexIntoLucene;
this.addStaleOpToLucene = addStaleOpToLucene;
this.reservedDocs = reservedDocs;
this.earlyResultOnPreFlightError = earlyResultOnPreFlightError == null
? Optional.empty()
: Optional.of(earlyResultOnPreFlightError);
}
static IndexingStrategy optimizedAppendOnly(long versionForIndexing, int reservedDocs) {
return new IndexingStrategy(true, false, true, false, versionForIndexing, reservedDocs, null);
}
public static IndexingStrategy skipDueToVersionConflict(
VersionConflictEngineException e,
boolean currentNotFoundOrDeleted,
long currentVersion,
String id
) {
final IndexResult result = new IndexResult(e, currentVersion, id);
return new IndexingStrategy(currentNotFoundOrDeleted, false, false, false, Versions.NOT_FOUND, 0, result);
}
static IndexingStrategy processNormally(boolean currentNotFoundOrDeleted, long versionForIndexing, int reservedDocs) {
return new IndexingStrategy(
currentNotFoundOrDeleted,
currentNotFoundOrDeleted == false,
true,
false,
versionForIndexing,
reservedDocs,
null
);
}
public static IndexingStrategy processButSkipLucene(boolean currentNotFoundOrDeleted, long versionForIndexing) {
return new IndexingStrategy(currentNotFoundOrDeleted, false, false, false, versionForIndexing, 0, null);
}
static IndexingStrategy processAsStaleOp(long versionForIndexing, int reservedDocs) {
return new IndexingStrategy(false, false, false, true, versionForIndexing, reservedDocs, null);
}
static IndexingStrategy failAsTooManyDocs(Exception e, String id) {
final IndexResult result = new IndexResult(e, Versions.NOT_FOUND, id);
return new IndexingStrategy(false, false, false, false, Versions.NOT_FOUND, 0, result);
}
}
/**
* Asserts that the doc in the index operation really doesn't exist
*/
private boolean assertDocDoesNotExist(final Index index, final boolean allowDeleted) throws IOException {
// NOTE this uses direct access to the version map since we are in the assertion code where we maintain a secondary
// map in the version map such that we don't need to refresh if we are unsafe;
final VersionValue versionValue = versionMap.getVersionForAssert(index.uid().bytes());
if (versionValue != null) {
if (versionValue.isDelete() == false || allowDeleted == false) {
throw new AssertionError("doc [" + index.id() + "] exists in version map (version " + versionValue + ")");
}
} else {
try (Searcher searcher = acquireSearcher("assert doc doesn't exist", SearcherScope.INTERNAL)) {
searcher.setQueryCache(null); // so that it does not interfere with tests that check caching behavior
final long docsWithId = searcher.count(new TermQuery(index.uid()));
if (docsWithId > 0) {
throw new AssertionError("doc [" + index.id() + "] exists [" + docsWithId + "] times in index");
}
}
}
return true;
}
private void updateDocs(final Term uid, final List<LuceneDocument> docs, final IndexWriter indexWriter) throws IOException {
if (docs.size() > 1) {
indexWriter.softUpdateDocuments(uid, docs, softDeletesField);
} else {
indexWriter.softUpdateDocument(uid, docs.get(0), softDeletesField);
}
numDocUpdates.inc(docs.size());
}
@Override
public DeleteResult delete(Delete delete) throws IOException {
versionMap.enforceSafeAccess();
assert Objects.equals(delete.uid().field(), IdFieldMapper.NAME) : delete.uid().field();
assert assertIncomingSequenceNumber(delete.origin(), delete.seqNo());
final DeleteResult deleteResult;
int reservedDocs = 0;
// NOTE: we don't throttle this when merges fall behind because delete-by-id does not create new segments:
try (var ignored = acquireEnsureOpenRef(); Releasable ignored2 = versionMap.acquireLock(delete.uid().bytes())) {
lastWriteNanos = delete.startTime();
final DeletionStrategy plan = deletionStrategyForOperation(delete);
reservedDocs = plan.reservedDocs;
if (plan.earlyResultOnPreflightError.isPresent()) {
assert delete.origin() == Operation.Origin.PRIMARY : delete.origin();
deleteResult = plan.earlyResultOnPreflightError.get();
} else {
// generate or register sequence number
if (delete.origin() == Operation.Origin.PRIMARY) {
delete = new Delete(
delete.id(),
delete.uid(),
generateSeqNoForOperationOnPrimary(delete),
delete.primaryTerm(),
delete.version(),
delete.versionType(),
delete.origin(),
delete.startTime(),
delete.getIfSeqNo(),
delete.getIfPrimaryTerm()
);
advanceMaxSeqNoOfDeletesOnPrimary(delete.seqNo());
} else {
markSeqNoAsSeen(delete.seqNo());
}
assert delete.seqNo() >= 0 : "ops should have an assigned seq no.; origin: " + delete.origin();
if (plan.deleteFromLucene || plan.addStaleOpToLucene) {
deleteResult = deleteInLucene(delete, plan);
} else {
deleteResult = new DeleteResult(
plan.versionOfDeletion,
delete.primaryTerm(),
delete.seqNo(),
plan.currentlyDeleted == false,
delete.id()
);
}
if (plan.deleteFromLucene) {
numDocDeletes.inc();
versionMap.putDeleteUnderLock(
delete.uid().bytes(),
new DeleteVersionValue(
plan.versionOfDeletion,
delete.seqNo(),
delete.primaryTerm(),
engineConfig.getThreadPool().relativeTimeInMillis()
)
);
}
}
if (delete.origin().isFromTranslog() == false && deleteResult.getResultType() == Result.Type.SUCCESS) {
final Translog.Location location = translog.add(new Translog.Delete(delete, deleteResult));
deleteResult.setTranslogLocation(location);
}
localCheckpointTracker.markSeqNoAsProcessed(deleteResult.getSeqNo());
if (deleteResult.getTranslogLocation() == null) {
// the op is coming from the translog (and is hence persisted already) or does not have a sequence number (version conflict)
assert delete.origin().isFromTranslog() || deleteResult.getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO;
localCheckpointTracker.markSeqNoAsPersisted(deleteResult.getSeqNo());
}
deleteResult.setTook(System.nanoTime() - delete.startTime());
deleteResult.freeze();
} catch (RuntimeException | IOException e) {
try {
maybeFailEngine("delete", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw e;
} finally {
releaseInFlightDocs(reservedDocs);
}
maybePruneDeletes();
return deleteResult;
}
private Exception tryAcquireInFlightDocs(Operation operation, int addingDocs) {
assert operation.origin() == Operation.Origin.PRIMARY : operation;
assert operation.seqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO : operation;
assert addingDocs > 0 : addingDocs;
final long totalDocs = indexWriter.getPendingNumDocs() + inFlightDocCount.addAndGet(addingDocs);
if (totalDocs > maxDocs) {
releaseInFlightDocs(addingDocs);
return new IllegalArgumentException("Number of documents in the index can't exceed [" + maxDocs + "]");
} else {
return null;
}
}
private void releaseInFlightDocs(int numDocs) {
assert numDocs >= 0 : numDocs;
final long newValue = inFlightDocCount.addAndGet(-numDocs);
assert newValue >= 0 : "inFlightDocCount must not be negative [" + newValue + "]";
}
long getInFlightDocCount() {
return inFlightDocCount.get();
}
protected DeletionStrategy deletionStrategyForOperation(final Delete delete) throws IOException {
if (delete.origin() == Operation.Origin.PRIMARY) {
return planDeletionAsPrimary(delete);
} else {
// non-primary mode (i.e., replica or recovery)
return planDeletionAsNonPrimary(delete);
}
}
protected final DeletionStrategy planDeletionAsNonPrimary(Delete delete) throws IOException {
assert assertNonPrimaryOrigin(delete);
final DeletionStrategy plan;
if (hasBeenProcessedBefore(delete)) {
// the operation seq# was processed thus this operation was already put into lucene
// this can happen during recovery where older operations are sent from the translog that are already
// part of the lucene commit (either from a peer recovery or a local translog)
// or due to concurrent indexing & recovery. For the former it is important to skip lucene as the operation in
// question may have been deleted in an out of order op that is not replayed.
// See testRecoverFromStoreWithOutOfOrderDelete for an example of local recovery
// See testRecoveryWithOutOfOrderDelete for an example of peer recovery
plan = DeletionStrategy.processButSkipLucene(false, delete.version());
} else {
final OpVsLuceneDocStatus opVsLucene = compareOpToLuceneDocBasedOnSeqNo(delete);
if (opVsLucene == OpVsLuceneDocStatus.OP_STALE_OR_EQUAL) {
plan = DeletionStrategy.processAsStaleOp(delete.version());
} else {
plan = DeletionStrategy.processNormally(opVsLucene == OpVsLuceneDocStatus.LUCENE_DOC_NOT_FOUND, delete.version(), 0);
}
}
return plan;
}
protected boolean assertNonPrimaryOrigin(final Operation operation) {
assert operation.origin() != Operation.Origin.PRIMARY : "planing as primary but got " + operation.origin();
return true;
}
private DeletionStrategy planDeletionAsPrimary(Delete delete) throws IOException {
assert delete.origin() == Operation.Origin.PRIMARY : "planing as primary but got " + delete.origin();
// resolve operation from external to internal
final VersionValue versionValue = resolveDocVersion(delete, delete.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO);
assert incrementVersionLookup();
final long currentVersion;
final boolean currentlyDeleted;
if (versionValue == null) {
currentVersion = Versions.NOT_FOUND;
currentlyDeleted = true;
} else {
currentVersion = versionValue.version;
currentlyDeleted = versionValue.isDelete();
}
final DeletionStrategy plan;
if (delete.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && currentlyDeleted) {
final VersionConflictEngineException e = new VersionConflictEngineException(
shardId,
delete.id(),
delete.getIfSeqNo(),
delete.getIfPrimaryTerm(),
SequenceNumbers.UNASSIGNED_SEQ_NO,
SequenceNumbers.UNASSIGNED_PRIMARY_TERM
);
plan = DeletionStrategy.skipDueToVersionConflict(e, currentVersion, true, delete.id());
} else if (delete.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO
&& (versionValue.seqNo != delete.getIfSeqNo() || versionValue.term != delete.getIfPrimaryTerm())) {
final VersionConflictEngineException e = new VersionConflictEngineException(
shardId,
delete.id(),
delete.getIfSeqNo(),
delete.getIfPrimaryTerm(),
versionValue.seqNo,
versionValue.term
);
plan = DeletionStrategy.skipDueToVersionConflict(e, currentVersion, currentlyDeleted, delete.id());
} else if (delete.versionType().isVersionConflictForWrites(currentVersion, delete.version(), currentlyDeleted)) {
final VersionConflictEngineException e = new VersionConflictEngineException(
shardId,
"[" + delete.id() + "]",
delete.versionType().explainConflictForWrites(currentVersion, delete.version(), true)
);
plan = DeletionStrategy.skipDueToVersionConflict(e, currentVersion, currentlyDeleted, delete.id());
} else {
final Exception reserveError = tryAcquireInFlightDocs(delete, 1);
if (reserveError != null) {
plan = DeletionStrategy.failAsTooManyDocs(reserveError, delete.id());
} else {
final long versionOfDeletion = delete.versionType().updateVersion(currentVersion, delete.version());
plan = DeletionStrategy.processNormally(currentlyDeleted, versionOfDeletion, 1);
}
}
return plan;
}
private DeleteResult deleteInLucene(Delete delete, DeletionStrategy plan) throws IOException {
assert assertMaxSeqNoOfUpdatesIsAdvanced(delete.uid(), delete.seqNo(), false, false);
try {
final ParsedDocument tombstone = ParsedDocument.deleteTombstone(delete.id());
assert tombstone.docs().size() == 1 : "Tombstone doc should have single doc [" + tombstone + "]";
tombstone.updateSeqID(delete.seqNo(), delete.primaryTerm());
tombstone.version().setLongValue(plan.versionOfDeletion);
final LuceneDocument doc = tombstone.docs().get(0);
assert doc.getField(SeqNoFieldMapper.TOMBSTONE_NAME) != null
: "Delete tombstone document but _tombstone field is not set [" + doc + " ]";
doc.add(softDeletesField);
if (plan.addStaleOpToLucene || plan.currentlyDeleted) {
indexWriter.addDocument(doc);
} else {
indexWriter.softUpdateDocument(delete.uid(), doc, softDeletesField);
}
return new DeleteResult(
plan.versionOfDeletion,
delete.primaryTerm(),
delete.seqNo(),
plan.currentlyDeleted == false,
delete.id()
);
} catch (final Exception ex) {
/*
* Document level failures when deleting are unexpected, we likely hit something fatal such as the Lucene index being corrupt,
* or the Lucene document limit. We have already issued a sequence number here so this is fatal, fail the engine.
*/
if (ex instanceof AlreadyClosedException == false && indexWriter.getTragicException() == null) {
final String reason = String.format(
Locale.ROOT,
"delete id[%s] origin [%s] seq#[%d] failed at the document level",
delete.id(),
delete.origin(),
delete.seqNo()
);
failEngine(reason, ex);
}
throw ex;
}
}
protected static final class DeletionStrategy {
// of a rare double delete
final boolean deleteFromLucene;
final boolean addStaleOpToLucene;
final boolean currentlyDeleted;
final long versionOfDeletion;
final Optional<DeleteResult> earlyResultOnPreflightError;
final int reservedDocs;
private DeletionStrategy(
boolean deleteFromLucene,
boolean addStaleOpToLucene,
boolean currentlyDeleted,
long versionOfDeletion,
int reservedDocs,
DeleteResult earlyResultOnPreflightError
) {
assert (deleteFromLucene && earlyResultOnPreflightError != null) == false
: "can only delete from lucene or have a preflight result but not both."
+ "deleteFromLucene: "
+ deleteFromLucene
+ " earlyResultOnPreFlightError:"
+ earlyResultOnPreflightError;
this.deleteFromLucene = deleteFromLucene;
this.addStaleOpToLucene = addStaleOpToLucene;
this.currentlyDeleted = currentlyDeleted;
this.versionOfDeletion = versionOfDeletion;
this.reservedDocs = reservedDocs;
assert reservedDocs == 0 || deleteFromLucene || addStaleOpToLucene : reservedDocs;
this.earlyResultOnPreflightError = earlyResultOnPreflightError == null
? Optional.empty()
: Optional.of(earlyResultOnPreflightError);
}
public static DeletionStrategy skipDueToVersionConflict(
VersionConflictEngineException e,
long currentVersion,
boolean currentlyDeleted,
String id
) {
final DeleteResult deleteResult = new DeleteResult(
e,
currentVersion,
SequenceNumbers.UNASSIGNED_PRIMARY_TERM,
SequenceNumbers.UNASSIGNED_SEQ_NO,
currentlyDeleted == false,
id
);
return new DeletionStrategy(false, false, currentlyDeleted, Versions.NOT_FOUND, 0, deleteResult);
}
static DeletionStrategy processNormally(boolean currentlyDeleted, long versionOfDeletion, int reservedDocs) {
return new DeletionStrategy(true, false, currentlyDeleted, versionOfDeletion, reservedDocs, null);
}
public static DeletionStrategy processButSkipLucene(boolean currentlyDeleted, long versionOfDeletion) {
return new DeletionStrategy(false, false, currentlyDeleted, versionOfDeletion, 0, null);
}
static DeletionStrategy processAsStaleOp(long versionOfDeletion) {
return new DeletionStrategy(false, true, false, versionOfDeletion, 0, null);
}
static DeletionStrategy failAsTooManyDocs(Exception e, String id) {
final DeleteResult deleteResult = new DeleteResult(
e,
Versions.NOT_FOUND,
SequenceNumbers.UNASSIGNED_PRIMARY_TERM,
SequenceNumbers.UNASSIGNED_SEQ_NO,
false,
id
);
return new DeletionStrategy(false, false, false, Versions.NOT_FOUND, 0, deleteResult);
}
}
@Override
public void maybePruneDeletes() {
// It's expensive to prune because we walk the deletes map acquiring dirtyLock for each uid so we only do it
// every 1/4 of gcDeletesInMillis:
if (engineConfig.isEnableGcDeletes()
&& engineConfig.getThreadPool().relativeTimeInMillis() - lastDeleteVersionPruneTimeMSec > getGcDeletesInMillis() * 0.25) {
pruneDeletedTombstones();
}
}
@Override
public NoOpResult noOp(final NoOp noOp) throws IOException {
final NoOpResult noOpResult;
try (var ignored = acquireEnsureOpenRef()) {
noOpResult = innerNoOp(noOp);
} catch (final Exception e) {
try {
maybeFailEngine("noop", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw e;
}
return noOpResult;
}
private NoOpResult innerNoOp(final NoOp noOp) throws IOException {
assert isDrainedForClose() == false;
assert noOp.seqNo() > SequenceNumbers.NO_OPS_PERFORMED;
final long seqNo = noOp.seqNo();
try (Releasable ignored = noOpKeyedLock.acquire(seqNo)) {
final NoOpResult noOpResult;
final Optional<Exception> preFlightError = preFlightCheckForNoOp(noOp);
if (preFlightError.isPresent()) {
noOpResult = new NoOpResult(
SequenceNumbers.UNASSIGNED_PRIMARY_TERM,
SequenceNumbers.UNASSIGNED_SEQ_NO,
preFlightError.get()
);
} else {
markSeqNoAsSeen(noOp.seqNo());
if (hasBeenProcessedBefore(noOp) == false) {
try {
final ParsedDocument tombstone = ParsedDocument.noopTombstone(noOp.reason());
tombstone.updateSeqID(noOp.seqNo(), noOp.primaryTerm());
// A noop tombstone does not require a _version but it's added to have a fully dense docvalues for the version
// field. 1L is selected to optimize the compression because it might probably be the most common value in
// version field.
tombstone.version().setLongValue(1L);
assert tombstone.docs().size() == 1 : "Tombstone should have a single doc [" + tombstone + "]";
final LuceneDocument doc = tombstone.docs().get(0);
assert doc.getField(SeqNoFieldMapper.TOMBSTONE_NAME) != null
: "Noop tombstone document but _tombstone field is not set [" + doc + " ]";
doc.add(softDeletesField);
indexWriter.addDocument(doc);
} catch (final Exception ex) {
/*
* Document level failures when adding a no-op are unexpected, we likely hit something fatal such as the Lucene
* index being corrupt, or the Lucene document limit. We have already issued a sequence number here so this is
* fatal, fail the engine.
*/
if (ex instanceof AlreadyClosedException == false && indexWriter.getTragicException() == null) {
failEngine("no-op origin[" + noOp.origin() + "] seq#[" + noOp.seqNo() + "] failed at document level", ex);
}
throw ex;
}
}
noOpResult = new NoOpResult(noOp.primaryTerm(), noOp.seqNo());
if (noOp.origin().isFromTranslog() == false && noOpResult.getResultType() == Result.Type.SUCCESS) {
final Translog.Location location = translog.add(new Translog.NoOp(noOp.seqNo(), noOp.primaryTerm(), noOp.reason()));
noOpResult.setTranslogLocation(location);
}
}
localCheckpointTracker.markSeqNoAsProcessed(noOpResult.getSeqNo());
if (noOpResult.getTranslogLocation() == null) {
// the op is coming from the translog (and is hence persisted already) or it does not have a sequence number
assert noOp.origin().isFromTranslog() || noOpResult.getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO;
localCheckpointTracker.markSeqNoAsPersisted(noOpResult.getSeqNo());
}
noOpResult.setTook(System.nanoTime() - noOp.startTime());
noOpResult.freeze();
return noOpResult;
} finally {
assert isDrainedForClose() == false;
}
}
/**
* Executes a pre-flight check for a given NoOp.
* If this method returns a non-empty result, the engine won't process this NoOp and returns a failure.
*/
protected Optional<Exception> preFlightCheckForNoOp(final NoOp noOp) throws IOException {
return Optional.empty();
}
@Override
public RefreshResult refresh(String source) throws EngineException {
return refresh(source, SearcherScope.EXTERNAL, true);
}
@Override
public void maybeRefresh(String source, ActionListener<RefreshResult> listener) throws EngineException {
ActionListener.completeWith(listener, () -> refresh(source, SearcherScope.EXTERNAL, false));
}
protected RefreshResult refreshInternalSearcher(String source, boolean block) throws EngineException {
return refresh(source, SearcherScope.INTERNAL, block);
}
protected final RefreshResult refresh(String source, SearcherScope scope, boolean block) throws EngineException {
// both refresh types will result in an internal refresh but only the external will also
// pass the new reader reference to the external reader manager.
final long localCheckpointBeforeRefresh = localCheckpointTracker.getProcessedCheckpoint();
boolean refreshed;
long segmentGeneration = RefreshResult.UNKNOWN_GENERATION;
try {
// refresh does not need to hold readLock as ReferenceManager can handle correctly if the engine is closed in mid-way.
if (store.tryIncRef()) {
// increment the ref just to ensure nobody closes the store during a refresh
try {
// even though we maintain 2 managers we really do the heavy-lifting only once.
// the second refresh will only do the extra work we have to do for warming caches etc.
ReferenceManager<ElasticsearchDirectoryReader> referenceManager = getReferenceManager(scope);
long generationBeforeRefresh = lastCommittedSegmentInfos.getGeneration();
// it is intentional that we never refresh both internal / external together
if (block) {
referenceManager.maybeRefreshBlocking();
refreshed = true;
} else {
refreshed = referenceManager.maybeRefresh();
}
if (refreshed) {
final ElasticsearchDirectoryReader current = referenceManager.acquire();
try {
// Just use the generation from the reader when https://github.com/apache/lucene/pull/12177 is included.
segmentGeneration = Math.max(current.getIndexCommit().getGeneration(), generationBeforeRefresh);
} finally {
referenceManager.release(current);
}
}
} finally {
store.decRef();
}
if (refreshed) {
lastRefreshedCheckpointListener.updateRefreshedCheckpoint(localCheckpointBeforeRefresh);
}
} else {
refreshed = false;
}
} catch (AlreadyClosedException e) {
failOnTragicEvent(e);
throw e;
} catch (Exception e) {
try {
failEngine("refresh failed source[" + source + "]", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw new RefreshFailedEngineException(shardId, e);
}
assert refreshed == false || lastRefreshedCheckpoint() >= localCheckpointBeforeRefresh
: "refresh checkpoint was not advanced; "
+ "local_checkpoint="
+ localCheckpointBeforeRefresh
+ " refresh_checkpoint="
+ lastRefreshedCheckpoint();
// TODO: maybe we should just put a scheduled job in threadPool?
// We check for pruning in each delete request, but we also prune here e.g. in case a delete burst comes in and then no more deletes
// for a long time:
maybePruneDeletes();
mergeScheduler.refreshConfig();
long primaryTerm = config().getPrimaryTermSupplier().getAsLong();
return new RefreshResult(refreshed, primaryTerm, segmentGeneration);
}
@Override
public void writeIndexingBuffer() throws IOException {
final long reclaimableVersionMapBytes = versionMap.reclaimableRefreshRamBytes();
// Only count bytes that are not already being written to disk. Note: this number may be negative at times if these two metrics get
// updated concurrently. It's fine as it's only being used as a heuristic to decide on a full refresh vs. writing a single segment.
// TODO: it might be more relevant to use the RAM usage of the largest DWPT as opposed to the overall RAM usage? Can we get this
// exposed in Lucene?
final long indexWriterBytesUsed = indexWriter.ramBytesUsed() - indexWriter.getFlushingBytes();
if (reclaimableVersionMapBytes >= indexWriterBytesUsed) {
// This method expects to reclaim memory quickly, so if the version map is using more memory than the IndexWriter buffer then we
// do a refresh, which is the only way to reclaim memory from the version map. IndexWriter#flushNextBuffer has similar logic: if
// pending deletes occupy more than half of RAMBufferSizeMB then deletes are applied too.
reclaimVersionMapMemory();
} else {
// Write the largest pending segment.
indexWriter.flushNextBuffer();
}
}
protected void reclaimVersionMapMemory() {
// If we're already halfway through the flush thresholds, then we do a flush. This will save us from writing segments twice
// independently in a short period of time, once to reclaim version map memory and then to reclaim the translog. For
// memory-constrained deployments that need to refresh often to reclaim memory, this may require flushing 2x more often than
// expected, but the general assumption is that this downside is an ok trade-off given the benefit of flushing the whole content of
// the indexing buffer less often.
final long flushThresholdSizeInBytes = Math.max(
Translog.DEFAULT_HEADER_SIZE_IN_BYTES + 1,
config().getIndexSettings().getFlushThresholdSize(totalDiskSpace).getBytes() / 2
);
final long flushThresholdAgeInNanos = config().getIndexSettings().getFlushThresholdAge().getNanos() / 2;
if (shouldPeriodicallyFlush(flushThresholdSizeInBytes, flushThresholdAgeInNanos)) {
flush(false, false, ActionListener.noop());
} else {
refresh("write indexing buffer", SearcherScope.INTERNAL, false);
}
}
@Override
public boolean shouldPeriodicallyFlush() {
final long flushThresholdSizeInBytes = config().getIndexSettings().getFlushThresholdSize(totalDiskSpace).getBytes();
final long flushThresholdAgeInNanos = config().getIndexSettings().getFlushThresholdAge().getNanos();
return shouldPeriodicallyFlush(flushThresholdSizeInBytes, flushThresholdAgeInNanos);
}
private boolean shouldPeriodicallyFlush(long flushThresholdSizeInBytes, long flushThresholdAgeInNanos) {
ensureOpen();
if (shouldPeriodicallyFlushAfterBigMerge.get()) {
return true;
}
final long localCheckpointOfLastCommit = Long.parseLong(
lastCommittedSegmentInfos.userData.get(SequenceNumbers.LOCAL_CHECKPOINT_KEY)
);
final long translogGenerationOfLastCommit = translog.getMinGenerationForSeqNo(
localCheckpointOfLastCommit + 1
).translogFileGeneration;
if (translog.sizeInBytesByMinGen(translogGenerationOfLastCommit) < flushThresholdSizeInBytes
&& relativeTimeInNanosSupplier.getAsLong() - lastFlushTimestamp < flushThresholdAgeInNanos) {
return false;
}
/*
* We flush to reduce the size of uncommitted translog but strictly speaking the uncommitted size won't always be
* below the flush-threshold after a flush. To avoid getting into an endless loop of flushing, we only enable the
* periodically flush condition if this condition is disabled after a flush. The condition will change if the new
* commit points to the later generation the last commit's(eg. gen-of-last-commit < gen-of-new-commit)[1].
*
* When the local checkpoint equals to max_seqno, and translog-gen of the last commit equals to translog-gen of
* the new commit, we know that the last generation must contain operations because its size is above the flush
* threshold and the flush-threshold is guaranteed to be higher than an empty translog by the setting validation.
* This guarantees that the new commit will point to the newly rolled generation. In fact, this scenario only
* happens when the generation-threshold is close to or above the flush-threshold; otherwise we have rolled
* generations as the generation-threshold was reached, then the first condition (eg. [1]) is already satisfied.
*
* This method is to maintain translog only, thus IndexWriter#hasUncommittedChanges condition is not considered.
*/
final long translogGenerationOfNewCommit = translog.getMinGenerationForSeqNo(
localCheckpointTracker.getProcessedCheckpoint() + 1
).translogFileGeneration;
return translogGenerationOfLastCommit < translogGenerationOfNewCommit
|| localCheckpointTracker.getProcessedCheckpoint() == localCheckpointTracker.getMaxSeqNo();
}
@Override
protected void flushHoldingLock(boolean force, boolean waitIfOngoing, ActionListener<FlushResult> listener) throws EngineException {
ensureOpen(); // best-effort, a concurrent failEngine() can still happen but that's ok
if (force && waitIfOngoing == false) {
final String message = "wait_if_ongoing must be true for a force flush: force=" + force + " wait_if_ongoing=" + waitIfOngoing;
assert false : message;
throw new IllegalArgumentException(message);
}
final long generation;
if (flushLock.tryLock() == false) {
// if we can't get the lock right away we block if needed otherwise barf
if (waitIfOngoing == false) {
logger.trace("detected an in-flight flush, not blocking to wait for it's completion");
listener.onResponse(FlushResult.NO_FLUSH);
return;
}
logger.trace("waiting for in-flight flush to finish");
flushLock.lock();
logger.trace("acquired flush lock after blocking");
} else {
logger.trace("acquired flush lock immediately");
}
final long startTime = System.nanoTime();
try {
// Only flush if (1) Lucene has uncommitted docs, or (2) forced by caller, or (3) the
// newly created commit points to a different translog generation (can free translog),
// or (4) the local checkpoint information in the last commit is stale, which slows down future recoveries.
boolean hasUncommittedChanges = hasUncommittedChanges();
if (hasUncommittedChanges
|| force
|| shouldPeriodicallyFlush()
|| getProcessedLocalCheckpoint() > Long.parseLong(
lastCommittedSegmentInfos.userData.get(SequenceNumbers.LOCAL_CHECKPOINT_KEY)
)) {
ensureCanFlush();
Translog.Location commitLocation = getTranslogLastWriteLocation();
try {
translog.rollGeneration();
logger.trace("starting commit for flush; commitTranslog=true");
long lastFlushTimestamp = relativeTimeInNanosSupplier.getAsLong();
// Pre-emptively recording the upcoming segment generation so that the live version map archive records
// the correct segment generation for doc IDs that go to the archive while a flush is happening. Otherwise,
// if right after committing the IndexWriter new docs get indexed/updated and a refresh moves them to the archive,
// we clear them from the archive once we see that segment generation on the search shards, but those changes
// were not included in the commit since they happened right after it.
preCommitSegmentGeneration.set(lastCommittedSegmentInfos.getGeneration() + 1);
commitIndexWriter(indexWriter, translog);
logger.trace("finished commit for flush");
// we need to refresh in order to clear older version values
refresh("version_table_flush", SearcherScope.INTERNAL, true);
translog.trimUnreferencedReaders();
// Use the timestamp from when the flush started, but only update it in case of success, so that any exception in
// the above lines would not lead the engine to think that it recently flushed, when it did not.
this.lastFlushTimestamp = lastFlushTimestamp;
} catch (AlreadyClosedException e) {
failOnTragicEvent(e);
throw e;
} catch (Exception e) {
throw new FlushFailedEngineException(shardId, e);
}
refreshLastCommittedSegmentInfos();
generation = lastCommittedSegmentInfos.getGeneration();
flushListener.afterFlush(generation, commitLocation);
} else {
generation = lastCommittedSegmentInfos.getGeneration();
}
} catch (FlushFailedEngineException ex) {
maybeFailEngine("flush", ex);
listener.onFailure(ex);
return;
} catch (Exception e) {
listener.onFailure(e);
return;
} finally {
totalFlushTimeExcludingWaitingOnLock.inc(System.nanoTime() - startTime);
flushLock.unlock();
logger.trace("released flush lock");
}
afterFlush(generation);
// We don't have to do this here; we do it defensively to make sure that even if wall clock time is misbehaving
// (e.g., moves backwards) we will at least still sometimes prune deleted tombstones:
if (engineConfig.isEnableGcDeletes()) {
pruneDeletedTombstones();
}
waitForCommitDurability(generation, listener.map(v -> new FlushResult(true, generation)));
}
protected final boolean isFlushLockIsHeldByCurrentThread() {
return flushLock.isHeldByCurrentThread();
}
protected boolean hasUncommittedChanges() {
return indexWriter.hasUncommittedChanges();
}
private void refreshLastCommittedSegmentInfos() {
/*
* we have to inc-ref the store here since if the engine is closed by a tragic event
* we don't acquire the write lock and wait until we have exclusive access. This might also
* dec the store reference which can essentially close the store and unless we can inc the reference
* we can't use it.
*/
store.incRef();
try {
// reread the last committed segment infos
lastCommittedSegmentInfos = store.readLastCommittedSegmentsInfo();
} catch (Exception e) {
if (isClosed.get() == false) {
logger.warn("failed to read latest segment infos on flush", e);
if (Lucene.isCorruptionException(e)) {
throw new FlushFailedEngineException(shardId, e);
}
}
} finally {
store.decRef();
}
}
protected void afterFlush(long generation) {}
@Override
public void rollTranslogGeneration() throws EngineException {
try (var ignored = acquireEnsureOpenRef()) {
translog.rollGeneration();
translog.trimUnreferencedReaders();
} catch (AlreadyClosedException e) {
failOnTragicEvent(e);
throw e;
} catch (Exception e) {
try {
failEngine("translog trimming failed", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw new EngineException(shardId, "failed to roll translog", e);
}
}
@Override
public void trimUnreferencedTranslogFiles() throws EngineException {
try (var ignored = acquireEnsureOpenRef()) {
translog.trimUnreferencedReaders();
} catch (AlreadyClosedException e) {
failOnTragicEvent(e);
throw e;
} catch (Exception e) {
try {
failEngine("translog trimming failed", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw new EngineException(shardId, "failed to trim translog", e);
}
}
@Override
public boolean shouldRollTranslogGeneration() {
return getTranslog().shouldRollGeneration();
}
@Override
public void trimOperationsFromTranslog(long belowTerm, long aboveSeqNo) throws EngineException {
try (var ignored = acquireEnsureOpenRef()) {
translog.trimOperations(belowTerm, aboveSeqNo);
} catch (AlreadyClosedException e) {
failOnTragicEvent(e);
throw e;
} catch (Exception e) {
try {
failEngine("translog operations trimming failed", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw new EngineException(shardId, "failed to trim translog operations", e);
}
}
private void pruneDeletedTombstones() {
/*
* We need to deploy two different trimming strategies for GC deletes on primary and replicas. Delete operations on primary
* are remembered for at least one GC delete cycle and trimmed periodically. This is, at the moment, the best we can do on
* primary for user facing APIs but this arbitrary time limit is problematic for replicas. On replicas however we should
* trim only deletes whose seqno at most the local checkpoint. This requirement is explained as follows.
*
* Suppose o1 and o2 are two operations on the same document with seq#(o1) < seq#(o2), and o2 arrives before o1 on the replica.
* o2 is processed normally since it arrives first; when o1 arrives it should be discarded:
* - If seq#(o1) <= LCP, then it will be not be added to Lucene, as it was already previously added.
* - If seq#(o1) > LCP, then it depends on the nature of o2:
* *) If o2 is a delete then its seq# is recorded in the VersionMap, since seq#(o2) > seq#(o1) > LCP,
* so a lookup can find it and determine that o1 is stale.
* *) If o2 is an indexing then its seq# is either in Lucene (if refreshed) or the VersionMap (if not refreshed yet),
* so a real-time lookup can find it and determine that o1 is stale.
*
* Here we prefer to deploy a single trimming strategy, which satisfies two constraints, on both primary and replicas because:
* - It's simpler - no need to distinguish if an engine is running at primary mode or replica mode or being promoted.
* - If a replica subsequently is promoted, user experience is maintained as that replica remembers deletes for the last GC cycle.
*
* However, the version map may consume less memory if we deploy two different trimming strategies for primary and replicas.
*/
final long timeMSec = engineConfig.getThreadPool().relativeTimeInMillis();
final long maxTimestampToPrune = timeMSec - engineConfig.getIndexSettings().getGcDeletesInMillis();
versionMap.pruneTombstones(maxTimestampToPrune, localCheckpointTracker.getProcessedCheckpoint());
lastDeleteVersionPruneTimeMSec = timeMSec;
}
// testing
void clearDeletedTombstones() {
versionMap.pruneTombstones(Long.MAX_VALUE, localCheckpointTracker.getMaxSeqNo());
}
// for testing
final Map<BytesRef, VersionValue> getVersionMap() {
return Stream.concat(versionMap.getAllCurrent().entrySet().stream(), versionMap.getAllTombstones().entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@Override
public void forceMerge(final boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, final String forceMergeUUID)
throws EngineException, IOException {
if (onlyExpungeDeletes && maxNumSegments >= 0) {
throw new IllegalArgumentException("only_expunge_deletes and max_num_segments are mutually exclusive");
}
/*
* We do NOT acquire the readlock here since we are waiting on the merges to finish
* that's fine since the IW.rollback should stop all the threads and trigger an IOException
* causing us to fail the forceMerge
*/
optimizeLock.lock();
try {
ensureOpen();
store.incRef(); // increment the ref just to ensure nobody closes the store while we optimize
try {
if (onlyExpungeDeletes) {
indexWriter.forceMergeDeletes(true /* blocks and waits for merges*/);
} else if (maxNumSegments <= 0) {
indexWriter.maybeMerge();
} else {
indexWriter.forceMerge(maxNumSegments, true /* blocks and waits for merges*/);
this.forceMergeUUID = forceMergeUUID;
}
if (flush) {
// TODO: Migrate to using async apic
flush(false, true);
// If any merges happened then we need to release the unmerged input segments so they can be deleted. A periodic refresh
// will do this eventually unless the user has disabled refreshes or isn't searching this shard frequently, in which
// case we should do something here to ensure a timely refresh occurs. However there's no real need to defer it nor to
// have any should-we-actually-refresh-here logic: we're already doing an expensive force-merge operation at the user's
// request and therefore don't expect any further writes so we may as well do the final refresh immediately and get it
// out of the way.
refresh("force-merge");
}
} finally {
store.decRef();
}
} catch (AlreadyClosedException ex) {
/* in this case we first check if the engine is still open. If so this exception is just fine
* and expected. We don't hold any locks while we block on forceMerge otherwise it would block
* closing the engine as well. If we are not closed we pass it on to failOnTragicEvent which ensures
* we are handling a tragic even exception here */
ensureOpen(ex);
failOnTragicEvent(ex);
throw ex;
} catch (Exception e) {
try {
maybeFailEngine("force merge", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw e;
} finally {
optimizeLock.unlock();
}
}
private IndexCommitRef acquireIndexCommitRef(final Supplier<IndexCommit> indexCommitSupplier) {
store.incRef();
boolean success = false;
try {
final IndexCommit indexCommit = indexCommitSupplier.get();
final IndexCommitRef commitRef = new IndexCommitRef(
indexCommit,
() -> IOUtils.close(() -> releaseIndexCommit(indexCommit), store::decRef)
);
success = true;
return commitRef;
} finally {
if (success == false) {
store.decRef();
}
}
}
@Override
public IndexCommitRef acquireLastIndexCommit(final boolean flushFirst) throws EngineException {
// we have to flush outside of the readlock otherwise we might have a problem upgrading
// the to a write lock when we fail the engine in this operation
if (flushFirst) {
logger.trace("start flush for snapshot");
// TODO: Split acquireLastIndexCommit into two apis one with blocking flushes one without
PlainActionFuture<FlushResult> future = new PlainActionFuture<>();
flush(false, true, future);
future.actionGet();
logger.trace("finish flush for snapshot");
}
return acquireIndexCommitRef(() -> combinedDeletionPolicy.acquireIndexCommit(false));
}
@Override
public IndexCommitRef acquireSafeIndexCommit() throws EngineException {
return acquireIndexCommitRef(() -> combinedDeletionPolicy.acquireIndexCommit(true));
}
private void releaseIndexCommit(IndexCommit snapshot) throws IOException {
// Revisit the deletion policy if we can clean up the snapshotting commit.
if (combinedDeletionPolicy.releaseCommit(snapshot)) {
try {
// Here we don't have to trim translog because snapshotting an index commit
// does not lock translog or prevents unreferenced files from trimming.
indexWriter.deleteUnusedFiles();
} catch (AlreadyClosedException ignored) {
// That's ok, we'll clean up unused files the next time it's opened.
}
}
}
@Override
public SafeCommitInfo getSafeCommitInfo() {
return combinedDeletionPolicy.getSafeCommitInfo();
}
private boolean failOnTragicEvent(AlreadyClosedException ex) {
final boolean engineFailed;
// if we are already closed due to some tragic exception
// we need to fail the engine. it might have already been failed before
// but we are double-checking it's failed and closed
if (indexWriter.isOpen() == false && indexWriter.getTragicException() != null) {
final Exception tragicException;
if (indexWriter.getTragicException() instanceof Exception) {
tragicException = (Exception) indexWriter.getTragicException();
} else {
tragicException = new RuntimeException(indexWriter.getTragicException());
}
failEngine("already closed by tragic event on the index writer", tragicException);
engineFailed = true;
} else if (translog.isOpen() == false && translog.getTragicException() != null) {
failEngine("already closed by tragic event on the translog", translog.getTragicException());
engineFailed = true;
} else if (failedEngine.get() == null && isClosing() == false && isClosed.get() == false) {
// we are closed but the engine is not failed yet?
// this smells like a bug - we only expect ACE if we are in a fatal case ie. either translog or IW is closed by
// a tragic event or has closed itself. if that is not the case we are in a buggy state and raise an assertion error
throw new AssertionError("Unexpected AlreadyClosedException", ex);
} else {
engineFailed = false;
}
return engineFailed;
}
@Override
protected boolean maybeFailEngine(String source, Exception e) {
boolean shouldFail = super.maybeFailEngine(source, e);
if (shouldFail) {
return true;
}
// Check for AlreadyClosedException -- ACE is a very special
// exception that should only be thrown in a tragic event. we pass on the checks to failOnTragicEvent which will
// throw and AssertionError if the tragic event condition is not met.
if (e instanceof AlreadyClosedException) {
return failOnTragicEvent((AlreadyClosedException) e);
} else if (e != null
&& ((indexWriter.isOpen() == false && indexWriter.getTragicException() == e)
|| (translog.isOpen() == false && translog.getTragicException() == e))) {
// this spot on - we are handling the tragic event exception here so we have to fail the engine
// right away
failEngine(source, e);
return true;
}
return false;
}
@Override
public SegmentInfos getLastCommittedSegmentInfos() {
return lastCommittedSegmentInfos;
}
@Override
protected final void writerSegmentStats(SegmentsStats stats) {
stats.addVersionMapMemoryInBytes(versionMap.ramBytesUsed());
stats.addIndexWriterMemoryInBytes(indexWriter.ramBytesUsed());
stats.updateMaxUnsafeAutoIdTimestamp(maxUnsafeAutoIdTimestamp.get());
}
@Override
public long getIndexBufferRAMBytesUsed() {
// We don't guard w/ readLock here, so we could throw AlreadyClosedException
return indexWriter.ramBytesUsed() + versionMap.ramBytesUsedForRefresh();
}
@Override
public List<Segment> segments() {
return segments(false);
}
@Override
public List<Segment> segments(boolean includeVectorFormatsInfo) {
try (var ignored = acquireEnsureOpenRef()) {
Segment[] segmentsArr = getSegmentInfo(lastCommittedSegmentInfos, includeVectorFormatsInfo);
// fill in the merges flag
Set<OnGoingMerge> onGoingMerges = mergeScheduler.onGoingMerges();
for (OnGoingMerge onGoingMerge : onGoingMerges) {
for (SegmentCommitInfo segmentInfoPerCommit : onGoingMerge.getMergedSegments()) {
for (Segment segment : segmentsArr) {
if (segment.getName().equals(segmentInfoPerCommit.info.name)) {
segment.mergeId = onGoingMerge.getId();
break;
}
}
}
}
return Arrays.asList(segmentsArr);
}
}
@Override
protected final void closeNoLock(String reason, CountDownLatch closedLatch) {
if (isClosed.compareAndSet(false, true)) {
assert isDrainedForClose() || failEngineLock.isHeldByCurrentThread()
: "Either all operations must have been drained or the engine must be currently be failing itself";
try {
this.versionMap.clear();
if (internalReaderManager != null) {
internalReaderManager.removeListener(versionMap);
}
try {
IOUtils.close(flushListener, externalReaderManager, internalReaderManager);
} catch (Exception e) {
logger.warn("Failed to close ReaderManager", e);
}
try {
IOUtils.close(translog);
} catch (Exception e) {
logger.warn("Failed to close translog", e);
}
// no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed
logger.trace("rollback indexWriter");
try {
assert ClusterApplierService.assertNotApplyingClusterState();
indexWriter.rollback();
} catch (AlreadyClosedException ex) {
failOnTragicEvent(ex);
throw ex;
}
logger.trace("rollback indexWriter done");
} catch (Exception e) {
logger.warn("failed to rollback writer on close", e);
} finally {
try {
store.decRef();
logger.debug("engine closed [{}]", reason);
} finally {
closedLatch.countDown();
}
}
}
}
@Override
protected final ReferenceManager<ElasticsearchDirectoryReader> getReferenceManager(SearcherScope scope) {
return switch (scope) {
case INTERNAL -> internalReaderManager;
case EXTERNAL -> externalReaderManager;
};
}
private IndexWriter createWriter() throws IOException {
try {
final IndexWriterConfig iwc = getIndexWriterConfig();
return createWriter(store.directory(), iwc);
} catch (LockObtainFailedException ex) {
logger.warn("could not lock IndexWriter", ex);
throw ex;
}
}
// pkg-private for testing
IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException {
if (Assertions.ENABLED) {
return new AssertingIndexWriter(directory, iwc);
} else {
return new IndexWriter(directory, iwc);
}
}
private IndexWriterConfig getIndexWriterConfig() {
final IndexWriterConfig iwc = new IndexWriterConfig(engineConfig.getAnalyzer());
iwc.setCommitOnClose(false); // we by default don't commit on close
iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
iwc.setIndexDeletionPolicy(combinedDeletionPolicy);
// with tests.verbose, lucene sets this up: plumb to align with filesystem stream
boolean verbose = false;
try {
verbose = Boolean.parseBoolean(System.getProperty("tests.verbose"));
} catch (Exception ignore) {}
iwc.setInfoStream(verbose ? InfoStream.getDefault() : new LoggerInfoStream(logger));
iwc.setMergeScheduler(mergeScheduler);
// Give us the opportunity to upgrade old segments while performing
// background merges
MergePolicy mergePolicy = config().getMergePolicy();
// always configure soft-deletes field so an engine with soft-deletes disabled can open a Lucene index with soft-deletes.
iwc.setSoftDeletesField(Lucene.SOFT_DELETES_FIELD);
mergePolicy = new RecoverySourcePruneMergePolicy(
SourceFieldMapper.RECOVERY_SOURCE_NAME,
engineConfig.getIndexSettings().getMode() == IndexMode.TIME_SERIES,
softDeletesPolicy::getRetentionQuery,
new SoftDeletesRetentionMergePolicy(
Lucene.SOFT_DELETES_FIELD,
softDeletesPolicy::getRetentionQuery,
new PrunePostingsMergePolicy(mergePolicy, IdFieldMapper.NAME)
)
);
boolean shuffleForcedMerge = Booleans.parseBoolean(System.getProperty("es.shuffle_forced_merge", Boolean.TRUE.toString()));
if (shuffleForcedMerge) {
// We wrap the merge policy for all indices even though it is mostly useful for time-based indices
// but there should be no overhead for other type of indices so it's simpler than adding a setting
// to enable it.
mergePolicy = new ShuffleForcedMergePolicy(mergePolicy);
}
iwc.setMergePolicy(mergePolicy);
// TODO: Introduce an index setting for setMaxFullFlushMergeWaitMillis
iwc.setMaxFullFlushMergeWaitMillis(-1);
iwc.setSimilarity(engineConfig.getSimilarity());
iwc.setRAMBufferSizeMB(engineConfig.getIndexingBufferSize().getMbFrac());
iwc.setCodec(engineConfig.getCodec());
boolean useCompoundFile = engineConfig.getUseCompoundFile();
iwc.setUseCompoundFile(useCompoundFile);
if (useCompoundFile == false) {
logger.warn(
"[{}] is set to false, this should only be used in tests and can cause serious problems in production environments",
EngineConfig.USE_COMPOUND_FILE
);
}
if (config().getIndexSort() != null) {
iwc.setIndexSort(config().getIndexSort());
}
// Provide a custom leaf sorter, so that index readers opened from this writer
// will have its leaves sorted according the given leaf sorter.
if (engineConfig.getLeafSorter() != null) {
iwc.setLeafSorter(engineConfig.getLeafSorter());
}
return iwc;
}
/** A listener that warms the segments if needed when acquiring a new reader */
static final class RefreshWarmerListener implements BiConsumer<ElasticsearchDirectoryReader, ElasticsearchDirectoryReader> {
private final Engine.Warmer warmer;
private final Logger logger;
private final AtomicBoolean isEngineClosed;
RefreshWarmerListener(Logger logger, AtomicBoolean isEngineClosed, EngineConfig engineConfig) {
warmer = engineConfig.getWarmer();
this.logger = logger;
this.isEngineClosed = isEngineClosed;
}
@Override
public void accept(ElasticsearchDirectoryReader reader, ElasticsearchDirectoryReader previousReader) {
if (warmer != null) {
try {
warmer.warm(reader);
} catch (Exception e) {
if (isEngineClosed.get() == false) {
logger.warn("failed to prepare/warm", e);
}
}
}
}
}
@Override
public void activateThrottling() {
int count = throttleRequestCount.incrementAndGet();
assert count >= 1 : "invalid post-increment throttleRequestCount=" + count;
if (count == 1) {
throttle.activate();
}
}
@Override
public void deactivateThrottling() {
int count = throttleRequestCount.decrementAndGet();
assert count >= 0 : "invalid post-decrement throttleRequestCount=" + count;
if (count == 0) {
throttle.deactivate();
}
}
@Override
public boolean isThrottled() {
return throttle.isThrottled();
}
boolean throttleLockIsHeldByCurrentThread() { // to be used in assertions and tests only
return throttle.throttleLockIsHeldByCurrentThread();
}
@Override
public long getIndexThrottleTimeInMillis() {
return throttle.getThrottleTimeInMillis();
}
long getGcDeletesInMillis() {
return engineConfig.getIndexSettings().getGcDeletesInMillis();
}
LiveIndexWriterConfig getCurrentIndexWriterConfig() {
return indexWriter.getConfig();
}
private final class EngineMergeScheduler extends ElasticsearchConcurrentMergeScheduler {
private final AtomicInteger numMergesInFlight = new AtomicInteger(0);
private final AtomicBoolean isThrottling = new AtomicBoolean();
EngineMergeScheduler(ShardId shardId, IndexSettings indexSettings) {
super(shardId, indexSettings);
}
@Override
public synchronized void beforeMerge(OnGoingMerge merge) {
int maxNumMerges = mergeScheduler.getMaxMergeCount();
if (numMergesInFlight.incrementAndGet() > maxNumMerges) {
if (isThrottling.getAndSet(true) == false) {
logger.info("now throttling indexing: numMergesInFlight={}, maxNumMerges={}", numMergesInFlight, maxNumMerges);
activateThrottling();
}
}
}
@Override
public synchronized void afterMerge(OnGoingMerge merge) {
int maxNumMerges = mergeScheduler.getMaxMergeCount();
if (numMergesInFlight.decrementAndGet() < maxNumMerges) {
if (isThrottling.getAndSet(false)) {
logger.info("stop throttling indexing: numMergesInFlight={}, maxNumMerges={}", numMergesInFlight, maxNumMerges);
deactivateThrottling();
}
}
if (indexWriter.hasPendingMerges() == false
&& System.nanoTime() - lastWriteNanos >= engineConfig.getFlushMergesAfter().nanos()) {
// NEVER do this on a merge thread since we acquire some locks blocking here and if we concurrently rollback the writer
// we deadlock on engine#close for instance.
engineConfig.getThreadPool().executor(ThreadPool.Names.FLUSH).execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
if (isClosed.get() == false) {
logger.warn("failed to flush after merge has finished");
}
}
@Override
protected void doRun() {
// if we have no pending merges and we are supposed to flush once merges have finished to
// free up transient disk usage of the (presumably biggish) segments that were just merged
flush();
}
});
} else if (merge.getTotalBytesSize() >= engineConfig.getIndexSettings().getFlushAfterMergeThresholdSize().getBytes()) {
// we hit a significant merge which would allow us to free up memory if we'd commit it hence on the next change
// we should execute a flush on the next operation if that's a flush after inactive or indexing a document.
// we could fork a thread and do it right away but we try to minimize forking and piggyback on outside events.
shouldPeriodicallyFlushAfterBigMerge.set(true);
}
}
@Override
protected void handleMergeException(final Throwable exc) {
engineConfig.getThreadPool().generic().execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
logger.debug("merge failure action rejected", e);
}
@Override
protected void doRun() throws Exception {
/*
* We do this on another thread rather than the merge thread that we are initially called on so that we have complete
* confidence that the call stack does not contain catch statements that would cause the error that might be thrown
* here from being caught and never reaching the uncaught exception handler.
*/
failEngine("merge failed", new MergePolicy.MergeException(exc));
}
});
}
}
/**
* Commits the specified index writer.
*
* @param writer the index writer to commit
* @param translog the translog
*/
protected void commitIndexWriter(final IndexWriter writer, final Translog translog) throws IOException {
assert isFlushLockIsHeldByCurrentThread();
ensureCanFlush();
try {
final long localCheckpoint = localCheckpointTracker.getProcessedCheckpoint();
writer.setLiveCommitData(() -> {
/*
* The user data captured above (e.g. local checkpoint) contains data that must be evaluated *before* Lucene flushes
* segments, including the local checkpoint amongst other values. The maximum sequence number is different, we never want
* the maximum sequence number to be less than the last sequence number to go into a Lucene commit, otherwise we run the
* risk of re-using a sequence number for two different documents when restoring from this commit point and subsequently
* writing new documents to the index. Since we only know which Lucene documents made it into the final commit after the
* {@link IndexWriter#commit()} call flushes all documents, we defer computation of the maximum sequence number to the time
* of invocation of the commit data iterator (which occurs after all documents have been flushed to Lucene).
*/
final Map<String, String> extraCommitUserData = getCommitExtraUserData();
final Map<String, String> commitData = Maps.newMapWithExpectedSize(8 + extraCommitUserData.size());
commitData.putAll(extraCommitUserData);
commitData.put(Translog.TRANSLOG_UUID_KEY, translog.getTranslogUUID());
commitData.put(SequenceNumbers.LOCAL_CHECKPOINT_KEY, Long.toString(localCheckpoint));
commitData.put(SequenceNumbers.MAX_SEQ_NO, Long.toString(localCheckpointTracker.getMaxSeqNo()));
commitData.put(MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID, Long.toString(maxUnsafeAutoIdTimestamp.get()));
commitData.put(HISTORY_UUID_KEY, historyUUID);
final String currentForceMergeUUID = forceMergeUUID;
if (currentForceMergeUUID != null) {
commitData.put(FORCE_MERGE_UUID_KEY, currentForceMergeUUID);
}
commitData.put(Engine.MIN_RETAINED_SEQNO, Long.toString(softDeletesPolicy.getMinRetainedSeqNo()));
commitData.put(ES_VERSION, IndexVersion.current().toString());
logger.trace("committing writer with commit data [{}]", commitData);
return commitData.entrySet().iterator();
});
shouldPeriodicallyFlushAfterBigMerge.set(false);
writer.commit();
} catch (final Exception ex) {
try {
failEngine("lucene commit failed", ex);
} catch (final Exception inner) {
ex.addSuppressed(inner);
}
throw ex;
} catch (final AssertionError e) {
/*
* If assertions are enabled, IndexWriter throws AssertionError on commit if any files don't exist, but tests that randomly
* throw FileNotFoundException or NoSuchFileException can also hit this.
*/
if (ExceptionsHelper.stackTrace(e).contains("org.apache.lucene.index.IndexWriter.filesExist")) {
final EngineException engineException = new EngineException(shardId, "failed to commit engine", e);
try {
failEngine("lucene commit failed", engineException);
} catch (final Exception inner) {
engineException.addSuppressed(inner);
}
throw engineException;
} else {
throw e;
}
}
}
/**
* Allows InternalEngine extenders to return custom key-value pairs which will be included in the Lucene commit user-data. Custom user
* data keys can be overwritten by if their keys conflict keys used by InternalEngine.
*/
protected Map<String, String> getCommitExtraUserData() {
return Collections.emptyMap();
}
final void ensureCanFlush() {
// translog recovery happens after the engine is fully constructed.
// If we are in this stage we have to prevent flushes from this
// engine otherwise we might loose documents if the flush succeeds
// and the translog recovery fails when we "commit" the translog on flush.
if (pendingTranslogRecovery.get()) {
throw new IllegalStateException(shardId.toString() + " flushes are disabled - pending translog recovery");
}
}
@Override
public void onSettingsChanged() {
mergeScheduler.refreshConfig();
// config().isEnableGcDeletes() or config.getGcDeletesInMillis() may have changed:
maybePruneDeletes();
softDeletesPolicy.setRetentionOperations(config().getIndexSettings().getSoftDeleteRetentionOperations());
}
public MergeStats getMergeStats() {
return mergeScheduler.stats();
}
protected LocalCheckpointTracker getLocalCheckpointTracker() {
return localCheckpointTracker;
}
@Override
public long getLastSyncedGlobalCheckpoint() {
return getTranslog().getLastSyncedGlobalCheckpoint();
}
@Override
public long getMaxSeqNo() {
return localCheckpointTracker.getMaxSeqNo();
}
@Override
public long getProcessedLocalCheckpoint() {
return localCheckpointTracker.getProcessedCheckpoint();
}
@Override
public long getPersistedLocalCheckpoint() {
return localCheckpointTracker.getPersistedCheckpoint();
}
/**
* Marks the given seq_no as seen and advances the max_seq_no of this engine to at least that value.
*/
protected final void markSeqNoAsSeen(long seqNo) {
localCheckpointTracker.advanceMaxSeqNo(seqNo);
}
/**
* Checks if the given operation has been processed in this engine or not.
* @return true if the given operation was processed; otherwise false.
*/
protected final boolean hasBeenProcessedBefore(Operation op) {
if (Assertions.ENABLED) {
assert op.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO : "operation is not assigned seq_no";
if (op.operationType() == Operation.TYPE.NO_OP) {
assert noOpKeyedLock.isHeldByCurrentThread(op.seqNo());
} else {
assert versionMap.assertKeyedLockHeldByCurrentThread(op.uid().bytes());
}
}
return localCheckpointTracker.hasProcessed(op.seqNo());
}
@Override
public SeqNoStats getSeqNoStats(long globalCheckpoint) {
return localCheckpointTracker.getStats(globalCheckpoint);
}
/**
* Returns the number of times a version was looked up either from the index.
* Note this is only available if assertions are enabled
*/
long getNumIndexVersionsLookups() { // for testing
return numIndexVersionsLookups.count();
}
/**
* Returns the number of times a version was looked up either from memory or from the index.
* Note this is only available if assertions are enabled
*/
long getNumVersionLookups() { // for testing
return numVersionLookups.count();
}
private boolean incrementVersionLookup() { // only used by asserts
numVersionLookups.inc();
return true;
}
private boolean incrementIndexVersionLookup() {
numIndexVersionsLookups.inc();
return true;
}
boolean isSafeAccessRequired() {
return versionMap.isSafeAccessRequired();
}
/**
* Returns the number of documents have been deleted since this engine was opened.
* This count does not include the deletions from the existing segments before opening engine.
*/
long getNumDocDeletes() {
return numDocDeletes.count();
}
/**
* Returns the number of documents have been appended since this engine was opened.
* This count does not include the appends from the existing segments before opening engine.
*/
long getNumDocAppends() {
return numDocAppends.count();
}
/**
* Returns the number of documents have been updated since this engine was opened.
* This count does not include the updates from the existing segments before opening engine.
*/
long getNumDocUpdates() {
return numDocUpdates.count();
}
@Override
public long getTotalFlushTimeExcludingWaitingOnLockInMillis() {
return TimeUnit.NANOSECONDS.toMillis(totalFlushTimeExcludingWaitingOnLock.sum());
}
@Override
public int countChanges(String source, long fromSeqNo, long toSeqNo) throws IOException {
ensureOpen();
refreshIfNeeded(source, toSeqNo);
try (Searcher searcher = acquireSearcher(source, SearcherScope.INTERNAL)) {
return LuceneChangesSnapshot.countOperations(
searcher,
fromSeqNo,
toSeqNo,
config().getIndexSettings().getIndexVersionCreated()
);
} catch (Exception e) {
try {
maybeFailEngine("count changes", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw e;
}
}
@Override
public Translog.Snapshot newChangesSnapshot(
String source,
long fromSeqNo,
long toSeqNo,
boolean requiredFullRange,
boolean singleConsumer,
boolean accessStats
) throws IOException {
ensureOpen();
refreshIfNeeded(source, toSeqNo);
Searcher searcher = acquireSearcher(source, SearcherScope.INTERNAL);
try {
LuceneChangesSnapshot snapshot = new LuceneChangesSnapshot(
searcher,
LuceneChangesSnapshot.DEFAULT_BATCH_SIZE,
fromSeqNo,
toSeqNo,
requiredFullRange,
singleConsumer,
accessStats,
config().getIndexSettings().getIndexVersionCreated()
);
searcher = null;
return snapshot;
} catch (Exception e) {
try {
maybeFailEngine("acquire changes snapshot", e);
} catch (Exception inner) {
e.addSuppressed(inner);
}
throw e;
} finally {
IOUtils.close(searcher);
}
}
@Override
public boolean hasCompleteOperationHistory(String reason, long startingSeqNo) {
return getMinRetainedSeqNo() <= startingSeqNo;
}
/**
* Returns the minimum seqno that is retained in the Lucene index.
* Operations whose seq# are at least this value should exist in the Lucene index.
*/
public final long getMinRetainedSeqNo() {
return softDeletesPolicy.getMinRetainedSeqNo();
}
@Override
public Closeable acquireHistoryRetentionLock() {
return softDeletesPolicy.acquireRetentionLock();
}
/**
* Gets the commit data from {@link IndexWriter} as a map.
*/
private static Map<String, String> commitDataAsMap(final IndexWriter indexWriter) {
final Map<String, String> commitData = Maps.newMapWithExpectedSize(8);
for (Map.Entry<String, String> entry : indexWriter.getLiveCommitData()) {
commitData.put(entry.getKey(), entry.getValue());
}
return commitData;
}
private static class AssertingIndexWriter extends IndexWriter {
AssertingIndexWriter(Directory d, IndexWriterConfig conf) throws IOException {
super(d, conf);
}
@Override
public long deleteDocuments(Term... terms) {
throw new AssertionError("must not hard delete documents");
}
@Override
public long tryDeleteDocument(IndexReader readerIn, int docID) {
throw new AssertionError("tryDeleteDocument is not supported. See Lucene#DirectoryReaderWithAllLiveDocs");
}
}
/**
* Returned the last local checkpoint value has been refreshed internally.
*/
final long lastRefreshedCheckpoint() {
return lastRefreshedCheckpointListener.refreshedCheckpoint.get();
}
private final Object refreshIfNeededMutex = new Object();
/**
* Refresh this engine **internally** iff the requesting seq_no is greater than the last refreshed checkpoint.
*/
protected final void refreshIfNeeded(String source, long requestingSeqNo) {
if (lastRefreshedCheckpoint() < requestingSeqNo) {
synchronized (refreshIfNeededMutex) {
if (lastRefreshedCheckpoint() < requestingSeqNo) {
refreshInternalSearcher(source, true);
}
}
}
}
private final class LastRefreshedCheckpointListener implements ReferenceManager.RefreshListener {
final AtomicLong refreshedCheckpoint;
private long pendingCheckpoint;
LastRefreshedCheckpointListener(long initialLocalCheckpoint) {
this.refreshedCheckpoint = new AtomicLong(initialLocalCheckpoint);
}
@Override
public void beforeRefresh() {
// all changes until this point should be visible after refresh
pendingCheckpoint = localCheckpointTracker.getProcessedCheckpoint();
}
@Override
public void afterRefresh(boolean didRefresh) {
if (didRefresh) {
updateRefreshedCheckpoint(pendingCheckpoint);
}
}
void updateRefreshedCheckpoint(long checkpoint) {
refreshedCheckpoint.accumulateAndGet(checkpoint, Math::max);
assert refreshedCheckpoint.get() >= checkpoint : refreshedCheckpoint.get() + " < " + checkpoint;
}
}
@Override
public final long getMaxSeenAutoIdTimestamp() {
return maxSeenAutoIdTimestamp.get();
}
@Override
public final void updateMaxUnsafeAutoIdTimestamp(long newTimestamp) {
updateAutoIdTimestamp(newTimestamp, true);
}
private void updateAutoIdTimestamp(long newTimestamp, boolean unsafe) {
assert newTimestamp >= -1 : "invalid timestamp [" + newTimestamp + "]";
maxSeenAutoIdTimestamp.accumulateAndGet(newTimestamp, Math::max);
if (unsafe) {
maxUnsafeAutoIdTimestamp.accumulateAndGet(newTimestamp, Math::max);
}
assert maxUnsafeAutoIdTimestamp.get() <= maxSeenAutoIdTimestamp.get();
}
@Override
public long getMaxSeqNoOfUpdatesOrDeletes() {
return maxSeqNoOfUpdatesOrDeletes.get();
}
@Override
public void advanceMaxSeqNoOfUpdatesOrDeletes(long maxSeqNoOfUpdatesOnPrimary) {
if (maxSeqNoOfUpdatesOnPrimary == SequenceNumbers.UNASSIGNED_SEQ_NO) {
assert false : "max_seq_no_of_updates on primary is unassigned";
throw new IllegalArgumentException("max_seq_no_of_updates on primary is unassigned");
}
this.maxSeqNoOfUpdatesOrDeletes.accumulateAndGet(maxSeqNoOfUpdatesOnPrimary, Math::max);
}
private boolean assertMaxSeqNoOfUpdatesIsAdvanced(Term id, long seqNo, boolean allowDeleted, boolean relaxIfGapInSeqNo) {
final long maxSeqNoOfUpdates = getMaxSeqNoOfUpdatesOrDeletes();
// We treat a delete on the tombstones on replicas as a regular document, then use updateDocument (not addDocument).
if (allowDeleted) {
final VersionValue versionValue = versionMap.getVersionForAssert(id.bytes());
if (versionValue != null && versionValue.isDelete()) {
return true;
}
}
// Operations can be processed on a replica in a different order than on the primary. If the order on the primary is index-1,
// delete-2, index-3, and the order on a replica is index-1, index-3, delete-2, then the msu of index-3 on the replica is 2
// even though it is an update (overwrites index-1). We should relax this assertion if there is a pending gap in the seq_no.
if (relaxIfGapInSeqNo && localCheckpointTracker.getProcessedCheckpoint() < maxSeqNoOfUpdates) {
return true;
}
assert seqNo <= maxSeqNoOfUpdates : "id=" + id + " seq_no=" + seqNo + " msu=" + maxSeqNoOfUpdates;
return true;
}
/**
* Restores the live version map and local checkpoint of this engine using documents (including soft-deleted)
* after the local checkpoint in the safe commit. This step ensures the live version map and checkpoint tracker
* are in sync with the Lucene commit.
*/
private void restoreVersionMapAndCheckpointTracker(DirectoryReader directoryReader, IndexVersion indexVersionCreated)
throws IOException {
final IndexSearcher searcher = new IndexSearcher(directoryReader);
searcher.setQueryCache(null);
final Query query = new BooleanQuery.Builder().add(
LongPoint.newRangeQuery(SeqNoFieldMapper.NAME, getPersistedLocalCheckpoint() + 1, Long.MAX_VALUE),
BooleanClause.Occur.MUST
)
.add(Queries.newNonNestedFilter(indexVersionCreated), BooleanClause.Occur.MUST) // exclude non-root nested documents
.build();
final Weight weight = searcher.createWeight(searcher.rewrite(query), ScoreMode.COMPLETE_NO_SCORES, 1.0f);
for (LeafReaderContext leaf : directoryReader.leaves()) {
final Scorer scorer = weight.scorer(leaf);
if (scorer == null) {
continue;
}
final CombinedDocValues dv = new CombinedDocValues(leaf.reader());
final IdStoredFieldLoader idFieldLoader = new IdStoredFieldLoader(leaf.reader());
final DocIdSetIterator iterator = scorer.iterator();
int docId;
while ((docId = iterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final long primaryTerm = dv.docPrimaryTerm(docId);
final long seqNo = dv.docSeqNo(docId);
localCheckpointTracker.markSeqNoAsProcessed(seqNo);
localCheckpointTracker.markSeqNoAsPersisted(seqNo);
String id = idFieldLoader.id(docId);
if (id == null) {
assert dv.isTombstone(docId);
continue;
}
final BytesRef uid = new Term(IdFieldMapper.NAME, Uid.encodeId(id)).bytes();
try (Releasable ignored = versionMap.acquireLock(uid)) {
final VersionValue curr = versionMap.getUnderLock(uid);
if (curr == null || compareOpToVersionMapOnSeqNo(id, seqNo, primaryTerm, curr) == OpVsLuceneDocStatus.OP_NEWER) {
if (dv.isTombstone(docId)) {
// use 0L for the start time so we can prune this delete tombstone quickly
// when the local checkpoint advances (i.e., after a recovery completed).
final long startTime = 0L;
versionMap.putDeleteUnderLock(uid, new DeleteVersionValue(dv.docVersion(docId), seqNo, primaryTerm, startTime));
} else {
versionMap.putIndexUnderLock(uid, new IndexVersionValue(null, dv.docVersion(docId), seqNo, primaryTerm));
}
}
}
}
}
// remove live entries in the version map
refresh("restore_version_map_and_checkpoint_tracker", SearcherScope.INTERNAL, true);
}
@Override
public ShardLongFieldRange getRawFieldRange(String field) {
return ShardLongFieldRange.UNKNOWN;
}
@Override
public void addFlushListener(Translog.Location location, ActionListener<Long> listener) {
this.flushListener.addOrNotify(location, new ActionListener<>() {
@Override
public void onResponse(Long generation) {
waitForCommitDurability(generation, listener.map(v -> generation));
}
@Override
public void onFailure(Exception e) {
listener.onFailure(e);
}
});
}
protected void waitForCommitDurability(long generation, ActionListener<Void> listener) {
try {
ensureOpen();
} catch (AlreadyClosedException e) {
listener.onFailure(e);
return;
}
if (lastCommittedSegmentInfos.getGeneration() < generation) {
listener.onFailure(new IllegalStateException("Cannot wait on generation which has not been committed"));
} else {
listener.onResponse(null);
}
}
public long getLastUnsafeSegmentGenerationForGets() {
return lastUnsafeSegmentGenerationForGets.get();
}
protected LiveVersionMapArchive createLiveVersionMapArchive() {
return LiveVersionMapArchive.NOOP_ARCHIVE;
}
protected LiveVersionMapArchive getLiveVersionMapArchive() {
return liveVersionMapArchive;
}
// Visible for testing purposes only
public LiveVersionMap getLiveVersionMap() {
return versionMap;
}
private static boolean assertGetUsesIdField(Get get) {
assert Objects.equals(get.uid().field(), IdFieldMapper.NAME) : get.uid().field();
return true;
}
protected long getPreCommitSegmentGeneration() {
return preCommitSegmentGeneration.get();
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java |
631 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gateway;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.FailedNodeException;
import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.action.support.nodes.BaseNodesResponse;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.util.Maps;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Releasable;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.transport.ReceiveTimeoutTransportException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.Collections.emptySet;
import static org.elasticsearch.core.Strings.format;
/**
* Allows to asynchronously fetch shard related data from other nodes for allocation, without blocking
* the cluster update thread.
* <p>
* The async fetch logic maintains a map of which nodes are being fetched from in an async manner,
* and once the results are back, it makes sure to schedule a reroute to make sure those results will
* be taken into account.
*/
public abstract class AsyncShardFetch<T extends BaseNodeResponse> implements Releasable {
protected final Logger logger;
protected final String type;
protected final ShardId shardId;
protected final String customDataPath;
private final Map<String, NodeEntry<T>> cache;
private final Set<String> nodesToIgnore = new HashSet<>();
private final AtomicLong round = new AtomicLong();
private boolean closed;
private volatile int fetchingCount;
@SuppressWarnings("unchecked")
protected AsyncShardFetch(Logger logger, String type, ShardId shardId, String customDataPath, int expectedSize) {
this.logger = logger;
this.type = type;
this.shardId = Objects.requireNonNull(shardId);
this.customDataPath = Objects.requireNonNull(customDataPath);
this.fetchingCount = 0;
this.cache = Maps.newHashMapWithExpectedSize(expectedSize);
}
@Override
public synchronized void close() {
this.closed = true;
}
/**
* Returns the number of async fetches that are currently ongoing.
*/
public int getNumberOfInFlightFetches() {
return fetchingCount;
}
/**
* Fetches the data for the relevant shard. If there any ongoing async fetches going on, or new ones have
* been initiated by this call, the result will have no data.
* <p>
* The ignoreNodes are nodes that are supposed to be ignored for this round, since fetching is async, we need
* to keep them around and make sure we add them back when all the responses are fetched and returned.
*/
public synchronized FetchResult<T> fetchData(DiscoveryNodes nodes, Set<String> ignoreNodes) {
if (closed) {
throw new IllegalStateException(shardId + ": can't fetch data on closed async fetch");
}
nodesToIgnore.addAll(ignoreNodes);
fillShardCacheWithDataNodes(cache, nodes);
List<NodeEntry<T>> nodesToFetch = findNodesToFetch(cache);
if (nodesToFetch.isEmpty() == false) {
// mark all node as fetching and go ahead and async fetch them
// use a unique round id to detect stale responses in processAsyncFetch
final long fetchingRound = round.incrementAndGet();
for (NodeEntry<T> nodeEntry : nodesToFetch) {
nodeEntry.markAsFetching(fetchingRound);
fetchingCount++;
}
DiscoveryNode[] discoNodesToFetch = nodesToFetch.stream()
.map(NodeEntry::getNodeId)
.map(nodes::get)
.toArray(DiscoveryNode[]::new);
asyncFetch(discoNodesToFetch, fetchingRound);
}
assert assertFetchingCountConsistent();
// if we are still fetching, return null to indicate it
if (hasAnyNodeFetching()) {
return new FetchResult<>(shardId, null, emptySet());
} else {
// nothing to fetch, yay, build the return value
Map<DiscoveryNode, T> fetchData = new HashMap<>();
Set<String> failedNodes = new HashSet<>();
for (Iterator<Map.Entry<String, NodeEntry<T>>> it = cache.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, NodeEntry<T>> entry = it.next();
String nodeId = entry.getKey();
NodeEntry<T> nodeEntry = entry.getValue();
DiscoveryNode node = nodes.get(nodeId);
if (node != null) {
if (nodeEntry.isFailed()) {
// if its failed, remove it from the list of nodes, so if this run doesn't work
// we try again next round to fetch it again
it.remove();
failedNodes.add(nodeEntry.getNodeId());
} else {
if (nodeEntry.getValue() != null) {
fetchData.put(node, nodeEntry.getValue());
}
}
}
}
Set<String> allIgnoreNodes = Set.copyOf(nodesToIgnore);
// clear the nodes to ignore, we had a successful run in fetching everything we can
// we need to try them if another full run is needed
nodesToIgnore.clear();
// if at least one node failed, make sure to have a protective reroute
// here, just case this round won't find anything, and we need to retry fetching data
if (failedNodes.isEmpty() == false || allIgnoreNodes.isEmpty() == false) {
reroute(shardId, "nodes failed [" + failedNodes.size() + "], ignored [" + allIgnoreNodes.size() + "]");
}
return new FetchResult<>(shardId, fetchData, allIgnoreNodes);
}
}
/**
* Called by the response handler of the async action to fetch data. Verifies that its still working
* on the same cache generation, otherwise the results are discarded. It then goes and fills the relevant data for
* the shard (response + failures), issuing a reroute at the end of it to make sure there will be another round
* of allocations taking this new data into account.
*/
protected synchronized void processAsyncFetch(List<T> responses, List<FailedNodeException> failures, long fetchingRound) {
if (closed) {
// we are closed, no need to process this async fetch at all
logger.trace("{} ignoring fetched [{}] results, already closed", shardId, type);
return;
}
logger.trace("{} processing fetched [{}] results", shardId, type);
if (responses != null) {
for (T response : responses) {
NodeEntry<T> nodeEntry = cache.get(response.getNode().getId());
if (nodeEntry != null) {
if (nodeEntry.getFetchingRound() != fetchingRound) {
assert nodeEntry.getFetchingRound() > fetchingRound : "node entries only replaced by newer rounds";
logger.trace(
"{} received response for [{}] from node {} for an older fetching round (expected: {} but was: {})",
shardId,
nodeEntry.getNodeId(),
type,
nodeEntry.getFetchingRound(),
fetchingRound
);
} else if (nodeEntry.isFailed()) {
logger.trace(
"{} node {} has failed for [{}] (failure [{}])",
shardId,
nodeEntry.getNodeId(),
type,
nodeEntry.getFailure()
);
} else {
// if the entry is there, for the right fetching round and not marked as failed already, process it
logger.trace("{} marking {} as done for [{}], result is [{}]", shardId, nodeEntry.getNodeId(), type, response);
nodeEntry.doneFetching(response);
fetchingCount--;
}
}
}
}
if (failures != null) {
for (FailedNodeException failure : failures) {
logger.trace("{} processing failure {} for [{}]", shardId, failure, type);
NodeEntry<T> nodeEntry = cache.get(failure.nodeId());
if (nodeEntry != null) {
if (nodeEntry.getFetchingRound() != fetchingRound) {
assert nodeEntry.getFetchingRound() > fetchingRound : "node entries only replaced by newer rounds";
logger.trace(
"{} received failure for [{}] from node {} for an older fetching round (expected: {} but was: {})",
shardId,
nodeEntry.getNodeId(),
type,
nodeEntry.getFetchingRound(),
fetchingRound
);
} else if (nodeEntry.isFailed() == false) {
// if the entry is there, for the right fetching round and not marked as failed already, process it
Throwable unwrappedCause = ExceptionsHelper.unwrapCause(failure.getCause());
// if the request got rejected or timed out, we need to try it again next time...
if (unwrappedCause instanceof EsRejectedExecutionException
|| unwrappedCause instanceof ReceiveTimeoutTransportException
|| unwrappedCause instanceof ElasticsearchTimeoutException) {
nodeEntry.restartFetching();
fetchingCount--;
} else {
logger.warn(
() -> format("%s: failed to list shard for %s on node [%s]", shardId, type, failure.nodeId()),
failure
);
nodeEntry.doneFetching(failure.getCause());
fetchingCount--;
}
}
}
}
}
reroute(shardId, "post_response");
assert assertFetchingCountConsistent();
}
/**
* Implement this in order to scheduled another round that causes a call to fetch data.
*/
protected abstract void reroute(ShardId shardId, String reason);
/**
* Clear cache for node, ensuring next fetch will fetch a fresh copy.
*/
synchronized void clearCacheForNode(String nodeId) {
NodeEntry<T> nodeEntry = cache.remove(nodeId);
if (nodeEntry != null && nodeEntry.fetching) {
fetchingCount--;
}
assert assertFetchingCountConsistent();
}
/**
* Fills the shard fetched data with new (data) nodes and a fresh NodeEntry, and removes from
* it nodes that are no longer part of the state.
*/
private void fillShardCacheWithDataNodes(Map<String, NodeEntry<T>> shardCache, DiscoveryNodes nodes) {
// verify that all current data nodes are there
for (Map.Entry<String, DiscoveryNode> cursor : nodes.getDataNodes().entrySet()) {
DiscoveryNode node = cursor.getValue();
if (shardCache.containsKey(node.getId()) == false) {
shardCache.put(node.getId(), new NodeEntry<T>(node.getId()));
}
}
// remove nodes that are not longer part of the data nodes set
for (Iterator<Map.Entry<String, NodeEntry<T>>> iterator = shardCache.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, NodeEntry<T>> entry = iterator.next();
String nodeId = entry.getKey();
NodeEntry<T> nodeEntry = entry.getValue();
if (nodes.nodeExists(nodeId) == false) {
if (nodeEntry.fetching) {
fetchingCount--;
}
iterator.remove();
}
}
assert assertFetchingCountConsistent();
}
/**
* Finds all the nodes that need to be fetched. Those are nodes that have no
* data, and are not in fetch mode.
*/
private List<NodeEntry<T>> findNodesToFetch(Map<String, NodeEntry<T>> shardCache) {
List<NodeEntry<T>> nodesToFetch = new ArrayList<>();
for (NodeEntry<T> nodeEntry : shardCache.values()) {
if (nodeEntry.hasData() == false && nodeEntry.isFetching() == false) {
nodesToFetch.add(nodeEntry);
}
}
return nodesToFetch;
}
/**
* Are there any nodes that are fetching data?
*/
private boolean hasAnyNodeFetching() {
return fetchingCount != 0;
}
/**
* Async fetches data for the provided shard with the set of nodes that need to be fetched from.
*/
// visible for testing
void asyncFetch(final DiscoveryNode[] nodes, long fetchingRound) {
logger.trace("{} fetching [{}] from {}", shardId, type, nodes);
list(shardId, customDataPath, nodes, new ActionListener<>() {
@Override
public void onResponse(BaseNodesResponse<T> response) {
assert assertSameNodes(response);
processAsyncFetch(response.getNodes(), response.failures(), fetchingRound);
}
@Override
public void onFailure(Exception e) {
List<FailedNodeException> failures = new ArrayList<>(nodes.length);
for (final DiscoveryNode node : nodes) {
failures.add(new FailedNodeException(node.getId(), "total failure in fetching", e));
}
processAsyncFetch(null, failures, fetchingRound);
}
private boolean assertSameNodes(BaseNodesResponse<T> response) {
final Map<String, DiscoveryNode> nodesById = Arrays.stream(nodes)
.collect(Collectors.toMap(DiscoveryNode::getEphemeralId, Function.identity()));
for (T nodeResponse : response.getNodes()) {
final DiscoveryNode responseNode = nodeResponse.getNode();
final DiscoveryNode localNode = nodesById.get(responseNode.getEphemeralId());
assert localNode == responseNode : "not reference equal: " + localNode + " vs " + responseNode;
}
return true;
}
});
}
protected abstract void list(
ShardId shardId,
@Nullable String customDataPath,
DiscoveryNode[] nodes,
ActionListener<BaseNodesResponse<T>> listener
);
/**
* The result of a fetch operation. Make sure to first check {@link #hasData()} before
* fetching the actual data.
*/
public static class FetchResult<T extends BaseNodeResponse> {
private final ShardId shardId;
private final Map<DiscoveryNode, T> data;
private final Set<String> ignoreNodes;
public FetchResult(ShardId shardId, Map<DiscoveryNode, T> data, Set<String> ignoreNodes) {
this.shardId = shardId;
this.data = data;
this.ignoreNodes = ignoreNodes;
}
/**
* Does the result actually contain data? If not, then there are on going fetch
* operations happening, and it should wait for it.
*/
public boolean hasData() {
return data != null;
}
/**
* Returns the actual data, note, make sure to check {@link #hasData()} first and
* only use this when there is an actual data.
*/
public Map<DiscoveryNode, T> getData() {
assert data != null : "getData should only be called if there is data to be fetched, please check hasData first";
return this.data;
}
/**
* Process any changes needed to the allocation based on this fetch result.
*/
public void processAllocation(RoutingAllocation allocation) {
for (String ignoreNode : ignoreNodes) {
allocation.addIgnoreShardForNode(shardId, ignoreNode);
}
}
}
/**
* A node entry, holding the state of the fetched data for a specific shard
* for a giving node.
*/
static class NodeEntry<T> {
private final String nodeId;
private boolean fetching;
@Nullable
private T value;
private boolean valueSet;
private Throwable failure;
private long fetchingRound;
NodeEntry(String nodeId) {
this.nodeId = nodeId;
}
String getNodeId() {
return this.nodeId;
}
boolean isFetching() {
return fetching;
}
void markAsFetching(long fetchingRound) {
assert fetching == false : "double marking a node as fetching";
this.fetching = true;
this.fetchingRound = fetchingRound;
}
void doneFetching(T value) {
assert fetching : "setting value but not in fetching mode";
assert failure == null : "setting value when failure already set";
this.valueSet = true;
this.value = value;
this.fetching = false;
}
void doneFetching(Throwable failure) {
assert fetching : "setting value but not in fetching mode";
assert valueSet == false : "setting failure when already set value";
assert failure != null : "setting failure can't be null";
this.failure = failure;
this.fetching = false;
}
void restartFetching() {
assert fetching : "restarting fetching, but not in fetching mode";
assert valueSet == false : "value can't be set when restarting fetching";
assert failure == null : "failure can't be set when restarting fetching";
this.fetching = false;
}
boolean isFailed() {
return failure != null;
}
boolean hasData() {
return valueSet || failure != null;
}
Throwable getFailure() {
assert hasData() : "getting failure when data has not been fetched";
return failure;
}
@Nullable
T getValue() {
assert failure == null : "trying to fetch value, but its marked as failed, check isFailed";
assert valueSet : "value is not set, hasn't been fetched yet";
return value;
}
long getFetchingRound() {
return fetchingRound;
}
}
private boolean assertFetchingCountConsistent() {
assert Thread.holdsLock(this);
assert fetchingCount == cache.values().stream().filter(NodeEntry::isFetching).count();
return true;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java |
632 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.network;
import org.elasticsearch.core.Tuple;
import java.net.InetAddress;
import java.util.Arrays;
public class CIDRUtils {
// Borrowed from Lucene, rfc4291 prefix
static final byte[] IPV4_PREFIX = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1 };
private CIDRUtils() {}
public static boolean isInRange(String address, String... cidrAddresses) {
// Check if address is parsable first
byte[] addr = InetAddresses.forString(address).getAddress();
if (cidrAddresses == null || cidrAddresses.length == 0) {
return false;
}
for (String cidrAddress : cidrAddresses) {
if (cidrAddress != null && isInRange(addr, cidrAddress)) {
return true;
}
}
return false;
}
public static boolean isInRange(byte[] addr, String cidrAddress) {
byte[] lower, upper;
if (cidrAddress.contains("/")) {
final Tuple<byte[], byte[]> range = getLowerUpper(InetAddresses.parseCidr(cidrAddress));
lower = range.v1();
upper = range.v2();
} else {
lower = InetAddresses.forString(cidrAddress).getAddress();
upper = lower;
}
return isBetween(addr, lower, upper);
}
public static Tuple<byte[], byte[]> getLowerUpper(Tuple<InetAddress, Integer> cidr) {
final InetAddress value = cidr.v1();
final Integer prefixLength = cidr.v2();
if (prefixLength < 0 || prefixLength > 8 * value.getAddress().length) {
throw new IllegalArgumentException(
"illegal prefixLength '" + prefixLength + "'. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges"
);
}
byte[] lower = value.getAddress();
byte[] upper = value.getAddress();
// Borrowed from Lucene
for (int i = prefixLength; i < 8 * lower.length; i++) {
int m = 1 << (7 - (i & 7));
lower[i >> 3] &= (byte) ~m;
upper[i >> 3] |= (byte) m;
}
return new Tuple<>(lower, upper);
}
private static boolean isBetween(byte[] addr, byte[] lower, byte[] upper) {
// Encode the addresses bytes if lengths do not match
if (addr.length != lower.length) {
addr = encode(addr);
lower = encode(lower);
upper = encode(upper);
}
return Arrays.compareUnsigned(lower, addr) <= 0 && Arrays.compareUnsigned(upper, addr) >= 0;
}
// Borrowed from Lucene to make this consistent IP fields matching for the mix of IPv4 and IPv6 values
// Modified signature to avoid extra conversions
public static byte[] encode(byte[] address) {
if (address.length == 4) {
byte[] mapped = new byte[16];
System.arraycopy(IPV4_PREFIX, 0, mapped, 0, IPV4_PREFIX.length);
System.arraycopy(address, 0, mapped, IPV4_PREFIX.length, address.length);
address = mapped;
} else if (address.length != 16) {
throw new UnsupportedOperationException("Only IPv4 and IPv6 addresses are supported");
}
return address;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/network/CIDRUtils.java |
633 | /*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.ImmutableMapEntry.createEntryArray;
import static com.google.common.collect.RegularImmutableMap.MAX_HASH_BUCKET_LENGTH;
import static com.google.common.collect.RegularImmutableMap.checkNoConflictInKeyBucket;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableBiMapEntry;
import com.google.common.collect.RegularImmutableMap.BucketOverflowException;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Bimap with zero or more mappings.
*
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
@ElementTypesAreNonnullByDefault
class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
@SuppressWarnings("unchecked") // TODO(cpovirk): Consider storing Entry<?, ?>[] instead.
static final RegularImmutableBiMap<Object, Object> EMPTY =
new RegularImmutableBiMap<>(
null, null, (Entry<Object, Object>[]) ImmutableMap.EMPTY_ENTRY_ARRAY, 0, 0);
static final double MAX_LOAD_FACTOR = 1.2;
@CheckForNull private final transient @Nullable ImmutableMapEntry<K, V>[] keyTable;
@CheckForNull private final transient @Nullable ImmutableMapEntry<K, V>[] valueTable;
@VisibleForTesting final transient Entry<K, V>[] entries;
private final transient int mask;
private final transient int hashCode;
static <K, V> ImmutableBiMap<K, V> fromEntries(Entry<K, V>... entries) {
return fromEntryArray(entries.length, entries);
}
static <K, V> ImmutableBiMap<K, V> fromEntryArray(int n, @Nullable Entry<K, V>[] entryArray) {
checkPositionIndex(n, entryArray.length);
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
int mask = tableSize - 1;
@Nullable ImmutableMapEntry<K, V>[] keyTable = createEntryArray(tableSize);
@Nullable ImmutableMapEntry<K, V>[] valueTable = createEntryArray(tableSize);
/*
* The cast is safe: n==entryArray.length means that we have filled the whole array with Entry
* instances, in which case it is safe to cast it from an array of nullable entries to an array
* of non-null entries.
*/
@SuppressWarnings("nullness")
Entry<K, V>[] entries =
(n == entryArray.length) ? (Entry<K, V>[]) entryArray : createEntryArray(n);
int hashCode = 0;
for (int i = 0; i < n; i++) {
// requireNonNull is safe because the first `n` elements have been filled in.
Entry<K, V> entry = requireNonNull(entryArray[i]);
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int keyHash = key.hashCode();
int valueHash = value.hashCode();
int keyBucket = Hashing.smear(keyHash) & mask;
int valueBucket = Hashing.smear(valueHash) & mask;
ImmutableMapEntry<K, V> nextInKeyBucket = keyTable[keyBucket];
ImmutableMapEntry<K, V> nextInValueBucket = valueTable[valueBucket];
try {
checkNoConflictInKeyBucket(key, value, nextInKeyBucket, /* throwIfDuplicateKeys= */ true);
checkNoConflictInValueBucket(value, entry, nextInValueBucket);
} catch (BucketOverflowException e) {
return JdkBackedImmutableBiMap.create(n, entryArray);
}
ImmutableMapEntry<K, V> newEntry =
(nextInValueBucket == null && nextInKeyBucket == null)
? RegularImmutableMap.makeImmutable(entry, key, value)
: new NonTerminalImmutableBiMapEntry<>(
key, value, nextInKeyBucket, nextInValueBucket);
keyTable[keyBucket] = newEntry;
valueTable[valueBucket] = newEntry;
entries[i] = newEntry;
hashCode += keyHash ^ valueHash;
}
return new RegularImmutableBiMap<>(keyTable, valueTable, entries, mask, hashCode);
}
private RegularImmutableBiMap(
@CheckForNull @Nullable ImmutableMapEntry<K, V>[] keyTable,
@CheckForNull @Nullable ImmutableMapEntry<K, V>[] valueTable,
Entry<K, V>[] entries,
int mask,
int hashCode) {
this.keyTable = keyTable;
this.valueTable = valueTable;
this.entries = entries;
this.mask = mask;
this.hashCode = hashCode;
}
// checkNoConflictInKeyBucket is static imported from RegularImmutableMap
/**
* @throws IllegalArgumentException if another entry in the bucket has the same key
* @throws BucketOverflowException if this bucket has too many entries, which may indicate a hash
* flooding attack
*/
private static void checkNoConflictInValueBucket(
Object value, Entry<?, ?> entry, @CheckForNull ImmutableMapEntry<?, ?> valueBucketHead)
throws BucketOverflowException {
int bucketSize = 0;
for (; valueBucketHead != null; valueBucketHead = valueBucketHead.getNextInValueBucket()) {
checkNoConflict(!value.equals(valueBucketHead.getValue()), "value", entry, valueBucketHead);
if (++bucketSize > MAX_HASH_BUCKET_LENGTH) {
throw new BucketOverflowException();
}
}
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return RegularImmutableMap.get(key, keyTable, mask);
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return isEmpty()
? ImmutableSet.<Entry<K, V>>of()
: new ImmutableMapEntrySet.RegularEntrySet<K, V>(this, entries);
}
@Override
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<>(this);
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
for (Entry<K, V> entry : entries) {
action.accept(entry.getKey(), entry.getValue());
}
}
@Override
boolean isHashCodeFast() {
return true;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
boolean isPartialView() {
return false;
}
@Override
public int size() {
return entries.length;
}
@LazyInit @RetainedWith @CheckForNull private transient ImmutableBiMap<V, K> inverse;
@Override
public ImmutableBiMap<V, K> inverse() {
if (isEmpty()) {
return ImmutableBiMap.of();
}
ImmutableBiMap<V, K> result = inverse;
return (result == null) ? inverse = new Inverse() : result;
}
private final class Inverse extends ImmutableBiMap<V, K> {
@Override
public int size() {
return inverse().size();
}
@Override
public ImmutableBiMap<K, V> inverse() {
return RegularImmutableBiMap.this;
}
@Override
public void forEach(BiConsumer<? super V, ? super K> action) {
checkNotNull(action);
RegularImmutableBiMap.this.forEach((k, v) -> action.accept(v, k));
}
@Override
@CheckForNull
public K get(@CheckForNull Object value) {
if (value == null || valueTable == null) {
return null;
}
int bucket = Hashing.smear(value.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = valueTable[bucket];
entry != null;
entry = entry.getNextInValueBucket()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
ImmutableSet<V> createKeySet() {
return new ImmutableMapKeySet<>(this);
}
@Override
ImmutableSet<Entry<V, K>> createEntrySet() {
return new InverseEntrySet();
}
final class InverseEntrySet extends ImmutableMapEntrySet<V, K> {
@Override
ImmutableMap<V, K> map() {
return Inverse.this;
}
@Override
boolean isHashCodeFast() {
return true;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public UnmodifiableIterator<Entry<V, K>> iterator() {
return asList().iterator();
}
@Override
public void forEach(Consumer<? super Entry<V, K>> action) {
asList().forEach(action);
}
@Override
ImmutableList<Entry<V, K>> createAsList() {
return new ImmutableAsList<Entry<V, K>>() {
@Override
public Entry<V, K> get(int index) {
Entry<K, V> entry = entries[index];
return Maps.immutableEntry(entry.getValue(), entry.getKey());
}
@Override
ImmutableCollection<Entry<V, K>> delegateCollection() {
return InverseEntrySet.this;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
@Override
boolean isPartialView() {
return false;
}
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return new InverseSerializedForm<>(RegularImmutableBiMap.this);
}
@J2ktIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use InverseSerializedForm");
}
}
@J2ktIncompatible // serialization
private static class InverseSerializedForm<K, V> implements Serializable {
private final ImmutableBiMap<K, V> forward;
InverseSerializedForm(ImmutableBiMap<K, V> forward) {
this.forward = forward;
}
Object readResolve() {
return forward.inverse();
}
private static final long serialVersionUID = 1;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
| google/guava | guava/src/com/google/common/collect/RegularImmutableBiMap.java |
635 | /*
* Copyright (C) 2015 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.hash;
import com.google.common.primitives.Longs;
import java.lang.reflect.Field;
import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import sun.misc.Unsafe;
/**
* Utility functions for loading and storing values from a byte array.
*
* @author Kevin Damm
* @author Kyle Maddison
*/
@ElementTypesAreNonnullByDefault
final class LittleEndianByteArray {
/** The instance that actually does the work; delegates to Unsafe or a pure-Java fallback. */
private static final LittleEndianBytes byteArray;
/**
* Load 8 bytes into long in a little endian manner, from the substring between position and
* position + 8. The array must have at least 8 bytes from offset (inclusive).
*
* @param input the input bytes
* @param offset the offset into the array at which to start
* @return a long of a concatenated 8 bytes
*/
static long load64(byte[] input, int offset) {
// We don't want this in production code as this is the most critical part of the loop.
assert input.length >= offset + 8;
// Delegates to the fast (unsafe) version or the fallback.
return byteArray.getLongLittleEndian(input, offset);
}
/**
* Similar to load64, but allows offset + 8 > input.length, padding the result with zeroes. This
* has to explicitly reverse the order of the bytes as it packs them into the result which makes
* it slower than the native version.
*
* @param input the input bytes
* @param offset the offset into the array at which to start reading
* @param length the number of bytes from the input to read
* @return a long of a concatenated 8 bytes
*/
static long load64Safely(byte[] input, int offset, int length) {
long result = 0;
// Due to the way we shift, we can stop iterating once we've run out of data, the rest
// of the result already being filled with zeros.
// This loop is critical to performance, so please check HashBenchmark if altering it.
int limit = Math.min(length, 8);
for (int i = 0; i < limit; i++) {
// Shift value left while iterating logically through the array.
result |= (input[offset + i] & 0xFFL) << (i * 8);
}
return result;
}
/**
* Store 8 bytes into the provided array at the indicated offset, using the value provided.
*
* @param sink the output byte array
* @param offset the offset into the array at which to start writing
* @param value the value to write
*/
static void store64(byte[] sink, int offset, long value) {
// We don't want to assert in production code.
assert offset >= 0 && offset + 8 <= sink.length;
// Delegates to the fast (unsafe)version or the fallback.
byteArray.putLongLittleEndian(sink, offset, value);
}
/**
* Load 4 bytes from the provided array at the indicated offset.
*
* @param source the input bytes
* @param offset the offset into the array at which to start
* @return the value found in the array in the form of a long
*/
static int load32(byte[] source, int offset) {
// TODO(user): Measure the benefit of delegating this to LittleEndianBytes also.
return (source[offset] & 0xFF)
| ((source[offset + 1] & 0xFF) << 8)
| ((source[offset + 2] & 0xFF) << 16)
| ((source[offset + 3] & 0xFF) << 24);
}
/**
* Indicates that the loading of Unsafe was successful and the load and store operations will be
* very efficient. May be useful for calling code to fall back on an alternative implementation
* that is slower than Unsafe.get/store but faster than the pure-Java mask-and-shift.
*/
static boolean usingUnsafe() {
return (byteArray instanceof UnsafeByteArray);
}
/**
* Common interface for retrieving a 64-bit long from a little-endian byte array.
*
* <p>This abstraction allows us to use single-instruction load and put when available, or fall
* back on the slower approach of using Longs.fromBytes(byte...).
*/
private interface LittleEndianBytes {
long getLongLittleEndian(byte[] array, int offset);
void putLongLittleEndian(byte[] array, int offset, long value);
}
/**
* The only reference to Unsafe is in this nested class. We set things up so that if
* Unsafe.theUnsafe is inaccessible, the attempt to load the nested class fails, and the outer
* class's static initializer can fall back on a non-Unsafe version.
*/
private enum UnsafeByteArray implements LittleEndianBytes {
// Do *not* change the order of these constants!
UNSAFE_LITTLE_ENDIAN {
@Override
public long getLongLittleEndian(byte[] array, int offset) {
return theUnsafe.getLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET);
}
@Override
public void putLongLittleEndian(byte[] array, int offset, long value) {
theUnsafe.putLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET, value);
}
},
UNSAFE_BIG_ENDIAN {
@Override
public long getLongLittleEndian(byte[] array, int offset) {
long bigEndian = theUnsafe.getLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET);
// The hardware is big-endian, so we need to reverse the order of the bytes.
return Long.reverseBytes(bigEndian);
}
@Override
public void putLongLittleEndian(byte[] array, int offset, long value) {
// Reverse the order of the bytes before storing, since we're on big-endian hardware.
long littleEndianValue = Long.reverseBytes(value);
theUnsafe.putLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET, littleEndianValue);
}
};
// Provides load and store operations that use native instructions to get better performance.
private static final Unsafe theUnsafe;
// The offset to the first element in a byte array.
private static final int BYTE_ARRAY_BASE_OFFSET;
/**
* Returns an Unsafe. Suitable for use in a 3rd party package. Replace with a simple call to
* Unsafe.getUnsafe when integrating into a JDK.
*
* @return an Unsafe instance if successful
*/
@SuppressWarnings("removal") // b/318391980
private static Unsafe getUnsafe() {
try {
return Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {
// We'll try reflection instead.
}
try {
return AccessController.doPrivileged(
(PrivilegedExceptionAction<Unsafe>)
() -> {
Class<Unsafe> k = Unsafe.class;
for (Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x)) {
return k.cast(x);
}
}
throw new NoSuchFieldError("the Unsafe");
});
} catch (PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics", e.getCause());
}
}
static {
theUnsafe = getUnsafe();
BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
// sanity check - this should never fail
if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
throw new AssertionError();
}
}
}
/** Fallback implementation for when Unsafe is not available in our current environment. */
private enum JavaLittleEndianBytes implements LittleEndianBytes {
INSTANCE {
@Override
public long getLongLittleEndian(byte[] source, int offset) {
return Longs.fromBytes(
source[offset + 7],
source[offset + 6],
source[offset + 5],
source[offset + 4],
source[offset + 3],
source[offset + 2],
source[offset + 1],
source[offset]);
}
@Override
public void putLongLittleEndian(byte[] sink, int offset, long value) {
long mask = 0xFFL;
for (int i = 0; i < 8; mask <<= 8, i++) {
sink[offset + i] = (byte) ((value & mask) >> (i * 8));
}
}
}
}
static {
LittleEndianBytes theGetter = JavaLittleEndianBytes.INSTANCE;
try {
/*
* UnsafeByteArray uses Unsafe.getLong() in an unsupported way, which is known to cause
* crashes on Android when running in 32-bit mode. For maximum safety, we shouldn't use
* Unsafe.getLong() at all, but the performance benefit on x86_64 is too great to ignore, so
* as a compromise, we enable the optimization only on platforms that we specifically know to
* work.
*
* In the future, the use of Unsafe.getLong() should be replaced by ByteBuffer.getLong(),
* which will have an efficient native implementation in JDK 9.
*
*/
String arch = System.getProperty("os.arch");
if ("amd64".equals(arch) || "aarch64".equals(arch)) {
theGetter =
ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)
? UnsafeByteArray.UNSAFE_LITTLE_ENDIAN
: UnsafeByteArray.UNSAFE_BIG_ENDIAN;
}
} catch (Throwable t) {
// ensure we really catch *everything*
}
byteArray = theGetter;
}
/** Deter instantiation of this class. */
private LittleEndianByteArray() {}
}
| google/guava | guava/src/com/google/common/hash/LittleEndianByteArray.java |
637 | /*
* Copyright (C) 2018 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of ImmutableBiMap backed by a pair of JDK HashMaps, which have smartness
* protecting against hash flooding.
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
final class JdkBackedImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
@VisibleForTesting
static <K, V> ImmutableBiMap<K, V> create(int n, @Nullable Entry<K, V>[] entryArray) {
Map<K, V> forwardDelegate = Maps.newHashMapWithExpectedSize(n);
Map<V, K> backwardDelegate = Maps.newHashMapWithExpectedSize(n);
for (int i = 0; i < n; i++) {
// requireNonNull is safe because the first `n` elements have been filled in.
Entry<K, V> e = RegularImmutableMap.makeImmutable(requireNonNull(entryArray[i]));
entryArray[i] = e;
V oldValue = forwardDelegate.putIfAbsent(e.getKey(), e.getValue());
if (oldValue != null) {
throw conflictException("key", e.getKey() + "=" + oldValue, entryArray[i]);
}
K oldKey = backwardDelegate.putIfAbsent(e.getValue(), e.getKey());
if (oldKey != null) {
throw conflictException("value", oldKey + "=" + e.getValue(), entryArray[i]);
}
}
ImmutableList<Entry<K, V>> entryList = ImmutableList.asImmutableList(entryArray, n);
return new JdkBackedImmutableBiMap<>(entryList, forwardDelegate, backwardDelegate);
}
private final transient ImmutableList<Entry<K, V>> entries;
private final Map<K, V> forwardDelegate;
private final Map<V, K> backwardDelegate;
private JdkBackedImmutableBiMap(
ImmutableList<Entry<K, V>> entries, Map<K, V> forwardDelegate, Map<V, K> backwardDelegate) {
this.entries = entries;
this.forwardDelegate = forwardDelegate;
this.backwardDelegate = backwardDelegate;
}
@Override
public int size() {
return entries.size();
}
@LazyInit @RetainedWith @CheckForNull private transient JdkBackedImmutableBiMap<V, K> inverse;
@Override
public ImmutableBiMap<V, K> inverse() {
JdkBackedImmutableBiMap<V, K> result = inverse;
if (result == null) {
inverse =
result =
new JdkBackedImmutableBiMap<>(
new InverseEntries(), backwardDelegate, forwardDelegate);
result.inverse = this;
}
return result;
}
@WeakOuter
private final class InverseEntries extends ImmutableList<Entry<V, K>> {
@Override
public Entry<V, K> get(int index) {
Entry<K, V> entry = entries.get(index);
return Maps.immutableEntry(entry.getValue(), entry.getKey());
}
@Override
boolean isPartialView() {
return false;
}
@Override
public int size() {
return entries.size();
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return forwardDelegate.get(key);
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet.RegularEntrySet<>(this, entries);
}
@Override
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<>(this);
}
@Override
boolean isPartialView() {
return false;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
| google/guava | guava/src/com/google/common/collect/JdkBackedImmutableBiMap.java |
639 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Version
*/
public final class Version {
private static final Logger logger = LoggerFactory.getLogger(Version.class);
private static final Pattern PREFIX_DIGITS_PATTERN = Pattern.compile("^([0-9]*).*");
// Dubbo RPC protocol version, for compatibility, it must not be between 2.0.10 ~ 2.6.2
public static final String DEFAULT_DUBBO_PROTOCOL_VERSION = "2.0.2";
// version 1.0.0 represents Dubbo rpc protocol before v2.6.2
public static final int LEGACY_DUBBO_PROTOCOL_VERSION = 10000; // 1.0.0
// Dubbo implementation version, usually is jar version.
private static final String VERSION = getVersion(Version.class, "");
/**
* For protocol compatibility purpose.
* Because {@link #isSupportResponseAttachment} is checked for every call, int compare expect to has higher
* performance than string.
*/
public static final int LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 2000200; // 2.0.2
public static final int HIGHEST_PROTOCOL_VERSION = 2009900; // 2.0.99
private static final Map<String, Integer> VERSION2INT = new HashMap<String, Integer>();
static {
// check if there's duplicated jar
Version.checkDuplicate(Version.class);
}
private Version() {
}
public static String getProtocolVersion() {
return DEFAULT_DUBBO_PROTOCOL_VERSION;
}
public static String getVersion() {
return VERSION;
}
/**
* Check the framework release version number to decide if it's 2.7.0 or higher
*/
public static boolean isRelease270OrHigher(String version) {
if (StringUtils.isEmpty(version)) {
return false;
}
if (getIntVersion(version) >= 2070000) {
return true;
}
return false;
}
/**
* Check the framework release version number to decide if it's 2.6.3 or higher
*
* @param version, the sdk version
*/
public static boolean isRelease263OrHigher(String version) {
return getIntVersion(version) >= 2060300;
}
/**
* Dubbo 2.x protocol version numbers are limited to 2.0.2/2000200 ~ 2.0.99/2009900, other versions are consider as
* invalid or not from official release.
*
* @param version, the protocol version.
* @return
*/
public static boolean isSupportResponseAttachment(String version) {
if (StringUtils.isEmpty(version)) {
return false;
}
int iVersion = getIntVersion(version);
if (iVersion >= LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT && iVersion <= HIGHEST_PROTOCOL_VERSION) {
return true;
}
return false;
}
public static int getIntVersion(String version) {
Integer v = VERSION2INT.get(version);
if (v == null) {
try {
v = parseInt(version);
// e.g., version number 2.6.3 will convert to 2060300
if (version.split("\\.").length == 3) {
v = v * 100;
}
} catch (Exception e) {
logger.warn("Please make sure your version value has the right format: " +
"\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " +
"\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version.");
v = LEGACY_DUBBO_PROTOCOL_VERSION;
}
VERSION2INT.put(version, v);
}
return v;
}
private static int parseInt(String version) {
int v = 0;
String[] vArr = version.split("\\.");
int len = vArr.length;
for (int i = 0; i < len; i++) {
String subV = getPrefixDigits(vArr[i]);
if (StringUtils.isNotEmpty(subV)) {
v += Integer.parseInt(subV) * Math.pow(10, (len - i - 1) * 2);
}
}
return v;
}
/**
* get prefix digits from given version string
*/
private static String getPrefixDigits(String v) {
Matcher matcher = PREFIX_DIGITS_PATTERN.matcher(v);
if (matcher.find()) {
return matcher.group(1);
}
return "";
}
public static String getVersion(Class<?> cls, String defaultVersion) {
try {
// find version info from MANIFEST.MF first
Package pkg = cls.getPackage();
String version = null;
if (pkg != null) {
version = pkg.getImplementationVersion();
if (StringUtils.isNotEmpty(version)) {
return version;
}
version = pkg.getSpecificationVersion();
if (StringUtils.isNotEmpty(version)) {
return version;
}
}
// guess version from jar file name if nothing's found from MANIFEST.MF
CodeSource codeSource = cls.getProtectionDomain().getCodeSource();
if (codeSource == null) {
logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion);
return defaultVersion;
}
URL location = codeSource.getLocation();
if (location == null){
logger.info("No location for class " + cls.getName() + " when getVersion, use default version " + defaultVersion);
return defaultVersion;
}
String file = location.getFile();
if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) {
version = getFromFile(file);
}
// return default version if no version info is found
return StringUtils.isEmpty(version) ? defaultVersion : version;
} catch (Throwable e) {
// return default version when any exception is thrown
logger.error("return default version, ignore exception " + e.getMessage(), e);
return defaultVersion;
}
}
/**
* get version from file: path/to/group-module-x.y.z.jar, returns x.y.z
*/
private static String getFromFile(String file) {
// remove suffix ".jar": "path/to/group-module-x.y.z"
file = file.substring(0, file.length() - 4);
// remove path: "group-module-x.y.z"
int i = file.lastIndexOf('/');
if (i >= 0) {
file = file.substring(i + 1);
}
// remove group: "module-x.y.z"
i = file.indexOf("-");
if (i >= 0) {
file = file.substring(i + 1);
}
// remove module: "x.y.z"
while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
i = file.indexOf("-");
if (i >= 0) {
file = file.substring(i + 1);
} else {
break;
}
}
return file;
}
public static void checkDuplicate(Class<?> cls, boolean failOnError) {
checkDuplicate(cls.getName().replace('.', '/') + ".class", failOnError);
}
public static void checkDuplicate(Class<?> cls) {
checkDuplicate(cls, false);
}
public static void checkDuplicate(String path, boolean failOnError) {
try {
// search in caller's classloader
Set<String> files = getResources(path);
// duplicated jar is found
if (files.size() > 1) {
String error = "Duplicate class " + path + " in " + files.size() + " jar " + files;
if (failOnError) {
throw new IllegalStateException(error);
} else {
logger.error(error);
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
/**
* search resources in caller's classloader
*/
private static Set<String> getResources(String path) throws IOException {
Enumeration<URL> urls = ClassUtils.getCallerClassLoader(Version.class).getResources(path);
Set<String> files = new HashSet<String>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (url != null) {
String file = url.getFile();
if (StringUtils.isNotEmpty(file)) {
files.add(file);
}
}
}
return files;
}
}
| apache/dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/Version.java |
642 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gateway;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.action.support.nodes.BaseNodesResponse;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RerouteService;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;
import org.elasticsearch.cluster.routing.allocation.ExistingShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.FailedShard;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.store.TransportNodesListShardStoreMetadata;
import org.elasticsearch.indices.store.TransportNodesListShardStoreMetadata.NodeStoreFilesMetadata;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.elasticsearch.common.util.set.Sets.difference;
import static org.elasticsearch.core.Strings.format;
public class GatewayAllocator implements ExistingShardsAllocator {
public static final String ALLOCATOR_NAME = "gateway_allocator";
private static final Logger logger = LogManager.getLogger(GatewayAllocator.class);
private final RerouteService rerouteService;
private final PrimaryShardAllocator primaryShardAllocator;
private final ReplicaShardAllocator replicaShardAllocator;
private final ConcurrentMap<ShardId, AsyncShardFetch<NodeGatewayStartedShards>> asyncFetchStarted = ConcurrentCollections
.newConcurrentMap();
private final ConcurrentMap<ShardId, AsyncShardFetch<NodeStoreFilesMetadata>> asyncFetchStore = ConcurrentCollections
.newConcurrentMap();
private Set<String> lastSeenEphemeralIds = Collections.emptySet();
@Inject
public GatewayAllocator(RerouteService rerouteService, NodeClient client) {
this.rerouteService = rerouteService;
this.primaryShardAllocator = new InternalPrimaryShardAllocator(client);
this.replicaShardAllocator = new InternalReplicaShardAllocator(client);
}
@Override
public void cleanCaches() {
Releasables.close(asyncFetchStarted.values());
asyncFetchStarted.clear();
Releasables.close(asyncFetchStore.values());
asyncFetchStore.clear();
}
// for tests
protected GatewayAllocator() {
this.rerouteService = null;
this.primaryShardAllocator = null;
this.replicaShardAllocator = null;
}
@Override
public int getNumberOfInFlightFetches() {
int count = 0;
for (AsyncShardFetch<NodeGatewayStartedShards> fetch : asyncFetchStarted.values()) {
count += fetch.getNumberOfInFlightFetches();
}
for (AsyncShardFetch<NodeStoreFilesMetadata> fetch : asyncFetchStore.values()) {
count += fetch.getNumberOfInFlightFetches();
}
return count;
}
@Override
public void applyStartedShards(final List<ShardRouting> startedShards, final RoutingAllocation allocation) {
for (ShardRouting startedShard : startedShards) {
Releasables.close(asyncFetchStarted.remove(startedShard.shardId()));
Releasables.close(asyncFetchStore.remove(startedShard.shardId()));
}
}
@Override
public void applyFailedShards(final List<FailedShard> failedShards, final RoutingAllocation allocation) {
for (FailedShard failedShard : failedShards) {
Releasables.close(asyncFetchStarted.remove(failedShard.routingEntry().shardId()));
Releasables.close(asyncFetchStore.remove(failedShard.routingEntry().shardId()));
}
}
@Override
public void beforeAllocation(final RoutingAllocation allocation) {
assert primaryShardAllocator != null;
assert replicaShardAllocator != null;
ensureAsyncFetchStorePrimaryRecency(allocation);
}
@Override
public void afterPrimariesBeforeReplicas(RoutingAllocation allocation, Predicate<ShardRouting> isRelevantShardPredicate) {
assert replicaShardAllocator != null;
if (allocation.routingNodes().hasInactiveReplicas()) {
// cancel existing recoveries if we have a better match
replicaShardAllocator.processExistingRecoveries(allocation, isRelevantShardPredicate);
}
}
@Override
public void allocateUnassigned(
ShardRouting shardRouting,
final RoutingAllocation allocation,
UnassignedAllocationHandler unassignedAllocationHandler
) {
assert primaryShardAllocator != null;
assert replicaShardAllocator != null;
innerAllocatedUnassigned(allocation, primaryShardAllocator, replicaShardAllocator, shardRouting, unassignedAllocationHandler);
}
// allow for testing infra to change shard allocators implementation
protected static void innerAllocatedUnassigned(
RoutingAllocation allocation,
PrimaryShardAllocator primaryShardAllocator,
ReplicaShardAllocator replicaShardAllocator,
ShardRouting shardRouting,
ExistingShardsAllocator.UnassignedAllocationHandler unassignedAllocationHandler
) {
assert shardRouting.unassigned();
if (shardRouting.primary()) {
primaryShardAllocator.allocateUnassigned(shardRouting, allocation, unassignedAllocationHandler);
} else {
replicaShardAllocator.allocateUnassigned(shardRouting, allocation, unassignedAllocationHandler);
}
}
@Override
public AllocateUnassignedDecision explainUnassignedShardAllocation(ShardRouting unassignedShard, RoutingAllocation routingAllocation) {
assert unassignedShard.unassigned();
assert routingAllocation.debugDecision();
if (unassignedShard.primary()) {
assert primaryShardAllocator != null;
return primaryShardAllocator.makeAllocationDecision(unassignedShard, routingAllocation, logger);
} else {
assert replicaShardAllocator != null;
return replicaShardAllocator.makeAllocationDecision(unassignedShard, routingAllocation, logger);
}
}
/**
* Clear the fetched data for the primary to ensure we do not cancel recoveries based on excessively stale data.
*/
private void ensureAsyncFetchStorePrimaryRecency(RoutingAllocation allocation) {
DiscoveryNodes nodes = allocation.nodes();
if (hasNewNodes(nodes)) {
final Set<String> newEphemeralIds = nodes.getDataNodes()
.values()
.stream()
.map(DiscoveryNode::getEphemeralId)
.collect(Collectors.toSet());
// Invalidate the cache if a data node has been added to the cluster. This ensures that we do not cancel a recovery if a node
// drops out, we fetch the shard data, then some indexing happens and then the node rejoins the cluster again. There are other
// ways we could decide to cancel a recovery based on stale data (e.g. changing allocation filters or a primary failure) but
// making the wrong decision here is not catastrophic so we only need to cover the common case.
logger.trace(
() -> format(
"new nodes %s found, clearing primary async-fetch-store cache",
difference(newEphemeralIds, lastSeenEphemeralIds)
)
);
asyncFetchStore.values().forEach(fetch -> clearCacheForPrimary(fetch, allocation));
// recalc to also (lazily) clear out old nodes.
this.lastSeenEphemeralIds = newEphemeralIds;
}
}
private static void clearCacheForPrimary(
AsyncShardFetch<TransportNodesListShardStoreMetadata.NodeStoreFilesMetadata> fetch,
RoutingAllocation allocation
) {
ShardRouting primary = allocation.routingNodes().activePrimary(fetch.shardId);
if (primary != null) {
fetch.clearCacheForNode(primary.currentNodeId());
}
}
private boolean hasNewNodes(DiscoveryNodes nodes) {
for (Map.Entry<String, DiscoveryNode> node : nodes.getDataNodes().entrySet()) {
if (lastSeenEphemeralIds.contains(node.getValue().getEphemeralId()) == false) {
return true;
}
}
return false;
}
abstract class InternalAsyncFetch<T extends BaseNodeResponse> extends AsyncShardFetch<T> {
InternalAsyncFetch(Logger logger, String type, ShardId shardId, String customDataPath, int expectedSize) {
super(logger, type, shardId, customDataPath, expectedSize);
}
@Override
protected void reroute(ShardId shardId, String reason) {
logger.trace("{} scheduling reroute for {}", shardId, reason);
assert rerouteService != null;
rerouteService.reroute(
"async_shard_fetch",
Priority.HIGH,
ActionListener.wrap(
r -> logger.trace("{} scheduled reroute completed for {}", shardId, reason),
e -> logger.debug(() -> format("%s scheduled reroute failed for %s", shardId, reason), e)
)
);
}
}
class InternalPrimaryShardAllocator extends PrimaryShardAllocator {
private final NodeClient client;
InternalPrimaryShardAllocator(NodeClient client) {
this.client = client;
}
@Override
protected AsyncShardFetch.FetchResult<NodeGatewayStartedShards> fetchData(ShardRouting shard, RoutingAllocation allocation) {
// explicitly type lister, some IDEs (Eclipse) are not able to correctly infer the function type
AsyncShardFetch<NodeGatewayStartedShards> fetch = asyncFetchStarted.computeIfAbsent(
shard.shardId(),
shardId -> new InternalAsyncFetch<>(
logger,
"shard_started",
shardId,
IndexMetadata.INDEX_DATA_PATH_SETTING.get(allocation.metadata().index(shard.index()).getSettings()),
allocation.routingNodes().size()
) {
@Override
protected void list(
ShardId shardId,
String customDataPath,
DiscoveryNode[] nodes,
ActionListener<BaseNodesResponse<NodeGatewayStartedShards>> listener
) {
client.executeLocally(
TransportNodesListGatewayStartedShards.TYPE,
new TransportNodesListGatewayStartedShards.Request(shardId, customDataPath, nodes),
listener.safeMap(r -> r) // weaken type
);
}
}
);
AsyncShardFetch.FetchResult<NodeGatewayStartedShards> shardState = fetch.fetchData(
allocation.nodes(),
allocation.getIgnoreNodes(shard.shardId())
);
if (shardState.hasData()) {
shardState.processAllocation(allocation);
}
return shardState;
}
}
class InternalReplicaShardAllocator extends ReplicaShardAllocator {
private final NodeClient client;
InternalReplicaShardAllocator(NodeClient client) {
this.client = client;
}
@Override
protected AsyncShardFetch.FetchResult<NodeStoreFilesMetadata> fetchData(ShardRouting shard, RoutingAllocation allocation) {
AsyncShardFetch<NodeStoreFilesMetadata> fetch = asyncFetchStore.computeIfAbsent(
shard.shardId(),
shardId -> new InternalAsyncFetch<>(
logger,
"shard_store",
shard.shardId(),
IndexMetadata.INDEX_DATA_PATH_SETTING.get(allocation.metadata().index(shard.index()).getSettings()),
allocation.routingNodes().size()
) {
@Override
protected void list(
ShardId shardId,
String customDataPath,
DiscoveryNode[] nodes,
ActionListener<BaseNodesResponse<NodeStoreFilesMetadata>> listener
) {
client.executeLocally(
TransportNodesListShardStoreMetadata.TYPE,
new TransportNodesListShardStoreMetadata.Request(shardId, customDataPath, nodes),
listener.safeMap(r -> r) // weaken type
);
}
}
);
AsyncShardFetch.FetchResult<NodeStoreFilesMetadata> shardStores = fetch.fetchData(
allocation.nodes(),
allocation.getIgnoreNodes(shard.shardId())
);
if (shardStores.hasData()) {
shardStores.processAllocation(allocation);
}
return shardStores;
}
@Override
protected boolean hasInitiatedFetching(ShardRouting shard) {
return asyncFetchStore.get(shard.shardId()) != null;
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/gateway/GatewayAllocator.java |
643 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* CompactLinkedHashSet is an implementation of a Set, which a predictable iteration order that
* matches the insertion order. All optional operations (adding and removing) are supported. All
* elements, including {@code null}, are permitted.
*
* <p>{@code contains(x)}, {@code add(x)} and {@code remove(x)}, are all (expected and amortized)
* constant time operations. Expected in the hashtable sense (depends on the hash function doing a
* good job of distributing the elements to the buckets to a distribution not far from uniform), and
* amortized since some operations can trigger a hash table resize.
*
* <p>This implementation consumes significantly less memory than {@code java.util.LinkedHashSet} or
* even {@code java.util.HashSet}, and places considerably less load on the garbage collector. Like
* {@code java.util.LinkedHashSet}, it offers insertion-order iteration, with identical behavior.
*
* <p>This class should not be assumed to be universally superior to {@code
* java.util.LinkedHashSet}. Generally speaking, this class reduces object allocation and memory
* consumption at the price of moderately increased constant factors of CPU. Only use this class
* when there is a specific reason to prioritize memory over CPU.
*
* @author Louis Wasserman
*/
@GwtIncompatible // not worth using in GWT for now
@ElementTypesAreNonnullByDefault
class CompactLinkedHashSet<E extends @Nullable Object> extends CompactHashSet<E> {
/** Creates an empty {@code CompactLinkedHashSet} instance. */
public static <E extends @Nullable Object> CompactLinkedHashSet<E> create() {
return new CompactLinkedHashSet<>();
}
/**
* Creates a <i>mutable</i> {@code CompactLinkedHashSet} instance containing the elements of the
* given collection in the order returned by the collection's iterator.
*
* @param collection the elements that the set should contain
* @return a new {@code CompactLinkedHashSet} containing those elements (minus duplicates)
*/
public static <E extends @Nullable Object> CompactLinkedHashSet<E> create(
Collection<? extends E> collection) {
CompactLinkedHashSet<E> set = createWithExpectedSize(collection.size());
set.addAll(collection);
return set;
}
/**
* Creates a {@code CompactLinkedHashSet} instance containing the given elements in unspecified
* order.
*
* @param elements the elements that the set should contain
* @return a new {@code CompactLinkedHashSet} containing those elements (minus duplicates)
*/
@SafeVarargs
@SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix.
public static <E extends @Nullable Object> CompactLinkedHashSet<E> create(E... elements) {
CompactLinkedHashSet<E> set = createWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a {@code CompactLinkedHashSet} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without rebuilding internal data structures.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code CompactLinkedHashSet} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E extends @Nullable Object> CompactLinkedHashSet<E> createWithExpectedSize(
int expectedSize) {
return new CompactLinkedHashSet<>(expectedSize);
}
private static final int ENDPOINT = -2;
// TODO(user): predecessors and successors should be collocated (reducing cache misses).
// Might also explore collocating all of [hash, next, predecessor, successor] fields of an
// entry in a *single* long[], though that reduces the maximum size of the set by a factor of 2
/**
* Pointer to the predecessor of an entry in insertion order. ENDPOINT indicates a node is the
* first node in insertion order; all values at indices ≥ {@link #size()} are UNSET.
*/
@CheckForNull private transient int[] predecessor;
/**
* Pointer to the successor of an entry in insertion order. ENDPOINT indicates a node is the last
* node in insertion order; all values at indices ≥ {@link #size()} are UNSET.
*/
@CheckForNull private transient int[] successor;
/** Pointer to the first node in the linked list, or {@code ENDPOINT} if there are no entries. */
private transient int firstEntry;
/** Pointer to the last node in the linked list, or {@code ENDPOINT} if there are no entries. */
private transient int lastEntry;
CompactLinkedHashSet() {
super();
}
CompactLinkedHashSet(int expectedSize) {
super(expectedSize);
}
@Override
void init(int expectedSize) {
super.init(expectedSize);
this.firstEntry = ENDPOINT;
this.lastEntry = ENDPOINT;
}
@Override
int allocArrays() {
int expectedSize = super.allocArrays();
this.predecessor = new int[expectedSize];
this.successor = new int[expectedSize];
return expectedSize;
}
@Override
@CanIgnoreReturnValue
Set<E> convertToHashFloodingResistantImplementation() {
Set<E> result = super.convertToHashFloodingResistantImplementation();
this.predecessor = null;
this.successor = null;
return result;
}
/*
* For discussion of the safety of the following methods for operating on predecessors and
* successors, see the comments near the end of CompactHashMap, noting that the methods here call
* requirePredecessors() and requireSuccessors(), which are defined at the end of this file.
*/
private int getPredecessor(int entry) {
return requirePredecessors()[entry] - 1;
}
@Override
int getSuccessor(int entry) {
return requireSuccessors()[entry] - 1;
}
private void setSuccessor(int entry, int succ) {
requireSuccessors()[entry] = succ + 1;
}
private void setPredecessor(int entry, int pred) {
requirePredecessors()[entry] = pred + 1;
}
private void setSucceeds(int pred, int succ) {
if (pred == ENDPOINT) {
firstEntry = succ;
} else {
setSuccessor(pred, succ);
}
if (succ == ENDPOINT) {
lastEntry = pred;
} else {
setPredecessor(succ, pred);
}
}
@Override
void insertEntry(int entryIndex, @ParametricNullness E object, int hash, int mask) {
super.insertEntry(entryIndex, object, hash, mask);
setSucceeds(lastEntry, entryIndex);
setSucceeds(entryIndex, ENDPOINT);
}
@Override
void moveLastEntry(int dstIndex, int mask) {
int srcIndex = size() - 1;
super.moveLastEntry(dstIndex, mask);
setSucceeds(getPredecessor(dstIndex), getSuccessor(dstIndex));
if (dstIndex < srcIndex) {
setSucceeds(getPredecessor(srcIndex), dstIndex);
setSucceeds(dstIndex, getSuccessor(srcIndex));
}
requirePredecessors()[srcIndex] = 0;
requireSuccessors()[srcIndex] = 0;
}
@Override
void resizeEntries(int newCapacity) {
super.resizeEntries(newCapacity);
predecessor = Arrays.copyOf(requirePredecessors(), newCapacity);
successor = Arrays.copyOf(requireSuccessors(), newCapacity);
}
@Override
int firstEntryIndex() {
return firstEntry;
}
@Override
int adjustAfterRemove(int indexBeforeRemove, int indexRemoved) {
return (indexBeforeRemove >= size()) ? indexRemoved : indexBeforeRemove;
}
@Override
public @Nullable Object[] toArray() {
return ObjectArrays.toArrayImpl(this);
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] a) {
return ObjectArrays.toArrayImpl(this, a);
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.ORDERED | Spliterator.DISTINCT);
}
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
this.firstEntry = ENDPOINT;
this.lastEntry = ENDPOINT;
// Either both arrays are null or neither is, but we check both to satisfy the nullness checker.
if (predecessor != null && successor != null) {
Arrays.fill(predecessor, 0, size(), 0);
Arrays.fill(successor, 0, size(), 0);
}
super.clear();
}
/*
* For discussion of the safety of the following methods, see the comments near the end of
* CompactHashMap.
*/
private int[] requirePredecessors() {
return requireNonNull(predecessor);
}
private int[] requireSuccessors() {
return requireNonNull(successor);
}
/*
* We don't define getPredecessor+getSuccessor and setPredecessor+setSuccessor here because
* they're defined above -- including logic to add and subtract 1 to map between the values stored
* in the predecessor/successor arrays and the indexes in the elements array that they identify.
*/
}
| google/guava | guava/src/com/google/common/collect/CompactLinkedHashSet.java |
644 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.CompactHashing.UNSET;
import static com.google.common.collect.Hashing.smearedHash;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* CompactHashSet is an implementation of a Set. All optional operations (adding and removing) are
* supported. The elements can be any objects.
*
* <p>{@code contains(x)}, {@code add(x)} and {@code remove(x)}, are all (expected and amortized)
* constant time operations. Expected in the hashtable sense (depends on the hash function doing a
* good job of distributing the elements to the buckets to a distribution not far from uniform), and
* amortized since some operations can trigger a hash table resize.
*
* <p>Unlike {@code java.util.HashSet}, iteration is only proportional to the actual {@code size()},
* which is optimal, and <i>not</i> the size of the internal hashtable, which could be much larger
* than {@code size()}. Furthermore, this structure only depends on a fixed number of arrays; {@code
* add(x)} operations <i>do not</i> create objects for the garbage collector to deal with, and for
* every element added, the garbage collector will have to traverse {@code 1.5} references on
* average, in the marking phase, not {@code 5.0} as in {@code java.util.HashSet}.
*
* <p>If there are no removals, then {@link #iterator iteration} order is the same as insertion
* order. Any removal invalidates any ordering guarantees.
*
* <p>This class should not be assumed to be universally superior to {@code java.util.HashSet}.
* Generally speaking, this class reduces object allocation and memory consumption at the price of
* moderately increased constant factors of CPU. Only use this class when there is a specific reason
* to prioritize memory over CPU.
*
* @author Dimitris Andreou
* @author Jon Noack
*/
@GwtIncompatible // not worth using in GWT for now
@ElementTypesAreNonnullByDefault
class CompactHashSet<E extends @Nullable Object> extends AbstractSet<E> implements Serializable {
// TODO(user): cache all field accesses in local vars
/** Creates an empty {@code CompactHashSet} instance. */
public static <E extends @Nullable Object> CompactHashSet<E> create() {
return new CompactHashSet<>();
}
/**
* Creates a <i>mutable</i> {@code CompactHashSet} instance containing the elements of the given
* collection in unspecified order.
*
* @param collection the elements that the set should contain
* @return a new {@code CompactHashSet} containing those elements (minus duplicates)
*/
public static <E extends @Nullable Object> CompactHashSet<E> create(
Collection<? extends E> collection) {
CompactHashSet<E> set = createWithExpectedSize(collection.size());
set.addAll(collection);
return set;
}
/**
* Creates a <i>mutable</i> {@code CompactHashSet} instance containing the given elements in
* unspecified order.
*
* @param elements the elements that the set should contain
* @return a new {@code CompactHashSet} containing those elements (minus duplicates)
*/
@SafeVarargs
@SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix.
public static <E extends @Nullable Object> CompactHashSet<E> create(E... elements) {
CompactHashSet<E> set = createWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a {@code CompactHashSet} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code CompactHashSet} with enough capacity to hold {@code expectedSize}
* elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E extends @Nullable Object> CompactHashSet<E> createWithExpectedSize(
int expectedSize) {
return new CompactHashSet<>(expectedSize);
}
/**
* Maximum allowed false positive probability of detecting a hash flooding attack given random
* input.
*/
@VisibleForTesting(
)
static final double HASH_FLOODING_FPP = 0.001;
/**
* Maximum allowed length of a hash table bucket before falling back to a j.u.LinkedHashSet based
* implementation. Experimentally determined.
*/
private static final int MAX_HASH_BUCKET_LENGTH = 9;
// See CompactHashMap for a detailed description of how the following fields work. That
// description talks about `keys`, `values`, and `entries`; here the `keys` and `values` arrays
// are replaced by a single `elements` array but everything else works similarly.
/**
* The hashtable object. This can be either:
*
* <ul>
* <li>a byte[], short[], or int[], with size a power of two, created by
* CompactHashing.createTable, whose values are either
* <ul>
* <li>UNSET, meaning "null pointer"
* <li>one plus an index into the entries and elements array
* </ul>
* <li>another java.util.Set delegate implementation. In most modern JDKs, normal java.util hash
* collections intelligently fall back to a binary search tree if hash table collisions are
* detected. Rather than going to all the trouble of reimplementing this ourselves, we
* simply switch over to use the JDK implementation wholesale if probable hash flooding is
* detected, sacrificing the compactness guarantee in very rare cases in exchange for much
* more reliable worst-case behavior.
* <li>null, if no entries have yet been added to the map
* </ul>
*/
@CheckForNull private transient Object table;
/**
* Contains the logical entries, in the range of [0, size()). The high bits of each int are the
* part of the smeared hash of the element not covered by the hashtable mask, whereas the low bits
* are the "next" pointer (pointing to the next entry in the bucket chain), which will always be
* less than or equal to the hashtable mask.
*
* <pre>
* hash = aaaaaaaa
* mask = 00000fff
* next = 00000bbb
* entry = aaaaabbb
* </pre>
*
* <p>The pointers in [size(), entries.length) are all "null" (UNSET).
*/
@CheckForNull private transient int[] entries;
/**
* The elements contained in the set, in the range of [0, size()). The elements in [size(),
* elements.length) are all {@code null}.
*/
@VisibleForTesting @CheckForNull transient @Nullable Object[] elements;
/**
* Keeps track of metadata like the number of hash table bits and modifications of this data
* structure (to make it possible to throw ConcurrentModificationException in the iterator). Note
* that we choose not to make this volatile, so we do less of a "best effort" to track such
* errors, for better performance.
*/
private transient int metadata;
/** The number of elements contained in the set. */
private transient int size;
/** Constructs a new empty instance of {@code CompactHashSet}. */
CompactHashSet() {
init(CompactHashing.DEFAULT_SIZE);
}
/**
* Constructs a new instance of {@code CompactHashSet} with the specified capacity.
*
* @param expectedSize the initial capacity of this {@code CompactHashSet}.
*/
CompactHashSet(int expectedSize) {
init(expectedSize);
}
/** Pseudoconstructor for serialization support. */
void init(int expectedSize) {
Preconditions.checkArgument(expectedSize >= 0, "Expected size must be >= 0");
// Save expectedSize for use in allocArrays()
this.metadata = Ints.constrainToRange(expectedSize, 1, CompactHashing.MAX_SIZE);
}
/** Returns whether arrays need to be allocated. */
@VisibleForTesting
boolean needsAllocArrays() {
return table == null;
}
/** Handle lazy allocation of arrays. */
@CanIgnoreReturnValue
int allocArrays() {
Preconditions.checkState(needsAllocArrays(), "Arrays already allocated");
int expectedSize = metadata;
int buckets = CompactHashing.tableSize(expectedSize);
this.table = CompactHashing.createTable(buckets);
setHashTableMask(buckets - 1);
this.entries = new int[expectedSize];
this.elements = new Object[expectedSize];
return expectedSize;
}
@SuppressWarnings("unchecked")
@VisibleForTesting
@CheckForNull
Set<E> delegateOrNull() {
if (table instanceof Set) {
return (Set<E>) table;
}
return null;
}
private Set<E> createHashFloodingResistantDelegate(int tableSize) {
return new LinkedHashSet<>(tableSize, 1.0f);
}
@VisibleForTesting
@CanIgnoreReturnValue
Set<E> convertToHashFloodingResistantImplementation() {
Set<E> newDelegate = createHashFloodingResistantDelegate(hashTableMask() + 1);
for (int i = firstEntryIndex(); i >= 0; i = getSuccessor(i)) {
newDelegate.add(element(i));
}
this.table = newDelegate;
this.entries = null;
this.elements = null;
incrementModCount();
return newDelegate;
}
@VisibleForTesting
boolean isUsingHashFloodingResistance() {
return delegateOrNull() != null;
}
/** Stores the hash table mask as the number of bits needed to represent an index. */
private void setHashTableMask(int mask) {
int hashTableBits = Integer.SIZE - Integer.numberOfLeadingZeros(mask);
metadata =
CompactHashing.maskCombine(metadata, hashTableBits, CompactHashing.HASH_TABLE_BITS_MASK);
}
/** Gets the hash table mask using the stored number of hash table bits. */
private int hashTableMask() {
return (1 << (metadata & CompactHashing.HASH_TABLE_BITS_MASK)) - 1;
}
void incrementModCount() {
metadata += CompactHashing.MODIFICATION_COUNT_INCREMENT;
}
@CanIgnoreReturnValue
@Override
public boolean add(@ParametricNullness E object) {
if (needsAllocArrays()) {
allocArrays();
}
Set<E> delegate = delegateOrNull();
if (delegate != null) {
return delegate.add(object);
}
int[] entries = requireEntries();
@Nullable Object[] elements = requireElements();
int newEntryIndex = this.size; // current size, and pointer to the entry to be appended
int newSize = newEntryIndex + 1;
int hash = smearedHash(object);
int mask = hashTableMask();
int tableIndex = hash & mask;
int next = CompactHashing.tableGet(requireTable(), tableIndex);
if (next == UNSET) { // uninitialized bucket
if (newSize > mask) {
// Resize and add new entry
mask = resizeTable(mask, CompactHashing.newCapacity(mask), hash, newEntryIndex);
} else {
CompactHashing.tableSet(requireTable(), tableIndex, newEntryIndex + 1);
}
} else {
int entryIndex;
int entry;
int hashPrefix = CompactHashing.getHashPrefix(hash, mask);
int bucketLength = 0;
do {
entryIndex = next - 1;
entry = entries[entryIndex];
if (CompactHashing.getHashPrefix(entry, mask) == hashPrefix
&& Objects.equal(object, elements[entryIndex])) {
return false;
}
next = CompactHashing.getNext(entry, mask);
bucketLength++;
} while (next != UNSET);
if (bucketLength >= MAX_HASH_BUCKET_LENGTH) {
return convertToHashFloodingResistantImplementation().add(object);
}
if (newSize > mask) {
// Resize and add new entry
mask = resizeTable(mask, CompactHashing.newCapacity(mask), hash, newEntryIndex);
} else {
entries[entryIndex] = CompactHashing.maskCombine(entry, newEntryIndex + 1, mask);
}
}
resizeMeMaybe(newSize);
insertEntry(newEntryIndex, object, hash, mask);
this.size = newSize;
incrementModCount();
return true;
}
/**
* Creates a fresh entry with the specified object at the specified position in the entry arrays.
*/
void insertEntry(int entryIndex, @ParametricNullness E object, int hash, int mask) {
setEntry(entryIndex, CompactHashing.maskCombine(hash, UNSET, mask));
setElement(entryIndex, object);
}
/** Resizes the entries storage if necessary. */
private void resizeMeMaybe(int newSize) {
int entriesSize = requireEntries().length;
if (newSize > entriesSize) {
// 1.5x but round up to nearest odd (this is optimal for memory consumption on Android)
int newCapacity =
Math.min(CompactHashing.MAX_SIZE, (entriesSize + Math.max(1, entriesSize >>> 1)) | 1);
if (newCapacity != entriesSize) {
resizeEntries(newCapacity);
}
}
}
/**
* Resizes the internal entries array to the specified capacity, which may be greater or less than
* the current capacity.
*/
void resizeEntries(int newCapacity) {
this.entries = Arrays.copyOf(requireEntries(), newCapacity);
this.elements = Arrays.copyOf(requireElements(), newCapacity);
}
@CanIgnoreReturnValue
private int resizeTable(int oldMask, int newCapacity, int targetHash, int targetEntryIndex) {
Object newTable = CompactHashing.createTable(newCapacity);
int newMask = newCapacity - 1;
if (targetEntryIndex != UNSET) {
// Add target first; it must be last in the chain because its entry hasn't yet been created
CompactHashing.tableSet(newTable, targetHash & newMask, targetEntryIndex + 1);
}
Object oldTable = requireTable();
int[] entries = requireEntries();
// Loop over current hashtable
for (int oldTableIndex = 0; oldTableIndex <= oldMask; oldTableIndex++) {
int oldNext = CompactHashing.tableGet(oldTable, oldTableIndex);
while (oldNext != UNSET) {
int entryIndex = oldNext - 1;
int oldEntry = entries[entryIndex];
// Rebuild hash using entry hashPrefix and tableIndex ("hashSuffix")
int hash = CompactHashing.getHashPrefix(oldEntry, oldMask) | oldTableIndex;
int newTableIndex = hash & newMask;
int newNext = CompactHashing.tableGet(newTable, newTableIndex);
CompactHashing.tableSet(newTable, newTableIndex, oldNext);
entries[entryIndex] = CompactHashing.maskCombine(hash, newNext, newMask);
oldNext = CompactHashing.getNext(oldEntry, oldMask);
}
}
this.table = newTable;
setHashTableMask(newMask);
return newMask;
}
@Override
public boolean contains(@CheckForNull Object object) {
if (needsAllocArrays()) {
return false;
}
Set<E> delegate = delegateOrNull();
if (delegate != null) {
return delegate.contains(object);
}
int hash = smearedHash(object);
int mask = hashTableMask();
int next = CompactHashing.tableGet(requireTable(), hash & mask);
if (next == UNSET) {
return false;
}
int hashPrefix = CompactHashing.getHashPrefix(hash, mask);
do {
int entryIndex = next - 1;
int entry = entry(entryIndex);
if (CompactHashing.getHashPrefix(entry, mask) == hashPrefix
&& Objects.equal(object, element(entryIndex))) {
return true;
}
next = CompactHashing.getNext(entry, mask);
} while (next != UNSET);
return false;
}
@CanIgnoreReturnValue
@Override
public boolean remove(@CheckForNull Object object) {
if (needsAllocArrays()) {
return false;
}
Set<E> delegate = delegateOrNull();
if (delegate != null) {
return delegate.remove(object);
}
int mask = hashTableMask();
int index =
CompactHashing.remove(
object,
/* value= */ null,
mask,
requireTable(),
requireEntries(),
requireElements(),
/* values= */ null);
if (index == -1) {
return false;
}
moveLastEntry(index, mask);
size--;
incrementModCount();
return true;
}
/**
* Moves the last entry in the entry array into {@code dstIndex}, and nulls out its old position.
*/
void moveLastEntry(int dstIndex, int mask) {
Object table = requireTable();
int[] entries = requireEntries();
@Nullable Object[] elements = requireElements();
int srcIndex = size() - 1;
if (dstIndex < srcIndex) {
// move last entry to deleted spot
Object object = elements[srcIndex];
elements[dstIndex] = object;
elements[srcIndex] = null;
// move the last entry to the removed spot, just like we moved the element
entries[dstIndex] = entries[srcIndex];
entries[srcIndex] = 0;
// also need to update whoever's "next" pointer was pointing to the last entry place
int tableIndex = smearedHash(object) & mask;
int next = CompactHashing.tableGet(table, tableIndex);
int srcNext = srcIndex + 1;
if (next == srcNext) {
// we need to update the root pointer
CompactHashing.tableSet(table, tableIndex, dstIndex + 1);
} else {
// we need to update a pointer in an entry
int entryIndex;
int entry;
do {
entryIndex = next - 1;
entry = entries[entryIndex];
next = CompactHashing.getNext(entry, mask);
} while (next != srcNext);
// here, entries[entryIndex] points to the old entry location; update it
entries[entryIndex] = CompactHashing.maskCombine(entry, dstIndex + 1, mask);
}
} else {
elements[dstIndex] = null;
entries[dstIndex] = 0;
}
}
int firstEntryIndex() {
return isEmpty() ? -1 : 0;
}
int getSuccessor(int entryIndex) {
return (entryIndex + 1 < size) ? entryIndex + 1 : -1;
}
/**
* Updates the index an iterator is pointing to after a call to remove: returns the index of the
* entry that should be looked at after a removal on indexRemoved, with indexBeforeRemove as the
* index that *was* the next entry that would be looked at.
*/
int adjustAfterRemove(int indexBeforeRemove, @SuppressWarnings("unused") int indexRemoved) {
return indexBeforeRemove - 1;
}
@Override
public Iterator<E> iterator() {
Set<E> delegate = delegateOrNull();
if (delegate != null) {
return delegate.iterator();
}
return new Iterator<E>() {
int expectedMetadata = metadata;
int currentIndex = firstEntryIndex();
int indexToRemove = -1;
@Override
public boolean hasNext() {
return currentIndex >= 0;
}
@Override
@ParametricNullness
public E next() {
checkForConcurrentModification();
if (!hasNext()) {
throw new NoSuchElementException();
}
indexToRemove = currentIndex;
E result = element(currentIndex);
currentIndex = getSuccessor(currentIndex);
return result;
}
@Override
public void remove() {
checkForConcurrentModification();
checkRemove(indexToRemove >= 0);
incrementExpectedModCount();
CompactHashSet.this.remove(element(indexToRemove));
currentIndex = adjustAfterRemove(currentIndex, indexToRemove);
indexToRemove = -1;
}
void incrementExpectedModCount() {
expectedMetadata += CompactHashing.MODIFICATION_COUNT_INCREMENT;
}
private void checkForConcurrentModification() {
if (metadata != expectedMetadata) {
throw new ConcurrentModificationException();
}
}
};
}
@Override
public int size() {
Set<E> delegate = delegateOrNull();
return (delegate != null) ? delegate.size() : size;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public @Nullable Object[] toArray() {
if (needsAllocArrays()) {
return new Object[0];
}
Set<E> delegate = delegateOrNull();
return (delegate != null) ? delegate.toArray() : Arrays.copyOf(requireElements(), size);
}
@CanIgnoreReturnValue
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] a) {
if (needsAllocArrays()) {
if (a.length > 0) {
a[0] = null;
}
return a;
}
Set<E> delegate = delegateOrNull();
return (delegate != null)
? delegate.toArray(a)
: ObjectArrays.toArrayImpl(requireElements(), 0, size, a);
}
/**
* Ensures that this {@code CompactHashSet} has the smallest representation in memory, given its
* current size.
*/
public void trimToSize() {
if (needsAllocArrays()) {
return;
}
Set<E> delegate = delegateOrNull();
if (delegate != null) {
Set<E> newDelegate = createHashFloodingResistantDelegate(size());
newDelegate.addAll(delegate);
this.table = newDelegate;
return;
}
int size = this.size;
if (size < requireEntries().length) {
resizeEntries(size);
}
int minimumTableSize = CompactHashing.tableSize(size);
int mask = hashTableMask();
if (minimumTableSize < mask) { // smaller table size will always be less than current mask
resizeTable(mask, minimumTableSize, UNSET, UNSET);
}
}
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
incrementModCount();
Set<E> delegate = delegateOrNull();
if (delegate != null) {
metadata =
Ints.constrainToRange(size(), CompactHashing.DEFAULT_SIZE, CompactHashing.MAX_SIZE);
delegate.clear(); // invalidate any iterators left over!
table = null;
size = 0;
} else {
Arrays.fill(requireElements(), 0, size, null);
CompactHashing.tableClear(requireTable());
Arrays.fill(requireEntries(), 0, size, 0);
this.size = 0;
}
}
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
for (E e : this) {
stream.writeObject(e);
}
}
@SuppressWarnings("unchecked")
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
if (elementCount < 0) {
throw new InvalidObjectException("Invalid size: " + elementCount);
}
init(elementCount);
for (int i = 0; i < elementCount; i++) {
E element = (E) stream.readObject();
add(element);
}
}
/*
* For discussion of the safety of the following methods, see the comments near the end of
* CompactHashMap.
*/
private Object requireTable() {
return requireNonNull(table);
}
private int[] requireEntries() {
return requireNonNull(entries);
}
private @Nullable Object[] requireElements() {
return requireNonNull(elements);
}
@SuppressWarnings("unchecked")
private E element(int i) {
return (E) requireElements()[i];
}
private int entry(int i) {
return requireEntries()[i];
}
private void setElement(int i, E value) {
requireElements()[i] = value;
}
private void setEntry(int i, int value) {
requireEntries()[i] = value;
}
}
| google/guava | android/guava/src/com/google/common/collect/CompactHashSet.java |
647 | // Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
// Note:
// A word cannot be split into two lines.
// The order of words in the sentence must remain unchanged.
// Two consecutive words in a line must be separated by a single space.
// Total words in the sentence won't exceed 100.
// Length of each word is greater than 0 and won't exceed 10.
// 1 ≤ rows, cols ≤ 20,000.
// Example 1:
// Input:
// rows = 2, cols = 8, sentence = ["hello", "world"]
// Output:
// 1
// Explanation:
// hello---
// world---
// The character '-' signifies an empty space on the screen.
// Example 2:
// Input:
// rows = 3, cols = 6, sentence = ["a", "bcd", "e"]
// Output:
// 2
// Explanation:
// a-bcd-
// e-a---
// bcd-e-
// The character '-' signifies an empty space on the screen.
// Example 3:
// Input:
// rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]
// Output:
// 1
// Explanation:
// I-had
// apple
// pie-I
// had--
// The character '-' signifies an empty space on the screen.
public class SentenceScreenFitting {
public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int start = 0;
int l = s.length();
for(int i = 0; i < rows; i++) {
start += cols;
if(s.charAt(start % l) == ' ') {
start++;
} else {
while(start > 0 && s.charAt((start - 1) % l) != ' ') {
start--;
}
}
}
return start / s.length();
}
}
| kdn251/interviews | company/google/SentenceScreenFitting.java |
648 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.objectmother;
/**
* Defines all attributes and behaviour related to the Queen.
*/
public class Queen implements Royalty {
private boolean isDrunk = false;
private boolean isHappy = false;
private boolean isFlirty = false;
@Override
public void makeDrunk() {
isDrunk = true;
}
@Override
public void makeSober() {
isDrunk = false;
}
@Override
public void makeHappy() {
isHappy = true;
}
@Override
public void makeUnhappy() {
isHappy = false;
}
public boolean isFlirty() {
return isFlirty;
}
public void setFlirtiness(boolean flirtiness) {
this.isFlirty = flirtiness;
}
/**
* Method which is called when the king is flirting to a queen.
*
* @param king King who initialized the flirt.
* @return A value which describes if the flirt was successful or not.
*/
public boolean getFlirted(King king) {
return this.isFlirty && king.isHappy && !king.isDrunk;
}
}
| smedals/java-design-patterns | object-mother/src/main/java/com/iluwatar/objectmother/Queen.java |
650 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* CompactLinkedHashMap is an implementation of a Map with insertion or LRU iteration order,
* maintained with a doubly linked list through the entries. All optional operations (put and
* remove) are supported. Null keys and values are supported.
*
* <p>{@code containsKey(k)}, {@code put(k, v)} and {@code remove(k)} are all (expected and
* amortized) constant time operations. Expected in the hashtable sense (depends on the hash
* function doing a good job of distributing the elements to the buckets to a distribution not far
* from uniform), and amortized since some operations can trigger a hash table resize.
*
* <p>As compared with {@link java.util.LinkedHashMap}, this structure places significantly reduced
* load on the garbage collector by only using a constant number of internal objects.
*
* <p>This class should not be assumed to be universally superior to {@code
* java.util.LinkedHashMap}. Generally speaking, this class reduces object allocation and memory
* consumption at the price of moderately increased constant factors of CPU. Only use this class
* when there is a specific reason to prioritize memory over CPU.
*
* @author Louis Wasserman
*/
@J2ktIncompatible // no support for access-order mode in LinkedHashMap delegate
@GwtIncompatible // not worth using in GWT for now
@ElementTypesAreNonnullByDefault
class CompactLinkedHashMap<K extends @Nullable Object, V extends @Nullable Object>
extends CompactHashMap<K, V> {
// TODO(lowasser): implement removeEldestEntry so this can be used as a drop-in replacement
/** Creates an empty {@code CompactLinkedHashMap} instance. */
public static <K extends @Nullable Object, V extends @Nullable Object>
CompactLinkedHashMap<K, V> create() {
return new CompactLinkedHashMap<>();
}
/**
* Creates a {@code CompactLinkedHashMap} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without rebuilding internal data structures.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code CompactLinkedHashMap} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
CompactLinkedHashMap<K, V> createWithExpectedSize(int expectedSize) {
return new CompactLinkedHashMap<>(expectedSize);
}
private static final int ENDPOINT = -2;
/**
* Contains the link pointers corresponding with the entries, in the range of [0, size()). The
* high 32 bits of each long is the "prev" pointer, whereas the low 32 bits is the "succ" pointer
* (pointing to the next entry in the linked list). The pointers in [size(), entries.length) are
* all "null" (UNSET).
*
* <p>A node with "prev" pointer equal to {@code ENDPOINT} is the first node in the linked list,
* and a node with "next" pointer equal to {@code ENDPOINT} is the last node.
*/
@CheckForNull @VisibleForTesting transient long[] links;
/** Pointer to the first node in the linked list, or {@code ENDPOINT} if there are no entries. */
private transient int firstEntry;
/** Pointer to the last node in the linked list, or {@code ENDPOINT} if there are no entries. */
private transient int lastEntry;
private final boolean accessOrder;
CompactLinkedHashMap() {
this(CompactHashing.DEFAULT_SIZE);
}
CompactLinkedHashMap(int expectedSize) {
this(expectedSize, false);
}
CompactLinkedHashMap(int expectedSize, boolean accessOrder) {
super(expectedSize);
this.accessOrder = accessOrder;
}
@Override
void init(int expectedSize) {
super.init(expectedSize);
this.firstEntry = ENDPOINT;
this.lastEntry = ENDPOINT;
}
@Override
int allocArrays() {
int expectedSize = super.allocArrays();
this.links = new long[expectedSize];
return expectedSize;
}
@Override
Map<K, V> createHashFloodingResistantDelegate(int tableSize) {
return new LinkedHashMap<>(tableSize, 1.0f, accessOrder);
}
@Override
@CanIgnoreReturnValue
Map<K, V> convertToHashFloodingResistantImplementation() {
Map<K, V> result = super.convertToHashFloodingResistantImplementation();
links = null;
return result;
}
/*
* For discussion of the safety of the following methods for operating on predecessors and
* successors, see the comments near the end of CompactHashMap, noting that the methods here call
* link(), which is defined at the end of this file.
*/
private int getPredecessor(int entry) {
return ((int) (link(entry) >>> 32)) - 1;
}
@Override
int getSuccessor(int entry) {
return ((int) link(entry)) - 1;
}
private void setSuccessor(int entry, int succ) {
long succMask = (~0L) >>> 32;
setLink(entry, (link(entry) & ~succMask) | ((succ + 1) & succMask));
}
private void setPredecessor(int entry, int pred) {
long predMask = ~0L << 32;
setLink(entry, (link(entry) & ~predMask) | ((long) (pred + 1) << 32));
}
private void setSucceeds(int pred, int succ) {
if (pred == ENDPOINT) {
firstEntry = succ;
} else {
setSuccessor(pred, succ);
}
if (succ == ENDPOINT) {
lastEntry = pred;
} else {
setPredecessor(succ, pred);
}
}
@Override
void insertEntry(
int entryIndex, @ParametricNullness K key, @ParametricNullness V value, int hash, int mask) {
super.insertEntry(entryIndex, key, value, hash, mask);
setSucceeds(lastEntry, entryIndex);
setSucceeds(entryIndex, ENDPOINT);
}
@Override
void accessEntry(int index) {
if (accessOrder) {
// delete from previous position...
setSucceeds(getPredecessor(index), getSuccessor(index));
// ...and insert at the end.
setSucceeds(lastEntry, index);
setSucceeds(index, ENDPOINT);
incrementModCount();
}
}
@Override
void moveLastEntry(int dstIndex, int mask) {
int srcIndex = size() - 1;
super.moveLastEntry(dstIndex, mask);
setSucceeds(getPredecessor(dstIndex), getSuccessor(dstIndex));
if (dstIndex < srcIndex) {
setSucceeds(getPredecessor(srcIndex), dstIndex);
setSucceeds(dstIndex, getSuccessor(srcIndex));
}
setLink(srcIndex, 0);
}
@Override
void resizeEntries(int newCapacity) {
super.resizeEntries(newCapacity);
links = Arrays.copyOf(requireLinks(), newCapacity);
}
@Override
int firstEntryIndex() {
return firstEntry;
}
@Override
int adjustAfterRemove(int indexBeforeRemove, int indexRemoved) {
return (indexBeforeRemove >= size()) ? indexRemoved : indexBeforeRemove;
}
@Override
Set<Entry<K, V>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends EntrySetView {
@Override
public Spliterator<Entry<K, V>> spliterator() {
return Spliterators.spliterator(this, Spliterator.ORDERED | Spliterator.DISTINCT);
}
}
return new EntrySetImpl();
}
@Override
Set<K> createKeySet() {
@WeakOuter
class KeySetImpl extends KeySetView {
@Override
public @Nullable Object[] toArray() {
return ObjectArrays.toArrayImpl(this);
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] a) {
return ObjectArrays.toArrayImpl(this, a);
}
@Override
public Spliterator<K> spliterator() {
return Spliterators.spliterator(this, Spliterator.ORDERED | Spliterator.DISTINCT);
}
}
return new KeySetImpl();
}
@Override
Collection<V> createValues() {
@WeakOuter
class ValuesImpl extends ValuesView {
@Override
public @Nullable Object[] toArray() {
return ObjectArrays.toArrayImpl(this);
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] a) {
return ObjectArrays.toArrayImpl(this, a);
}
@Override
public Spliterator<V> spliterator() {
return Spliterators.spliterator(this, Spliterator.ORDERED);
}
}
return new ValuesImpl();
}
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
this.firstEntry = ENDPOINT;
this.lastEntry = ENDPOINT;
if (links != null) {
Arrays.fill(links, 0, size(), 0);
}
super.clear();
}
/*
* For discussion of the safety of the following methods, see the comments near the end of
* CompactHashMap.
*/
private long[] requireLinks() {
return requireNonNull(links);
}
private long link(int i) {
return requireLinks()[i];
}
private void setLink(int i, long value) {
requireLinks()[i] = value;
}
/*
* We don't define getPredecessor+getSuccessor and setPredecessor+setSuccessor here because
* they're defined above -- including logic to add and subtract 1 to map between the values stored
* in the predecessor/successor arrays and the indexes in the elements array that they identify.
*/
}
| google/guava | guava/src/com/google/common/collect/CompactLinkedHashMap.java |
655 | /*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.WeakOuter;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link Map} whose contents will never change, with many other important properties detailed at
* {@link ImmutableCollection}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @since 2.0
*/
@DoNotMock("Use ImmutableMap.of or another implementation")
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements.
* Entries appear in the result {@code ImmutableMap} in encounter order.
*
* <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}, an {@code
* IllegalArgumentException} is thrown when the collection operation is performed. (This differs
* from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, which
* throws an {@code IllegalStateException}.)
*
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
@IgnoreJRERequirement // Users will use this only if they're already using streams.
@Beta // TODO: b/288085449 - Remove.
public static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
return CollectCollectors.toImmutableMap(keyFunction, valueFunction);
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements.
*
* <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}), the
* values are merged using the specified merging function. If the merging function returns {@code
* null}, then the collector removes the value that has been computed for the key thus far (though
* future occurrences of the key would reinsert it).
*
* <p>Entries will appear in the encounter order of the first occurrence of the key.
*
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
@IgnoreJRERequirement // Users will use this only if they're already using streams.
@Beta // TODO: b/288085449 - Remove.
public static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
return CollectCollectors.toImmutableMap(keyFunction, valueFunction, mergeFunction);
}
/**
* Returns the empty map. This map behaves and performs comparably to {@link
* Collections#emptyMap}, and is preferable mainly for consistency and maintainability of your
* code.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
@SuppressWarnings("unchecked")
public static <K, V> ImmutableMap<K, V> of() {
return (ImmutableMap<K, V>) RegularImmutableMap.EMPTY;
}
/**
* Returns an immutable map containing a single entry. This map behaves and performs comparably to
* {@link Collections#singletonMap} but will not accept a null key or value. It is preferable
* mainly for consistency and maintainability of your code.
*/
public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
checkEntryNotNull(k1, v1);
return RegularImmutableMap.create(1, new Object[] {k1, v1});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
return RegularImmutableMap.create(2, new Object[] {k1, v1, k2, v2});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
return RegularImmutableMap.create(3, new Object[] {k1, v1, k2, v2, k3, v3});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
return RegularImmutableMap.create(4, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
*/
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
checkEntryNotNull(k5, v5);
return RegularImmutableMap.create(5, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
* @since 31.0
*/
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
checkEntryNotNull(k5, v5);
checkEntryNotNull(k6, v6);
return RegularImmutableMap.create(
6, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
* @since 31.0
*/
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
checkEntryNotNull(k5, v5);
checkEntryNotNull(k6, v6);
checkEntryNotNull(k7, v7);
return RegularImmutableMap.create(
7, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
* @since 31.0
*/
public static <K, V> ImmutableMap<K, V> of(
K k1,
V v1,
K k2,
V v2,
K k3,
V v3,
K k4,
V v4,
K k5,
V v5,
K k6,
V v6,
K k7,
V v7,
K k8,
V v8) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
checkEntryNotNull(k5, v5);
checkEntryNotNull(k6, v6);
checkEntryNotNull(k7, v7);
checkEntryNotNull(k8, v8);
return RegularImmutableMap.create(
8, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
* @since 31.0
*/
public static <K, V> ImmutableMap<K, V> of(
K k1,
V v1,
K k2,
V v2,
K k3,
V v3,
K k4,
V v4,
K k5,
V v5,
K k6,
V v6,
K k7,
V v7,
K k8,
V v8,
K k9,
V v9) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
checkEntryNotNull(k5, v5);
checkEntryNotNull(k6, v6);
checkEntryNotNull(k7, v7);
checkEntryNotNull(k8, v8);
checkEntryNotNull(k9, v9);
return RegularImmutableMap.create(
9, new Object[] {k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9});
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
* @since 31.0
*/
public static <K, V> ImmutableMap<K, V> of(
K k1,
V v1,
K k2,
V v2,
K k3,
V v3,
K k4,
V v4,
K k5,
V v5,
K k6,
V v6,
K k7,
V v7,
K k8,
V v8,
K k9,
V v9,
K k10,
V v10) {
checkEntryNotNull(k1, v1);
checkEntryNotNull(k2, v2);
checkEntryNotNull(k3, v3);
checkEntryNotNull(k4, v4);
checkEntryNotNull(k5, v5);
checkEntryNotNull(k6, v6);
checkEntryNotNull(k7, v7);
checkEntryNotNull(k8, v8);
checkEntryNotNull(k9, v9);
checkEntryNotNull(k10, v10);
return RegularImmutableMap.create(
10,
new Object[] {
k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10
});
}
// looking for of() with > 10 entries? Use the builder or ofEntries instead.
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys are provided
* @since 31.0
*/
@SafeVarargs
public static <K, V> ImmutableMap<K, V> ofEntries(Entry<? extends K, ? extends V>... entries) {
@SuppressWarnings("unchecked") // we will only ever read these
Entry<K, V>[] entries2 = (Entry<K, V>[]) entries;
return copyOf(Arrays.asList(entries2));
}
/**
* Verifies that {@code key} and {@code value} are non-null, and returns a new immutable entry
* with those values.
*
* <p>A call to {@link Entry#setValue} on the returned entry will always throw {@link
* UnsupportedOperationException}.
*/
static <K, V> Entry<K, V> entryOf(K key, V value) {
checkEntryNotNull(key, value);
return new AbstractMap.SimpleImmutableEntry<>(key, value);
}
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<>();
}
/**
* Returns a new builder, expecting the specified number of entries to be added.
*
* <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
* Builder#build} is called, the builder is likely to perform better than an unsized {@link
* #builder()} would have.
*
* <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
* but not exactly, the number of entries added to the builder.
*
* @since 23.1
*/
public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<>(expectedSize);
}
static void checkNoConflict(
boolean safe, String conflictDescription, Object entry1, Object entry2) {
if (!safe) {
throw conflictException(conflictDescription, entry1, entry2);
}
}
static IllegalArgumentException conflictException(
String conflictDescription, Object entry1, Object entry2) {
return new IllegalArgumentException(
"Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2);
}
/**
* A builder for creating immutable map instances, especially {@code public static final} maps
* ("constant maps"). Example:
*
* <pre>{@code
* static final ImmutableMap<String, Integer> WORD_TO_INT =
* new ImmutableMap.Builder<String, Integer>()
* .put("one", 1)
* .put("two", 2)
* .put("three", 3)
* .buildOrThrow();
* }</pre>
*
* <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are even more
* convenient.
*
* <p>By default, a {@code Builder} will generate maps that iterate over entries in the order they
* were inserted into the builder, equivalently to {@code LinkedHashMap}. For example, in the
* above example, {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the
* order {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect
* the same order. If you want a different order, consider using {@link ImmutableSortedMap} to
* sort by keys, or call {@link #orderEntriesByValue(Comparator)}, which changes this builder to
* sort entries by value.
*
* <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to
* build multiple maps in series. Each map is a superset of the maps created before it.
*
* @since 2.0
*/
@DoNotMock
public static class Builder<K, V> {
@CheckForNull Comparator<? super V> valueComparator;
@Nullable Object[] alternatingKeysAndValues;
int size;
boolean entriesUsed;
/**
* If non-null, a duplicate key we found in a previous buildKeepingLast() or buildOrThrow()
* call. A later buildOrThrow() can simply report this duplicate immediately.
*/
@Nullable DuplicateKey duplicateKey;
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by {@link
* ImmutableMap#builder}.
*/
public Builder() {
this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY);
}
@SuppressWarnings({"unchecked", "rawtypes"})
Builder(int initialCapacity) {
this.alternatingKeysAndValues = new @Nullable Object[2 * initialCapacity];
this.size = 0;
this.entriesUsed = false;
}
private void ensureCapacity(int minCapacity) {
if (minCapacity * 2 > alternatingKeysAndValues.length) {
alternatingKeysAndValues =
Arrays.copyOf(
alternatingKeysAndValues,
ImmutableCollection.Builder.expandedCapacity(
alternatingKeysAndValues.length, minCapacity * 2));
entriesUsed = false;
}
}
/**
* Associates {@code key} with {@code value} in the built map. If the same key is put more than
* once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep the last
* value put for that key.
*/
@CanIgnoreReturnValue
public Builder<K, V> put(K key, V value) {
ensureCapacity(size + 1);
checkEntryNotNull(key, value);
alternatingKeysAndValues[2 * size] = key;
alternatingKeysAndValues[2 * size + 1] = value;
size++;
return this;
}
/**
* Adds the given {@code entry} to the map, making it immutable if necessary. If the same key is
* put more than once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will
* keep the last value put for that key.
*
* @since 11.0
*/
@CanIgnoreReturnValue
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
return put(entry.getKey(), entry.getValue());
}
/**
* Associates all of the given map's keys and values in the built map. If the same key is put
* more than once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep
* the last value put for that key.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
@CanIgnoreReturnValue
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
return putAll(map.entrySet());
}
/**
* Adds all of the given entries to the built map. If the same key is put more than once, {@link
* #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep the last value put for
* that key.
*
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
@CanIgnoreReturnValue
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
if (entries instanceof Collection) {
ensureCapacity(size + ((Collection<?>) entries).size());
}
for (Entry<? extends K, ? extends V> entry : entries) {
put(entry);
}
return this;
}
/**
* Configures this {@code Builder} to order entries by value according to the specified
* comparator.
*
* <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
* the entry that was inserted first will be first in the built map's iteration order.
*
* @throws IllegalStateException if this method was already called
* @since 19.0
*/
@CanIgnoreReturnValue
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
checkState(this.valueComparator == null, "valueComparator was already set");
this.valueComparator = checkNotNull(valueComparator, "valueComparator");
return this;
}
@CanIgnoreReturnValue
Builder<K, V> combine(Builder<K, V> other) {
checkNotNull(other);
ensureCapacity(this.size + other.size);
System.arraycopy(
other.alternatingKeysAndValues,
0,
this.alternatingKeysAndValues,
this.size * 2,
other.size * 2);
this.size += other.size;
return this;
}
private ImmutableMap<K, V> build(boolean throwIfDuplicateKeys) {
if (throwIfDuplicateKeys && duplicateKey != null) {
throw duplicateKey.exception();
}
/*
* If entries is full, then this implementation may end up using the entries array
* directly and writing over the entry objects with non-terminal entries, but this is
* safe; if this Builder is used further, it will grow the entries array (so it can't
* affect the original array), and future build() calls will always copy any entry
* objects that cannot be safely reused.
*/
// localAlternatingKeysAndValues is an alias for the alternatingKeysAndValues field, except if
// we end up removing duplicates in a copy of the array.
@Nullable Object[] localAlternatingKeysAndValues;
int localSize = size;
if (valueComparator == null) {
localAlternatingKeysAndValues = alternatingKeysAndValues;
} else {
if (entriesUsed) {
alternatingKeysAndValues = Arrays.copyOf(alternatingKeysAndValues, 2 * size);
}
localAlternatingKeysAndValues = alternatingKeysAndValues;
if (!throwIfDuplicateKeys) {
// We want to retain only the last-put value for any given key, before sorting.
// This could be improved, but orderEntriesByValue is rather rarely used anyway.
localAlternatingKeysAndValues = lastEntryForEachKey(localAlternatingKeysAndValues, size);
if (localAlternatingKeysAndValues.length < alternatingKeysAndValues.length) {
localSize = localAlternatingKeysAndValues.length >>> 1;
}
}
sortEntries(localAlternatingKeysAndValues, localSize, valueComparator);
}
entriesUsed = true;
ImmutableMap<K, V> map =
RegularImmutableMap.create(localSize, localAlternatingKeysAndValues, this);
if (throwIfDuplicateKeys && duplicateKey != null) {
throw duplicateKey.exception();
}
return map;
}
/**
* Returns a newly-created immutable map. The iteration order of the returned map is the order
* in which entries were inserted into the builder, unless {@link #orderEntriesByValue} was
* called, in which case entries are sorted by value.
*
* <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method
* will throw an exception if there are duplicate keys. The {@code build()} method will soon be
* deprecated.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableMap<K, V> build() {
return buildOrThrow();
}
/**
* Returns a newly-created immutable map, or throws an exception if any key was added more than
* once. The iteration order of the returned map is the order in which entries were inserted
* into the builder, unless {@link #orderEntriesByValue} was called, in which case entries are
* sorted by value.
*
* @throws IllegalArgumentException if duplicate keys were added
* @since 31.0
*/
public ImmutableMap<K, V> buildOrThrow() {
return build(true);
}
/**
* Returns a newly-created immutable map, using the last value for any key that was added more
* than once. The iteration order of the returned map is the order in which entries were
* inserted into the builder, unless {@link #orderEntriesByValue} was called, in which case
* entries are sorted by value. If a key was added more than once, it appears in iteration order
* based on the first time it was added, again unless {@link #orderEntriesByValue} was called.
*
* <p>In the current implementation, all values associated with a given key are stored in the
* {@code Builder} object, even though only one of them will be used in the built map. If there
* can be many repeated keys, it may be more space-efficient to use a {@link
* java.util.LinkedHashMap LinkedHashMap} and {@link ImmutableMap#copyOf(Map)} rather than
* {@code ImmutableMap.Builder}.
*
* @since 31.1
*/
public ImmutableMap<K, V> buildKeepingLast() {
return build(false);
}
static <V> void sortEntries(
@Nullable Object[] alternatingKeysAndValues,
int size,
Comparator<? super V> valueComparator) {
@SuppressWarnings({"rawtypes", "unchecked"})
Entry<Object, V>[] entries = new Entry[size];
for (int i = 0; i < size; i++) {
// requireNonNull is safe because the first `2*size` elements have been filled in.
Object key = requireNonNull(alternatingKeysAndValues[2 * i]);
@SuppressWarnings("unchecked")
V value = (V) requireNonNull(alternatingKeysAndValues[2 * i + 1]);
entries[i] = new AbstractMap.SimpleImmutableEntry<Object, V>(key, value);
}
Arrays.sort(
entries, 0, size, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
for (int i = 0; i < size; i++) {
alternatingKeysAndValues[2 * i] = entries[i].getKey();
alternatingKeysAndValues[2 * i + 1] = entries[i].getValue();
}
}
private @Nullable Object[] lastEntryForEachKey(
@Nullable Object[] localAlternatingKeysAndValues, int size) {
Set<Object> seenKeys = new HashSet<>();
BitSet dups = new BitSet(); // slots that are overridden by a later duplicate key
for (int i = size - 1; i >= 0; i--) {
Object key = requireNonNull(localAlternatingKeysAndValues[2 * i]);
if (!seenKeys.add(key)) {
dups.set(i);
}
}
if (dups.isEmpty()) {
return localAlternatingKeysAndValues;
}
Object[] newAlternatingKeysAndValues = new Object[(size - dups.cardinality()) * 2];
for (int inI = 0, outI = 0; inI < size * 2; ) {
if (dups.get(inI >>> 1)) {
inI += 2;
} else {
newAlternatingKeysAndValues[outI++] =
requireNonNull(localAlternatingKeysAndValues[inI++]);
newAlternatingKeysAndValues[outI++] =
requireNonNull(localAlternatingKeysAndValues[inI++]);
}
}
return newAlternatingKeysAndValues;
}
static final class DuplicateKey {
private final Object key;
private final Object value1;
private final Object value2;
DuplicateKey(Object key, Object value1, Object value2) {
this.key = key;
this.value1 = value1;
this.value2 = value2;
}
IllegalArgumentException exception() {
return new IllegalArgumentException(
"Multiple entries with same key: " + key + "=" + value1 + " and " + key + "=" + value2);
}
}
}
/**
* Returns an immutable map containing the same entries as {@code map}. The returned map iterates
* over entries in the same order as the {@code entrySet} of the original map. If {@code map}
* somehow contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
* comparator is not <i>consistent with equals</i>), the results of this method are undefined.
*
* <p>Despite the method name, this method attempts to avoid actually copying the data when it is
* safe to do so. The exact circumstances under which a copy will or will not be performed are
* undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
public static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
if ((map instanceof ImmutableMap) && !(map instanceof SortedMap)) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
if (!kvMap.isPartialView()) {
return kvMap;
}
}
return copyOf(map.entrySet());
}
/**
* Returns an immutable map containing the specified entries. The returned map iterates over
* entries in the same order as the original iterable.
*
* @throws NullPointerException if any key, value, or entry is null
* @throws IllegalArgumentException if two entries have the same key
* @since 19.0
*/
public static <K, V> ImmutableMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
int initialCapacity =
(entries instanceof Collection)
? ((Collection<?>) entries).size()
: ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
ImmutableMap.Builder<K, V> builder = new ImmutableMap.Builder<K, V>(initialCapacity);
builder.putAll(entries);
return builder.build();
}
static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0];
abstract static class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> {
abstract UnmodifiableIterator<Entry<K, V>> entryIterator();
@Override
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<>(this);
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
class EntrySetImpl extends ImmutableMapEntrySet<K, V> {
@Override
ImmutableMap<K, V> map() {
return IteratorBasedImmutableMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return entryIterator();
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
return new EntrySetImpl();
}
@Override
ImmutableCollection<V> createValues() {
return new ImmutableMapValues<>(this);
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
ImmutableMap() {}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public final V put(K k, V v) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@CheckForNull
public final V remove(@CheckForNull Object o) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return values().contains(value);
}
// Overriding to mark it Nullable
@Override
@CheckForNull
public abstract V get(@CheckForNull Object key);
/**
* {@inheritDoc}
*
* <p>See <a
* href="https://developer.android.com/reference/java/util/Map.html#getOrDefault%28java.lang.Object,%20V%29">{@code
* Map.getOrDefault}</a>.
*
* @since 23.5 (but since 21.0 in the JRE <a
* href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>).
* Note, however, that Java 8+ users can call this method with any version and flavor of
* Guava.
*/
// @Override under Java 8 / API Level 24
@CheckForNull
public final V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
/*
* Even though it's weird to pass a defaultValue that is null, some callers do so. Those who
* pass a literal "null" should probably just use `get`, but I would expect other callers to
* pass an expression that *might* be null. This could happen with:
*
* - a `getFooOrDefault(@CheckForNull Foo defaultValue)` method that returns
* `map.getOrDefault(FOO_KEY, defaultValue)`
*
* - a call that consults a chain of maps, as in `mapA.getOrDefault(key, mapB.getOrDefault(key,
* ...))`
*
* So it makes sense for the parameter (and thus the return type) to be @CheckForNull.
*
* Two other points:
*
* 1. We'll want to use something like @PolyNull once we can make that work for the various
* platforms we target.
*
* 2. Kotlin's Map type has a getOrDefault method that accepts and returns a "plain V," in
* contrast to the "V?" type that we're using. As a result, Kotlin sees a conflict between the
* nullness annotations in ImmutableMap and those in its own Map type. In response, it considers
* the parameter and return type both to be platform types. As a result, Kotlin permits calls
* that can lead to NullPointerException. That's unfortunate. But hopefully most Kotlin callers
* use `get(key) ?: defaultValue` instead of this method, anyway.
*/
V result = get(key);
// TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker.
if (result != null) {
return result;
} else {
return defaultValue;
}
}
@LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entrySet;
/**
* Returns an immutable set of the mappings in this map. The iteration order is specified by the
* method used to create this map. Typically, this is insertion order.
*/
@Override
public ImmutableSet<Entry<K, V>> entrySet() {
ImmutableSet<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
abstract ImmutableSet<Entry<K, V>> createEntrySet();
@LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<K> keySet;
/**
* Returns an immutable set of the keys in this map, in the same order that they appear in {@link
* #entrySet}.
*/
@Override
public ImmutableSet<K> keySet() {
ImmutableSet<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
/*
* This could have a good default implementation of return new ImmutableKeySet<K, V>(this),
* but ProGuard can't figure out how to eliminate that default when RegularImmutableMap
* overrides it.
*/
abstract ImmutableSet<K> createKeySet();
UnmodifiableIterator<K> keyIterator() {
final UnmodifiableIterator<Entry<K, V>> entryIterator = entrySet().iterator();
return new UnmodifiableIterator<K>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public K next() {
return entryIterator.next().getKey();
}
};
}
@LazyInit @RetainedWith @CheckForNull private transient ImmutableCollection<V> values;
/**
* Returns an immutable collection of the values in this map, in the same order that they appear
* in {@link #entrySet}.
*/
@Override
public ImmutableCollection<V> values() {
ImmutableCollection<V> result = values;
return (result == null) ? values = createValues() : result;
}
/*
* This could have a good default implementation of {@code return new
* ImmutableMapValues<K, V>(this)}, but ProGuard can't figure out how to eliminate that default
* when RegularImmutableMap overrides it.
*/
abstract ImmutableCollection<V> createValues();
// cached so that this.multimapView().inverse() only computes inverse once
@LazyInit @CheckForNull private transient ImmutableSetMultimap<K, V> multimapView;
/**
* Returns a multimap view of the map.
*
* @since 14.0
*/
public ImmutableSetMultimap<K, V> asMultimap() {
if (isEmpty()) {
return ImmutableSetMultimap.of();
}
ImmutableSetMultimap<K, V> result = multimapView;
return (result == null)
? (multimapView =
new ImmutableSetMultimap<>(new MapViewOfValuesAsSingletonSets(), size(), null))
: result;
}
@WeakOuter
private final class MapViewOfValuesAsSingletonSets
extends IteratorBasedImmutableMap<K, ImmutableSet<V>> {
@Override
public int size() {
return ImmutableMap.this.size();
}
@Override
ImmutableSet<K> createKeySet() {
return ImmutableMap.this.keySet();
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return ImmutableMap.this.containsKey(key);
}
@Override
@CheckForNull
public ImmutableSet<V> get(@CheckForNull Object key) {
V outerValue = ImmutableMap.this.get(key);
return (outerValue == null) ? null : ImmutableSet.of(outerValue);
}
@Override
boolean isPartialView() {
return ImmutableMap.this.isPartialView();
}
@Override
public int hashCode() {
// ImmutableSet.of(value).hashCode() == value.hashCode(), so the hashes are the same
return ImmutableMap.this.hashCode();
}
@Override
boolean isHashCodeFast() {
return ImmutableMap.this.isHashCodeFast();
}
@Override
UnmodifiableIterator<Entry<K, ImmutableSet<V>>> entryIterator() {
final Iterator<Entry<K, V>> backingIterator = ImmutableMap.this.entrySet().iterator();
return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() {
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public Entry<K, ImmutableSet<V>> next() {
final Entry<K, V> backingEntry = backingIterator.next();
return new AbstractMapEntry<K, ImmutableSet<V>>() {
@Override
public K getKey() {
return backingEntry.getKey();
}
@Override
public ImmutableSet<V> getValue() {
return ImmutableSet.of(backingEntry.getValue());
}
};
}
};
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
@Override
public boolean equals(@CheckForNull Object object) {
return Maps.equalsImpl(this, object);
}
abstract boolean isPartialView();
@Override
public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
boolean isHashCodeFast() {
return false;
}
@Override
public String toString() {
return Maps.toStringImpl(this);
}
/**
* Serialized type for all ImmutableMap instances. It captures the logical contents and they are
* reconstructed using public factory methods. This ensures that the implementation types remain
* as implementation details.
*/
@J2ktIncompatible // serialization
static class SerializedForm<K, V> implements Serializable {
// This object retains references to collections returned by keySet() and value(). This saves
// bytes when the both the map and its keySet or value collection are written to the same
// instance of ObjectOutputStream.
// TODO(b/160980469): remove support for the old serialization format after some time
private static final boolean USE_LEGACY_SERIALIZATION = true;
private final Object keys;
private final Object values;
SerializedForm(ImmutableMap<K, V> map) {
if (USE_LEGACY_SERIALIZATION) {
Object[] keys = new Object[map.size()];
Object[] values = new Object[map.size()];
int i = 0;
// "extends Object" works around https://github.com/typetools/checker-framework/issues/3013
for (Entry<? extends Object, ? extends Object> entry : map.entrySet()) {
keys[i] = entry.getKey();
values[i] = entry.getValue();
i++;
}
this.keys = keys;
this.values = values;
return;
}
this.keys = map.keySet();
this.values = map.values();
}
@SuppressWarnings("unchecked")
final Object readResolve() {
if (!(this.keys instanceof ImmutableSet)) {
return legacyReadResolve();
}
ImmutableSet<K> keySet = (ImmutableSet<K>) this.keys;
ImmutableCollection<V> values = (ImmutableCollection<V>) this.values;
Builder<K, V> builder = makeBuilder(keySet.size());
UnmodifiableIterator<K> keyIter = keySet.iterator();
UnmodifiableIterator<V> valueIter = values.iterator();
while (keyIter.hasNext()) {
builder.put(keyIter.next(), valueIter.next());
}
return builder.buildOrThrow();
}
@SuppressWarnings("unchecked")
final Object legacyReadResolve() {
K[] keys = (K[]) this.keys;
V[] values = (V[]) this.values;
Builder<K, V> builder = makeBuilder(keys.length);
for (int i = 0; i < keys.length; i++) {
builder.put(keys[i], values[i]);
}
return builder.buildOrThrow();
}
/**
* Returns a builder that builds the unserialized type. Subclasses should override this method.
*/
Builder<K, V> makeBuilder(int size) {
return new Builder<>(size);
}
private static final long serialVersionUID = 0;
}
/**
* Returns a serializable form of this object. Non-public subclasses should not override this
* method. Publicly-accessible subclasses must override this method and should return a subclass
* of SerializedForm whose readResolve() method returns objects of the subclass type.
*/
@J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
@J2ktIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
private static final long serialVersionUID = 0xdecaf;
}
| google/guava | android/guava/src/com/google/common/collect/ImmutableMap.java |
656 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.node;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.action.search.TransportSearchAction;
import org.elasticsearch.bootstrap.BootstrapCheck;
import org.elasticsearch.bootstrap.BootstrapContext;
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.NodeConnectionsService;
import org.elasticsearch.cluster.action.index.MappingUpdatedAction;
import org.elasticsearch.cluster.coordination.CoordinationDiagnosticsService;
import org.elasticsearch.cluster.coordination.Coordinator;
import org.elasticsearch.cluster.metadata.IndexMetadataVerifier;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.version.CompatibilityVersions;
import org.elasticsearch.common.StopWatch;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.logging.NodeAndClusterIdStateListener;
import org.elasticsearch.common.network.NetworkAddress;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.util.concurrent.FutureUtils;
import org.elasticsearch.core.Assertions;
import org.elasticsearch.core.IOUtils;
import org.elasticsearch.core.PathUtils;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.env.BuildVersion;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.NodeMetadata;
import org.elasticsearch.gateway.GatewayMetaState;
import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.gateway.MetaStateService;
import org.elasticsearch.gateway.PersistedClusterStateService;
import org.elasticsearch.health.HealthPeriodicLogger;
import org.elasticsearch.http.HttpServerTransport;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.cluster.IndicesClusterStateService;
import org.elasticsearch.indices.recovery.PeerRecoverySourceService;
import org.elasticsearch.indices.store.IndicesStore;
import org.elasticsearch.monitor.fs.FsHealthService;
import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.monitor.metrics.NodeMetrics;
import org.elasticsearch.node.internal.TerminationHandler;
import org.elasticsearch.plugins.ClusterCoordinationPlugin;
import org.elasticsearch.plugins.ClusterPlugin;
import org.elasticsearch.plugins.MetadataUpgrader;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.PluginsService;
import org.elasticsearch.readiness.ReadinessService;
import org.elasticsearch.repositories.RepositoriesService;
import org.elasticsearch.reservedstate.service.FileSettingsService;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchService;
import org.elasticsearch.snapshots.SnapshotShardsService;
import org.elasticsearch.snapshots.SnapshotsService;
import org.elasticsearch.tasks.TaskCancellationService;
import org.elasticsearch.tasks.TaskManager;
import org.elasticsearch.tasks.TaskResultsService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.RemoteClusterPortSettings;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;
import javax.net.ssl.SNIHostName;
import static org.elasticsearch.core.Strings.format;
/**
* A node represent a node within a cluster ({@code cluster.name}). The {@link #client()} can be used
* in order to use a {@link Client} to perform actions/operations against the cluster.
*/
public class Node implements Closeable {
public static final Setting<Boolean> WRITE_PORTS_FILE_SETTING = Setting.boolSetting("node.portsfile", false, Property.NodeScope);
public static final Setting<String> NODE_NAME_SETTING = Setting.simpleString("node.name", Property.NodeScope);
public static final Setting<String> NODE_EXTERNAL_ID_SETTING = Setting.simpleString(
"node.external_id",
NODE_NAME_SETTING,
Property.NodeScope
);
public static final Setting.AffixSetting<String> NODE_ATTRIBUTES = Setting.prefixKeySetting(
"node.attr.",
(key) -> new Setting<>(key, "", (value) -> {
if (value.length() > 0
&& (Character.isWhitespace(value.charAt(0)) || Character.isWhitespace(value.charAt(value.length() - 1)))) {
throw new IllegalArgumentException(key + " cannot have leading or trailing whitespace [" + value + "]");
}
if (value.length() > 0 && "node.attr.server_name".equals(key)) {
try {
new SNIHostName(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("invalid node.attr.server_name [" + value + "]", e);
}
}
return value;
}, Property.NodeScope)
);
public static final Setting<String> BREAKER_TYPE_KEY = new Setting<>("indices.breaker.type", "hierarchy", (s) -> {
return switch (s) {
case "hierarchy", "none" -> s;
default -> throw new IllegalArgumentException("indices.breaker.type must be one of [hierarchy, none] but was: " + s);
};
}, Setting.Property.NodeScope);
public static final Setting<TimeValue> INITIAL_STATE_TIMEOUT_SETTING = Setting.positiveTimeSetting(
"discovery.initial_state_timeout",
TimeValue.timeValueSeconds(30),
Property.NodeScope
);
public static final Setting<TimeValue> MAXIMUM_SHUTDOWN_TIMEOUT_SETTING = Setting.positiveTimeSetting(
"node.maximum_shutdown_grace_period",
TimeValue.ZERO,
Setting.Property.NodeScope
);
private final Lifecycle lifecycle = new Lifecycle();
/**
* This logger instance is an instance field as opposed to a static field. This ensures that the field is not
* initialized until an instance of Node is constructed, which is sure to happen after the logging infrastructure
* has been initialized to include the hostname. If this field were static, then it would be initialized when the
* class initializer runs. Alas, this happens too early, before logging is initialized as this class is referred to
* in InternalSettingsPreparer#finalizeSettings, which runs when creating the Environment, before logging is
* initialized.
*/
private final Logger logger = LogManager.getLogger(Node.class);
private final Injector injector;
private final Environment environment;
private final NodeEnvironment nodeEnvironment;
private final PluginsService pluginsService;
private final NodeClient client;
private final Collection<LifecycleComponent> pluginLifecycleComponents;
private final LocalNodeFactory localNodeFactory;
private final NodeService nodeService;
private final TerminationHandler terminationHandler;
// for testing
final NamedWriteableRegistry namedWriteableRegistry;
final NamedXContentRegistry namedXContentRegistry;
/**
* Constructs a node
*
* @param environment the initial environment for this node, which will be added to by plugins
*/
public Node(Environment environment) {
this(NodeConstruction.prepareConstruction(environment, new NodeServiceProvider(), true));
}
/**
* Constructs a node using information from {@code construction}
*/
Node(NodeConstruction construction) {
injector = construction.injector();
environment = construction.environment();
nodeEnvironment = construction.nodeEnvironment();
pluginsService = construction.pluginsService();
client = construction.client();
pluginLifecycleComponents = construction.pluginLifecycleComponents();
localNodeFactory = construction.localNodeFactory();
nodeService = construction.nodeService();
terminationHandler = construction.terminationHandler();
namedWriteableRegistry = construction.namedWriteableRegistry();
namedXContentRegistry = construction.namedXContentRegistry();
}
/**
* If the JVM was started with the Elastic APM agent and a config file argument was specified, then
* delete the config file. The agent only reads it once, when supplied in this fashion, and it
* may contain a secret token.
* <p>
* Public for testing only
*/
@SuppressForbidden(reason = "Cannot guarantee that the temp config path is relative to the environment")
public static void deleteTemporaryApmConfig(JvmInfo jvmInfo, BiConsumer<Exception, Path> errorHandler) {
for (String inputArgument : jvmInfo.getInputArguments()) {
if (inputArgument.startsWith("-javaagent:")) {
final String agentArg = inputArgument.substring(11);
final String[] parts = agentArg.split("=", 2);
String APM_AGENT_CONFIG_FILE_REGEX = String.join(
"\\" + File.separator,
".*modules",
"apm",
"elastic-apm-agent-\\d+\\.\\d+\\.\\d+\\.jar"
);
if (parts[0].matches(APM_AGENT_CONFIG_FILE_REGEX)) {
if (parts.length == 2 && parts[1].startsWith("c=")) {
final Path apmConfig = PathUtils.get(parts[1].substring(2));
if (apmConfig.getFileName().toString().matches("^\\.elstcapm\\..*\\.tmp")) {
try {
Files.deleteIfExists(apmConfig);
} catch (IOException e) {
errorHandler.accept(e, apmConfig);
}
}
}
return;
}
}
}
}
/**
* The settings that are used by this node. Contains original settings as well as additional settings provided by plugins.
*/
public Settings settings() {
return this.environment.settings();
}
/**
* A client that can be used to execute actions (operations) against the cluster.
*/
public Client client() {
return client;
}
/**
* Returns the environment of the node
*/
public Environment getEnvironment() {
return environment;
}
/**
* Returns the {@link NodeEnvironment} instance of this node
*/
public NodeEnvironment getNodeEnvironment() {
return nodeEnvironment;
}
/**
* Start the node. If the node is already started, this method is no-op.
*/
public Node start() throws NodeValidationException {
if (lifecycle.moveToStarted() == false) {
return this;
}
logger.info("starting ...");
pluginLifecycleComponents.forEach(LifecycleComponent::start);
if (ReadinessService.enabled(environment)) {
injector.getInstance(ReadinessService.class).start();
}
injector.getInstance(MappingUpdatedAction.class).setClient(client);
injector.getInstance(IndicesService.class).start();
injector.getInstance(IndicesClusterStateService.class).start();
injector.getInstance(SnapshotsService.class).start();
injector.getInstance(SnapshotShardsService.class).start();
injector.getInstance(RepositoriesService.class).start();
injector.getInstance(SearchService.class).start();
injector.getInstance(FsHealthService.class).start();
nodeService.getMonitorService().start();
final ClusterService clusterService = injector.getInstance(ClusterService.class);
final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class);
nodeConnectionsService.start();
clusterService.setNodeConnectionsService(nodeConnectionsService);
injector.getInstance(GatewayService.class).start();
final Coordinator coordinator = injector.getInstance(Coordinator.class);
clusterService.getMasterService().setClusterStatePublisher(coordinator);
// Start the transport service now so the publish address will be added to the local disco node in ClusterService
TransportService transportService = injector.getInstance(TransportService.class);
transportService.getTaskManager().setTaskResultsService(injector.getInstance(TaskResultsService.class));
transportService.getTaskManager().setTaskCancellationService(new TaskCancellationService(transportService));
transportService.start();
assert localNodeFactory.getNode() != null;
assert transportService.getLocalNode().equals(localNodeFactory.getNode())
: "transportService has a different local node than the factory provided";
injector.getInstance(PeerRecoverySourceService.class).start();
// Load (and maybe upgrade) the metadata stored on disk
final GatewayMetaState gatewayMetaState = injector.getInstance(GatewayMetaState.class);
gatewayMetaState.start(
settings(),
transportService,
clusterService,
injector.getInstance(MetaStateService.class),
injector.getInstance(IndexMetadataVerifier.class),
injector.getInstance(MetadataUpgrader.class),
injector.getInstance(PersistedClusterStateService.class),
pluginsService.filterPlugins(ClusterCoordinationPlugin.class).toList(),
injector.getInstance(CompatibilityVersions.class)
);
// TODO: Do not expect that the legacy metadata file is always present https://github.com/elastic/elasticsearch/issues/95211
if (Assertions.ENABLED && DiscoveryNode.isStateless(settings()) == false) {
try {
assert injector.getInstance(MetaStateService.class).loadFullState().v1().isEmpty();
final NodeMetadata nodeMetadata = NodeMetadata.FORMAT.loadLatestState(
logger,
NamedXContentRegistry.EMPTY,
nodeEnvironment.nodeDataPaths()
);
assert nodeMetadata != null;
assert nodeMetadata.nodeVersion().equals(BuildVersion.current());
assert nodeMetadata.nodeId().equals(localNodeFactory.getNode().getId());
} catch (IOException e) {
assert false : e;
}
}
// we load the global state here (the persistent part of the cluster state stored on disk) to
// pass it to the bootstrap checks to allow plugins to enforce certain preconditions based on the recovered state.
final Metadata onDiskMetadata = gatewayMetaState.getPersistedState().getLastAcceptedState().metadata();
assert onDiskMetadata != null : "metadata is null but shouldn't"; // this is never null
validateNodeBeforeAcceptingRequests(
new BootstrapContext(environment, onDiskMetadata),
transportService.boundAddress(),
pluginsService.flatMap(Plugin::getBootstrapChecks).toList()
);
final FileSettingsService fileSettingsService = injector.getInstance(FileSettingsService.class);
fileSettingsService.start();
clusterService.addStateApplier(transportService.getTaskManager());
// start after transport service so the local disco is known
coordinator.start(); // start before cluster service so that it can set initial state on ClusterApplierService
clusterService.start();
assert clusterService.localNode().equals(localNodeFactory.getNode())
: "clusterService has a different local node than the factory provided";
transportService.acceptIncomingRequests();
/*
* CoordinationDiagnosticsService expects to be able to send transport requests and use the cluster state, so it is important to
* start it here after the clusterService and transportService have been started.
*/
injector.getInstance(CoordinationDiagnosticsService.class).start();
coordinator.startInitialJoin();
final TimeValue initialStateTimeout = INITIAL_STATE_TIMEOUT_SETTING.get(settings());
configureNodeAndClusterIdStateListener(clusterService);
if (initialStateTimeout.millis() > 0) {
final ThreadPool thread = injector.getInstance(ThreadPool.class);
ClusterState clusterState = clusterService.state();
ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext());
if (clusterState.nodes().getMasterNodeId() == null) {
logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout);
final CountDownLatch latch = new CountDownLatch(1);
observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
latch.countDown();
}
@Override
public void onClusterServiceClose() {
latch.countDown();
}
@Override
public void onTimeout(TimeValue timeout) {
logger.warn("timed out while waiting for initial discovery state - timeout: {}", initialStateTimeout);
latch.countDown();
}
}, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout);
try {
latch.await();
} catch (InterruptedException e) {
throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state");
}
}
}
injector.getInstance(HttpServerTransport.class).start();
if (WRITE_PORTS_FILE_SETTING.get(settings())) {
TransportService transport = injector.getInstance(TransportService.class);
writePortsFile("transport", transport.boundAddress());
HttpServerTransport http = injector.getInstance(HttpServerTransport.class);
writePortsFile("http", http.boundAddress());
if (ReadinessService.enabled(environment)) {
ReadinessService readiness = injector.getInstance(ReadinessService.class);
readiness.addBoundAddressListener(address -> writePortsFile("readiness", address));
}
if (RemoteClusterPortSettings.REMOTE_CLUSTER_SERVER_ENABLED.get(environment.settings())) {
writePortsFile("remote_cluster", transport.boundRemoteAccessAddress());
}
}
injector.getInstance(NodeMetrics.class).start();
injector.getInstance(HealthPeriodicLogger.class).start();
logger.info("started {}", transportService.getLocalNode());
pluginsService.filterPlugins(ClusterPlugin.class).forEach(ClusterPlugin::onNodeStarted);
return this;
}
protected void configureNodeAndClusterIdStateListener(ClusterService clusterService) {
NodeAndClusterIdStateListener.getAndSetNodeIdAndClusterId(
clusterService,
injector.getInstance(ThreadPool.class).getThreadContext()
);
}
private void stop() {
if (lifecycle.moveToStopped() == false) {
return;
}
logger.info("stopping ...");
if (ReadinessService.enabled(environment)) {
stopIfStarted(ReadinessService.class);
}
// We stop the health periodic logger first since certain checks won't be possible anyway
stopIfStarted(HealthPeriodicLogger.class);
stopIfStarted(FileSettingsService.class);
injector.getInstance(ResourceWatcherService.class).close();
stopIfStarted(HttpServerTransport.class);
stopIfStarted(SnapshotsService.class);
stopIfStarted(SnapshotShardsService.class);
stopIfStarted(RepositoriesService.class);
// stop any changes happening as a result of cluster state changes
stopIfStarted(IndicesClusterStateService.class);
// close cluster coordinator early to not react to pings anymore.
// This can confuse other nodes and delay things - mostly if we're the master and we're running tests.
stopIfStarted(Coordinator.class);
// we close indices first, so operations won't be allowed on it
stopIfStarted(ClusterService.class);
stopIfStarted(NodeConnectionsService.class);
stopIfStarted(FsHealthService.class);
stopIfStarted(nodeService.getMonitorService());
stopIfStarted(GatewayService.class);
stopIfStarted(SearchService.class);
stopIfStarted(TransportService.class);
stopIfStarted(NodeMetrics.class);
pluginLifecycleComponents.forEach(Node::stopIfStarted);
// we should stop this last since it waits for resources to get released
// if we had scroll searchers etc or recovery going on we wait for to finish.
stopIfStarted(IndicesService.class);
logger.info("stopped");
}
private <T extends LifecycleComponent> void stopIfStarted(Class<T> componentClass) {
stopIfStarted(injector.getInstance(componentClass));
}
private static void stopIfStarted(LifecycleComponent component) {
// if we failed during startup then some of our components might not have started yet
if (component.lifecycleState() == Lifecycle.State.STARTED) {
component.stop();
}
}
// During concurrent close() calls we want to make sure that all of them return after the node has completed it's shutdown cycle.
// If not, the hook that is added in Bootstrap#setup() will be useless:
// close() might not be executed, in case another (for example api) call to close() has already set some lifecycles to stopped.
// In this case the process will be terminated even if the first call to close() has not finished yet.
@Override
public synchronized void close() throws IOException {
synchronized (lifecycle) {
if (lifecycle.started()) {
stop();
}
if (lifecycle.moveToClosed() == false) {
return;
}
}
logger.info("closing ...");
List<Closeable> toClose = new ArrayList<>();
StopWatch stopWatch = new StopWatch("node_close");
toClose.add(() -> stopWatch.start("node_service"));
toClose.add(nodeService);
toClose.add(() -> stopWatch.stop().start("http"));
toClose.add(injector.getInstance(HttpServerTransport.class));
toClose.add(() -> stopWatch.stop().start("snapshot_service"));
toClose.add(injector.getInstance(SnapshotsService.class));
toClose.add(injector.getInstance(SnapshotShardsService.class));
toClose.add(injector.getInstance(RepositoriesService.class));
toClose.add(() -> stopWatch.stop().start("indices_cluster"));
toClose.add(injector.getInstance(IndicesClusterStateService.class));
toClose.add(() -> stopWatch.stop().start("indices"));
toClose.add(injector.getInstance(IndicesService.class));
// close filter/fielddata caches after indices
toClose.add(injector.getInstance(IndicesStore.class));
toClose.add(injector.getInstance(PeerRecoverySourceService.class));
toClose.add(() -> stopWatch.stop().start("cluster"));
toClose.add(injector.getInstance(ClusterService.class));
toClose.add(() -> stopWatch.stop().start("node_connections_service"));
toClose.add(injector.getInstance(NodeConnectionsService.class));
toClose.add(() -> stopWatch.stop().start("cluster_coordinator"));
toClose.add(injector.getInstance(Coordinator.class));
toClose.add(() -> stopWatch.stop().start("monitor"));
toClose.add(nodeService.getMonitorService());
toClose.add(() -> stopWatch.stop().start("fsHealth"));
toClose.add(injector.getInstance(FsHealthService.class));
toClose.add(() -> stopWatch.stop().start("gateway"));
toClose.add(injector.getInstance(GatewayService.class));
toClose.add(() -> stopWatch.stop().start("search"));
toClose.add(injector.getInstance(SearchService.class));
toClose.add(() -> stopWatch.stop().start("transport"));
toClose.add(injector.getInstance(TransportService.class));
toClose.add(injector.getInstance(NodeMetrics.class));
if (ReadinessService.enabled(environment)) {
toClose.add(injector.getInstance(ReadinessService.class));
}
toClose.add(injector.getInstance(FileSettingsService.class));
toClose.add(injector.getInstance(HealthPeriodicLogger.class));
for (LifecycleComponent plugin : pluginLifecycleComponents) {
toClose.add(() -> stopWatch.stop().start("plugin(" + plugin.getClass().getName() + ")"));
toClose.add(plugin);
}
pluginsService.filterPlugins(Plugin.class).forEach(toClose::add);
toClose.add(() -> stopWatch.stop().start("script"));
toClose.add(injector.getInstance(ScriptService.class));
toClose.add(() -> stopWatch.stop().start("thread_pool"));
toClose.add(() -> injector.getInstance(ThreadPool.class).shutdown());
// Don't call shutdownNow here, it might break ongoing operations on Lucene indices.
// See https://issues.apache.org/jira/browse/LUCENE-7248. We call shutdownNow in
// awaitClose if the node doesn't finish closing within the specified time.
toClose.add(() -> stopWatch.stop().start("gateway_meta_state"));
toClose.add(injector.getInstance(GatewayMetaState.class));
toClose.add(() -> stopWatch.stop().start("node_environment"));
toClose.add(injector.getInstance(NodeEnvironment.class));
toClose.add(stopWatch::stop);
if (logger.isTraceEnabled()) {
toClose.add(() -> logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint()));
}
IOUtils.close(toClose);
logger.info("closed");
}
/**
* Invokes hooks to prepare this node to be closed. This should be called when Elasticsearch receives a request to shut down
* gracefully from the underlying operating system, before system resources are closed. This method will block
* until the node is ready to shut down.
*
* Note that this class is part of infrastructure to react to signals from the operating system - most graceful shutdown
* logic should use Node Shutdown, see {@link org.elasticsearch.cluster.metadata.NodesShutdownMetadata}.
*/
public void prepareForClose() {
HttpServerTransport httpServerTransport = injector.getInstance(HttpServerTransport.class);
Map<String, Runnable> stoppers = new HashMap<>();
TimeValue maxTimeout = MAXIMUM_SHUTDOWN_TIMEOUT_SETTING.get(this.settings());
stoppers.put("http-server-transport-stop", httpServerTransport::close);
stoppers.put("async-search-stop", () -> this.awaitSearchTasksComplete(maxTimeout));
if (terminationHandler != null) {
stoppers.put("termination-handler-stop", terminationHandler::handleTermination);
}
Map<String, CompletableFuture<Void>> futures = new HashMap<>(stoppers.size());
for (var stopperEntry : stoppers.entrySet()) {
var future = new CompletableFuture<Void>();
new Thread(() -> {
try {
stopperEntry.getValue().run();
} catch (Exception ex) {
logger.warn("unexpected exception in shutdown task [" + stopperEntry.getKey() + "]", ex);
} finally {
future.complete(null);
}
}, stopperEntry.getKey()).start();
futures.put(stopperEntry.getKey(), future);
}
@SuppressWarnings(value = "rawtypes") // Can't make an array of parameterized types, but it complains if you leave the type out
CompletableFuture<Void> allStoppers = CompletableFuture.allOf(futures.values().toArray(new CompletableFuture[stoppers.size()]));
try {
if (TimeValue.ZERO.equals(maxTimeout)) {
FutureUtils.get(allStoppers);
} else {
FutureUtils.get(allStoppers, maxTimeout.millis(), TimeUnit.MILLISECONDS);
}
} catch (ElasticsearchTimeoutException t) {
var unfinishedTasks = futures.entrySet()
.stream()
.filter(entry -> entry.getValue().isDone() == false)
.map(Map.Entry::getKey)
.toList();
logger.warn("timed out while waiting for graceful shutdown tasks: " + unfinishedTasks);
}
}
private void awaitSearchTasksComplete(TimeValue asyncSearchTimeout) {
TaskManager taskManager = injector.getInstance(TransportService.class).getTaskManager();
long millisWaited = 0;
while (true) {
long searchTasksRemaining = taskManager.getTasks()
.values()
.stream()
.filter(task -> TransportSearchAction.TYPE.name().equals(task.getAction()))
.count();
if (searchTasksRemaining == 0) {
logger.debug("all search tasks complete");
return;
} else {
// Let the system work on those searches for a while. We're on a dedicated thread to manage app shutdown, so we
// literally just want to wait and not take up resources on this thread for now. Poll period chosen to allow short
// response times, but checking the tasks list is relatively expensive, and we don't want to waste CPU time we could
// be spending on finishing those searches.
final TimeValue pollPeriod = TimeValue.timeValueMillis(500);
millisWaited += pollPeriod.millis();
if (TimeValue.ZERO.equals(asyncSearchTimeout) == false && millisWaited >= asyncSearchTimeout.millis()) {
logger.warn(
format(
"timed out after waiting [%s] for [%d] search tasks to finish",
asyncSearchTimeout.toString(),
searchTasksRemaining
)
);
return;
}
logger.debug(format("waiting for [%s] search tasks to finish, next poll in [%s]", searchTasksRemaining, pollPeriod));
try {
Thread.sleep(pollPeriod.millis());
} catch (InterruptedException ex) {
logger.warn(
format(
"interrupted while waiting [%s] for [%d] search tasks to finish",
asyncSearchTimeout.toString(),
searchTasksRemaining
)
);
return;
}
}
}
}
/**
* Wait for this node to be effectively closed.
*/
// synchronized to prevent running concurrently with close()
public synchronized boolean awaitClose(long timeout, TimeUnit timeUnit) throws InterruptedException {
if (lifecycle.closed() == false) {
// We don't want to shutdown the threadpool or interrupt threads on a node that is not
// closed yet.
throw new IllegalStateException("Call close() first");
}
ThreadPool threadPool = injector.getInstance(ThreadPool.class);
final boolean terminated = ThreadPool.terminate(threadPool, timeout, timeUnit);
if (terminated) {
// All threads terminated successfully. Because search, recovery and all other operations
// that run on shards run in the threadpool, indices should be effectively closed by now.
if (nodeService.awaitClose(0, TimeUnit.MILLISECONDS) == false) {
throw new IllegalStateException(
"Some shards are still open after the threadpool terminated. "
+ "Something is leaking index readers or store references."
);
}
}
return terminated;
}
/**
* Returns {@code true} if the node is closed.
*/
public boolean isClosed() {
return lifecycle.closed();
}
public Injector injector() {
return this.injector;
}
/**
* Hook for validating the node after network
* services are started but before the cluster service is started
* and before the network service starts accepting incoming network
* requests.
*
* @param context the bootstrap context for this node
* @param boundTransportAddress the network addresses the node is
* bound and publishing to
*/
@SuppressWarnings("unused")
protected void validateNodeBeforeAcceptingRequests(
final BootstrapContext context,
final BoundTransportAddress boundTransportAddress,
List<BootstrapCheck> bootstrapChecks
) throws NodeValidationException {}
/**
* Writes a file to the logs dir containing the ports for the given transport type
*/
private void writePortsFile(String type, BoundTransportAddress boundAddress) {
Path tmpPortsFile = environment.logsFile().resolve(type + ".ports.tmp");
try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, Charset.forName("UTF-8"))) {
for (TransportAddress address : boundAddress.boundAddresses()) {
InetAddress inetAddress = InetAddress.getByName(address.getAddress());
writer.write(NetworkAddress.format(new InetSocketAddress(inetAddress, address.getPort())) + "\n");
}
} catch (IOException e) {
throw new RuntimeException("Failed to write ports file", e);
}
Path portsFile = environment.logsFile().resolve(type + ".ports");
try {
Files.move(tmpPortsFile, portsFile, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
throw new RuntimeException("Failed to rename ports file", e);
}
}
/**
* The {@link PluginsService} used to build this node's components.
*/
protected PluginsService getPluginsService() {
return pluginsService;
}
/**
* Plugins can provide additional settings for the node, but two plugins
* cannot provide the same setting.
* @param pluginMap A map of plugin names to plugin instances
* @param originalSettings The node's original settings, which silently override any setting provided by the plugins.
* @return A {@link Settings} with the merged node and plugin settings
* @throws IllegalArgumentException if two plugins provide the same additional setting key
*/
static Settings mergePluginSettings(Map<String, Plugin> pluginMap, Settings originalSettings) {
Map<String, String> foundSettings = new HashMap<>();
final Settings.Builder builder = Settings.builder();
for (Map.Entry<String, Plugin> entry : pluginMap.entrySet()) {
Settings settings = entry.getValue().additionalSettings();
for (String setting : settings.keySet()) {
String oldPlugin = foundSettings.put(setting, entry.getKey());
if (oldPlugin != null) {
throw new IllegalArgumentException(
"Cannot have additional setting ["
+ setting
+ "] "
+ "in plugin ["
+ entry.getKey()
+ "], already added in plugin ["
+ oldPlugin
+ "]"
);
}
}
builder.put(settings);
}
return builder.put(originalSettings).build();
}
static class LocalNodeFactory implements Function<BoundTransportAddress, DiscoveryNode> {
private final SetOnce<DiscoveryNode> localNode = new SetOnce<>();
private final String persistentNodeId;
private final Settings settings;
LocalNodeFactory(Settings settings, String persistentNodeId) {
this.persistentNodeId = persistentNodeId;
this.settings = settings;
}
@Override
public DiscoveryNode apply(BoundTransportAddress boundTransportAddress) {
localNode.set(DiscoveryNode.createLocal(settings, boundTransportAddress.publishAddress(), persistentNodeId));
return localNode.get();
}
DiscoveryNode getNode() {
assert localNode.get() != null;
return localNode.get();
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/node/Node.java |
658 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Collections.singletonMap;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to {@link Map} instances (including instances of {@link
* SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts {@link Lists}, {@link Sets}
* and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#maps">{@code Maps}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Isaac Shum
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Maps {
private Maps() {}
private enum EntryFunction implements Function<Entry<?, ?>, @Nullable Object> {
KEY {
@Override
@CheckForNull
public Object apply(Entry<?, ?> entry) {
return entry.getKey();
}
},
VALUE {
@Override
@CheckForNull
public Object apply(Entry<?, ?> entry) {
return entry.getValue();
}
};
}
@SuppressWarnings("unchecked")
static <K extends @Nullable Object> Function<Entry<K, ?>, K> keyFunction() {
return (Function) EntryFunction.KEY;
}
@SuppressWarnings("unchecked")
static <V extends @Nullable Object> Function<Entry<?, V>, V> valueFunction() {
return (Function) EntryFunction.VALUE;
}
static <K extends @Nullable Object, V extends @Nullable Object> Iterator<K> keyIterator(
Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, K>(entryIterator) {
@Override
@ParametricNullness
K transform(Entry<K, V> entry) {
return entry.getKey();
}
};
}
static <K extends @Nullable Object, V extends @Nullable Object> Iterator<V> valueIterator(
Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, V>(entryIterator) {
@Override
@ParametricNullness
V transform(Entry<K, V> entry) {
return entry.getValue();
}
};
}
/**
* Returns an immutable map instance containing the given entries. Internally, the returned map
* will be backed by an {@link EnumMap}.
*
* <p>The iteration order of the returned map follows the enum's iteration order, not the order in
* which the elements appear in the given map.
*
* @param map the map to make an immutable copy of
* @return an immutable map containing those entries
* @since 14.0
*/
@GwtCompatible(serializable = true)
public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
Map<K, ? extends V> map) {
if (map instanceof ImmutableEnumMap) {
@SuppressWarnings("unchecked") // safe covariant cast
ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map;
return result;
}
Iterator<? extends Entry<K, ? extends V>> entryItr = map.entrySet().iterator();
if (!entryItr.hasNext()) {
return ImmutableMap.of();
}
Entry<K, ? extends V> entry1 = entryItr.next();
K key1 = entry1.getKey();
V value1 = entry1.getValue();
checkEntryNotNull(key1, value1);
// Do something that works for j2cl, where we can't call getDeclaredClass():
EnumMap<K, V> enumMap = new EnumMap<>(singletonMap(key1, value1));
while (entryItr.hasNext()) {
Entry<K, ? extends V> entry = entryItr.next();
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
enumMap.put(key, value);
}
return ImmutableEnumMap.asImmutable(enumMap);
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements. The
* resulting implementation is specialized for enum key types. The returned map and its views will
* iterate over keys in their enum definition order, not encounter order.
*
* <p>If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when
* the collection operation is performed. (This differs from the {@code Collector} returned by
* {@link java.util.stream.Collectors#toMap(java.util.function.Function,
* java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code
* IllegalStateException}.)
*
* @since 21.0
*/
public static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
java.util.function.Function<? super T, ? extends K> keyFunction,
java.util.function.Function<? super T, ? extends V> valueFunction) {
return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction);
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements. The
* resulting implementation is specialized for enum key types. The returned map and its views will
* iterate over keys in their enum definition order, not encounter order.
*
* <p>If the mapped keys contain duplicates, the values are merged using the specified merging
* function.
*
* @since 21.0
*/
public static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
java.util.function.Function<? super T, ? extends K> keyFunction,
java.util.function.Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction, mergeFunction);
}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code HashMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code HashMap}
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
HashMap<K, V> newHashMap() {
return new HashMap<>();
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link #newEnumMap} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code HashMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code map}
*/
public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMap(
Map<? extends K, ? extends V> map) {
return new HashMap<>(map);
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i>
* hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed,
* but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method
* isn't inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries
* without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
* larger than expectedSize and the load factor is ≥ its default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkNonnegative(expectedSize, "expectedSize");
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
// This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap
// ends up being used to compute a "threshold" size, beyond which the internal table
// will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where
// loadFactor is 0.75 by default. So with the calculation here we ensure that the
// threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code
// path when the first operation on the new map is putAll(otherMap). There, prior to
// https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug
// meant that sometimes a too-large threshold is calculated. However, this new threshold is
// independent of the initial capacity, except that it won't be lower than the threshold
// computed from that capacity. Because the internal table is only allocated on the first
// write, we won't see copying because of the new threshold. So it is always OK to use the
// calculation here.
return (int) Math.ceil(expectedSize / 0.75);
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedHashMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<>();
}
/**
* Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance with the same
* mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedHashMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from {@code map}
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
return new LinkedHashMap<>(map);
}
/**
* Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
* broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
* that the method isn't inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize}
* entries without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 19.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
return new LinkedHashMap<>(capacity(expectedSize));
}
/**
* Creates a new empty {@link ConcurrentHashMap} instance.
*
* @since 3.0
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new ConcurrentHashMap<>();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its
* elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedMap#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code TreeMap}
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <K extends Comparable, V extends @Nullable Object> TreeMap<K, V> newTreeMap() {
return new TreeMap<>();
}
/**
* Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as the specified map
* and using the same ordering as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the sorted map whose mappings are to be placed in the new map and whose comparator
* is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code map} and using the
* comparator of {@code map}
*/
public static <K extends @Nullable Object, V extends @Nullable Object> TreeMap<K, V> newTreeMap(
SortedMap<K, ? extends V> map) {
return new TreeMap<>(map);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static <C extends @Nullable Object, K extends C, V extends @Nullable Object>
TreeMap<K, V> newTreeMap(@CheckForNull Comparator<C> comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator<Class<?>> comparator = null;
// Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
return new TreeMap<>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap(
Class<K> type) {
return new EnumMap<>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code EnumMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} instance and contains
* no mappings
*/
public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap(
Map<K, ? extends V> map) {
return new EnumMap<>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code IdentityHashMap} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<>();
}
/**
* Computes the difference between two maps. This difference is an immutable snapshot of the state
* of the maps at the time this method is called. It will never change, even if the maps change at
* a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
* must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
*
* <p><b>Note:</b>If you only need to know whether two maps have the same mappings, call {@code
* left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
@SuppressWarnings("unchecked")
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
return difference(sortedLeft, right);
}
return difference(left, right, Equivalence.equals());
}
/**
* Computes the difference between two maps. This difference is an immutable snapshot of the state
* of the maps at the time this method is called. It will never change, even if the maps change at
* a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
* must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @param valueEquivalence the equivalence relationship to use to compare values
* @return the difference between the two maps
* @since 10.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
MapDifference<K, V> difference(
Map<? extends K, ? extends V> left,
Map<? extends K, ? extends V> right,
Equivalence<? super @NonNull V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newLinkedHashMap();
Map<K, V> onlyOnRight = new LinkedHashMap<>(right); // will whittle it down
Map<K, V> onBoth = newLinkedHashMap();
Map<K, MapDifference.ValueDifference<V>> differences = newLinkedHashMap();
doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
return new MapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
/**
* Computes the difference between two sorted maps, using the comparator of the left map, or
* {@code Ordering.natural()} if the left map uses the natural ordering of its elements. This
* difference is an immutable snapshot of the state of the maps at the time this method is called.
* It will never change, even if the maps change at a later time.
*
* <p>Since this method uses {@code TreeMap} instances internally, the keys of the right map must
* all compare as distinct according to the comparator of the left map.
*
* <p><b>Note:</b>If you only need to know whether two sorted maps have the same mappings, call
* {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
SortedMapDifference<K, V> difference(
SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator<? super K> comparator = orNaturalOrder(left.comparator());
SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator);
doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K extends @Nullable Object, V extends @Nullable Object> void doDifference(
Map<? extends K, ? extends V> left,
Map<? extends K, ? extends V> right,
Equivalence<? super @NonNull V> valueEquivalence,
Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight,
Map<K, V> onBoth,
Map<K, MapDifference.ValueDifference<V>> differences) {
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
/*
* The cast is safe because onlyOnRight contains all the keys of right.
*
* TODO(cpovirk): Consider checking onlyOnRight.containsKey instead of right.containsKey.
* That could change behavior if the input maps use different equivalence relations (and so
* a key that appears once in `right` might appear multiple times in `left`). We don't
* guarantee behavior in that case, anyway, and the current behavior is likely undesirable.
* So that's either a reason to feel free to change it or a reason to not bother thinking
* further about this.
*/
V rightValue = uncheckedCastNullableTToT(onlyOnRight.remove(leftKey));
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
onlyOnLeft.put(leftKey, leftValue);
}
}
}
private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> unmodifiableMap(
Map<K, ? extends V> map) {
if (map instanceof SortedMap) {
return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
} else {
return Collections.unmodifiableMap(map);
}
}
static class MapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object>
implements MapDifference<K, V> {
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(
Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight,
Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.onlyOnLeft = unmodifiableMap(onlyOnLeft);
this.onlyOnRight = unmodifiableMap(onlyOnRight);
this.onBoth = unmodifiableMap(onBoth);
this.differences = unmodifiableMap(differences);
}
@Override
public boolean areEqual() {
return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty();
}
@Override
public Map<K, V> entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map<K, V> entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map<K, V> entriesInCommon() {
return onBoth;
}
@Override
public Map<K, ValueDifference<V>> entriesDiffering() {
return differences;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference<?, ?> other = (MapDifference<?, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(
entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering());
}
@Override
public String toString() {
if (areEqual()) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl<V extends @Nullable Object>
implements MapDifference.ValueDifference<V> {
@ParametricNullness private final V left;
@ParametricNullness private final V right;
static <V extends @Nullable Object> ValueDifference<V> create(
@ParametricNullness V left, @ParametricNullness V right) {
return new ValueDifferenceImpl<>(left, right);
}
private ValueDifferenceImpl(@ParametricNullness V left, @ParametricNullness V right) {
this.left = left;
this.right = right;
}
@Override
@ParametricNullness
public V leftValue() {
return left;
}
@Override
@ParametricNullness
public V rightValue() {
return right;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof MapDifference.ValueDifference) {
MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(left, right);
}
@Override
public String toString() {
return "(" + left + ", " + right + ")";
}
}
static class SortedMapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object>
extends MapDifferenceImpl<K, V> implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(
SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight,
SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override
public SortedMap<K, ValueDifference<V>> entriesDiffering() {
return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
}
@Override
public SortedMap<K, V> entriesInCommon() {
return (SortedMap<K, V>) super.entriesInCommon();
}
@Override
public SortedMap<K, V> entriesOnlyOnLeft() {
return (SortedMap<K, V>) super.entriesOnlyOnLeft();
}
@Override
public SortedMap<K, V> entriesOnlyOnRight() {
return (SortedMap<K, V>) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code Ordering.natural()}.
* This method is an abomination of generics; the only purpose of this method is to contain the
* ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static <E extends @Nullable Object> Comparator<? super E> orNaturalOrder(
@CheckForNull Comparator<? super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator<E>) Ordering.natural();
}
/**
* Returns a live {@link Map} view whose keys are the contents of {@code set} and whose values are
* computed on demand using {@code function}. To get an immutable <i>copy</i> instead, use {@link
* #toMap(Iterable, Function)}.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
* <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> asMap(
Set<K> set, Function<? super K, V> function) {
return new AsMapView<>(set, function);
}
/**
* Returns a view of the sorted set as a map, mapping keys from the set according to the specified
* function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
* <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> asMap(
SortedSet<K> set, Function<? super K, V> function) {
return new SortedAsMapView<>(set, function);
}
/**
* Returns a view of the navigable set as a map, mapping keys from the set according to the
* specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
* <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> asMap(
NavigableSet<K> set, Function<? super K, V> function) {
return new NavigableAsMapView<>(set, function);
}
private static class AsMapView<K extends @Nullable Object, V extends @Nullable Object>
extends ViewCachingAbstractMap<K, V> {
private final Set<K> set;
final Function<? super K, V> function;
Set<K> backingSet() {
return set;
}
AsMapView(Set<K> set, Function<? super K, V> function) {
this.set = checkNotNull(set);
this.function = checkNotNull(function);
}
@Override
public Set<K> createKeySet() {
return removeOnlySet(backingSet());
}
@Override
Collection<V> createValues() {
return Collections2.transform(set, function);
}
@Override
public int size() {
return backingSet().size();
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return backingSet().contains(key);
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return getOrDefault(key, null);
}
@Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
if (Collections2.safeContains(backingSet(), key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return defaultValue;
}
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
if (backingSet().remove(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
backingSet().clear();
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends EntrySet<K, V> {
@Override
Map<K, V> map() {
return AsMapView.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return asMapEntryIterator(backingSet(), function);
}
}
return new EntrySetImpl();
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
// avoids allocation of entries
backingSet().forEach(k -> action.accept(k, function.apply(k)));
}
}
static <K extends @Nullable Object, V extends @Nullable Object>
Iterator<Entry<K, V>> asMapEntryIterator(Set<K> set, final Function<? super K, V> function) {
return new TransformedIterator<K, Entry<K, V>>(set.iterator()) {
@Override
Entry<K, V> transform(@ParametricNullness final K key) {
return immutableEntry(key, function.apply(key));
}
};
}
private static class SortedAsMapView<K extends @Nullable Object, V extends @Nullable Object>
extends AsMapView<K, V> implements SortedMap<K, V> {
SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) {
super(set, function);
}
@Override
SortedSet<K> backingSet() {
return (SortedSet<K>) super.backingSet();
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return backingSet().comparator();
}
@Override
public Set<K> keySet() {
return removeOnlySortedSet(backingSet());
}
@Override
public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return asMap(backingSet().subSet(fromKey, toKey), function);
}
@Override
public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
return asMap(backingSet().headSet(toKey), function);
}
@Override
public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
return asMap(backingSet().tailSet(fromKey), function);
}
@Override
@ParametricNullness
public K firstKey() {
return backingSet().first();
}
@Override
@ParametricNullness
public K lastKey() {
return backingSet().last();
}
}
@GwtIncompatible // NavigableMap
private static final class NavigableAsMapView<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractNavigableMap<K, V> {
/*
* Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the
* NavigableMap methods.
*/
private final NavigableSet<K> set;
private final Function<? super K, V> function;
NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) {
this.set = checkNotNull(ks);
this.function = checkNotNull(vFunction);
}
@Override
public NavigableMap<K, V> subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function);
}
@Override
public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
return asMap(set.headSet(toKey, inclusive), function);
}
@Override
public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
return asMap(set.tailSet(fromKey, inclusive), function);
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return set.comparator();
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return getOrDefault(key, null);
}
@Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
if (Collections2.safeContains(set, key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return defaultValue;
}
}
@Override
public void clear() {
set.clear();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return asMapEntryIterator(set, function);
}
@Override
Spliterator<Entry<K, V>> entrySpliterator() {
return CollectSpliterators.map(set.spliterator(), e -> immutableEntry(e, function.apply(e)));
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
set.forEach(k -> action.accept(k, function.apply(k)));
}
@Override
Iterator<Entry<K, V>> descendingEntryIterator() {
return descendingMap().entrySet().iterator();
}
@Override
public NavigableSet<K> navigableKeySet() {
return removeOnlyNavigableSet(set);
}
@Override
public int size() {
return set.size();
}
@Override
public NavigableMap<K, V> descendingMap() {
return asMap(set.descendingSet(), function);
}
}
private static <E extends @Nullable Object> Set<E> removeOnlySet(final Set<E> set) {
return new ForwardingSet<E>() {
@Override
protected Set<E> delegate() {
return set;
}
@Override
public boolean add(@ParametricNullness E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
};
}
private static <E extends @Nullable Object> SortedSet<E> removeOnlySortedSet(
final SortedSet<E> set) {
return new ForwardingSortedSet<E>() {
@Override
protected SortedSet<E> delegate() {
return set;
}
@Override
public boolean add(@ParametricNullness E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(@ParametricNullness E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet<E> subSet(
@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
};
}
@GwtIncompatible // NavigableSet
private static <E extends @Nullable Object> NavigableSet<E> removeOnlyNavigableSet(
final NavigableSet<E> set) {
return new ForwardingNavigableSet<E>() {
@Override
protected NavigableSet<E> delegate() {
return set;
}
@Override
public boolean add(@ParametricNullness E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(@ParametricNullness E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return removeOnlyNavigableSet(super.headSet(toElement, inclusive));
}
@Override
public SortedSet<E> subSet(
@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return removeOnlyNavigableSet(
super.subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive));
}
@Override
public NavigableSet<E> descendingSet() {
return removeOnlyNavigableSet(super.descendingSet());
}
};
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
* for each key was computed by {@code valueFunction}. The map's iteration order is the order of
* the first appearance of each key in {@code keys}.
*
* <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
* valueFunction} will be applied to more than one instance of that key and, if it is, which
* result will be mapped to that key in the returned map.
*
* <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of a copy using {@link
* Maps#asMap(Set, Function)}.
*
* @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public static <K, V> ImmutableMap<K, V> toMap(
Iterable<K> keys, Function<? super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
* for each key was computed by {@code valueFunction}. The map's iteration order is the order of
* the first appearance of each key in {@code keys}.
*
* <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
* valueFunction} will be applied to more than one instance of that key and, if it is, which
* result will be mapped to that key in the returned map.
*
* @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public static <K, V> ImmutableMap<K, V> toMap(
Iterator<K> keys, Function<? super K, V> valueFunction) {
checkNotNull(valueFunction);
ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (keys.hasNext()) {
K key = keys.next();
builder.put(key, valueFunction.apply(key));
}
// Using buildKeepingLast() so as not to fail on duplicate keys
return builder.buildKeepingLast();
}
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* <pre>{@code
* Color red = new Color("red", 255, 0, 0);
* ...
* ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue);
*
* ImmutableMap<String, Color> colorForName =
* uniqueIndex(allColors, c -> c.toString());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterable, Function) Multimaps.index}.
*
* <p><b>Note:</b> on Java 8+, it is usually better to use streams. For example:
*
* <pre>{@code
* import static com.google.common.collect.ImmutableMap.toImmutableMap;
* ...
* ImmutableMap<String, Color> colorForName =
* allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c));
* }</pre>
*
* <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys
* and values in the map are.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
*/
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
if (values instanceof Collection) {
return uniqueIndex(
values.iterator(),
keyFunction,
ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size()));
}
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* <pre>{@code
* Color red = new Color("red", 255, 0, 0);
* ...
* Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator();
*
* Map<String, Color> colorForName =
* uniqueIndex(allColors, toStringFunction());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterator, Function) Multimaps.index}.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
* @since 10.0
*/
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
return uniqueIndex(values, keyFunction, ImmutableMap.builder());
}
private static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) {
checkNotNull(keyFunction);
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
try {
return builder.buildOrThrow();
} catch (IllegalArgumentException duplicateKeys) {
throw new IllegalArgumentException(
duplicateKeys.getMessage()
+ ". To index multiple values under a key, use Multimaps.index.");
}
}
/**
* Creates an {@code ImmutableMap<String, String>} from a {@code Properties} instance. Properties
* normally derive from {@code Map<Object, Object>}, but they typically contain strings, which is
* awkward. This method lets you get a plain-old-{@code Map} out of a {@code Properties}.
*
* @param properties a {@code Properties} object to be converted
* @return an immutable map containing all the entries in {@code properties}
* @throws ClassCastException if any key in {@code properties} is not a {@code String}
* @throws NullPointerException if any key or value in {@code properties} is null
*/
@J2ktIncompatible
@GwtIncompatible // java.util.Properties
public static ImmutableMap<String, String> fromProperties(Properties properties) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
/*
* requireNonNull is safe because propertyNames contains only non-null elements.
*
* Accordingly, we have it annotated as returning `Enumeration<? extends Object>` in our
* prototype checker's JDK. However, the checker still sees the return type as plain
* `Enumeration<?>`, probably because of one of the following two bugs (and maybe those two
* bugs are themselves just symptoms of the same underlying problem):
*
* https://github.com/typetools/checker-framework/issues/3030
*
* https://github.com/typetools/checker-framework/issues/3236
*/
String key = (String) requireNonNull(e.nextElement());
/*
* requireNonNull is safe because the key came from propertyNames...
*
* ...except that it's possible for users to insert a string key with a non-string value, and
* in that case, getProperty *will* return null.
*
* TODO(b/192002623): Handle that case: Either:
*
* - Skip non-string keys and values entirely, as proposed in the linked bug.
*
* - Throw ClassCastException instead of NullPointerException, as documented in the current
* Javadoc. (Note that we can't necessarily "just" change our call to `getProperty` to `get`
* because `get` does not consult the default properties.)
*/
builder.put(key, requireNonNull(properties.getProperty(key)));
}
return builder.buildOrThrow();
}
/**
* Returns an immutable map entry with the specified key and value. The {@link Entry#setValue}
* operation throws an {@link UnsupportedOperationException}.
*
* <p>The returned entry is serializable.
*
* <p><b>Java 9 users:</b> consider using {@code java.util.Map.entry(key, value)} if the key and
* value are non-null and the entry does not need to be serializable.
*
* @param key the key to be associated with the returned entry
* @param value the value to be associated with the returned entry
*/
@GwtCompatible(serializable = true)
public static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> immutableEntry(
@ParametricNullness K key, @ParametricNullness V value) {
return new ImmutableEntry<>(key, value);
}
/**
* Returns an unmodifiable view of the specified set of entries. The {@link Entry#setValue}
* operation throws an {@link UnsupportedOperationException}, as do any operations that would
* modify the returned set.
*
* @param entrySet the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
static <K extends @Nullable Object, V extends @Nullable Object>
Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet) {
return new UnmodifiableEntrySet<>(Collections.unmodifiableSet(entrySet));
}
/**
* Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation
* throws an {@link UnsupportedOperationException}. This also has the side effect of redefining
* {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation
* of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> unmodifiableEntry(
final Entry<? extends K, ? extends V> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, V>() {
@Override
@ParametricNullness
public K getKey() {
return entry.getKey();
}
@Override
@ParametricNullness
public V getValue() {
return entry.getValue();
}
};
}
static <K extends @Nullable Object, V extends @Nullable Object>
UnmodifiableIterator<Entry<K, V>> unmodifiableEntryIterator(
final Iterator<Entry<K, V>> entryIterator) {
return new UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Entry<K, V> next() {
return unmodifiableEntry(entryIterator.next());
}
};
}
/** The implementation of {@link Multimaps#unmodifiableEntries}. */
static class UnmodifiableEntries<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
UnmodifiableEntries(Collection<Entry<K, V>> entries) {
this.entries = entries;
}
@Override
protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return unmodifiableEntryIterator(entries.iterator());
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override
public @Nullable Object[] toArray() {
/*
* standardToArray returns `@Nullable Object[]` rather than `Object[]` but because it can
* be used with collections that may contain null. This collection never contains nulls, so we
* could return `Object[]`. But this class is private and J2KT cannot change return types in
* overrides, so we declare `@Nullable Object[]` as the return type.
*/
return standardToArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return standardToArray(array);
}
}
/** The implementation of {@link Maps#unmodifiableEntrySet(Set)}. */
static class UnmodifiableEntrySet<K extends @Nullable Object, V extends @Nullable Object>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
super(entries);
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override
public boolean equals(@CheckForNull Object object) {
return Sets.equalsImpl(this, object);
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/**
* Returns a {@link Converter} that converts values using {@link BiMap#get bimap.get()}, and whose
* inverse view converts values using {@link BiMap#inverse bimap.inverse()}{@code .get()}.
*
* <p>To use a plain {@link Map} as a {@link Function}, see {@link
* com.google.common.base.Functions#forMap(Map)} or {@link
* com.google.common.base.Functions#forMap(Map, Object)}.
*
* @since 16.0
*/
public static <A, B> Converter<A, B> asConverter(final BiMap<A, B> bimap) {
return new BiMapConverter<>(bimap);
}
private static final class BiMapConverter<A, B> extends Converter<A, B> implements Serializable {
private final BiMap<A, B> bimap;
BiMapConverter(BiMap<A, B> bimap) {
this.bimap = checkNotNull(bimap);
}
@Override
protected B doForward(A a) {
return convert(bimap, a);
}
@Override
protected A doBackward(B b) {
return convert(bimap.inverse(), b);
}
private static <X, Y> Y convert(BiMap<X, Y> bimap, X input) {
Y output = bimap.get(input);
checkArgument(output != null, "No non-null mapping present for input: %s", input);
return output;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof BiMapConverter) {
BiMapConverter<?, ?> that = (BiMapConverter<?, ?>) object;
return this.bimap.equals(that.bimap);
}
return false;
}
@Override
public int hashCode() {
return bimap.hashCode();
}
// There's really no good way to implement toString() without printing the entire BiMap, right?
@Override
public String toString() {
return "Maps.asConverter(" + bimap + ")";
}
private static final long serialVersionUID = 0L;
}
/**
* Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee
* serial access, it is critical that <b>all</b> access to the backing bimap is accomplished
* through the returned bimap.
*
* <p>It is imperative that the user manually synchronize on the returned map when accessing any
* of its collection views:
*
* <pre>{@code
* BiMap<Long, String> map = Maps.synchronizedBiMap(
* HashBiMap.<Long, String>create());
* ...
* Set<Long> set = map.keySet(); // Needn't be in synchronized block
* ...
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<Long> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned bimap will be serializable if the specified bimap is serializable.
*
* @param bimap the bimap to be wrapped in a synchronized view
* @return a synchronized view of the specified bimap
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
return Synchronized.biMap(bimap, null);
}
/**
* Returns an unmodifiable view of the specified bimap. This method allows modules to provide
* users with "read-only" access to internal bimaps. Query operations on the returned bimap "read
* through" to the specified bimap, and attempts to modify the returned map, whether direct or via
* its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned bimap will be serializable if the specified bimap is serializable.
*
* @param bimap the bimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified bimap
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) {
return new UnmodifiableBiMap<>(bimap, null);
}
/**
* @see Maps#unmodifiableBiMap(BiMap)
*/
private static class UnmodifiableBiMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
@LazyInit @RetainedWith @CheckForNull BiMap<V, K> inverse;
@LazyInit @CheckForNull transient Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @CheckForNull BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
this.delegate = delegate;
this.inverse = inverse;
}
@Override
protected Map<K, V> delegate() {
return unmodifiableMap;
}
@Override
@CheckForNull
public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
throw new UnsupportedOperationException();
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V putIfAbsent(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V replace(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(
K key, java.util.function.Function<? super K, ? extends V> mappingFunction) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
/*
* Our checker arguably should produce a nullness error here until we see @NonNull in JDK APIs.
* But it doesn't, which may be a sign that we still permit parameter contravariance in some
* cases?
*/
public V computeIfPresent(
K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V compute(
K key,
BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
@SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs
public V merge(
K key,
@NonNull V value,
BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> function) {
throw new UnsupportedOperationException();
}
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null)
? inverse = new UnmodifiableBiMap<>(delegate.inverse(), this)
: result;
}
@Override
public Set<V> values() {
Set<V> result = values;
return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a view of a map where each value is transformed by a function. All other properties of
* the map, such as iteration order, are left intact. For example, the code:
*
* <pre>{@code
* Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* Map<String, Double> transformed = Maps.transformValues(map, sqrt);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed map might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
* view, copy the returned map into a new map of your choosing.
*/
public static <
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a sorted map where each value is transformed by a function. All other
* properties of the map, such as iteration order, are left intact. For example, the code:
*
* <pre>{@code
* SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* SortedMap<String, Double> transformed =
* Maps.transformValues(map, sqrt);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed map might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
* view, copy the returned map into a new map of your choosing.
*
* @since 11.0
*/
public static <
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a navigable map where each value is transformed by a function. All other
* properties of the map, such as iteration order, are left intact. For example, the code:
*
* <pre>{@code
* NavigableMap<String, Integer> map = Maps.newTreeMap();
* map.put("a", 4);
* map.put("b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* NavigableMap<String, Double> transformed =
* Maps.transformNavigableValues(map, sqrt);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed map might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
* view, copy the returned map into a new map of your choosing.
*
* @since 13.0
*/
@GwtIncompatible // NavigableMap
public static <
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
NavigableMap<K, V2> transformValues(
NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a map whose values are derived from the original map's entries. In contrast
* to {@link #transformValues}, this method's entry-transformation logic may depend on the key as
* well as the value.
*
* <p>All other properties of the transformed map, such as iteration order, are left intact. For
* example, the code:
*
* <pre>{@code
* Map<String, Boolean> options =
* ImmutableMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "no" + key;
* }
* };
* Map<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {verbose=verbose, sort=nosort}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null values provided that
* the transformer is capable of accepting null inputs. The transformed map might contain null
* values if the transformer sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
* map to be a view, but it means that the transformer will be applied many times for bulk
* operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
* doesn't need to be a view, copy the returned map into a new map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
* EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
* transformed map.
*
* @since 7.0
*/
public static <
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
Map<K, V2> transformEntries(
Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesMap<>(fromMap, transformer);
}
/**
* Returns a view of a sorted map whose values are derived from the original sorted map's entries.
* In contrast to {@link #transformValues}, this method's entry-transformation logic may depend on
* the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order, are left intact. For
* example, the code:
*
* <pre>{@code
* Map<String, Boolean> options =
* ImmutableSortedMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "yes" + key;
* }
* };
* SortedMap<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null values provided that
* the transformer is capable of accepting null inputs. The transformed map might contain null
* values if the transformer sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
* map to be a view, but it means that the transformer will be applied many times for bulk
* operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
* doesn't need to be a view, copy the returned map into a new map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
* EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
* transformed map.
*
* @since 11.0
*/
public static <
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
SortedMap<K, V2> transformEntries(
SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesSortedMap<>(fromMap, transformer);
}
/**
* Returns a view of a navigable map whose values are derived from the original navigable map's
* entries. In contrast to {@link #transformValues}, this method's entry-transformation logic may
* depend on the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order, are left intact. For
* example, the code:
*
* <pre>{@code
* NavigableMap<String, Boolean> options = Maps.newTreeMap();
* options.put("verbose", false);
* options.put("sort", true);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : ("yes" + key);
* }
* };
* NavigableMap<String, String> transformed =
* LabsMaps.transformNavigableEntries(options, flagPrefixer);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null values provided that
* the transformer is capable of accepting null inputs. The transformed map might contain null
* values if the transformer sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
* map to be a view, but it means that the transformer will be applied many times for bulk
* operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
* doesn't need to be a view, copy the returned map into a new map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
* EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
* transformed map.
*
* @since 13.0
*/
@GwtIncompatible // NavigableMap
public static <
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
NavigableMap<K, V2> transformEntries(
NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesNavigableMap<>(fromMap, transformer);
}
/**
* A transformation of the value of a key-value pair, using both key and value as inputs. To apply
* the transformation to a map, use {@link Maps#transformEntries(Map, EntryTransformer)}.
*
* @param <K> the key type of the input and output entries
* @param <V1> the value type of the input entry
* @param <V2> the value type of the output entry
* @since 7.0
*/
@FunctionalInterface
public interface EntryTransformer<
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> {
/**
* Determines an output value based on a key-value pair. This method is <i>generally
* expected</i>, but not absolutely required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (k1, k2) &&} {@link Objects#equal}{@code (v1, v2)} implies that
* {@code Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2))}.
* </ul>
*
* @throws NullPointerException if the key or value is null and this transformer does not accept
* null arguments
*/
@ParametricNullness
V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value);
}
/** Views a function as an entry transformer that ignores the entry key. */
static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
EntryTransformer<K, V1, V2> asEntryTransformer(final Function<? super V1, V2> function) {
checkNotNull(function);
return new EntryTransformer<K, V1, V2>() {
@Override
@ParametricNullness
public V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value) {
return function.apply(value);
}
};
}
static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
Function<V1, V2> asValueToValueFunction(
final EntryTransformer<? super K, V1, V2> transformer, @ParametricNullness final K key) {
checkNotNull(transformer);
return new Function<V1, V2>() {
@Override
@ParametricNullness
public V2 apply(@ParametricNullness V1 v1) {
return transformer.transformEntry(key, v1);
}
};
}
/** Views an entry transformer as a function from {@code Entry} to values. */
static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
Function<Entry<K, V1>, V2> asEntryToValueFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, V2>() {
@Override
@ParametricNullness
public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/** Returns a view of an entry transformed by the specified transformer. */
static <V2 extends @Nullable Object, K extends @Nullable Object, V1 extends @Nullable Object>
Entry<K, V2> transformEntry(
final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
checkNotNull(transformer);
checkNotNull(entry);
return new AbstractMapEntry<K, V2>() {
@Override
@ParametricNullness
public K getKey() {
return entry.getKey();
}
@Override
@ParametricNullness
public V2 getValue() {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/** Views an entry transformer as a function from entries to entries. */
static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override
public Entry<K, V2> apply(final Entry<K, V1> entry) {
return transformEntry(transformer, entry);
}
};
}
static class TransformedEntriesMap<
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
extends IteratorBasedAbstractMap<K, V2> {
final Map<K, V1> fromMap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMap(
Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMap = checkNotNull(fromMap);
this.transformer = checkNotNull(transformer);
}
@Override
public int size() {
return fromMap.size();
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return fromMap.containsKey(key);
}
@Override
@CheckForNull
public V2 get(@CheckForNull Object key) {
return getOrDefault(key, null);
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override
@CheckForNull
public V2 getOrDefault(@CheckForNull Object key, @CheckForNull V2 defaultValue) {
V1 value = fromMap.get(key);
if (value != null || fromMap.containsKey(key)) {
// The cast is safe because of the containsKey check.
return transformer.transformEntry((K) key, uncheckedCastNullableTToT(value));
}
return defaultValue;
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override
@CheckForNull
public V2 remove(@CheckForNull Object key) {
return fromMap.containsKey(key)
// The cast is safe because of the containsKey check.
? transformer.transformEntry((K) key, uncheckedCastNullableTToT(fromMap.remove(key)))
: null;
}
@Override
public void clear() {
fromMap.clear();
}
@Override
public Set<K> keySet() {
return fromMap.keySet();
}
@Override
Iterator<Entry<K, V2>> entryIterator() {
return Iterators.transform(
fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
@Override
Spliterator<Entry<K, V2>> entrySpliterator() {
return CollectSpliterators.map(
fromMap.entrySet().spliterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
@Override
public void forEach(BiConsumer<? super K, ? super V2> action) {
checkNotNull(action);
// avoids creating new Entry<K, V2> objects
fromMap.forEach((k, v1) -> action.accept(k, transformer.transformEntry(k, v1)));
}
@Override
public Collection<V2> values() {
return new Values<>(this);
}
}
static class TransformedEntriesSortedMap<
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
protected SortedMap<K, V1> fromMap() {
return (SortedMap<K, V1>) fromMap;
}
TransformedEntriesSortedMap(
SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return fromMap().comparator();
}
@Override
@ParametricNullness
public K firstKey() {
return fromMap().firstKey();
}
@Override
public SortedMap<K, V2> headMap(@ParametricNullness K toKey) {
return transformEntries(fromMap().headMap(toKey), transformer);
}
@Override
@ParametricNullness
public K lastKey() {
return fromMap().lastKey();
}
@Override
public SortedMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return transformEntries(fromMap().subMap(fromKey, toKey), transformer);
}
@Override
public SortedMap<K, V2> tailMap(@ParametricNullness K fromKey) {
return transformEntries(fromMap().tailMap(fromKey), transformer);
}
}
@GwtIncompatible // NavigableMap
private static class TransformedEntriesNavigableMap<
K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> {
TransformedEntriesNavigableMap(
NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override
@CheckForNull
public Entry<K, V2> ceilingEntry(@ParametricNullness K key) {
return transformEntry(fromMap().ceilingEntry(key));
}
@Override
@CheckForNull
public K ceilingKey(@ParametricNullness K key) {
return fromMap().ceilingKey(key);
}
@Override
public NavigableSet<K> descendingKeySet() {
return fromMap().descendingKeySet();
}
@Override
public NavigableMap<K, V2> descendingMap() {
return transformEntries(fromMap().descendingMap(), transformer);
}
@Override
@CheckForNull
public Entry<K, V2> firstEntry() {
return transformEntry(fromMap().firstEntry());
}
@Override
@CheckForNull
public Entry<K, V2> floorEntry(@ParametricNullness K key) {
return transformEntry(fromMap().floorEntry(key));
}
@Override
@CheckForNull
public K floorKey(@ParametricNullness K key) {
return fromMap().floorKey(key);
}
@Override
public NavigableMap<K, V2> headMap(@ParametricNullness K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, V2> headMap(@ParametricNullness K toKey, boolean inclusive) {
return transformEntries(fromMap().headMap(toKey, inclusive), transformer);
}
@Override
@CheckForNull
public Entry<K, V2> higherEntry(@ParametricNullness K key) {
return transformEntry(fromMap().higherEntry(key));
}
@Override
@CheckForNull
public K higherKey(@ParametricNullness K key) {
return fromMap().higherKey(key);
}
@Override
@CheckForNull
public Entry<K, V2> lastEntry() {
return transformEntry(fromMap().lastEntry());
}
@Override
@CheckForNull
public Entry<K, V2> lowerEntry(@ParametricNullness K key) {
return transformEntry(fromMap().lowerEntry(key));
}
@Override
@CheckForNull
public K lowerKey(@ParametricNullness K key) {
return fromMap().lowerKey(key);
}
@Override
public NavigableSet<K> navigableKeySet() {
return fromMap().navigableKeySet();
}
@Override
@CheckForNull
public Entry<K, V2> pollFirstEntry() {
return transformEntry(fromMap().pollFirstEntry());
}
@Override
@CheckForNull
public Entry<K, V2> pollLastEntry() {
return transformEntry(fromMap().pollLastEntry());
}
@Override
public NavigableMap<K, V2> subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return transformEntries(
fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer);
}
@Override
public NavigableMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer);
}
@CheckForNull
private Entry<K, V2> transformEntry(@CheckForNull Entry<K, V1> entry) {
return (entry == null) ? null : Maps.transformEntry(transformer, entry);
}
@Override
protected NavigableMap<K, V1> fromMap() {
return (NavigableMap<K, V1>) super.fromMap();
}
}
static <K extends @Nullable Object> Predicate<Entry<K, ?>> keyPredicateOnEntries(
Predicate<? super K> keyPredicate) {
return compose(keyPredicate, Maps.<K>keyFunction());
}
static <V extends @Nullable Object> Predicate<Entry<?, V>> valuePredicateOnEntries(
Predicate<? super V> valuePredicate) {
return compose(valuePredicate, Maps.<V>valueFunction());
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The
* returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
* {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose keys satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*/
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterKeys(
Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredKeyMap<K, V>(checkNotNull(unfiltered), keyPredicate, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose keys satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
* {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose keys satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 11.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
* {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose keys satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> filterKeys(
NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate.
* The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code put()},
* {@code forcePut()} and {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterKeys(
BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose values satisfy a predicate.
* The returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
* {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose values satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*/
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterValues(
Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose values satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
* {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose values satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 11.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a navigable map containing the mappings in {@code unfiltered} whose values satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
* {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose values satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> filterValues(
NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a predicate.
* The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a value that doesn't satisfy the predicate, the bimap's {@code
* put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method
* that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterValues(
BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a map containing the mappings in {@code unfiltered} that satisfy a predicate. The
* returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
* put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
* map's entries have a {@link Entry#setValue} method that throws an {@link
* IllegalArgumentException} when the existing key and the provided value don't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings that satisfy the filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}.
*/
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterEntries(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
* The returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
* put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
* map's entries have a {@link Entry#setValue} method that throws an {@link
* IllegalArgumentException} when the existing key and the provided value don't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings that satisfy the filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}.
*
* @since 11.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntrySortedMap)
? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
* The returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
* put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
* map's entries have a {@link Entry#setValue} method that throws an {@link
* IllegalArgumentException} when the existing key and the provided value don't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings that satisfy the filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> filterEntries(
NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryNavigableMap)
? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
* returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's
* {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} method
* that throws an {@link IllegalArgumentException} when the existing key and the provided value
* don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying bimap and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterEntries(
BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(unfiltered);
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryBiMap)
? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* map.
*/
private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterFiltered(
AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
return new FilteredEntryMap<>(
map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate));
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* sorted map.
*/
private static <K extends @Nullable Object, V extends @Nullable Object>
SortedMap<K, V> filterFiltered(
FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
return new FilteredEntrySortedMap<>(map.sortedMap(), predicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* navigable map.
*/
@GwtIncompatible // NavigableMap
private static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> filterFiltered(
FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate =
Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate);
return new FilteredEntryNavigableMap<>(map.unfiltered, predicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* map.
*/
private static <K extends @Nullable Object, V extends @Nullable Object>
BiMap<K, V> filterFiltered(
FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
return new FilteredEntryBiMap<>(map.unfiltered(), predicate);
}
private abstract static class AbstractFilteredMap<
K extends @Nullable Object, V extends @Nullable Object>
extends ViewCachingAbstractMap<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
AbstractFilteredMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
boolean apply(@CheckForNull Object key, @ParametricNullness V value) {
// This method is called only when the key is in the map (or about to be added to the map),
// implying that key is a K.
@SuppressWarnings({"unchecked", "nullness"})
K k = (K) key;
return predicate.apply(Maps.immutableEntry(k, value));
}
@Override
@CheckForNull
public V put(@ParametricNullness K key, @ParametricNullness V value) {
checkArgument(apply(key, value));
return unfiltered.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
checkArgument(apply(entry.getKey(), entry.getValue()));
}
unfiltered.putAll(map);
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
V value = unfiltered.get(key);
return ((value != null) && apply(key, value)) ? value : null;
}
@Override
public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
return containsKey(key) ? unfiltered.remove(key) : null;
}
@Override
Collection<V> createValues() {
return new FilteredMapValues<>(this, unfiltered, predicate);
}
}
private static final class FilteredMapValues<
K extends @Nullable Object, V extends @Nullable Object>
extends Maps.Values<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
FilteredMapValues(
Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
super(filteredMap);
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override
public boolean remove(@CheckForNull Object o) {
Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (predicate.apply(entry) && Objects.equal(entry.getValue(), o)) {
entryItr.remove();
return true;
}
}
return false;
}
@Override
public boolean removeAll(Collection<?> collection) {
Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (predicate.apply(entry) && collection.contains(entry.getValue())) {
entryItr.remove();
result = true;
}
}
return result;
}
@Override
public boolean retainAll(Collection<?> collection) {
Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (predicate.apply(entry) && !collection.contains(entry.getValue())) {
entryItr.remove();
result = true;
}
}
return result;
}
@Override
public @Nullable Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
private static class FilteredKeyMap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractFilteredMap<K, V> {
final Predicate<? super K> keyPredicate;
FilteredKeyMap(
Map<K, V> unfiltered,
Predicate<? super K> keyPredicate,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
Set<K> createKeySet() {
return Sets.filter(unfiltered.keySet(), keyPredicate);
}
// The cast is called only when the key is in the unfiltered map, implying
// that key is a K.
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(@CheckForNull Object key) {
return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
}
}
static class FilteredEntryMap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractFilteredMap<K, V> {
/**
* Entries in this set satisfy the predicate, but they don't validate the input to {@code
* Entry.setValue()}.
*/
final Set<Entry<K, V>> filteredEntrySet;
FilteredEntryMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
@WeakOuter
private class EntrySet extends ForwardingSet<Entry<K, V>> {
@Override
protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) {
@Override
Entry<K, V> transform(final Entry<K, V> entry) {
return new ForwardingMapEntry<K, V>() {
@Override
protected Entry<K, V> delegate() {
return entry;
}
@Override
@ParametricNullness
public V setValue(@ParametricNullness V newValue) {
checkArgument(apply(getKey(), newValue));
return super.setValue(newValue);
}
};
}
};
}
}
@Override
Set<K> createKeySet() {
return new KeySet();
}
static <K extends @Nullable Object, V extends @Nullable Object> boolean removeAllKeys(
Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (entryPredicate.apply(entry) && keyCollection.contains(entry.getKey())) {
entryItr.remove();
result = true;
}
}
return result;
}
static <K extends @Nullable Object, V extends @Nullable Object> boolean retainAllKeys(
Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (entryPredicate.apply(entry) && !keyCollection.contains(entry.getKey())) {
entryItr.remove();
result = true;
}
}
return result;
}
@WeakOuter
class KeySet extends Maps.KeySet<K, V> {
KeySet() {
super(FilteredEntryMap.this);
}
@Override
public boolean remove(@CheckForNull Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
@Override
public boolean removeAll(Collection<?> collection) {
return removeAllKeys(unfiltered, predicate, collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return retainAllKeys(unfiltered, predicate, collection);
}
@Override
public @Nullable Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
private static class FilteredEntrySortedMap<
K extends @Nullable Object, V extends @Nullable Object>
extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
FilteredEntrySortedMap(
SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
}
SortedMap<K, V> sortedMap() {
return (SortedMap<K, V>) unfiltered;
}
@Override
public SortedSet<K> keySet() {
return (SortedSet<K>) super.keySet();
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet();
}
@WeakOuter
class SortedKeySet extends KeySet implements SortedSet<K> {
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public SortedSet<K> subSet(
@ParametricNullness K fromElement, @ParametricNullness K toElement) {
return (SortedSet<K>) subMap(fromElement, toElement).keySet();
}
@Override
public SortedSet<K> headSet(@ParametricNullness K toElement) {
return (SortedSet<K>) headMap(toElement).keySet();
}
@Override
public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
return (SortedSet<K>) tailMap(fromElement).keySet();
}
@Override
@ParametricNullness
public K first() {
return firstKey();
}
@Override
@ParametricNullness
public K last() {
return lastKey();
}
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
@ParametricNullness
public K firstKey() {
// correctly throws NoSuchElementException when filtered map is empty.
return keySet().iterator().next();
}
@Override
@ParametricNullness
public K lastKey() {
SortedMap<K, V> headMap = sortedMap();
while (true) {
// correctly throws NoSuchElementException when filtered map is empty.
K key = headMap.lastKey();
// The cast is safe because the key is taken from the map.
if (apply(key, uncheckedCastNullableTToT(unfiltered.get(key)))) {
return key;
}
headMap = sortedMap().headMap(key);
}
}
@Override
public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
return new FilteredEntrySortedMap<>(sortedMap().headMap(toKey), predicate);
}
@Override
public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return new FilteredEntrySortedMap<>(sortedMap().subMap(fromKey, toKey), predicate);
}
@Override
public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
return new FilteredEntrySortedMap<>(sortedMap().tailMap(fromKey), predicate);
}
}
@GwtIncompatible // NavigableMap
private static class FilteredEntryNavigableMap<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractNavigableMap<K, V> {
/*
* It's less code to extend AbstractNavigableMap and forward the filtering logic to
* FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap
* methods.
*/
private final NavigableMap<K, V> unfiltered;
private final Predicate<? super Entry<K, V>> entryPredicate;
private final Map<K, V> filteredDelegate;
FilteredEntryNavigableMap(
NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
this.unfiltered = checkNotNull(unfiltered);
this.entryPredicate = entryPredicate;
this.filteredDelegate = new FilteredEntryMap<>(unfiltered, entryPredicate);
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return unfiltered.comparator();
}
@Override
public NavigableSet<K> navigableKeySet() {
return new Maps.NavigableKeySet<K, V>(this) {
@Override
public boolean removeAll(Collection<?> collection) {
return FilteredEntryMap.removeAllKeys(unfiltered, entryPredicate, collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return FilteredEntryMap.retainAllKeys(unfiltered, entryPredicate, collection);
}
};
}
@Override
public Collection<V> values() {
return new FilteredMapValues<>(this, unfiltered, entryPredicate);
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate);
}
@Override
Iterator<Entry<K, V>> descendingEntryIterator() {
return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate);
}
@Override
public int size() {
return filteredDelegate.size();
}
@Override
public boolean isEmpty() {
return !Iterables.any(unfiltered.entrySet(), entryPredicate);
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return filteredDelegate.get(key);
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return filteredDelegate.containsKey(key);
}
@Override
@CheckForNull
public V put(@ParametricNullness K key, @ParametricNullness V value) {
return filteredDelegate.put(key, value);
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
return filteredDelegate.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
filteredDelegate.putAll(m);
}
@Override
public void clear() {
filteredDelegate.clear();
}
@Override
public Set<Entry<K, V>> entrySet() {
return filteredDelegate.entrySet();
}
@Override
@CheckForNull
public Entry<K, V> pollFirstEntry() {
return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate);
}
@Override
@CheckForNull
public Entry<K, V> pollLastEntry() {
return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate);
}
@Override
public NavigableMap<K, V> descendingMap() {
return filterEntries(unfiltered.descendingMap(), entryPredicate);
}
@Override
public NavigableMap<K, V> subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return filterEntries(
unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate);
}
@Override
public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate);
}
@Override
public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate);
}
}
static final class FilteredEntryBiMap<K extends @Nullable Object, V extends @Nullable Object>
extends FilteredEntryMap<K, V> implements BiMap<K, V> {
@RetainedWith private final BiMap<V, K> inverse;
private static <K extends @Nullable Object, V extends @Nullable Object>
Predicate<Entry<V, K>> inversePredicate(
final Predicate<? super Entry<K, V>> forwardPredicate) {
return new Predicate<Entry<V, K>>() {
@Override
public boolean apply(Entry<V, K> input) {
return forwardPredicate.apply(
Maps.<K, V>immutableEntry(input.getValue(), input.getKey()));
}
};
}
FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) {
super(delegate, predicate);
this.inverse =
new FilteredEntryBiMap<>(delegate.inverse(), inversePredicate(predicate), this);
}
private FilteredEntryBiMap(
BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) {
super(delegate, predicate);
this.inverse = inverse;
}
BiMap<K, V> unfiltered() {
return (BiMap<K, V>) unfiltered;
}
@Override
@CheckForNull
public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
checkArgument(apply(key, value));
return unfiltered().forcePut(key, value);
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
unfiltered()
.replaceAll(
(key, value) ->
predicate.apply(Maps.<K, V>immutableEntry(key, value))
? function.apply(key, value)
: value);
}
@Override
public BiMap<V, K> inverse() {
return inverse;
}
@Override
public Set<V> values() {
return inverse.keySet();
}
}
/**
* Returns an unmodifiable view of the specified navigable map. Query operations on the returned
* map read through to the specified map, and attempts to modify the returned map, whether direct
* or via its views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned navigable map will be serializable if the specified navigable map is
* serializable.
*
* <p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K,
* V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code
* comparator()} method might return a {@code Comparator<? extends K>}, which works only on a
* particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which
* must work on any type of {@code K}.
*
* @param map the navigable map for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable map
* @since 12.0
*/
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> map) {
checkNotNull(map);
if (map instanceof UnmodifiableNavigableMap) {
@SuppressWarnings("unchecked") // covariant
NavigableMap<K, V> result = (NavigableMap<K, V>) map;
return result;
} else {
return new UnmodifiableNavigableMap<>(map);
}
}
@CheckForNull
private static <K extends @Nullable Object, V extends @Nullable Object>
Entry<K, V> unmodifiableOrNull(@CheckForNull Entry<K, ? extends V> entry) {
return (entry == null) ? null : Maps.unmodifiableEntry(entry);
}
@GwtIncompatible // NavigableMap
static class UnmodifiableNavigableMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable {
private final NavigableMap<K, ? extends V> delegate;
UnmodifiableNavigableMap(NavigableMap<K, ? extends V> delegate) {
this.delegate = delegate;
}
UnmodifiableNavigableMap(
NavigableMap<K, ? extends V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) {
this.delegate = delegate;
this.descendingMap = descendingMap;
}
@Override
protected SortedMap<K, V> delegate() {
return Collections.unmodifiableSortedMap(delegate);
}
@Override
@CheckForNull
public Entry<K, V> lowerEntry(@ParametricNullness K key) {
return unmodifiableOrNull(delegate.lowerEntry(key));
}
@Override
@CheckForNull
public K lowerKey(@ParametricNullness K key) {
return delegate.lowerKey(key);
}
@Override
@CheckForNull
public Entry<K, V> floorEntry(@ParametricNullness K key) {
return unmodifiableOrNull(delegate.floorEntry(key));
}
@Override
@CheckForNull
public K floorKey(@ParametricNullness K key) {
return delegate.floorKey(key);
}
@Override
@CheckForNull
public Entry<K, V> ceilingEntry(@ParametricNullness K key) {
return unmodifiableOrNull(delegate.ceilingEntry(key));
}
@Override
@CheckForNull
public K ceilingKey(@ParametricNullness K key) {
return delegate.ceilingKey(key);
}
@Override
@CheckForNull
public Entry<K, V> higherEntry(@ParametricNullness K key) {
return unmodifiableOrNull(delegate.higherEntry(key));
}
@Override
@CheckForNull
public K higherKey(@ParametricNullness K key) {
return delegate.higherKey(key);
}
@Override
@CheckForNull
public Entry<K, V> firstEntry() {
return unmodifiableOrNull(delegate.firstEntry());
}
@Override
@CheckForNull
public Entry<K, V> lastEntry() {
return unmodifiableOrNull(delegate.lastEntry());
}
@Override
@CheckForNull
public final Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public final Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V putIfAbsent(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V replace(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(
K key, java.util.function.Function<? super K, ? extends V> mappingFunction) {
throw new UnsupportedOperationException();
}
/*
* TODO(cpovirk): Uncomment the @NonNull annotations below once our JDK stubs and J2KT
* emulations include them.
*/
@Override
@CheckForNull
/*
* Our checker arguably should produce a nullness error here until we see @NonNull in JDK APIs.
* But it doesn't, which may be a sign that we still permit parameter contravariance in some
* cases?
*/
public V computeIfPresent(
K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V compute(
K key,
BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
@SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs
public V merge(
K key,
@NonNull V value,
BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> function) {
throw new UnsupportedOperationException();
}
@LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
@Override
public NavigableMap<K, V> descendingMap() {
UnmodifiableNavigableMap<K, V> result = descendingMap;
return (result == null)
? descendingMap = new UnmodifiableNavigableMap<>(delegate.descendingMap(), this)
: result;
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
@Override
public NavigableSet<K> navigableKeySet() {
return Sets.unmodifiableNavigableSet(delegate.navigableKeySet());
}
@Override
public NavigableSet<K> descendingKeySet() {
return Sets.unmodifiableNavigableSet(delegate.descendingKeySet());
}
@Override
public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V> subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return Maps.unmodifiableNavigableMap(
delegate.subMap(fromKey, fromInclusive, toKey, toInclusive));
}
@Override
public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive));
}
@Override
public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive));
}
}
/**
* Returns a synchronized (thread-safe) navigable map backed by the specified navigable map. In
* order to guarantee serial access, it is critical that <b>all</b> access to the backing
* navigable map is accomplished through the returned navigable map (or its views).
*
* <p>It is imperative that the user manually synchronize on the returned navigable map when
* iterating over any of its collection views, or the collections views of any of its {@code
* descendingMap}, {@code subMap}, {@code headMap} or {@code tailMap} views.
*
* <pre>{@code
* NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
*
* // Needn't be in synchronized block
* NavigableSet<K> set = map.navigableKeySet();
*
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<K> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>or:
*
* <pre>{@code
* NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
* NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true);
*
* // Needn't be in synchronized block
* NavigableSet<K> set2 = map2.descendingKeySet();
*
* synchronized (map) { // Synchronizing on map, not map2 or set2!
* Iterator<K> it = set2.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned navigable map will be serializable if the specified navigable map is
* serializable.
*
* @param navigableMap the navigable map to be "wrapped" in a synchronized navigable map.
* @return a synchronized view of the specified navigable map.
* @since 13.0
*/
@GwtIncompatible // NavigableMap
public static <K extends @Nullable Object, V extends @Nullable Object>
NavigableMap<K, V> synchronizedNavigableMap(NavigableMap<K, V> navigableMap) {
return Synchronized.navigableMap(navigableMap);
}
/**
* {@code AbstractMap} extension that makes it easy to cache customized keySet, values, and
* entrySet views.
*/
@GwtCompatible
abstract static class ViewCachingAbstractMap<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMap<K, V> {
/**
* Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most
* once on a given map, at the time when {@code entrySet} is first called.
*/
abstract Set<Entry<K, V>> createEntrySet();
@LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
@LazyInit @CheckForNull private transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
Set<K> createKeySet() {
return new KeySet<>(this);
}
@LazyInit @CheckForNull private transient Collection<V> values;
@Override
public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = createValues() : result;
}
Collection<V> createValues() {
return new Values<>(this);
}
}
abstract static class IteratorBasedAbstractMap<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMap<K, V> {
@Override
public abstract int size();
abstract Iterator<Entry<K, V>> entryIterator();
Spliterator<Entry<K, V>> entrySpliterator() {
return Spliterators.spliterator(
entryIterator(), size(), Spliterator.SIZED | Spliterator.DISTINCT);
}
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet<K, V>() {
@Override
Map<K, V> map() {
return IteratorBasedAbstractMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entryIterator();
}
@Override
public Spliterator<Entry<K, V>> spliterator() {
return entrySpliterator();
}
@Override
public void forEach(Consumer<? super Entry<K, V>> action) {
forEachEntry(action);
}
};
}
void forEachEntry(Consumer<? super Entry<K, V>> action) {
entryIterator().forEachRemaining(action);
}
@Override
public void clear() {
Iterators.clear(entryIterator());
}
}
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code ClassCastException} and {@code
* NullPointerException}.
*/
@CheckForNull
static <V extends @Nullable Object> V safeGet(Map<?, V> map, @CheckForNull Object key) {
checkNotNull(map);
try {
return map.get(key);
} catch (ClassCastException | NullPointerException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and
* {@code NullPointerException}.
*/
static boolean safeContainsKey(Map<?, ?> map, @CheckForNull Object key) {
checkNotNull(map);
try {
return map.containsKey(key);
} catch (ClassCastException | NullPointerException e) {
return false;
}
}
/**
* Delegates to {@link Map#remove}. Returns {@code null} on {@code ClassCastException} and {@code
* NullPointerException}.
*/
@CheckForNull
static <V extends @Nullable Object> V safeRemove(Map<?, V> map, @CheckForNull Object key) {
checkNotNull(map);
try {
return map.remove(key);
} catch (ClassCastException | NullPointerException e) {
return null;
}
}
/** An admittedly inefficient implementation of {@link Map#containsKey}. */
static boolean containsKeyImpl(Map<?, ?> map, @CheckForNull Object key) {
return Iterators.contains(keyIterator(map.entrySet().iterator()), key);
}
/** An implementation of {@link Map#containsValue}. */
static boolean containsValueImpl(Map<?, ?> map, @CheckForNull Object value) {
return Iterators.contains(valueIterator(map.entrySet().iterator()), value);
}
/**
* Implements {@code Collection.contains} safely for forwarding collections of map entries. If
* {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
* protect against a possible nefarious equals method.
*
* <p>Note that {@code c} is the backing (delegate) collection, rather than the forwarding
* collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object that might be contained in {@code c}
* @return {@code true} if {@code c} contains {@code o}
*/
static <K extends @Nullable Object, V extends @Nullable Object> boolean containsEntryImpl(
Collection<Entry<K, V>> c, @CheckForNull Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.contains(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* Implements {@code Collection.remove} safely for forwarding collections of map entries. If
* {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
* protect against a possible nefarious equals method.
*
* <p>Note that {@code c} is backing (delegate) collection, rather than the forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object to remove from {@code c}
* @return {@code true} if {@code c} was changed
*/
static <K extends @Nullable Object, V extends @Nullable Object> boolean removeEntryImpl(
Collection<Entry<K, V>> c, @CheckForNull Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.remove(unmodifiableEntry((Entry<?, ?>) o));
}
/** An implementation of {@link Map#equals}. */
static boolean equalsImpl(Map<?, ?> map, @CheckForNull Object object) {
if (map == object) {
return true;
} else if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
/** An implementation of {@link Map#toString}. */
static String toStringImpl(Map<?, ?> map) {
StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{');
boolean first = true;
for (Entry<?, ?> entry : map.entrySet()) {
if (!first) {
sb.append(", ");
}
first = false;
sb.append(entry.getKey()).append('=').append(entry.getValue());
}
return sb.append('}').toString();
}
/** An implementation of {@link Map#putAll}. */
static <K extends @Nullable Object, V extends @Nullable Object> void putAllImpl(
Map<K, V> self, Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
self.put(entry.getKey(), entry.getValue());
}
}
static class KeySet<K extends @Nullable Object, V extends @Nullable Object>
extends Sets.ImprovedAbstractSet<K> {
@Weak final Map<K, V> map;
KeySet(Map<K, V> map) {
this.map = checkNotNull(map);
}
Map<K, V> map() {
return map;
}
@Override
public Iterator<K> iterator() {
return keyIterator(map().entrySet().iterator());
}
@Override
public void forEach(Consumer<? super K> action) {
checkNotNull(action);
// avoids entry allocation for those maps that allocate entries on iteration
map.forEach((k, v) -> action.accept(k));
}
@Override
public int size() {
return map().size();
}
@Override
public boolean isEmpty() {
return map().isEmpty();
}
@Override
public boolean contains(@CheckForNull Object o) {
return map().containsKey(o);
}
@Override
public boolean remove(@CheckForNull Object o) {
if (contains(o)) {
map().remove(o);
return true;
}
return false;
}
@Override
public void clear() {
map().clear();
}
}
@CheckForNull
static <K extends @Nullable Object> K keyOrNull(@CheckForNull Entry<K, ?> entry) {
return (entry == null) ? null : entry.getKey();
}
@CheckForNull
static <V extends @Nullable Object> V valueOrNull(@CheckForNull Entry<?, V> entry) {
return (entry == null) ? null : entry.getValue();
}
static class SortedKeySet<K extends @Nullable Object, V extends @Nullable Object>
extends KeySet<K, V> implements SortedSet<K> {
SortedKeySet(SortedMap<K, V> map) {
super(map);
}
@Override
SortedMap<K, V> map() {
return (SortedMap<K, V>) super.map();
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return map().comparator();
}
@Override
public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
return new SortedKeySet<>(map().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> headSet(@ParametricNullness K toElement) {
return new SortedKeySet<>(map().headMap(toElement));
}
@Override
public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
return new SortedKeySet<>(map().tailMap(fromElement));
}
@Override
@ParametricNullness
public K first() {
return map().firstKey();
}
@Override
@ParametricNullness
public K last() {
return map().lastKey();
}
}
@GwtIncompatible // NavigableMap
static class NavigableKeySet<K extends @Nullable Object, V extends @Nullable Object>
extends SortedKeySet<K, V> implements NavigableSet<K> {
NavigableKeySet(NavigableMap<K, V> map) {
super(map);
}
@Override
NavigableMap<K, V> map() {
return (NavigableMap<K, V>) map;
}
@Override
@CheckForNull
public K lower(@ParametricNullness K e) {
return map().lowerKey(e);
}
@Override
@CheckForNull
public K floor(@ParametricNullness K e) {
return map().floorKey(e);
}
@Override
@CheckForNull
public K ceiling(@ParametricNullness K e) {
return map().ceilingKey(e);
}
@Override
@CheckForNull
public K higher(@ParametricNullness K e) {
return map().higherKey(e);
}
@Override
@CheckForNull
public K pollFirst() {
return keyOrNull(map().pollFirstEntry());
}
@Override
@CheckForNull
public K pollLast() {
return keyOrNull(map().pollLastEntry());
}
@Override
public NavigableSet<K> descendingSet() {
return map().descendingKeySet();
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> subSet(
@ParametricNullness K fromElement,
boolean fromInclusive,
@ParametricNullness K toElement,
boolean toInclusive) {
return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet();
}
@Override
public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) {
return map().headMap(toElement, inclusive).navigableKeySet();
}
@Override
public SortedSet<K> headSet(@ParametricNullness K toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) {
return map().tailMap(fromElement, inclusive).navigableKeySet();
}
@Override
public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
return tailSet(fromElement, true);
}
}
static class Values<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractCollection<V> {
@Weak final Map<K, V> map;
Values(Map<K, V> map) {
this.map = checkNotNull(map);
}
final Map<K, V> map() {
return map;
}
@Override
public Iterator<V> iterator() {
return valueIterator(map().entrySet().iterator());
}
@Override
public void forEach(Consumer<? super V> action) {
checkNotNull(action);
// avoids allocation of entries for those maps that generate fresh entries on iteration
map.forEach((k, v) -> action.accept(v));
}
@Override
public boolean remove(@CheckForNull Object o) {
try {
return super.remove(o);
} catch (UnsupportedOperationException e) {
for (Entry<K, V> entry : map().entrySet()) {
if (Objects.equal(o, entry.getValue())) {
map().remove(entry.getKey());
return true;
}
}
return false;
}
}
@Override
public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRemove = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRemove.add(entry.getKey());
}
}
return map().keySet().removeAll(toRemove);
}
}
@Override
public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRetain = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRetain.add(entry.getKey());
}
}
return map().keySet().retainAll(toRetain);
}
}
@Override
public int size() {
return map().size();
}
@Override
public boolean isEmpty() {
return map().isEmpty();
}
@Override
public boolean contains(@CheckForNull Object o) {
return map().containsValue(o);
}
@Override
public void clear() {
map().clear();
}
}
abstract static class EntrySet<K extends @Nullable Object, V extends @Nullable Object>
extends Sets.ImprovedAbstractSet<Entry<K, V>> {
abstract Map<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public void clear() {
map().clear();
}
@Override
public boolean contains(@CheckForNull Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
V value = Maps.safeGet(map(), key);
return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key));
}
return false;
}
@Override
public boolean isEmpty() {
return map().isEmpty();
}
@Override
public boolean remove(@CheckForNull Object o) {
/*
* `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
* nullness checker.
*/
if (contains(o) && o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return map().keySet().remove(entry.getKey());
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
return Sets.removeAllImpl(this, c.iterator());
}
}
@Override
public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
Set<@Nullable Object> keys = Sets.newHashSetWithExpectedSize(c.size());
for (Object o : c) {
/*
* `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
* nullness checker.
*/
if (contains(o) && o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
keys.add(entry.getKey());
}
}
return map().keySet().retainAll(keys);
}
}
}
@GwtIncompatible // NavigableMap
abstract static class DescendingMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingMap<K, V> implements NavigableMap<K, V> {
abstract NavigableMap<K, V> forward();
@Override
protected final Map<K, V> delegate() {
return forward();
}
@LazyInit @CheckForNull private transient Comparator<? super K> comparator;
@SuppressWarnings("unchecked")
@Override
public Comparator<? super K> comparator() {
Comparator<? super K> result = comparator;
if (result == null) {
Comparator<? super K> forwardCmp = forward().comparator();
if (forwardCmp == null) {
forwardCmp = (Comparator) Ordering.natural();
}
result = comparator = reverse(forwardCmp);
}
return result;
}
// If we inline this, we get a javac error.
private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) {
return Ordering.from(forward).reverse();
}
@Override
@ParametricNullness
public K firstKey() {
return forward().lastKey();
}
@Override
@ParametricNullness
public K lastKey() {
return forward().firstKey();
}
@Override
@CheckForNull
public Entry<K, V> lowerEntry(@ParametricNullness K key) {
return forward().higherEntry(key);
}
@Override
@CheckForNull
public K lowerKey(@ParametricNullness K key) {
return forward().higherKey(key);
}
@Override
@CheckForNull
public Entry<K, V> floorEntry(@ParametricNullness K key) {
return forward().ceilingEntry(key);
}
@Override
@CheckForNull
public K floorKey(@ParametricNullness K key) {
return forward().ceilingKey(key);
}
@Override
@CheckForNull
public Entry<K, V> ceilingEntry(@ParametricNullness K key) {
return forward().floorEntry(key);
}
@Override
@CheckForNull
public K ceilingKey(@ParametricNullness K key) {
return forward().floorKey(key);
}
@Override
@CheckForNull
public Entry<K, V> higherEntry(@ParametricNullness K key) {
return forward().lowerEntry(key);
}
@Override
@CheckForNull
public K higherKey(@ParametricNullness K key) {
return forward().lowerKey(key);
}
@Override
@CheckForNull
public Entry<K, V> firstEntry() {
return forward().lastEntry();
}
@Override
@CheckForNull
public Entry<K, V> lastEntry() {
return forward().firstEntry();
}
@Override
@CheckForNull
public Entry<K, V> pollFirstEntry() {
return forward().pollLastEntry();
}
@Override
@CheckForNull
public Entry<K, V> pollLastEntry() {
return forward().pollFirstEntry();
}
@Override
public NavigableMap<K, V> descendingMap() {
return forward();
}
@LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
abstract Iterator<Entry<K, V>> entryIterator();
Set<Entry<K, V>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends EntrySet<K, V> {
@Override
Map<K, V> map() {
return DescendingMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entryIterator();
}
}
return new EntrySetImpl();
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
@LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet;
@Override
public NavigableSet<K> navigableKeySet() {
NavigableSet<K> result = navigableKeySet;
return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result;
}
@Override
public NavigableSet<K> descendingKeySet() {
return forward().navigableKeySet();
}
@Override
public NavigableMap<K, V> subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap();
}
@Override
public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
return forward().tailMap(toKey, inclusive).descendingMap();
}
@Override
public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
return forward().headMap(fromKey, inclusive).descendingMap();
}
@Override
public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
return tailMap(fromKey, true);
}
@Override
public Collection<V> values() {
return new Values<>(this);
}
@Override
public String toString() {
return standardToString();
}
}
/** Returns a map from the ith element of list to i. */
static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) {
ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size());
int i = 0;
for (E e : list) {
builder.put(e, i++);
}
return builder.buildOrThrow();
}
/**
* Returns a view of the portion of {@code map} whose keys are contained by {@code range}.
*
* <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link
* NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link
* NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object,
* boolean) headMap()}) to actually construct the view. Consult these methods for a full
* description of the returned view's behavior.
*
* <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
* ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link
* Comparator}, which can violate the natural ordering. Using this method (or in general using
* {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior.
*
* @since 20.0
*/
@GwtIncompatible // NavigableMap
public static <K extends Comparable<? super K>, V extends @Nullable Object>
NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) {
if (map.comparator() != null
&& map.comparator() != Ordering.natural()
&& range.hasLowerBound()
&& range.hasUpperBound()) {
checkArgument(
map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
"map is using a custom comparator which is inconsistent with the natural ordering.");
}
if (range.hasLowerBound() && range.hasUpperBound()) {
return map.subMap(
range.lowerEndpoint(),
range.lowerBoundType() == BoundType.CLOSED,
range.upperEndpoint(),
range.upperBoundType() == BoundType.CLOSED);
} else if (range.hasLowerBound()) {
return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
} else if (range.hasUpperBound()) {
return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
}
return checkNotNull(map);
}
}
| google/guava | guava/src/com/google/common/collect/Maps.java |
659 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to {@link Set} instances. Also see this class's counterparts
* {@link Lists}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#sets">{@code Sets}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Chris Povirk
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Sets {
private Sets() {}
/**
* {@link AbstractSet} substitute without the potentially-quadratic {@code removeAll}
* implementation.
*/
abstract static class ImprovedAbstractSet<E extends @Nullable Object> extends AbstractSet<E> {
@Override
public boolean removeAll(Collection<?> c) {
return removeAllImpl(this, c);
}
@Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(checkNotNull(c)); // GWT compatibility
}
}
/**
* Returns an immutable set instance containing the given enum elements. Internally, the returned
* set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration order, not the order in
* which the elements are provided to the method.
*
* @param anElement one of the elements the set should contain
* @param otherElements the rest of the elements the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
E anElement, E... otherElements) {
return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
}
/**
* Returns an immutable set instance containing the given enum elements. Internally, the returned
* set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration order, not the order in
* which the elements appear in the given collection.
*
* @param elements the elements, all of the same {@code enum} type, that the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(Iterable<E> elements) {
if (elements instanceof ImmutableEnumSet) {
return (ImmutableEnumSet<E>) elements;
} else if (elements instanceof Collection) {
Collection<E> collection = (Collection<E>) elements;
if (collection.isEmpty()) {
return ImmutableSet.of();
} else {
return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
}
} else {
Iterator<E> itr = elements.iterator();
if (itr.hasNext()) {
EnumSet<E> enumSet = EnumSet.of(itr.next());
Iterators.addAll(enumSet, itr);
return ImmutableEnumSet.asImmutable(enumSet);
} else {
return ImmutableSet.of();
}
}
}
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code ImmutableSet}
* with an implementation specialized for enums. Unlike {@link ImmutableSet#toImmutableSet}, the
* resulting set will iterate over elements in their enum definition order, not encounter order.
*
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
@IgnoreJRERequirement // Users will use this only if they're already using streams.
@Beta // TODO: b/288085449 - Remove.
public static <E extends Enum<E>> Collector<E, ?, ImmutableSet<E>> toImmutableEnumSet() {
return CollectCollectors.toImmutableEnumSet();
}
/**
* Returns a new, <i>mutable</i> {@code EnumSet} instance containing the given elements in their
* natural order. This method behaves identically to {@link EnumSet#copyOf(Collection)}, but also
* accepts non-{@code Collection} iterables and empty iterables.
*/
public static <E extends Enum<E>> EnumSet<E> newEnumSet(
Iterable<E> iterable, Class<E> elementType) {
EnumSet<E> set = EnumSet.noneOf(elementType);
Iterables.addAll(set, iterable);
return set;
}
// HashSet
/**
* Creates a <i>mutable</i>, initially empty {@code HashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead. If {@code
* E} is an {@link Enum} type, use {@link EnumSet#noneOf} instead. Otherwise, strongly consider
* using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get
* deterministic iteration behavior.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code HashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
public static <E extends @Nullable Object> HashSet<E> newHashSet() {
return new HashSet<>();
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance initially containing the given elements.
*
* <p><b>Note:</b> if elements are non-null and won't be added or removed after this point, use
* {@link ImmutableSet#of()} or {@link ImmutableSet#copyOf(Object[])} instead. If {@code E} is an
* {@link Enum} type, use {@link EnumSet#of(Enum, Enum[])} instead. Otherwise, strongly consider
* using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get
* deterministic iteration behavior.
*
* <p>This method is just a small convenience, either for {@code newHashSet(}{@link Arrays#asList
* asList}{@code (...))}, or for creating an empty set then calling {@link Collections#addAll}.
* This method is not actually very useful and will likely be deprecated in the future.
*/
@SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix.
public static <E extends @Nullable Object> HashSet<E> newHashSet(E... elements) {
HashSet<E> set = newHashSetWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
* convenience for creating an empty set then calling {@link Collection#addAll} or {@link
* Iterables#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableSet#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
* FluentIterable} and call {@code elements.toSet()}.)
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link #newEnumSet(Iterable, Class)}
* instead.
*
* <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method.
* Instead, use the {@code HashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* <p>Overall, this method is not very useful and will likely be deprecated in the future.
*/
public static <E extends @Nullable Object> HashSet<E> newHashSet(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? new HashSet<E>((Collection<? extends E>) elements)
: newHashSet(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
* convenience for creating an empty set and then calling {@link Iterators#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableSet#copyOf(Iterator)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an {@link EnumSet}
* instead.
*
* <p>Overall, this method is not very useful and will likely be deprecated in the future.
*/
public static <E extends @Nullable Object> HashSet<E> newHashSet(Iterator<? extends E> elements) {
HashSet<E> set = newHashSet();
Iterators.addAll(set, elements);
return set;
}
/**
* Returns a new hash set using the smallest initial table size that can hold {@code expectedSize}
* elements without resizing. Note that this is not what {@link HashSet#HashSet(int)} does, but it
* is what most users want and expect it to do.
*
* <p>This behavior can't be broadly guaranteed, but has been tested with OpenJDK 1.7 and 1.8.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty hash set with enough capacity to hold {@code expectedSize} elements
* without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E extends @Nullable Object> HashSet<E> newHashSetWithExpectedSize(
int expectedSize) {
return new HashSet<>(Maps.capacity(expectedSize));
}
/**
* Creates a thread-safe set backed by a hash map. The set is backed by a {@link
* ConcurrentHashMap} instance, and thus carries the same concurrency guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The
* set is serializable.
*
* @return a new, empty thread-safe {@code Set}
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet() {
return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}
/**
* Creates a thread-safe set backed by a hash map and containing the given elements. The set is
* backed by a {@link ConcurrentHashMap} instance, and thus carries the same concurrency
* guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The
* set is serializable.
*
* @param elements the elements that the set should contain
* @return a new thread-safe set containing those elements (minus duplicates)
* @throws NullPointerException if {@code elements} or any of its contents is null
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet(Iterable<? extends E> elements) {
Set<E> set = newConcurrentHashSet();
Iterables.addAll(set, elements);
return set;
}
// LinkedHashSet
/**
* Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedHashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code LinkedHashSet}
*/
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet() {
return new LinkedHashSet<>();
}
/**
* Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the given elements in order.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method.
* Instead, use the {@code LinkedHashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* <p>Overall, this method is not very useful and will likely be deprecated in the future.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code LinkedHashSet} containing those elements (minus duplicates)
*/
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<>((Collection<? extends E>) elements);
}
LinkedHashSet<E> set = newLinkedHashSet();
Iterables.addAll(set, elements);
return set;
}
/**
* Creates a {@code LinkedHashSet} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
* broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
* that the method isn't inadvertently <i>oversizing</i> the returned set.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize}
* elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 11.0
*/
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
int expectedSize) {
return new LinkedHashSet<>(Maps.capacity(expectedSize));
}
// TreeSet
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the natural sort ordering of
* its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code TreeSet}
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <E extends Comparable> TreeSet<E> newTreeSet() {
return new TreeSet<>();
}
/**
* Creates a <i>mutable</i> {@code TreeSet} instance containing the given elements sorted by their
* natural ordering.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#copyOf(Iterable)}
* instead.
*
* <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit comparator, this
* method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code
* TreeSet} with that comparator.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* <p>This method is just a small convenience for creating an empty set and then calling {@link
* Iterables#addAll}. This method is not very useful and will likely be deprecated in the future.
*
* @param elements the elements that the set should contain
* @return a new {@code TreeSet} containing those elements (minus duplicates)
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
Iterables.addAll(set, elements);
return set;
}
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedSet.orderedBy(comparator).build()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>. One caveat to this is that the {@code TreeSet}
* constructor uses a null {@code Comparator} to mean "natural ordering," whereas this factory
* rejects null. Clean your code accordingly.
*
* @param comparator the comparator to use to sort the set
* @return a new, empty {@code TreeSet}
* @throws NullPointerException if {@code comparator} is null
*/
public static <E extends @Nullable Object> TreeSet<E> newTreeSet(
Comparator<? super E> comparator) {
return new TreeSet<>(checkNotNull(comparator));
}
/**
* Creates an empty {@code Set} that uses identity to determine equality. It compares object
* references, instead of calling {@code equals}, to determine whether a provided object matches
* an element in the set. For example, {@code contains} returns {@code false} when passed an
* object that equals a set member, but isn't the same instance. This behavior is similar to the
* way {@code IdentityHashMap} handles key lookups.
*
* @since 8.0
*/
public static <E extends @Nullable Object> Set<E> newIdentityHashSet() {
return Collections.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
}
/**
* Creates an empty {@code CopyOnWriteArraySet} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link Set}, use {@link Collections#emptySet}
* instead.
*
* @return a new, empty {@code CopyOnWriteArraySet}
* @since 12.0
*/
@J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
return new CopyOnWriteArraySet<>();
}
/**
* Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code CopyOnWriteArraySet} containing those elements
* @since 12.0
*/
@J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
Iterable<? extends E> elements) {
// We copy elements to an ArrayList first, rather than incurring the
// quadratic cost of adding them to the COWAS directly.
Collection<? extends E> elementsCollection =
(elements instanceof Collection)
? (Collection<? extends E>) elements
: Lists.newArrayList(elements);
return new CopyOnWriteArraySet<>(elementsCollection);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in the specified
* collection. If the collection is an {@link EnumSet}, this method has the same behavior as
* {@link EnumSet#complementOf}. Otherwise, the specified collection must contain at least one
* element, in order to determine the element type. If the collection could be empty, use {@link
* #complementOf(Collection, Class)} instead of this method.
*
* @param collection the collection whose complement should be stored in the enum set
* @return a new, modifiable {@code EnumSet} containing all values of the enum that aren't present
* in the given collection
* @throws IllegalArgumentException if {@code collection} is not an {@code EnumSet} instance and
* contains no elements
*/
@J2ktIncompatible
@GwtIncompatible // EnumSet.complementOf
public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) {
if (collection instanceof EnumSet) {
return EnumSet.complementOf((EnumSet<E>) collection);
}
checkArgument(
!collection.isEmpty(), "collection is empty; use the other version of this method");
Class<E> type = collection.iterator().next().getDeclaringClass();
return makeComplementByHand(collection, type);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in the specified
* collection. This is equivalent to {@link EnumSet#complementOf}, but can act on any input
* collection, as long as the elements are of enum type.
*
* @param collection the collection whose complement should be stored in the {@code EnumSet}
* @param type the type of the elements in the set
* @return a new, modifiable {@code EnumSet} initially containing all the values of the enum not
* present in the given collection
*/
@J2ktIncompatible
@GwtIncompatible // EnumSet.complementOf
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection, Class<E> type) {
checkNotNull(collection);
return (collection instanceof EnumSet)
? EnumSet.complementOf((EnumSet<E>) collection)
: makeComplementByHand(collection, type);
}
@J2ktIncompatible
@GwtIncompatible
private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
Collection<E> collection, Class<E> type) {
EnumSet<E> result = EnumSet.allOf(type);
result.removeAll(collection);
return result;
}
/**
* Returns a set backed by the specified map. The resulting set displays the same ordering,
* concurrency, and performance characteristics as the backing map. In essence, this factory
* method provides a {@link Set} implementation corresponding to any {@link Map} implementation.
* There is no need to use this method on a {@link Map} implementation that already has a
* corresponding {@link Set} implementation (such as {@link java.util.HashMap} or {@link
* java.util.TreeMap}).
*
* <p>Each method invocation on the set returned by this method results in exactly one method
* invocation on the backing map or its {@code keySet} view, with one exception. The {@code
* addAll} method is implemented as a sequence of {@code put} invocations on the backing map.
*
* <p>The specified map must be empty at the time this method is invoked, and should not be
* accessed directly after this method returns. These conditions are ensured if the map is created
* empty, passed directly to this method, and no reference to the map is retained, as illustrated
* in the following code fragment:
*
* <pre>{@code
* Set<Object> identityHashSet = Sets.newSetFromMap(
* new IdentityHashMap<Object, Boolean>());
* }</pre>
*
* <p>The returned set is serializable if the backing map is.
*
* @param map the backing map
* @return the set backed by the map
* @throws IllegalArgumentException if {@code map} is not empty
* @deprecated Use {@link Collections#newSetFromMap} instead.
*/
@Deprecated
public static <E extends @Nullable Object> Set<E> newSetFromMap(
Map<E, Boolean> map) {
return Collections.newSetFromMap(map);
}
/**
* An unmodifiable view of a set which may be backed by other sets; this view will change as the
* backing sets do. Contains methods to copy the data into a new set which will then remain
* stable. There is usually no reason to retain a reference of type {@code SetView}; typically,
* you either use it as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
* {@link #copyInto} and forget the {@code SetView} itself.
*
* @since 2.0
*/
public abstract static class SetView<E extends @Nullable Object> extends AbstractSet<E> {
private SetView() {} // no subclasses but our own
/**
* Returns an immutable copy of the current contents of this set view. Does not support null
* elements.
*
* <p><b>Warning:</b> this may have unexpected results if a backing set of this view uses a
* nonstandard notion of equivalence, for example if it is a {@link TreeSet} using a comparator
* that is inconsistent with {@link Object#equals(Object)}.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't fix it now.
public ImmutableSet<@NonNull E> immutableCopy() {
return ImmutableSet.copyOf((SetView<@NonNull E>) this);
}
/**
* Copies the current contents of this set view into an existing set. This method has equivalent
* behavior to {@code set.addAll(this)}, assuming that all the sets involved are based on the
* same notion of equivalence.
*
* @return a reference to {@code set}, for convenience
*/
// Note: S should logically extend Set<? super E> but can't due to either
// some javac bug or some weirdness in the spec, not sure which.
@CanIgnoreReturnValue
public <S extends Set<E>> S copyInto(S set) {
set.addAll(this);
return set;
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean add(@ParametricNullness E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean remove(@CheckForNull Object object) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean addAll(Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Scope the return type to {@link UnmodifiableIterator} to ensure this is an unmodifiable view.
*
* @since 20.0 (present with return type {@link Iterator} since 2.0)
*/
@Override
public abstract UnmodifiableIterator<E> iterator();
}
/**
* Returns an unmodifiable <b>view</b> of the union of two sets. The returned set contains all
* elements that are contained in either backing set. Iterating over the returned set iterates
* first over all the elements of {@code set1}, then over each element of {@code set2}, in order,
* that is not contained in {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*/
public static <E extends @Nullable Object> SetView<E> union(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public int size() {
int size = set1.size();
for (E e : set2) {
if (!set1.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return set1.isEmpty() && set2.isEmpty();
}
@Override
public UnmodifiableIterator<E> iterator() {
return new AbstractIterator<E>() {
final Iterator<? extends E> itr1 = set1.iterator();
final Iterator<? extends E> itr2 = set2.iterator();
@Override
@CheckForNull
protected E computeNext() {
if (itr1.hasNext()) {
return itr1.next();
}
while (itr2.hasNext()) {
E e = itr2.next();
if (!set1.contains(e)) {
return e;
}
}
return endOfData();
}
};
}
@Override
public boolean contains(@CheckForNull Object object) {
return set1.contains(object) || set2.contains(object);
}
@Override
public <S extends Set<E>> S copyInto(S set) {
set.addAll(set1);
set.addAll(set2);
return set;
}
@Override
@SuppressWarnings({"nullness", "unchecked"}) // see supertype
public ImmutableSet<@NonNull E> immutableCopy() {
ImmutableSet.Builder<@NonNull E> builder =
new ImmutableSet.Builder<@NonNull E>()
.addAll((Iterable<@NonNull E>) set1)
.addAll((Iterable<@NonNull E>) set2);
return (ImmutableSet<@NonNull E>) builder.build();
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the intersection of two sets. The returned set contains
* all elements that are contained by both backing sets. The iteration order of the returned set
* matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*
* <p><b>Note:</b> The returned view performs slightly better when {@code set1} is the smaller of
* the two sets. If you have reason to believe one of your sets will generally be smaller than the
* other, pass it first. Unfortunately, since this method sets the generic type of the returned
* set based on the type of the first set passed, this could in rare cases force you to make a
* cast, for example:
*
* <pre>{@code
* Set<Object> aFewBadObjects = ...
* Set<String> manyBadStrings = ...
*
* // impossible for a non-String to be in the intersection
* SuppressWarnings("unchecked")
* Set<String> badStrings = (Set) Sets.intersection(
* aFewBadObjects, manyBadStrings);
* }</pre>
*
* <p>This is unfortunate, but should come up only very rarely.
*/
public static <E extends @Nullable Object> SetView<E> intersection(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public UnmodifiableIterator<E> iterator() {
return new AbstractIterator<E>() {
final Iterator<E> itr = set1.iterator();
@Override
@CheckForNull
protected E computeNext() {
while (itr.hasNext()) {
E e = itr.next();
if (set2.contains(e)) {
return e;
}
}
return endOfData();
}
};
}
@Override
public int size() {
int size = 0;
for (E e : set1) {
if (set2.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return Collections.disjoint(set2, set1);
}
@Override
public boolean contains(@CheckForNull Object object) {
return set1.contains(object) && set2.contains(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return set1.containsAll(collection) && set2.containsAll(collection);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the difference of two sets. The returned set contains
* all elements that are contained by {@code set1} and not contained by {@code set2}. {@code set2}
* may also contain elements not present in {@code set1}; these are simply ignored. The iteration
* order of the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*/
public static <E extends @Nullable Object> SetView<E> difference(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public UnmodifiableIterator<E> iterator() {
return new AbstractIterator<E>() {
final Iterator<E> itr = set1.iterator();
@Override
@CheckForNull
protected E computeNext() {
while (itr.hasNext()) {
E e = itr.next();
if (!set2.contains(e)) {
return e;
}
}
return endOfData();
}
};
}
@Override
public int size() {
int size = 0;
for (E e : set1) {
if (!set2.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return set2.containsAll(set1);
}
@Override
public boolean contains(@CheckForNull Object element) {
return set1.contains(element) && !set2.contains(element);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the symmetric difference of two sets. The returned set
* contains all elements that are contained in either {@code set1} or {@code set2} but not in
* both. The iteration order of the returned set is undefined.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*
* @since 3.0
*/
public static <E extends @Nullable Object> SetView<E> symmetricDifference(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public UnmodifiableIterator<E> iterator() {
final Iterator<? extends E> itr1 = set1.iterator();
final Iterator<? extends E> itr2 = set2.iterator();
return new AbstractIterator<E>() {
@Override
@CheckForNull
public E computeNext() {
while (itr1.hasNext()) {
E elem1 = itr1.next();
if (!set2.contains(elem1)) {
return elem1;
}
}
while (itr2.hasNext()) {
E elem2 = itr2.next();
if (!set1.contains(elem2)) {
return elem2;
}
}
return endOfData();
}
};
}
@Override
public int size() {
int size = 0;
for (E e : set1) {
if (!set2.contains(e)) {
size++;
}
}
for (E e : set2) {
if (!set1.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return set1.equals(set2);
}
@Override
public boolean contains(@CheckForNull Object element) {
return set1.contains(element) ^ set2.contains(element);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The returned set is a live
* view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all other set methods
* are supported. When given an element that doesn't satisfy the predicate, the set's {@code
* add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements
* that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in
* the underlying set and determine which elements satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and
* use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link
* java.util.stream.Stream#filter}. This method is not being deprecated, but we gently encourage
* you to migrate to streams.
*/
// TODO(kevinb): how to omit that last sentence when building GWT javadoc?
public static <E extends @Nullable Object> Set<E> filter(
Set<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof SortedSet) {
return filter((SortedSet<E>) unfiltered, predicate);
}
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
return new FilteredSet<>((Set<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSet<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy a predicate. The
* returned set is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all other set methods
* are supported. When given an element that doesn't satisfy the predicate, the set's {@code
* add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements
* that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in
* the underlying set and determine which elements satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and
* use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* @since 11.0
*/
public static <E extends @Nullable Object> SortedSet<E> filter(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
return new FilteredSortedSet<>((SortedSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSortedSet<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that satisfy a predicate.
* The returned set is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all other set methods
* are supported. When given an element that doesn't satisfy the predicate, the set's {@code
* add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements
* that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in
* the underlying set and determine which elements satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and
* use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* @since 14.0
*/
@GwtIncompatible // NavigableSet
public static <E extends @Nullable Object> NavigableSet<E> filter(
NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
return new FilteredNavigableSet<>((NavigableSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredNavigableSet<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSet<E extends @Nullable Object> extends FilteredCollection<E>
implements Set<E> {
FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override
public boolean equals(@CheckForNull Object object) {
return equalsImpl(this, object);
}
@Override
public int hashCode() {
return hashCodeImpl(this);
}
}
private static class FilteredSortedSet<E extends @Nullable Object> extends FilteredSet<E>
implements SortedSet<E> {
FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override
@CheckForNull
public Comparator<? super E> comparator() {
return ((SortedSet<E>) unfiltered).comparator();
}
@Override
public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return new FilteredSortedSet<>(
((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate);
}
@Override
public SortedSet<E> headSet(@ParametricNullness E toElement) {
return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
}
@Override
public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
}
@Override
@ParametricNullness
public E first() {
return Iterators.find(unfiltered.iterator(), predicate);
}
@Override
@ParametricNullness
public E last() {
SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
while (true) {
E element = sortedUnfiltered.last();
if (predicate.apply(element)) {
return element;
}
sortedUnfiltered = sortedUnfiltered.headSet(element);
}
}
}
@GwtIncompatible // NavigableSet
private static class FilteredNavigableSet<E extends @Nullable Object> extends FilteredSortedSet<E>
implements NavigableSet<E> {
FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
NavigableSet<E> unfiltered() {
return (NavigableSet<E>) unfiltered;
}
@Override
@CheckForNull
public E lower(@ParametricNullness E e) {
return Iterators.find(unfiltered().headSet(e, false).descendingIterator(), predicate, null);
}
@Override
@CheckForNull
public E floor(@ParametricNullness E e) {
return Iterators.find(unfiltered().headSet(e, true).descendingIterator(), predicate, null);
}
@Override
@CheckForNull
public E ceiling(@ParametricNullness E e) {
return Iterables.find(unfiltered().tailSet(e, true), predicate, null);
}
@Override
@CheckForNull
public E higher(@ParametricNullness E e) {
return Iterables.find(unfiltered().tailSet(e, false), predicate, null);
}
@Override
@CheckForNull
public E pollFirst() {
return Iterables.removeFirstMatching(unfiltered(), predicate);
}
@Override
@CheckForNull
public E pollLast() {
return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate);
}
@Override
public NavigableSet<E> descendingSet() {
return Sets.filter(unfiltered().descendingSet(), predicate);
}
@Override
public Iterator<E> descendingIterator() {
return Iterators.filter(unfiltered().descendingIterator(), predicate);
}
@Override
@ParametricNullness
public E last() {
return Iterators.find(unfiltered().descendingIterator(), predicate);
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return filter(
unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate);
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return filter(unfiltered().headSet(toElement, inclusive), predicate);
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return filter(unfiltered().tailSet(fromElement, inclusive), predicate);
}
}
/**
* Returns every possible list that can be formed by choosing one element from each of the given
* sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example:
*
* <pre>{@code
* Sets.cartesianProduct(ImmutableList.of(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C")))
* }</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
* products that you would get from nesting for loops:
*
* <pre>{@code
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }
* }</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at
* all are provided (an empty list), the resulting Cartesian product has one element, an empty
* list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a
* set of size {@code m x n x p}, its actual memory consumption is much smaller. When the
* cartesian set is constructed, the input sets are merely copied. Only as the resulting set is
* iterated are the individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that the elements chosen from those
* sets should appear in the resulting lists
* @param <B> any common base class shared by all axes (often just {@link Object})
* @return the Cartesian product, as an immutable set containing immutable lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a
* provided set is null
* @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets) {
return CartesianSet.create(sets);
}
/**
* Returns every possible list that can be formed by choosing one element from each of the given
* sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example:
*
* <pre>{@code
* Sets.cartesianProduct(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C"))
* }</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
* products that you would get from nesting for loops:
*
* <pre>{@code
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }
* }</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at
* all are provided (an empty list), the resulting Cartesian product has one element, an empty
* list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a
* set of size {@code m x n x p}, its actual memory consumption is much smaller. When the
* cartesian set is constructed, the input sets are merely copied. Only as the resulting set is
* iterated are the individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that the elements chosen from those
* sets should appear in the resulting lists
* @param <B> any common base class shared by all axes (often just {@link Object})
* @return the Cartesian product, as an immutable set containing immutable lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a
* provided set is null
* @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range
* @since 2.0
*/
@SafeVarargs
public static <B> Set<List<B>> cartesianProduct(Set<? extends B>... sets) {
return cartesianProduct(Arrays.asList(sets));
}
private static final class CartesianSet<E> extends ForwardingCollection<List<E>>
implements Set<List<E>> {
private final transient ImmutableList<ImmutableSet<E>> axes;
private final transient CartesianList<E> delegate;
static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<>(sets.size());
for (Set<? extends E> set : sets) {
ImmutableSet<E> copy = ImmutableSet.copyOf(set);
if (copy.isEmpty()) {
return ImmutableSet.of();
}
axesBuilder.add(copy);
}
final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
ImmutableList<List<E>> listAxes =
new ImmutableList<List<E>>() {
@Override
public int size() {
return axes.size();
}
@Override
public List<E> get(int index) {
return axes.get(index).asList();
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
}
private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
this.axes = axes;
this.delegate = delegate;
}
@Override
protected Collection<List<E>> delegate() {
return delegate;
}
@Override
public boolean contains(@CheckForNull Object object) {
if (!(object instanceof List)) {
return false;
}
List<?> list = (List<?>) object;
if (list.size() != axes.size()) {
return false;
}
int i = 0;
for (Object o : list) {
if (!axes.get(i).contains(o)) {
return false;
}
i++;
}
return true;
}
@Override
public boolean equals(@CheckForNull Object object) {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
if (object instanceof CartesianSet) {
CartesianSet<?> that = (CartesianSet<?>) object;
return this.axes.equals(that.axes);
}
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return this.size() == that.size() && this.containsAll(that);
}
return false;
}
@Override
public int hashCode() {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
// It's a weird formula, but tests prove it works.
int adjust = size() - 1;
for (int i = 0; i < axes.size(); i++) {
adjust *= 31;
adjust = ~~adjust;
// in GWT, we have to deal with integer overflow carefully
}
int hash = 1;
for (Set<E> axis : axes) {
hash = 31 * hash + (size() / axis.size() * axis.hashCode());
hash = ~~hash;
}
hash += adjust;
return ~~hash;
}
}
/**
* Returns the set of all possible subsets of {@code set}. For example, {@code
* powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, {1}, {2}, {1, 2}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they appeared in the input
* set. The order in which these subsets appear in the outer set is undefined. Note that the power
* set of the empty set is not the empty set, but a one-element set containing the empty set.
*
* <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
* are identical, even if the input set uses a different concept of equivalence.
*
* <p><i>Performance notes:</i> while the power set of a set with size {@code n} is of size {@code
* 2^n}, its memory usage is only {@code O(n)}. When the power set is constructed, the input set
* is merely copied. Only as the power set is iterated are the individual subsets created, and
* these subsets themselves occupy only a small constant amount of memory.
*
* @param set the set of elements to construct a power set from
* @return the power set, as an immutable set of immutable sets
* @throws IllegalArgumentException if {@code set} has more than 30 unique elements (causing the
* power set size to exceed the {@code int} range)
* @throws NullPointerException if {@code set} is or contains {@code null}
* @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at Wikipedia</a>
* @since 4.0
*/
@GwtCompatible(serializable = false)
public static <E> Set<Set<E>> powerSet(Set<E> set) {
return new PowerSet<E>(set);
}
private static final class SubSet<E> extends AbstractSet<E> {
private final ImmutableMap<E, Integer> inputSet;
private final int mask;
SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
this.inputSet = inputSet;
this.mask = mask;
}
@Override
public Iterator<E> iterator() {
return new UnmodifiableIterator<E>() {
final ImmutableList<E> elements = inputSet.keySet().asList();
int remainingSetBits = mask;
@Override
public boolean hasNext() {
return remainingSetBits != 0;
}
@Override
public E next() {
int index = Integer.numberOfTrailingZeros(remainingSetBits);
if (index == 32) {
throw new NoSuchElementException();
}
remainingSetBits &= ~(1 << index);
return elements.get(index);
}
};
}
@Override
public int size() {
return Integer.bitCount(mask);
}
@Override
public boolean contains(@CheckForNull Object o) {
Integer index = inputSet.get(o);
return index != null && (mask & (1 << index)) != 0;
}
}
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableMap<E, Integer> inputSet;
PowerSet(Set<E> input) {
checkArgument(
input.size() <= 30, "Too many elements to create power set: %s > 30", input.size());
this.inputSet = Maps.indexMap(input);
}
@Override
public int size() {
return 1 << inputSet.size();
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<Set<E>> iterator() {
return new AbstractIndexedListIterator<Set<E>>(size()) {
@Override
protected Set<E> get(final int setBits) {
return new SubSet<>(inputSet, setBits);
}
};
}
@Override
public boolean contains(@CheckForNull Object obj) {
if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
return inputSet.keySet().containsAll(set);
}
return false;
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof PowerSet) {
PowerSet<?> that = (PowerSet<?>) obj;
return inputSet.keySet().equals(that.inputSet.keySet());
}
return super.equals(obj);
}
@Override
public int hashCode() {
/*
* The sum of the sums of the hash codes in each subset is just the sum of
* each input element's hash code times the number of sets that element
* appears in. Each element appears in exactly half of the 2^n sets, so:
*/
return inputSet.keySet().hashCode() << (inputSet.size() - 1);
}
@Override
public String toString() {
return "powerSet(" + inputSet + ")";
}
}
/**
* Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code
* combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they appeared in the input
* set. The order in which these subsets appear in the outer set is undefined.
*
* <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
* are identical, even if the input set uses a different concept of equivalence.
*
* <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When
* the result set is constructed, the input set is merely copied. Only as the result set is
* iterated are the individual subsets created. Each of these subsets occupies an additional O(n)
* memory but only for as long as the user retains a reference to it. That is, the set returned by
* {@code combinations} does not retain the individual subsets.
*
* @param set the set of elements to take combinations of
* @param size the number of elements per combination
* @return the set of all combinations of {@code size} elements from {@code set}
* @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()}
* inclusive
* @throws NullPointerException if {@code set} is or contains {@code null}
* @since 23.0
*/
public static <E> Set<Set<E>> combinations(Set<E> set, final int size) {
final ImmutableMap<E, Integer> index = Maps.indexMap(set);
checkNonnegative(size, "size");
checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size());
if (size == 0) {
return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of());
} else if (size == index.size()) {
return ImmutableSet.<Set<E>>of(index.keySet());
}
return new AbstractSet<Set<E>>() {
@Override
public boolean contains(@CheckForNull Object o) {
if (o instanceof Set) {
Set<?> s = (Set<?>) o;
return s.size() == size && index.keySet().containsAll(s);
}
return false;
}
@Override
public Iterator<Set<E>> iterator() {
return new AbstractIterator<Set<E>>() {
final BitSet bits = new BitSet(index.size());
@Override
@CheckForNull
protected Set<E> computeNext() {
if (bits.isEmpty()) {
bits.set(0, size);
} else {
int firstSetBit = bits.nextSetBit(0);
int bitToFlip = bits.nextClearBit(firstSetBit);
if (bitToFlip == index.size()) {
return endOfData();
}
/*
* The current set in sorted order looks like
* {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...}
* where it does *not* contain bitToFlip.
*
* The next combination is
*
* {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...}
*
* This is lexicographically next if you look at the combinations in descending order
* e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}...
*/
bits.set(0, bitToFlip - firstSetBit - 1);
bits.clear(bitToFlip - firstSetBit - 1, bitToFlip);
bits.set(bitToFlip);
}
final BitSet copy = (BitSet) bits.clone();
return new AbstractSet<E>() {
@Override
public boolean contains(@CheckForNull Object o) {
Integer i = index.get(o);
return i != null && copy.get(i);
}
@Override
public Iterator<E> iterator() {
return new AbstractIterator<E>() {
int i = -1;
@Override
@CheckForNull
protected E computeNext() {
i = copy.nextSetBit(i + 1);
if (i == -1) {
return endOfData();
}
return index.keySet().asList().get(i);
}
};
}
@Override
public int size() {
return size;
}
};
}
};
}
@Override
public int size() {
return IntMath.binomial(index.size(), size);
}
@Override
public String toString() {
return "Sets.combinations(" + index.keySet() + ", " + size + ")";
}
};
}
/** An implementation for {@link Set#hashCode()}. */
static int hashCodeImpl(Set<?> s) {
int hashCode = 0;
for (Object o : s) {
hashCode += o != null ? o.hashCode() : 0;
hashCode = ~~hashCode;
// Needed to deal with unusual integer overflow in GWT.
}
return hashCode;
}
/** An implementation for {@link Set#equals(Object)}. */
static boolean equalsImpl(Set<?> s, @CheckForNull Object object) {
if (s == object) {
return true;
}
if (object instanceof Set) {
Set<?> o = (Set<?>) object;
try {
return s.size() == o.size() && s.containsAll(o);
} catch (NullPointerException | ClassCastException ignored) {
return false;
}
}
return false;
}
/**
* Returns an unmodifiable view of the specified navigable set. This method allows modules to
* provide users with "read-only" access to internal navigable sets. Query operations on the
* returned set "read through" to the specified set, and attempts to modify the returned set,
* whether direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
* <p><b>Java 8+ users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}.
*
* @param set the navigable set for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable set
* @since 12.0
*/
public static <E extends @Nullable Object> NavigableSet<E> unmodifiableNavigableSet(
NavigableSet<E> set) {
if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) {
return set;
}
return new UnmodifiableNavigableSet<>(set);
}
static final class UnmodifiableNavigableSet<E extends @Nullable Object>
extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable {
private final NavigableSet<E> delegate;
private final SortedSet<E> unmodifiableDelegate;
UnmodifiableNavigableSet(NavigableSet<E> delegate) {
this.delegate = checkNotNull(delegate);
this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate);
}
@Override
protected SortedSet<E> delegate() {
return unmodifiableDelegate;
}
@Override
@CheckForNull
public E lower(@ParametricNullness E e) {
return delegate.lower(e);
}
@Override
@CheckForNull
public E floor(@ParametricNullness E e) {
return delegate.floor(e);
}
@Override
@CheckForNull
public E ceiling(@ParametricNullness E e) {
return delegate.ceiling(e);
}
@Override
@CheckForNull
public E higher(@ParametricNullness E e) {
return delegate.higher(e);
}
@Override
@CheckForNull
public E pollFirst() {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public E pollLast() {
throw new UnsupportedOperationException();
}
@LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
@Override
public NavigableSet<E> descendingSet() {
UnmodifiableNavigableSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = new UnmodifiableNavigableSet<>(delegate.descendingSet());
result.descendingSet = this;
}
return result;
}
@Override
public Iterator<E> descendingIterator() {
return Iterators.unmodifiableIterator(delegate.descendingIterator());
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return unmodifiableNavigableSet(
delegate.subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive));
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In
* order to guarantee serial access, it is critical that <b>all</b> access to the backing
* navigable set is accomplished through the returned navigable set (or its views).
*
* <p>It is imperative that the user manually synchronize on the returned sorted set when
* iterating over it or any of its {@code descendingSet}, {@code subSet}, {@code headSet}, or
* {@code tailSet} views.
*
* <pre>{@code
* NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
* ...
* synchronized (set) {
* // Must be in the synchronized block
* Iterator<E> it = set.iterator();
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>or:
*
* <pre>{@code
* NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
* NavigableSet<E> set2 = set.descendingSet().headSet(foo);
* ...
* synchronized (set) { // Note: set, not set2!!!
* // Must be in the synchronized block
* Iterator<E> it = set2.descendingIterator();
* while (it.hasNext())
* foo(it.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
* <p><b>Java 8+ users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}.
*
* @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set.
* @return a synchronized view of the specified navigable set.
* @since 13.0
*/
@GwtIncompatible // NavigableSet
public static <E extends @Nullable Object> NavigableSet<E> synchronizedNavigableSet(
NavigableSet<E> navigableSet) {
return Synchronized.navigableSet(navigableSet);
}
/** Remove each element in an iterable from a set. */
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
boolean changed = false;
while (iterator.hasNext()) {
changed |= set.remove(iterator.next());
}
return changed;
}
static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
checkNotNull(collection); // for GWT
if (collection instanceof Multiset) {
collection = ((Multiset<?>) collection).elementSet();
}
/*
* AbstractSet.removeAll(List) has quadratic behavior if the list size
* is just more than the set's size. We augment the test by
* assuming that sets have fast contains() performance, and other
* collections don't. See
* http://code.google.com/p/guava-libraries/issues/detail?id=1013
*/
if (collection instanceof Set && collection.size() > set.size()) {
return Iterators.removeAll(set.iterator(), collection);
} else {
return removeAllImpl(set, collection.iterator());
}
}
@GwtIncompatible // NavigableSet
static class DescendingSet<E extends @Nullable Object> extends ForwardingNavigableSet<E> {
private final NavigableSet<E> forward;
DescendingSet(NavigableSet<E> forward) {
this.forward = forward;
}
@Override
protected NavigableSet<E> delegate() {
return forward;
}
@Override
@CheckForNull
public E lower(@ParametricNullness E e) {
return forward.higher(e);
}
@Override
@CheckForNull
public E floor(@ParametricNullness E e) {
return forward.ceiling(e);
}
@Override
@CheckForNull
public E ceiling(@ParametricNullness E e) {
return forward.floor(e);
}
@Override
@CheckForNull
public E higher(@ParametricNullness E e) {
return forward.lower(e);
}
@Override
@CheckForNull
public E pollFirst() {
return forward.pollLast();
}
@Override
@CheckForNull
public E pollLast() {
return forward.pollFirst();
}
@Override
public NavigableSet<E> descendingSet() {
return forward;
}
@Override
public Iterator<E> descendingIterator() {
return forward.iterator();
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
}
@Override
public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return standardSubSet(fromElement, toElement);
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return forward.tailSet(toElement, inclusive).descendingSet();
}
@Override
public SortedSet<E> headSet(@ParametricNullness E toElement) {
return standardHeadSet(toElement);
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return forward.headSet(fromElement, inclusive).descendingSet();
}
@Override
public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
return standardTailSet(fromElement);
}
@SuppressWarnings("unchecked")
@Override
public Comparator<? super E> comparator() {
Comparator<? super E> forwardComparator = forward.comparator();
if (forwardComparator == null) {
return (Comparator) Ordering.natural().reverse();
} else {
return reverse(forwardComparator);
}
}
// If we inline this, we get a javac error.
private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) {
return Ordering.from(forward).reverse();
}
@Override
@ParametricNullness
public E first() {
return forward.last();
}
@Override
@ParametricNullness
public E last() {
return forward.first();
}
@Override
public Iterator<E> iterator() {
return forward.descendingIterator();
}
@Override
public @Nullable Object[] toArray() {
return standardToArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override
public String toString() {
return standardToString();
}
}
/**
* Returns a view of the portion of {@code set} whose elements are contained by {@code range}.
*
* <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely {@link
* NavigableSet#subSet(Object, boolean, Object, boolean) subSet()}, {@link
* NavigableSet#tailSet(Object, boolean) tailSet()}, and {@link NavigableSet#headSet(Object,
* boolean) headSet()}) to actually construct the view. Consult these methods for a full
* description of the returned view's behavior.
*
* <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
* ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a {@link
* Comparator}, which can violate the natural ordering. Using this method (or in general using
* {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined behavior.
*
* @since 20.0
*/
@GwtIncompatible // NavigableSet
public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
NavigableSet<K> set, Range<K> range) {
if (set.comparator() != null
&& set.comparator() != Ordering.natural()
&& range.hasLowerBound()
&& range.hasUpperBound()) {
checkArgument(
set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
"set is using a custom comparator which is inconsistent with the natural ordering.");
}
if (range.hasLowerBound() && range.hasUpperBound()) {
return set.subSet(
range.lowerEndpoint(),
range.lowerBoundType() == BoundType.CLOSED,
range.upperEndpoint(),
range.upperBoundType() == BoundType.CLOSED);
} else if (range.hasLowerBound()) {
return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
} else if (range.hasUpperBound()) {
return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
}
return checkNotNull(set);
}
}
| google/guava | android/guava/src/com/google/common/collect/Sets.java |
660 | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Spliterator;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
/**
* Implementation of {@link ImmutableSet} backed by a non-empty {@link java.util.EnumSet}.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
static <E extends Enum<E>> ImmutableSet<E> asImmutable(EnumSet<E> set) {
switch (set.size()) {
case 0:
return ImmutableSet.of();
case 1:
return ImmutableSet.of(Iterables.getOnlyElement(set));
default:
return new ImmutableEnumSet<>(set);
}
}
/*
* Notes on EnumSet and <E extends Enum<E>>:
*
* This class isn't an arbitrary ForwardingImmutableSet because we need to
* know that calling {@code clone()} during deserialization will return an
* object that no one else has a reference to, allowing us to guarantee
* immutability. Hence, we support only {@link EnumSet}.
*/
private final transient EnumSet<E> delegate;
private ImmutableEnumSet(EnumSet<E> delegate) {
this.delegate = delegate;
}
@Override
boolean isPartialView() {
return false;
}
@Override
public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override
public Spliterator<E> spliterator() {
return delegate.spliterator();
}
@Override
public void forEach(Consumer<? super E> action) {
delegate.forEach(action);
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean contains(@CheckForNull Object object) {
return delegate.contains(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
if (collection instanceof ImmutableEnumSet<?>) {
collection = ((ImmutableEnumSet<?>) collection).delegate;
}
return delegate.containsAll(collection);
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof ImmutableEnumSet) {
object = ((ImmutableEnumSet<?>) object).delegate;
}
return delegate.equals(object);
}
@Override
boolean isHashCodeFast() {
return true;
}
@LazyInit private transient int hashCode;
@Override
public int hashCode() {
int result = hashCode;
return (result == 0) ? hashCode = delegate.hashCode() : result;
}
@Override
public String toString() {
return delegate.toString();
}
// All callers of the constructor are restricted to <E extends Enum<E>>.
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return new EnumSerializedForm<E>(delegate);
}
@J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
@J2ktIncompatible // serialization
private static class EnumSerializedForm<E extends Enum<E>> implements Serializable {
final EnumSet<E> delegate;
EnumSerializedForm(EnumSet<E> delegate) {
this.delegate = delegate;
}
Object readResolve() {
// EJ2 #76: Write readObject() methods defensively.
return new ImmutableEnumSet<E>(delegate.clone());
}
private static final long serialVersionUID = 0;
}
}
| google/guava | guava/src/com/google/common/collect/ImmutableEnumSet.java |
661 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.engine;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.codecs.perfield.PerFieldKnnVectorsFormat;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.SegmentCommitInfo;
import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.index.SegmentReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.QueryCache;
import org.apache.lucene.search.QueryCachingPolicy;
import org.apache.lucene.search.ReferenceManager;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.SubscribableListener;
import org.elasticsearch.cluster.service.ClusterApplierService;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver;
import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndVersion;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.util.concurrent.ReleasableLock;
import org.elasticsearch.common.util.concurrent.UncategorizedExecutionException;
import org.elasticsearch.core.AbstractRefCounted;
import org.elasticsearch.core.CheckedRunnable;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.RefCounted;
import org.elasticsearch.core.Releasable;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.core.UpdateForV9;
import org.elasticsearch.index.IndexVersion;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.mapper.DocumentParser;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.LuceneDocument;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.MappingLookup;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.merge.MergeStats;
import org.elasticsearch.index.seqno.SeqNoStats;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.DenseVectorStats;
import org.elasticsearch.index.shard.DocsStats;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardLongFieldRange;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogStats;
import org.elasticsearch.search.suggest.completion.CompletionStats;
import org.elasticsearch.transport.Transports;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.elasticsearch.core.Strings.format;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
public abstract class Engine implements Closeable {
@UpdateForV9 // TODO: Remove sync_id in 9.0
public static final String SYNC_COMMIT_ID = "sync_id";
public static final String HISTORY_UUID_KEY = "history_uuid";
public static final String FORCE_MERGE_UUID_KEY = "force_merge_uuid";
public static final String MIN_RETAINED_SEQNO = "min_retained_seq_no";
public static final String MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID = "max_unsafe_auto_id_timestamp";
// Field name that stores the Elasticsearch version in Lucene commit user data, representing
// the version that was used to write the commit (and thus a max version for the underlying segments).
public static final String ES_VERSION = "es_version";
public static final String SEARCH_SOURCE = "search"; // TODO: Make source of search enum?
public static final String CAN_MATCH_SEARCH_SOURCE = "can_match";
protected static final String DOC_STATS_SOURCE = "doc_stats";
public static final long UNKNOWN_PRIMARY_TERM = -1L;
protected final ShardId shardId;
protected final Logger logger;
protected final EngineConfig engineConfig;
protected final Store store;
protected final AtomicBoolean isClosed = new AtomicBoolean(false);
private final CountDownLatch closedLatch = new CountDownLatch(1);
protected final EventListener eventListener;
protected final ReentrantLock failEngineLock = new ReentrantLock();
protected final SetOnce<Exception> failedEngine = new SetOnce<>();
private final AtomicBoolean isClosing = new AtomicBoolean();
private final SubscribableListener<Void> drainOnCloseListener = new SubscribableListener<>();
private final RefCounted ensureOpenRefs = AbstractRefCounted.of(() -> drainOnCloseListener.onResponse(null));
private final Releasable releaseEnsureOpenRef = ensureOpenRefs::decRef; // reuse this to avoid allocation for each op
/*
* on {@code lastWriteNanos} we use System.nanoTime() to initialize this since:
* - we use the value for figuring out if the shard / engine is active so if we startup and no write has happened yet we still
* consider it active for the duration of the configured active to inactive period. If we initialize to 0 or Long.MAX_VALUE we
* either immediately or never mark it inactive if no writes at all happen to the shard.
* - we also use this to flush big-ass merges on an inactive engine / shard but if we we initialize 0 or Long.MAX_VALUE we either
* immediately or never commit merges even though we shouldn't from a user perspective (this can also have funky side effects in
* tests when we open indices with lots of segments and suddenly merges kick in.
* NOTE: don't use this value for anything accurate it's a best effort for freeing up diskspace after merges and on a shard level to
* reduce index buffer sizes on inactive shards.
*/
protected volatile long lastWriteNanos = System.nanoTime();
protected Engine(EngineConfig engineConfig) {
Objects.requireNonNull(engineConfig.getStore(), "Store must be provided to the engine");
this.engineConfig = engineConfig;
this.shardId = engineConfig.getShardId();
this.store = engineConfig.getStore();
// we use the engine class directly here to make sure all subclasses have the same logger name
this.logger = Loggers.getLogger(Engine.class, engineConfig.getShardId());
this.eventListener = engineConfig.getEventListener();
}
/**
* Reads an {@code IndexVersion} from an {@code es_version} metadata string
*/
public static IndexVersion readIndexVersion(String esVersion) {
if (esVersion.contains(".")) {
// backwards-compatible Version-style
org.elasticsearch.Version v = org.elasticsearch.Version.fromString(esVersion);
assert v.onOrBefore(org.elasticsearch.Version.V_8_11_0);
return IndexVersion.fromId(v.id);
} else {
return IndexVersion.fromId(Integer.parseInt(esVersion));
}
}
public final EngineConfig config() {
return engineConfig;
}
public abstract SegmentInfos getLastCommittedSegmentInfos();
public MergeStats getMergeStats() {
return new MergeStats();
}
/** returns the history uuid for the engine */
public abstract String getHistoryUUID();
/** Returns how many bytes we are currently moving from heap to disk */
public abstract long getWritingBytes();
/**
* Returns the {@link CompletionStats} for this engine
*/
public abstract CompletionStats completionStats(String... fieldNamePatterns);
/**
* Returns the {@link DocsStats} for this engine
*/
public DocsStats docStats() {
// we calculate the doc stats based on the internal searcher that is more up-to-date and not subject
// to external refreshes. For instance we don't refresh an external searcher if we flush and indices with
// index.refresh_interval=-1 won't see any doc stats updates at all. This change will give more accurate statistics
// when indexing but not refreshing in general. Yet, if a refresh happens the internal searcher is refresh as well so we are
// safe here.
try (Searcher searcher = acquireSearcher(DOC_STATS_SOURCE, SearcherScope.INTERNAL)) {
return docsStats(searcher.getIndexReader());
}
}
protected final DocsStats docsStats(IndexReader indexReader) {
long numDocs = 0;
long numDeletedDocs = 0;
long sizeInBytes = 0;
// we don't wait for a pending refreshes here since it's a stats call instead we mark it as accessed only which will cause
// the next scheduled refresh to go through and refresh the stats as well
for (LeafReaderContext readerContext : indexReader.leaves()) {
// we go on the segment level here to get accurate numbers
final SegmentReader segmentReader = Lucene.segmentReader(readerContext.reader());
SegmentCommitInfo info = segmentReader.getSegmentInfo();
numDocs += readerContext.reader().numDocs();
numDeletedDocs += readerContext.reader().numDeletedDocs();
try {
sizeInBytes += info.sizeInBytes();
} catch (IOException e) {
logger.trace(() -> "failed to get size for [" + info.info.name + "]", e);
}
}
return new DocsStats(numDocs, numDeletedDocs, sizeInBytes);
}
/**
* Returns the {@link DenseVectorStats} for this engine
*/
public DenseVectorStats denseVectorStats() {
try (Searcher searcher = acquireSearcher(DOC_STATS_SOURCE, SearcherScope.INTERNAL)) {
return denseVectorStats(searcher.getIndexReader());
}
}
protected final DenseVectorStats denseVectorStats(IndexReader indexReader) {
long valueCount = 0;
// we don't wait for a pending refreshes here since it's a stats call instead we mark it as accessed only which will cause
// the next scheduled refresh to go through and refresh the stats as well
for (LeafReaderContext readerContext : indexReader.leaves()) {
try {
valueCount += getDenseVectorValueCount(readerContext.reader());
} catch (IOException e) {
logger.trace(() -> "failed to get dense vector stats for [" + readerContext + "]", e);
}
}
return new DenseVectorStats(valueCount);
}
private long getDenseVectorValueCount(final LeafReader atomicReader) throws IOException {
long count = 0;
for (FieldInfo info : atomicReader.getFieldInfos()) {
if (info.getVectorDimension() > 0) {
switch (info.getVectorEncoding()) {
case FLOAT32 -> {
FloatVectorValues values = atomicReader.getFloatVectorValues(info.name);
count += values != null ? values.size() : 0;
}
case BYTE -> {
ByteVectorValues values = atomicReader.getByteVectorValues(info.name);
count += values != null ? values.size() : 0;
}
}
}
}
return count;
}
/**
* Performs the pre-closing checks on the {@link Engine}.
*
* @throws IllegalStateException if the sanity checks failed
*/
public void verifyEngineBeforeIndexClosing() throws IllegalStateException {
final long globalCheckpoint = engineConfig.getGlobalCheckpointSupplier().getAsLong();
final long maxSeqNo = getSeqNoStats(globalCheckpoint).getMaxSeqNo();
if (globalCheckpoint != maxSeqNo) {
throw new IllegalStateException(
"Global checkpoint ["
+ globalCheckpoint
+ "] mismatches maximum sequence number ["
+ maxSeqNo
+ "] on index shard "
+ shardId
);
}
}
public interface IndexCommitListener {
/**
* This method is invoked each time a new Lucene commit is created through this engine. Note that commits are notified in order. The
* {@link IndexCommitRef} prevents the {@link IndexCommitRef} files to be deleted from disk until the reference is closed. As such,
* the listener must close the reference as soon as it is done with it.
*
* @param shardId the {@link ShardId} of shard
* @param store the index shard store
* @param primaryTerm the shard's primary term value
* @param indexCommitRef a reference on the newly created index commit
* @param additionalFiles the set of filenames that are added by the new commit
*/
void onNewCommit(ShardId shardId, Store store, long primaryTerm, IndexCommitRef indexCommitRef, Set<String> additionalFiles);
/**
* This method is invoked after the policy deleted the given {@link IndexCommit}. A listener is never notified of a deleted commit
* until the corresponding {@link Engine.IndexCommitRef} received through {@link #onNewCommit} has been closed; closing which in
* turn can call this method directly.
*
* @param shardId the {@link ShardId} of shard
* @param deletedCommit the deleted {@link IndexCommit}
*/
void onIndexCommitDelete(ShardId shardId, IndexCommit deletedCommit);
}
/**
* A throttling class that can be activated, causing the
* {@code acquireThrottle} method to block on a lock when throttling
* is enabled
*/
protected static final class IndexThrottle {
private final CounterMetric throttleTimeMillisMetric = new CounterMetric();
private volatile long startOfThrottleNS;
private static final ReleasableLock NOOP_LOCK = new ReleasableLock(new NoOpLock());
private final ReleasableLock lockReference = new ReleasableLock(new ReentrantLock());
private volatile ReleasableLock lock = NOOP_LOCK;
public Releasable acquireThrottle() {
return lock.acquire();
}
/** Activate throttling, which switches the lock to be a real lock */
public void activate() {
assert lock == NOOP_LOCK : "throttling activated while already active";
startOfThrottleNS = System.nanoTime();
lock = lockReference;
}
/** Deactivate throttling, which switches the lock to be an always-acquirable NoOpLock */
public void deactivate() {
assert lock != NOOP_LOCK : "throttling deactivated but not active";
lock = NOOP_LOCK;
assert startOfThrottleNS > 0 : "Bad state of startOfThrottleNS";
long throttleTimeNS = System.nanoTime() - startOfThrottleNS;
if (throttleTimeNS >= 0) {
// Paranoia (System.nanoTime() is supposed to be monotonic): time slip may have occurred but never want
// to add a negative number
throttleTimeMillisMetric.inc(TimeValue.nsecToMSec(throttleTimeNS));
}
}
long getThrottleTimeInMillis() {
long currentThrottleNS = 0;
if (isThrottled() && startOfThrottleNS != 0) {
currentThrottleNS += System.nanoTime() - startOfThrottleNS;
if (currentThrottleNS < 0) {
// Paranoia (System.nanoTime() is supposed to be monotonic): time slip must have happened, have to ignore this value
currentThrottleNS = 0;
}
}
return throttleTimeMillisMetric.count() + TimeValue.nsecToMSec(currentThrottleNS);
}
boolean isThrottled() {
return lock != NOOP_LOCK;
}
boolean throttleLockIsHeldByCurrentThread() { // to be used in assertions and tests only
if (isThrottled()) {
return lock.isHeldByCurrentThread();
}
return false;
}
}
/**
* Returns the number of milliseconds this engine was under index throttling.
*/
public abstract long getIndexThrottleTimeInMillis();
/**
* Returns the <code>true</code> iff this engine is currently under index throttling.
*
* @see #getIndexThrottleTimeInMillis()
*/
public abstract boolean isThrottled();
/**
* Trims translog for terms below <code>belowTerm</code> and seq# above <code>aboveSeqNo</code>
*
* @see Translog#trimOperations(long, long)
*/
public abstract void trimOperationsFromTranslog(long belowTerm, long aboveSeqNo) throws EngineException;
/**
* Returns the total time flushes have been executed excluding waiting on locks.
*/
public long getTotalFlushTimeExcludingWaitingOnLockInMillis() {
return 0;
}
/** A Lock implementation that always allows the lock to be acquired */
protected static final class NoOpLock implements Lock {
@Override
public void lock() {}
@Override
public void lockInterruptibly() throws InterruptedException {}
@Override
public boolean tryLock() {
return true;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public void unlock() {}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException("NoOpLock can't provide a condition");
}
}
/**
* Perform document index operation on the engine
* @param index operation to perform
* @return {@link IndexResult} containing updated translog location, version and
* document specific failures
*
* Note: engine level failures (i.e. persistent engine failures) are thrown
*/
public abstract IndexResult index(Index index) throws IOException;
/**
* Perform document delete operation on the engine
* @param delete operation to perform
* @return {@link DeleteResult} containing updated translog location, version and
* document specific failures
*
* Note: engine level failures (i.e. persistent engine failures) are thrown
*/
public abstract DeleteResult delete(Delete delete) throws IOException;
public abstract NoOpResult noOp(NoOp noOp) throws IOException;
/**
* Base class for index and delete operation results
* Holds result meta data (e.g. translog location, updated version)
* for an executed write {@link Operation}
**/
public abstract static class Result {
private final Operation.TYPE operationType;
private final Result.Type resultType;
private final long version;
private final long term;
private final long seqNo;
private final Exception failure;
private final SetOnce<Boolean> freeze = new SetOnce<>();
private final Mapping requiredMappingUpdate;
private final String id;
private Translog.Location translogLocation;
private long took;
protected Result(Operation.TYPE operationType, Exception failure, long version, long term, long seqNo, String id) {
this.operationType = operationType;
this.failure = Objects.requireNonNull(failure);
this.version = version;
this.term = term;
this.seqNo = seqNo;
this.requiredMappingUpdate = null;
this.resultType = Type.FAILURE;
this.id = id;
}
protected Result(Operation.TYPE operationType, long version, long term, long seqNo, String id) {
this.operationType = operationType;
this.version = version;
this.seqNo = seqNo;
this.term = term;
this.failure = null;
this.requiredMappingUpdate = null;
this.resultType = Type.SUCCESS;
this.id = id;
}
protected Result(Operation.TYPE operationType, Mapping requiredMappingUpdate, String id) {
this.operationType = operationType;
this.version = Versions.NOT_FOUND;
this.seqNo = UNASSIGNED_SEQ_NO;
this.term = UNASSIGNED_PRIMARY_TERM;
this.failure = null;
this.requiredMappingUpdate = requiredMappingUpdate;
this.resultType = Type.MAPPING_UPDATE_REQUIRED;
this.id = id;
}
/** whether the operation was successful, has failed or was aborted due to a mapping update */
public Type getResultType() {
return resultType;
}
/** get the updated document version */
public long getVersion() {
return version;
}
/**
* Get the sequence number on the primary.
*
* @return the sequence number
*/
public long getSeqNo() {
return seqNo;
}
public long getTerm() {
return term;
}
/**
* If the operation was aborted due to missing mappings, this method will return the mappings
* that are required to complete the operation.
*/
public Mapping getRequiredMappingUpdate() {
return requiredMappingUpdate;
}
/** get the translog location after executing the operation */
public Translog.Location getTranslogLocation() {
return translogLocation;
}
/** get document failure while executing the operation {@code null} in case of no failure */
public Exception getFailure() {
return failure;
}
/** get total time in nanoseconds */
public long getTook() {
return took;
}
public Operation.TYPE getOperationType() {
return operationType;
}
public String getId() {
return id;
}
void setTranslogLocation(Translog.Location translogLocation) {
if (freeze.get() == null) {
this.translogLocation = translogLocation;
} else {
throw new IllegalStateException("result is already frozen");
}
}
void setTook(long took) {
if (freeze.get() == null) {
this.took = took;
} else {
throw new IllegalStateException("result is already frozen");
}
}
void freeze() {
freeze.set(true);
}
public enum Type {
SUCCESS,
FAILURE,
MAPPING_UPDATE_REQUIRED
}
}
public static class IndexResult extends Result {
private final boolean created;
public IndexResult(long version, long term, long seqNo, boolean created, String id) {
super(Operation.TYPE.INDEX, version, term, seqNo, id);
this.created = created;
}
/**
* use in case of the index operation failed before getting to internal engine
**/
public IndexResult(Exception failure, long version, String id) {
this(failure, version, UNASSIGNED_PRIMARY_TERM, UNASSIGNED_SEQ_NO, id);
}
public IndexResult(Exception failure, long version, long term, long seqNo, String id) {
super(Operation.TYPE.INDEX, failure, version, term, seqNo, id);
this.created = false;
}
public IndexResult(Mapping requiredMappingUpdate, String id) {
super(Operation.TYPE.INDEX, requiredMappingUpdate, id);
this.created = false;
}
public boolean isCreated() {
return created;
}
}
public static class DeleteResult extends Result {
private final boolean found;
public DeleteResult(long version, long term, long seqNo, boolean found, String id) {
super(Operation.TYPE.DELETE, version, term, seqNo, id);
this.found = found;
}
/**
* use in case of the delete operation failed before getting to internal engine
**/
public DeleteResult(Exception failure, long version, long term, String id) {
this(failure, version, term, UNASSIGNED_SEQ_NO, false, id);
}
public DeleteResult(Exception failure, long version, long term, long seqNo, boolean found, String id) {
super(Operation.TYPE.DELETE, failure, version, term, seqNo, id);
this.found = found;
}
public boolean isFound() {
return found;
}
}
public static class NoOpResult extends Result {
public NoOpResult(long term, long seqNo) {
super(Operation.TYPE.NO_OP, 0, term, seqNo, null);
}
NoOpResult(long term, long seqNo, Exception failure) {
super(Operation.TYPE.NO_OP, failure, 0, term, seqNo, null);
}
}
protected final GetResult getFromSearcher(Get get, Engine.Searcher searcher, boolean uncachedLookup) throws EngineException {
final DocIdAndVersion docIdAndVersion;
try {
if (uncachedLookup) {
docIdAndVersion = VersionsAndSeqNoResolver.loadDocIdAndVersionUncached(searcher.getIndexReader(), get.uid(), true);
} else {
docIdAndVersion = VersionsAndSeqNoResolver.timeSeriesLoadDocIdAndVersion(searcher.getIndexReader(), get.uid(), true);
}
} catch (Exception e) {
Releasables.closeWhileHandlingException(searcher);
// TODO: A better exception goes here
throw new EngineException(shardId, "Couldn't resolve version", e);
}
if (docIdAndVersion != null) {
if (get.versionType().isVersionConflictForReads(docIdAndVersion.version, get.version())) {
Releasables.close(searcher);
throw new VersionConflictEngineException(
shardId,
"[" + get.id() + "]",
get.versionType().explainConflictForReads(docIdAndVersion.version, get.version())
);
}
if (get.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO
&& (get.getIfSeqNo() != docIdAndVersion.seqNo || get.getIfPrimaryTerm() != docIdAndVersion.primaryTerm)) {
Releasables.close(searcher);
throw new VersionConflictEngineException(
shardId,
get.id(),
get.getIfSeqNo(),
get.getIfPrimaryTerm(),
docIdAndVersion.seqNo,
docIdAndVersion.primaryTerm
);
}
}
if (docIdAndVersion != null) {
// don't release the searcher on this path, it is the
// responsibility of the caller to call GetResult.release
return new GetResult(searcher, docIdAndVersion);
} else {
Releasables.close(searcher);
return GetResult.NOT_EXISTS;
}
}
public abstract GetResult get(
Get get,
MappingLookup mappingLookup,
DocumentParser documentParser,
Function<Engine.Searcher, Engine.Searcher> searcherWrapper
);
/**
* Similar to {@link Engine#get}, but it only attempts to serve the get from the translog.
* If not found in translog, it returns null, as {@link GetResult#NOT_EXISTS} could mean deletion.
*/
public GetResult getFromTranslog(
Get get,
MappingLookup mappingLookup,
DocumentParser documentParser,
Function<Engine.Searcher, Engine.Searcher> searcherWrapper
) {
throw new UnsupportedOperationException();
}
/**
* Acquires a point-in-time reader that can be used to create {@link Engine.Searcher}s on demand.
*/
public final SearcherSupplier acquireSearcherSupplier(Function<Searcher, Searcher> wrapper) throws EngineException {
return acquireSearcherSupplier(wrapper, SearcherScope.EXTERNAL);
}
/**
* Acquires a point-in-time reader that can be used to create {@link Engine.Searcher}s on demand.
*/
public SearcherSupplier acquireSearcherSupplier(Function<Searcher, Searcher> wrapper, SearcherScope scope) throws EngineException {
/* Acquire order here is store -> manager since we need
* to make sure that the store is not closed before
* the searcher is acquired. */
if (store.tryIncRef() == false) {
throw new AlreadyClosedException(shardId + " store is closed", failedEngine.get());
}
Releasable releasable = store::decRef;
try {
ReferenceManager<ElasticsearchDirectoryReader> referenceManager = getReferenceManager(scope);
ElasticsearchDirectoryReader acquire = referenceManager.acquire();
SearcherSupplier reader = new SearcherSupplier(wrapper) {
@Override
public Searcher acquireSearcherInternal(String source) {
assert assertSearcherIsWarmedUp(source, scope);
return new Searcher(
source,
acquire,
engineConfig.getSimilarity(),
engineConfig.getQueryCache(),
engineConfig.getQueryCachingPolicy(),
() -> {}
);
}
@Override
protected void doClose() {
try {
referenceManager.release(acquire);
} catch (IOException e) {
throw new UncheckedIOException("failed to close", e);
} catch (AlreadyClosedException e) {
// This means there's a bug somewhere: don't suppress it
throw new AssertionError(e);
} finally {
store.decRef();
}
}
};
releasable = null; // success - hand over the reference to the engine reader
return reader;
} catch (AlreadyClosedException ex) {
throw ex;
} catch (Exception ex) {
maybeFailEngine("acquire_reader", ex);
ensureOpen(ex); // throw EngineCloseException here if we are already closed
logger.error("failed to acquire reader", ex);
throw new EngineException(shardId, "failed to acquire reader", ex);
} finally {
Releasables.close(releasable);
}
}
public final Searcher acquireSearcher(String source) throws EngineException {
return acquireSearcher(source, SearcherScope.EXTERNAL);
}
public Searcher acquireSearcher(String source, SearcherScope scope) throws EngineException {
return acquireSearcher(source, scope, Function.identity());
}
public Searcher acquireSearcher(String source, SearcherScope scope, Function<Searcher, Searcher> wrapper) throws EngineException {
SearcherSupplier releasable = null;
try {
SearcherSupplier reader = releasable = acquireSearcherSupplier(wrapper, scope);
Searcher searcher = reader.acquireSearcher(source);
releasable = null;
return new Searcher(
source,
searcher.getDirectoryReader(),
searcher.getSimilarity(),
searcher.getQueryCache(),
searcher.getQueryCachingPolicy(),
() -> Releasables.close(searcher, reader)
);
} finally {
Releasables.close(releasable);
}
}
protected abstract ReferenceManager<ElasticsearchDirectoryReader> getReferenceManager(SearcherScope scope);
boolean assertSearcherIsWarmedUp(String source, SearcherScope scope) {
return true;
}
public enum SearcherScope {
EXTERNAL,
INTERNAL
}
/**
* Checks if the underlying storage sync is required.
*/
public abstract boolean isTranslogSyncNeeded();
/**
* Whether search idleness may be allowed to be considered for skipping a scheduled refresh.
*/
public boolean allowSearchIdleOptimization() {
return true;
}
/**
* Ensures that the location has been written to the underlying storage.
*/
public abstract void asyncEnsureTranslogSynced(Translog.Location location, Consumer<Exception> listener);
/**
* Ensures that the global checkpoint has been persisted to the underlying storage.
*/
public abstract void asyncEnsureGlobalCheckpointSynced(long globalCheckpoint, Consumer<Exception> listener);
public abstract void syncTranslog() throws IOException;
/**
* Acquires a lock on the translog files and Lucene soft-deleted documents to prevent them from being trimmed
*/
public abstract Closeable acquireHistoryRetentionLock();
/**
* Counts the number of operations in the range of the given sequence numbers.
*
* @param source the source of the request
* @param fromSeqNo the start sequence number (inclusive)
* @param toSeqNo the end sequence number (inclusive)
* @see #newChangesSnapshot(String, long, long, boolean, boolean, boolean)
*/
public abstract int countChanges(String source, long fromSeqNo, long toSeqNo) throws IOException;
/**
* Creates a new history snapshot from Lucene for reading operations whose seqno in the requesting seqno range (both inclusive).
* This feature requires soft-deletes enabled. If soft-deletes are disabled, this method will throw an {@link IllegalStateException}.
*/
public abstract Translog.Snapshot newChangesSnapshot(
String source,
long fromSeqNo,
long toSeqNo,
boolean requiredFullRange,
boolean singleConsumer,
boolean accessStats
) throws IOException;
/**
* Checks if this engine has every operations since {@code startingSeqNo}(inclusive) in its history (either Lucene or translog)
*/
public abstract boolean hasCompleteOperationHistory(String reason, long startingSeqNo);
/**
* Gets the minimum retained sequence number for this engine.
*
* @return the minimum retained sequence number
*/
public abstract long getMinRetainedSeqNo();
public abstract TranslogStats getTranslogStats();
/**
* Returns the last location that the translog of this engine has written into.
*/
public abstract Translog.Location getTranslogLastWriteLocation();
protected final void ensureOpen(Exception suppressed) {
if (isClosed.get()) {
AlreadyClosedException ace = new AlreadyClosedException(shardId + " engine is closed", failedEngine.get());
if (suppressed != null) {
ace.addSuppressed(suppressed);
}
throw ace;
}
}
protected final void ensureOpen() {
ensureOpen(null);
}
/** get commits stats for the last commit */
public final CommitStats commitStats() {
return new CommitStats(getLastCommittedSegmentInfos());
}
/**
* @return the max issued or seen seqNo for this Engine
*/
public abstract long getMaxSeqNo();
/**
* @return the processed local checkpoint for this Engine
*/
public abstract long getProcessedLocalCheckpoint();
/**
* @return the persisted local checkpoint for this Engine
*/
public abstract long getPersistedLocalCheckpoint();
/**
* @return a {@link SeqNoStats} object, using local state and the supplied global checkpoint
*/
public abstract SeqNoStats getSeqNoStats(long globalCheckpoint);
/**
* Returns the latest global checkpoint value that has been persisted in the underlying storage (i.e. translog's checkpoint)
*/
public abstract long getLastSyncedGlobalCheckpoint();
/**
* Global stats on segments.
*/
public SegmentsStats segmentsStats(boolean includeSegmentFileSizes, boolean includeUnloadedSegments) {
ensureOpen();
Set<String> segmentName = new HashSet<>();
SegmentsStats stats = new SegmentsStats();
try (Searcher searcher = acquireSearcher("segments_stats", SearcherScope.INTERNAL)) {
for (LeafReaderContext ctx : searcher.getIndexReader().getContext().leaves()) {
SegmentReader segmentReader = Lucene.segmentReader(ctx.reader());
fillSegmentStats(segmentReader, includeSegmentFileSizes, stats);
segmentName.add(segmentReader.getSegmentName());
}
}
try (Searcher searcher = acquireSearcher("segments_stats", SearcherScope.EXTERNAL)) {
for (LeafReaderContext ctx : searcher.getIndexReader().getContext().leaves()) {
SegmentReader segmentReader = Lucene.segmentReader(ctx.reader());
if (segmentName.contains(segmentReader.getSegmentName()) == false) {
fillSegmentStats(segmentReader, includeSegmentFileSizes, stats);
}
}
}
writerSegmentStats(stats);
return stats;
}
protected void fillSegmentStats(SegmentReader segmentReader, boolean includeSegmentFileSizes, SegmentsStats stats) {
stats.add(1);
if (includeSegmentFileSizes) {
stats.addFiles(getSegmentFileSizes(segmentReader));
}
}
private Map<String, SegmentsStats.FileStats> getSegmentFileSizes(SegmentReader segmentReader) {
try {
Map<String, SegmentsStats.FileStats> files = new HashMap<>();
final SegmentCommitInfo segmentCommitInfo = segmentReader.getSegmentInfo();
for (String fileName : segmentCommitInfo.files()) {
String fileExtension = IndexFileNames.getExtension(fileName);
if (fileExtension != null) {
try {
long fileLength = segmentReader.directory().fileLength(fileName);
files.put(fileExtension, new SegmentsStats.FileStats(fileExtension, fileLength, 1L, fileLength, fileLength));
} catch (IOException ioe) {
logger.warn(() -> "Error when retrieving file length for [" + fileName + "]", ioe);
} catch (AlreadyClosedException ace) {
logger.warn(() -> "Error when retrieving file length for [" + fileName + "], directory is closed", ace);
return Map.of();
}
}
}
return Collections.unmodifiableMap(files);
} catch (IOException e) {
logger.warn(
() -> format(
"Error when listing files for segment reader [%s] and segment info [%s]",
segmentReader,
segmentReader.getSegmentInfo()
),
e
);
return Map.of();
}
}
protected void writerSegmentStats(SegmentsStats stats) {
// by default we don't have a writer here... subclasses can override this
stats.addVersionMapMemoryInBytes(0);
stats.addIndexWriterMemoryInBytes(0);
}
/** How much heap is used that would be freed by a refresh. This includes both the current memory being freed and any remaining
* memory usage that could be freed, e.g., by refreshing. Note that this may throw {@link AlreadyClosedException}. */
public abstract long getIndexBufferRAMBytesUsed();
final Segment[] getSegmentInfo(SegmentInfos lastCommittedSegmentInfos) {
return getSegmentInfo(lastCommittedSegmentInfos, false);
}
final Segment[] getSegmentInfo(SegmentInfos lastCommittedSegmentInfos, boolean includeVectorFormatsInfo) {
ensureOpen();
Map<String, Segment> segments = new HashMap<>();
// first, go over and compute the search ones...
try (Searcher searcher = acquireSearcher("segments", SearcherScope.EXTERNAL)) {
for (LeafReaderContext ctx : searcher.getIndexReader().getContext().leaves()) {
fillSegmentInfo(Lucene.segmentReader(ctx.reader()), true, segments, includeVectorFormatsInfo);
}
}
try (Searcher searcher = acquireSearcher("segments", SearcherScope.INTERNAL)) {
for (LeafReaderContext ctx : searcher.getIndexReader().getContext().leaves()) {
SegmentReader segmentReader = Lucene.segmentReader(ctx.reader());
if (segments.containsKey(segmentReader.getSegmentName()) == false) {
fillSegmentInfo(segmentReader, false, segments, includeVectorFormatsInfo);
}
}
}
// now, correlate or add the committed ones...
if (lastCommittedSegmentInfos != null) {
for (SegmentCommitInfo info : lastCommittedSegmentInfos) {
Segment segment = segments.get(info.info.name);
if (segment == null) {
segment = new Segment(info.info.name);
segment.search = false;
segment.committed = true;
segment.delDocCount = info.getDelCount() + info.getSoftDelCount();
segment.docCount = info.info.maxDoc() - segment.delDocCount;
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace(() -> "failed to get size for [" + info.info.name + "]", e);
}
segment.segmentSort = info.info.getIndexSort();
segment.attributes = info.info.getAttributes();
segments.put(info.info.name, segment);
} else {
segment.committed = true;
}
}
}
Segment[] segmentsArr = segments.values().toArray(new Segment[segments.values().size()]);
Arrays.sort(segmentsArr, Comparator.comparingLong(Segment::getGeneration));
return segmentsArr;
}
private void fillSegmentInfo(
SegmentReader segmentReader,
boolean search,
Map<String, Segment> segments,
boolean includeVectorFormatsInfo
) {
SegmentCommitInfo info = segmentReader.getSegmentInfo();
assert segments.containsKey(info.info.name) == false;
Segment segment = new Segment(info.info.name);
segment.search = search;
segment.docCount = segmentReader.numDocs();
segment.delDocCount = segmentReader.numDeletedDocs();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace(() -> "failed to get size for [" + info.info.name + "]", e);
}
segment.segmentSort = info.info.getIndexSort();
segment.attributes = new HashMap<>();
segment.attributes.putAll(info.info.getAttributes());
Map<String, List<String>> knnFormats = null;
if (includeVectorFormatsInfo) {
try {
FieldInfos fieldInfos = segmentReader.getFieldInfos();
if (fieldInfos.hasVectorValues()) {
for (FieldInfo fieldInfo : fieldInfos) {
String name = fieldInfo.getName();
if (fieldInfo.hasVectorValues()) {
if (knnFormats == null) {
knnFormats = new HashMap<>();
}
String key = fieldInfo.getAttribute(PerFieldKnnVectorsFormat.PER_FIELD_FORMAT_KEY);
knnFormats.compute(key, (s, a) -> {
if (a == null) {
a = new ArrayList<>();
}
a.add(name);
return a;
});
}
}
}
} catch (AlreadyClosedException ace) {
// silently ignore
}
}
if (knnFormats != null) {
for (Map.Entry<String, List<String>> entry : knnFormats.entrySet()) {
segment.attributes.put(entry.getKey(), entry.getValue().toString());
}
}
// TODO: add more fine grained mem stats values to per segment info here
segments.put(info.info.name, segment);
}
/**
* The list of segments in the engine.
*/
public abstract List<Segment> segments();
public abstract List<Segment> segments(boolean includeVectorFormatsInfo);
public boolean refreshNeeded() {
if (store.tryIncRef()) {
/*
we need to inc the store here since we acquire a searcher and that might keep a file open on the
store. this violates the assumption that all files are closed when
the store is closed so we need to make sure we increment it here
*/
try {
try (Searcher searcher = acquireSearcher("refresh_needed", SearcherScope.EXTERNAL)) {
return searcher.getDirectoryReader().isCurrent() == false;
}
} catch (IOException e) {
logger.error("failed to access searcher manager", e);
failEngine("failed to access searcher manager", e);
throw new EngineException(shardId, "failed to access searcher manager", e);
} finally {
store.decRef();
}
}
return false;
}
/**
* Synchronously refreshes the engine for new search operations to reflect the latest
* changes.
*/
@Nullable
public abstract RefreshResult refresh(String source) throws EngineException;
/**
* An async variant of {@link Engine#refresh(String)} that may apply some rate-limiting.
*/
public void externalRefresh(String source, ActionListener<Engine.RefreshResult> listener) {
ActionListener.completeWith(listener, () -> {
logger.trace("external refresh with source [{}]", source);
return refresh(source);
});
}
/**
* Asynchronously refreshes the engine for new search operations to reflect the latest
* changes unless another thread is already refreshing the engine concurrently.
*/
@Nullable
public abstract void maybeRefresh(String source, ActionListener<RefreshResult> listener) throws EngineException;
/**
* Called when our engine is using too much heap and should move buffered indexed/deleted documents to disk.
*/
// NOTE: do NOT rename this to something containing flush or refresh!
public abstract void writeIndexingBuffer() throws IOException;
/**
* Checks if this engine should be flushed periodically.
* This check is mainly based on the uncommitted translog size and the translog flush threshold setting.
*/
public abstract boolean shouldPeriodicallyFlush();
/**
* A Blocking helper method for calling the async flush method.
*/
// TODO: Remove or rename for increased clarity
public void flush(boolean force, boolean waitIfOngoing) throws EngineException {
PlainActionFuture<FlushResult> future = new PlainActionFuture<>();
flush(force, waitIfOngoing, future);
future.actionGet();
}
/**
* Flushes the state of the engine including the transaction log, clearing memory, and writing the
* documents in the Lucene index to disk. This method will synchronously flush on the calling thread.
* However, depending on engine implementation, full durability will not be guaranteed until the listener
* is triggered.
*
* @param force if <code>true</code> a lucene commit is executed even if no changes need to be committed.
* @param waitIfOngoing if <code>true</code> this call will block until all currently running flushes have finished.
* Otherwise this call will return without blocking.
* @param listener to notify after fully durability has been achieved. if <code>waitIfOngoing==false</code> and ongoing
* request is detected, no flush will have occurred and the listener will be completed with a marker
* indicating no flush and unknown generation.
*/
public final void flush(boolean force, boolean waitIfOngoing, ActionListener<FlushResult> listener) throws EngineException {
try (var ignored = acquireEnsureOpenRef()) {
flushHoldingLock(force, waitIfOngoing, listener);
}
}
/**
* The actual implementation of {@link #flush(boolean, boolean, ActionListener)}, to be called either when holding a ref that ensures
* the engine remains open, or holding {@code IndexShard#engineMutex} while closing the engine.
*
*/
protected abstract void flushHoldingLock(boolean force, boolean waitIfOngoing, ActionListener<FlushResult> listener)
throws EngineException;
/**
* Flushes the state of the engine including the transaction log, clearing memory and persisting
* documents in the lucene index to disk including a potentially heavy and durable fsync operation.
* This operation is not going to block if another flush operation is currently running and won't write
* a lucene commit if nothing needs to be committed.
*/
public final void flush() throws EngineException {
PlainActionFuture<FlushResult> future = new PlainActionFuture<>();
flush(false, false, future);
future.actionGet();
}
/**
* checks and removes translog files that no longer need to be retained. See
* {@link org.elasticsearch.index.translog.TranslogDeletionPolicy} for details
*/
public abstract void trimUnreferencedTranslogFiles() throws EngineException;
/**
* Tests whether or not the translog generation should be rolled to a new generation.
* This test is based on the size of the current generation compared to the configured generation threshold size.
*
* @return {@code true} if the current generation should be rolled to a new generation
*/
public abstract boolean shouldRollTranslogGeneration();
/**
* Rolls the translog generation and cleans unneeded.
*/
public abstract void rollTranslogGeneration() throws EngineException;
/**
* Triggers a forced merge on this engine
*/
public abstract void forceMerge(boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, String forceMergeUUID)
throws EngineException, IOException;
/**
* Snapshots the most recent index and returns a handle to it. If needed will try and "commit" the
* lucene index to make sure we have a "fresh" copy of the files to snapshot.
*
* @param flushFirst indicates whether the engine should flush before returning the snapshot
*/
public abstract IndexCommitRef acquireLastIndexCommit(boolean flushFirst) throws EngineException;
/**
* Snapshots the most recent safe index commit from the engine.
*/
public abstract IndexCommitRef acquireSafeIndexCommit() throws EngineException;
/**
* Acquires the index commit that should be included in a snapshot.
*/
public final IndexCommitRef acquireIndexCommitForSnapshot() throws EngineException {
return engineConfig.getSnapshotCommitSupplier().acquireIndexCommitForSnapshot(this);
}
/**
* @return a summary of the contents of the current safe commit
*/
public abstract SafeCommitInfo getSafeCommitInfo();
/**
* If the specified throwable contains a fatal error in the throwable graph, such a fatal error will be thrown. Callers should ensure
* that there are no catch statements that would catch an error in the stack as the fatal error here should go uncaught and be handled
* by the uncaught exception handler that we install during bootstrap. If the specified throwable does indeed contain a fatal error,
* the specified message will attempt to be logged before throwing the fatal error. If the specified throwable does not contain a fatal
* error, this method is a no-op.
*
* @param maybeMessage the message to maybe log
* @param maybeFatal the throwable that maybe contains a fatal error
*/
@SuppressWarnings("finally")
private void maybeDie(final String maybeMessage, final Throwable maybeFatal) {
ExceptionsHelper.maybeError(maybeFatal).ifPresent(error -> {
try {
logger.error(maybeMessage, error);
} finally {
throw error;
}
});
}
/**
* fail engine due to some error. the engine will also be closed.
* The underlying store is marked corrupted iff failure is caused by index corruption
*/
public void failEngine(String reason, @Nullable Exception failure) {
assert Transports.assertNotTransportThread("failEngine can block on IO");
if (failure != null) {
maybeDie(reason, failure);
}
if (failEngineLock.tryLock()) {
try {
if (failedEngine.get() != null) {
logger.warn(() -> "tried to fail engine but engine is already failed. ignoring. [" + reason + "]", failure);
return;
}
// this must happen before we close IW or Translog such that we can check this state to opt out of failing the engine
// again on any caught AlreadyClosedException
failedEngine.set((failure != null) ? failure : new IllegalStateException(reason));
try {
// we just go and close this engine - no way to recover
closeNoLock("engine failed on: [" + reason + "]", closedLatch);
} finally {
logger.warn(() -> "failed engine [" + reason + "]", failure);
// we must set a failure exception, generate one if not supplied
// we first mark the store as corrupted before we notify any listeners
// this must happen first otherwise we might try to reallocate so quickly
// on the same node that we don't see the corrupted marker file when
// the shard is initializing
if (Lucene.isCorruptionException(failure)) {
if (store.tryIncRef()) {
try {
store.markStoreCorrupted(
new IOException("failed engine (reason: [" + reason + "])", ExceptionsHelper.unwrapCorruption(failure))
);
} catch (IOException e) {
logger.warn("Couldn't mark store corrupted", e);
} finally {
store.decRef();
}
} else {
logger.warn(
() -> format("tried to mark store as corrupted but store is already closed. [%s]", reason),
failure
);
}
}
eventListener.onFailedEngine(reason, failure);
}
} catch (Exception inner) {
if (failure != null) inner.addSuppressed(failure);
// don't bubble up these exceptions up
logger.warn("failEngine threw exception", inner);
}
} else {
logger.debug(
() -> format("tried to fail engine but could not acquire lock - engine should be failed by now [%s]", reason),
failure
);
}
}
/** Check whether the engine should be failed */
protected boolean maybeFailEngine(String source, Exception e) {
if (Lucene.isCorruptionException(e)) {
failEngine("corrupt file (source: [" + source + "])", e);
return true;
}
return false;
}
public interface EventListener {
/**
* Called when a fatal exception occurred
*/
default void onFailedEngine(String reason, @Nullable Exception e) {}
}
public abstract static class SearcherSupplier implements Releasable {
private final Function<Searcher, Searcher> wrapper;
private final AtomicBoolean released = new AtomicBoolean(false);
public SearcherSupplier(Function<Searcher, Searcher> wrapper) {
this.wrapper = wrapper;
}
public final Searcher acquireSearcher(String source) {
if (released.get()) {
throw new AlreadyClosedException("SearcherSupplier was closed");
}
final Searcher searcher = acquireSearcherInternal(source);
return wrapper.apply(searcher);
}
@Override
public final void close() {
if (released.compareAndSet(false, true)) {
doClose();
} else {
assert false : "SearchSupplier was released twice";
}
}
protected abstract void doClose();
protected abstract Searcher acquireSearcherInternal(String source);
/**
* Returns an id associated with this searcher if exists. Two searchers with the same searcher id must have
* identical Lucene level indices (i.e., identical segments with same docs using same doc-ids).
*/
@Nullable
public String getSearcherId() {
return null;
}
}
public static final class Searcher extends IndexSearcher implements Releasable {
private final String source;
private final Closeable onClose;
public Searcher(
String source,
IndexReader reader,
Similarity similarity,
QueryCache queryCache,
QueryCachingPolicy queryCachingPolicy,
Closeable onClose
) {
super(reader);
setSimilarity(similarity);
setQueryCache(queryCache);
setQueryCachingPolicy(queryCachingPolicy);
this.source = source;
this.onClose = onClose;
}
/**
* The source that caused this searcher to be acquired.
*/
public String source() {
return source;
}
public DirectoryReader getDirectoryReader() {
if (getIndexReader() instanceof DirectoryReader) {
return (DirectoryReader) getIndexReader();
}
throw new IllegalStateException("Can't use " + getIndexReader().getClass() + " as a directory reader");
}
@Override
public void close() {
try {
onClose.close();
} catch (IOException e) {
throw new UncheckedIOException("failed to close", e);
} catch (AlreadyClosedException e) {
// This means there's a bug somewhere: don't suppress it
throw new AssertionError(e);
}
}
}
public abstract static class Operation {
/** type of operation (index, delete), subclasses use static types */
public enum TYPE {
INDEX,
DELETE,
NO_OP;
private final String lowercase;
TYPE() {
this.lowercase = this.toString().toLowerCase(Locale.ROOT);
}
public String getLowercase() {
return lowercase;
}
}
private final Term uid;
private final long version;
private final long seqNo;
private final long primaryTerm;
private final VersionType versionType;
private final Origin origin;
private final long startTime;
public Operation(Term uid, long seqNo, long primaryTerm, long version, VersionType versionType, Origin origin, long startTime) {
this.uid = uid;
this.seqNo = seqNo;
this.primaryTerm = primaryTerm;
this.version = version;
this.versionType = versionType;
this.origin = origin;
this.startTime = startTime;
}
public enum Origin {
PRIMARY,
REPLICA,
PEER_RECOVERY,
LOCAL_TRANSLOG_RECOVERY,
LOCAL_RESET;
public boolean isRecovery() {
return this == PEER_RECOVERY || this == LOCAL_TRANSLOG_RECOVERY;
}
boolean isFromTranslog() {
return this == LOCAL_TRANSLOG_RECOVERY || this == LOCAL_RESET;
}
}
public Origin origin() {
return this.origin;
}
public Term uid() {
return this.uid;
}
public long version() {
return this.version;
}
public long seqNo() {
return seqNo;
}
public long primaryTerm() {
return primaryTerm;
}
public abstract int estimatedSizeInBytes();
public VersionType versionType() {
return this.versionType;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
abstract String id();
public abstract TYPE operationType();
}
public static class Index extends Operation {
private final ParsedDocument doc;
private final long autoGeneratedIdTimestamp;
private final boolean isRetry;
private final long ifSeqNo;
private final long ifPrimaryTerm;
public Index(
Term uid,
ParsedDocument doc,
long seqNo,
long primaryTerm,
long version,
VersionType versionType,
Origin origin,
long startTime,
long autoGeneratedIdTimestamp,
boolean isRetry,
long ifSeqNo,
long ifPrimaryTerm
) {
super(uid, seqNo, primaryTerm, version, versionType, origin, startTime);
assert (origin == Origin.PRIMARY) == (versionType != null) : "invalid version_type=" + versionType + " for origin=" + origin;
assert ifPrimaryTerm >= 0 : "ifPrimaryTerm [" + ifPrimaryTerm + "] must be non negative";
assert ifSeqNo == UNASSIGNED_SEQ_NO || ifSeqNo >= 0 : "ifSeqNo [" + ifSeqNo + "] must be non negative or unset";
assert (origin == Origin.PRIMARY) || (ifSeqNo == UNASSIGNED_SEQ_NO && ifPrimaryTerm == UNASSIGNED_PRIMARY_TERM)
: "cas operations are only allowed if origin is primary. get [" + origin + "]";
this.doc = doc;
this.isRetry = isRetry;
this.autoGeneratedIdTimestamp = autoGeneratedIdTimestamp;
this.ifSeqNo = ifSeqNo;
this.ifPrimaryTerm = ifPrimaryTerm;
}
public Index(Term uid, long primaryTerm, ParsedDocument doc) {
this(uid, primaryTerm, doc, Versions.MATCH_ANY);
} // TEST ONLY
Index(Term uid, long primaryTerm, ParsedDocument doc, long version) {
this(
uid,
doc,
UNASSIGNED_SEQ_NO,
primaryTerm,
version,
VersionType.INTERNAL,
Origin.PRIMARY,
System.nanoTime(),
-1,
false,
UNASSIGNED_SEQ_NO,
0
);
} // TEST ONLY
public ParsedDocument parsedDoc() {
return this.doc;
}
@Override
public String id() {
return this.doc.id();
}
@Override
public TYPE operationType() {
return TYPE.INDEX;
}
public String routing() {
return this.doc.routing();
}
public List<LuceneDocument> docs() {
return this.doc.docs();
}
public BytesReference source() {
return this.doc.source();
}
@Override
public int estimatedSizeInBytes() {
return (id().length() * 2) + source().length() + 12;
}
/**
* Returns a positive timestamp if the ID of this document is auto-generated by elasticsearch.
* if this property is non-negative indexing code might optimize the addition of this document
* due to it's append only nature.
*/
public long getAutoGeneratedIdTimestamp() {
return autoGeneratedIdTimestamp;
}
/**
* Returns <code>true</code> if this index requests has been retried on the coordinating node and can therefor be delivered
* multiple times. Note: this might also be set to true if an equivalent event occurred like the replay of the transaction log
*/
public boolean isRetry() {
return isRetry;
}
public long getIfSeqNo() {
return ifSeqNo;
}
public long getIfPrimaryTerm() {
return ifPrimaryTerm;
}
}
public static class Delete extends Operation {
private final String id;
private final long ifSeqNo;
private final long ifPrimaryTerm;
public Delete(
String id,
Term uid,
long seqNo,
long primaryTerm,
long version,
VersionType versionType,
Origin origin,
long startTime,
long ifSeqNo,
long ifPrimaryTerm
) {
super(uid, seqNo, primaryTerm, version, versionType, origin, startTime);
assert (origin == Origin.PRIMARY) == (versionType != null) : "invalid version_type=" + versionType + " for origin=" + origin;
assert ifPrimaryTerm >= 0 : "ifPrimaryTerm [" + ifPrimaryTerm + "] must be non negative";
assert ifSeqNo == UNASSIGNED_SEQ_NO || ifSeqNo >= 0 : "ifSeqNo [" + ifSeqNo + "] must be non negative or unset";
assert (origin == Origin.PRIMARY) || (ifSeqNo == UNASSIGNED_SEQ_NO && ifPrimaryTerm == UNASSIGNED_PRIMARY_TERM)
: "cas operations are only allowed if origin is primary. get [" + origin + "]";
this.id = Objects.requireNonNull(id);
this.ifSeqNo = ifSeqNo;
this.ifPrimaryTerm = ifPrimaryTerm;
}
public Delete(String id, Term uid, long primaryTerm) {
this(
id,
uid,
UNASSIGNED_SEQ_NO,
primaryTerm,
Versions.MATCH_ANY,
VersionType.INTERNAL,
Origin.PRIMARY,
System.nanoTime(),
UNASSIGNED_SEQ_NO,
0
);
}
public Delete(Delete template, VersionType versionType) {
this(
template.id(),
template.uid(),
template.seqNo(),
template.primaryTerm(),
template.version(),
versionType,
template.origin(),
template.startTime(),
UNASSIGNED_SEQ_NO,
0
);
}
@Override
public String id() {
return this.id;
}
@Override
public TYPE operationType() {
return TYPE.DELETE;
}
@Override
public int estimatedSizeInBytes() {
return (uid().field().length() + uid().text().length()) * 2 + 20;
}
public long getIfSeqNo() {
return ifSeqNo;
}
public long getIfPrimaryTerm() {
return ifPrimaryTerm;
}
}
public static class NoOp extends Operation {
private final String reason;
public String reason() {
return reason;
}
public NoOp(final long seqNo, final long primaryTerm, final Origin origin, final long startTime, final String reason) {
super(null, seqNo, primaryTerm, Versions.NOT_FOUND, null, origin, startTime);
this.reason = reason;
}
@Override
public Term uid() {
throw new UnsupportedOperationException();
}
@Override
public long version() {
throw new UnsupportedOperationException();
}
@Override
public VersionType versionType() {
throw new UnsupportedOperationException();
}
@Override
String id() {
throw new UnsupportedOperationException();
}
@Override
public TYPE operationType() {
return TYPE.NO_OP;
}
@Override
public int estimatedSizeInBytes() {
return 2 * reason.length() + 2 * Long.BYTES;
}
}
public static class Get {
private final boolean realtime;
private final Term uid;
private final String id;
private final boolean readFromTranslog;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private long ifSeqNo = UNASSIGNED_SEQ_NO;
private long ifPrimaryTerm = UNASSIGNED_PRIMARY_TERM;
public Get(boolean realtime, boolean readFromTranslog, String id) {
this.realtime = realtime;
this.id = id;
this.uid = new Term(IdFieldMapper.NAME, Uid.encodeId(id));
this.readFromTranslog = readFromTranslog;
}
public boolean realtime() {
return this.realtime;
}
public String id() {
return id;
}
public Term uid() {
return uid;
}
public long version() {
return version;
}
public Get version(long version) {
this.version = version;
return this;
}
public VersionType versionType() {
return versionType;
}
public Get versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
public boolean isReadFromTranslog() {
return readFromTranslog;
}
public Get setIfSeqNo(long seqNo) {
this.ifSeqNo = seqNo;
return this;
}
public long getIfSeqNo() {
return ifSeqNo;
}
public Get setIfPrimaryTerm(long primaryTerm) {
this.ifPrimaryTerm = primaryTerm;
return this;
}
public long getIfPrimaryTerm() {
return ifPrimaryTerm;
}
}
public static class GetResult implements Releasable {
private final boolean exists;
private final long version;
private final DocIdAndVersion docIdAndVersion;
private final Engine.Searcher searcher;
public static final GetResult NOT_EXISTS = new GetResult(false, Versions.NOT_FOUND, null, null);
private GetResult(boolean exists, long version, DocIdAndVersion docIdAndVersion, Engine.Searcher searcher) {
this.exists = exists;
this.version = version;
this.docIdAndVersion = docIdAndVersion;
this.searcher = searcher;
}
public GetResult(Engine.Searcher searcher, DocIdAndVersion docIdAndVersion) {
this(true, docIdAndVersion.version, docIdAndVersion, searcher);
}
public boolean exists() {
return exists;
}
public long version() {
return this.version;
}
public Engine.Searcher searcher() {
return this.searcher;
}
public DocIdAndVersion docIdAndVersion() {
return docIdAndVersion;
}
@Override
public void close() {
Releasables.close(searcher);
}
}
/**
* Closes the engine without acquiring any refs or locks. The caller should either have changed {@link #isClosing} from {@code false} to
* {@code true} or else must hold the {@link #failEngineLock}. The implementation must decrement the supplied latch when done.
*/
protected abstract void closeNoLock(String reason, CountDownLatch closedLatch);
protected final boolean isDrainedForClose() {
return ensureOpenRefs.hasReferences() == false;
}
protected final boolean isClosing() {
return isClosing.get();
}
protected final Releasable acquireEnsureOpenRef() {
if (isClosing() || ensureOpenRefs.tryIncRef() == false) {
ensureOpen(); // throws "engine is closed" exception if we're actually closed, otherwise ...
throw new AlreadyClosedException(shardId + " engine is closing", failedEngine.get());
}
return Releasables.assertOnce(releaseEnsureOpenRef);
}
/**
* When called for the first time, puts the engine into a closing state in which further calls to {@link #acquireEnsureOpenRef()} will
* fail with an {@link AlreadyClosedException} and waits for all outstanding ensure-open refs to be released, before returning {@code
* true}. If called again, returns {@code false} without waiting.
*
* @return a flag indicating whether this was the first call or not.
*/
private boolean drainForClose() {
if (isClosing.compareAndSet(false, true) == false) {
logger.trace("drainForClose(): already closing");
return false;
}
logger.debug("drainForClose(): draining ops");
releaseEnsureOpenRef.close();
final var future = new PlainActionFuture<Void>() {
@Override
protected boolean blockingAllowed() {
// TODO remove this blocking, or at least do it elsewhere, see https://github.com/elastic/elasticsearch/issues/89821
return Thread.currentThread().getName().contains(ClusterApplierService.CLUSTER_UPDATE_THREAD_NAME)
|| super.blockingAllowed();
}
};
drainOnCloseListener.addListener(future);
try {
future.get();
return true;
} catch (ExecutionException e) {
logger.error("failure while draining operations on close", e);
assert false : e;
throw new IllegalStateException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("interrupted while draining operations on close");
throw new IllegalStateException(e);
}
}
/**
* Flush the engine (committing segments to disk and truncating the translog) and close it.
*/
public void flushAndClose() throws IOException {
logger.trace("flushAndClose() maybe draining ops");
if (isClosed.get() == false && drainForClose()) {
logger.trace("flushAndClose drained ops");
try {
logger.debug("flushing shard on close - this might take some time to sync files to disk");
try {
// TODO: We are not waiting for full durability here atm because we are on the cluster state update thread
flushHoldingLock(false, false, ActionListener.noop());
} catch (AlreadyClosedException ex) {
logger.debug("engine already closed - skipping flushAndClose");
}
} finally {
closeNoLock("flushAndClose", closedLatch);
}
}
awaitPendingClose();
}
@Override
public void close() throws IOException {
logger.debug("close() maybe draining ops");
if (isClosed.get() == false && drainForClose()) {
logger.debug("close drained ops");
closeNoLock("api", closedLatch);
}
awaitPendingClose();
}
private void awaitPendingClose() {
try {
closedLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static class IndexCommitRef implements Closeable {
private final AtomicBoolean closed = new AtomicBoolean();
private final CheckedRunnable<IOException> onClose;
private final IndexCommit indexCommit;
public IndexCommitRef(IndexCommit indexCommit, CheckedRunnable<IOException> onClose) {
this.indexCommit = indexCommit;
this.onClose = onClose;
}
@Override
public void close() throws IOException {
if (closed.compareAndSet(false, true)) {
onClose.run();
}
}
public IndexCommit getIndexCommit() {
return indexCommit;
}
}
public void onSettingsChanged() {
}
/**
* Returns the timestamp of the last write in nanoseconds.
* Note: this time might not be absolutely accurate since the {@link Operation#startTime()} is used which might be
* slightly inaccurate.
*
* @see System#nanoTime()
* @see Operation#startTime()
*/
public long getLastWriteNanos() {
return this.lastWriteNanos;
}
/**
* Called for each new opened engine reader to warm new segments
*
* @see EngineConfig#getWarmer()
*/
public interface Warmer {
/**
* Called once a new top-level reader is opened.
*/
void warm(ElasticsearchDirectoryReader reader);
}
/**
* Request that this engine throttle incoming indexing requests to one thread.
* Must be matched by a later call to {@link #deactivateThrottling()}.
*/
public abstract void activateThrottling();
/**
* Reverses a previous {@link #activateThrottling} call.
*/
public abstract void deactivateThrottling();
/**
* This method replays translog to restore the Lucene index which might be reverted previously.
* This ensures that all acknowledged writes are restored correctly when this engine is promoted.
*
* @return the number of translog operations have been recovered
*/
public abstract int restoreLocalHistoryFromTranslog(TranslogRecoveryRunner translogRecoveryRunner) throws IOException;
/**
* Fills up the local checkpoints history with no-ops until the local checkpoint
* and the max seen sequence ID are identical.
* @param primaryTerm the shards primary term this engine was created for
* @return the number of no-ops added
*/
public abstract int fillSeqNoGaps(long primaryTerm) throws IOException;
/**
* Performs recovery from the transaction log up to {@code recoverUpToSeqNo} (inclusive).
* This operation will close the engine if the recovery fails. Use EngineTestCase#recoverFromTranslog for test usages
*
* @param translogRecoveryRunner the translog recovery runner
* @param recoverUpToSeqNo the upper bound, inclusive, of sequence number to be recovered
*/
// TODO make all the production usages fully async
public final void recoverFromTranslog(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo) throws IOException {
final var future = new PlainActionFuture<Void>();
recoverFromTranslog(translogRecoveryRunner, recoverUpToSeqNo, future);
try {
future.get();
} catch (ExecutionException e) {
// This is a (temporary) adapter between the older synchronous (blocking) code and the newer (async) API. Callers expect
// exceptions to be thrown directly, but Future#get adds an ExecutionException wrapper which we must remove to preserve the
// expected exception semantics.
if (e.getCause() instanceof IOException ioException) {
throw ioException;
} else if (e.getCause() instanceof RuntimeException runtimeException) {
throw runtimeException;
} else {
// the old code was "throws IOException" so we shouldn't see any other exception types here
logger.error("checked non-IOException unexpectedly thrown", e);
assert false : e;
throw new UncategorizedExecutionException("recoverFromTranslog", e);
}
} catch (InterruptedException e) {
// We don't really use interrupts in this area so this is somewhat unexpected (unless perhaps we're shutting down), just treat
// it like any other exception.
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* Performs recovery from the transaction log up to {@code recoverUpToSeqNo} (inclusive).
* This operation will close the engine if the recovery fails.
*
* @param translogRecoveryRunner the translog recovery runner
* @param recoverUpToSeqNo the upper bound, inclusive, of sequence number to be recovered
* @param listener listener notified on completion of the recovery, whether successful or otherwise
*/
public abstract void recoverFromTranslog(
TranslogRecoveryRunner translogRecoveryRunner,
long recoverUpToSeqNo,
ActionListener<Void> listener
);
/**
* Do not replay translog operations, but make the engine be ready.
*/
public abstract void skipTranslogRecovery();
/**
* Tries to prune buffered deletes from the version map.
*/
public abstract void maybePruneDeletes();
/**
* Returns the maximum auto_id_timestamp of all append-only index requests have been processed by this engine
* or the auto_id_timestamp received from its primary shard via {@link #updateMaxUnsafeAutoIdTimestamp(long)}.
* Notes this method returns the auto_id_timestamp of all append-only requests, not max_unsafe_auto_id_timestamp.
*/
public long getMaxSeenAutoIdTimestamp() {
return IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP;
}
/**
* Forces this engine to advance its max_unsafe_auto_id_timestamp marker to at least the given timestamp.
* The engine will disable optimization for all append-only whose timestamp at most {@code newTimestamp}.
*/
public abstract void updateMaxUnsafeAutoIdTimestamp(long newTimestamp);
@FunctionalInterface
public interface TranslogRecoveryRunner {
int run(Engine engine, Translog.Snapshot snapshot) throws IOException;
}
/**
* Returns the maximum sequence number of either update or delete operations have been processed in this engine
* or the sequence number from {@link #advanceMaxSeqNoOfUpdatesOrDeletes(long)}. An index request is considered
* as an update operation if it overwrites the existing documents in Lucene index with the same document id.
* <p>
* A note on the optimization using max_seq_no_of_updates_or_deletes:
* For each operation O, the key invariants are:
* <ol>
* <li> I1: There is no operation on docID(O) with seqno that is {@literal > MSU(O) and < seqno(O)} </li>
* <li> I2: If {@literal MSU(O) < seqno(O)} then docID(O) did not exist when O was applied; more precisely, if there is any O'
* with {@literal seqno(O') < seqno(O) and docID(O') = docID(O)} then the one with the greatest seqno is a delete.</li>
* </ol>
* <p>
* When a receiving shard (either a replica or a follower) receives an operation O, it must first ensure its own MSU at least MSU(O),
* and then compares its MSU to its local checkpoint (LCP). If {@literal LCP < MSU} then there's a gap: there may be some operations
* that act on docID(O) about which we do not yet know, so we cannot perform an add. Note this also covers the case where a future
* operation O' with {@literal seqNo(O') > seqNo(O) and docId(O') = docID(O)} is processed before O. In that case MSU(O') is at least
* seqno(O') and this means {@literal MSU >= seqNo(O') > seqNo(O) > LCP} (because O wasn't processed yet).
* <p>
* However, if {@literal MSU <= LCP} then there is no gap: we have processed every {@literal operation <= LCP}, and no operation O'
* with {@literal seqno(O') > LCP and seqno(O') < seqno(O) also has docID(O') = docID(O)}, because such an operation would have
* {@literal seqno(O') > LCP >= MSU >= MSU(O)} which contradicts the first invariant. Furthermore in this case we immediately know
* that docID(O) has been deleted (or never existed) without needing to check Lucene for the following reason. If there's no earlier
* operation on docID(O) then this is clear, so suppose instead that the preceding operation on docID(O) is O':
* 1. The first invariant above tells us that {@literal seqno(O') <= MSU(O) <= LCP} so we have already applied O' to Lucene.
* 2. Also {@literal MSU(O) <= MSU <= LCP < seqno(O)} (we discard O if {@literal seqno(O) <= LCP}) so the second invariant applies,
* meaning that the O' was a delete.
* <p>
* Therefore, if {@literal MSU <= LCP < seqno(O)} we know that O can safely be optimized with and added to lucene with addDocument.
* Moreover, operations that are optimized using the MSU optimization must not be processed twice as this will create duplicates
* in Lucene. To avoid this we check the local checkpoint tracker to see if an operation was already processed.
*
* @see #advanceMaxSeqNoOfUpdatesOrDeletes(long)
*/
public abstract long getMaxSeqNoOfUpdatesOrDeletes();
/**
* A replica shard receives a new max_seq_no_of_updates from its primary shard, then calls this method
* to advance this marker to at least the given sequence number.
*/
public abstract void advanceMaxSeqNoOfUpdatesOrDeletes(long maxSeqNoOfUpdatesOnPrimary);
/**
* @return a {@link ShardLongFieldRange} containing the min and max raw values of the given field for this shard if the engine
* guarantees these values never to change, or {@link ShardLongFieldRange#EMPTY} if this field is empty, or
* {@link ShardLongFieldRange#UNKNOWN} if this field's value range may change in future.
*/
public abstract ShardLongFieldRange getRawFieldRange(String field) throws IOException;
public final EngineConfig getEngineConfig() {
return engineConfig;
}
/**
* Allows registering a listener for when the index shard is on a segment generation >= minGeneration.
*
* @deprecated use {@link #addPrimaryTermAndGenerationListener(long, long, ActionListener)} instead.
*/
@Deprecated
public void addSegmentGenerationListener(long minGeneration, ActionListener<Long> listener) {
addPrimaryTermAndGenerationListener(UNKNOWN_PRIMARY_TERM, minGeneration, listener);
}
/**
* Allows registering a listener for when the index shard is on a primary term >= minPrimaryTerm
* and a segment generation >= minGeneration.
*/
public void addPrimaryTermAndGenerationListener(long minPrimaryTerm, long minGeneration, ActionListener<Long> listener) {
throw new UnsupportedOperationException();
}
public void addFlushListener(Translog.Location location, ActionListener<Long> listener) {
listener.onFailure(new UnsupportedOperationException("Engine type " + this.getClass() + " does not support flush listeners."));
}
/**
* Captures the result of a refresh operation on the index shard.
* <p>
* <code>refreshed</code> is true if a refresh happened. If refreshed, <code>generation</code>
* contains the generation of the index commit that the reader has opened upon refresh.
*/
public record RefreshResult(boolean refreshed, long primaryTerm, long generation) {
public static final long UNKNOWN_GENERATION = -1L;
public static final RefreshResult NO_REFRESH = new RefreshResult(false);
public RefreshResult(boolean refreshed) {
this(refreshed, UNKNOWN_PRIMARY_TERM, UNKNOWN_GENERATION);
}
}
public record FlushResult(boolean flushPerformed, long generation) {
public static final long UNKNOWN_GENERATION = -1L;
public static final FlushResult NO_FLUSH = new FlushResult(false, UNKNOWN_GENERATION);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/engine/Engine.java |
663 | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.net.URI;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
/**
* Extension of {@link HttpEntity} that adds an {@link HttpStatusCode} status code.
* Used in {@code RestTemplate} as well as in {@code @Controller} methods.
*
* <p>In {@code RestTemplate}, this class is returned by
* {@link org.springframework.web.client.RestTemplate#getForEntity getForEntity()} and
* {@link org.springframework.web.client.RestTemplate#exchange exchange()}:
* <pre class="code">
* ResponseEntity<String> entity = template.getForEntity("https://example.com", String.class);
* String body = entity.getBody();
* MediaType contentType = entity.getHeaders().getContentType();
* HttpStatus statusCode = entity.getStatusCode();
* </pre>
*
* <p>This can also be used in Spring MVC as the return value from an
* {@code @Controller} method:
* <pre class="code">
* @RequestMapping("/handle")
* public ResponseEntity<String> handle() {
* URI location = ...;
* HttpHeaders responseHeaders = new HttpHeaders();
* responseHeaders.setLocation(location);
* responseHeaders.set("MyResponseHeader", "MyValue");
* return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
* }
* </pre>
*
* Or, by using a builder accessible via static methods:
* <pre class="code">
* @RequestMapping("/handle")
* public ResponseEntity<String> handle() {
* URI location = ...;
* return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World");
* }
* </pre>
*
* @author Arjen Poutsma
* @author Brian Clozel
* @author Sebastien Deleuze
* @since 3.0.2
* @param <T> the body type
* @see #getStatusCode()
* @see org.springframework.web.client.RestOperations#getForEntity(String, Class, Object...)
* @see org.springframework.web.client.RestOperations#getForEntity(String, Class, java.util.Map)
* @see org.springframework.web.client.RestOperations#getForEntity(URI, Class)
* @see RequestEntity
*/
public class ResponseEntity<T> extends HttpEntity<T> {
private final HttpStatusCode status;
/**
* Create a {@code ResponseEntity} with a status code only.
* @param status the status code
*/
public ResponseEntity(HttpStatusCode status) {
this(null, null, status);
}
/**
* Create a {@code ResponseEntity} with a body and status code.
* @param body the entity body
* @param status the status code
*/
public ResponseEntity(@Nullable T body, HttpStatusCode status) {
this(body, null, status);
}
/**
* Create a {@code ResponseEntity} with headers and a status code.
* @param headers the entity headers
* @param status the status code
*/
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatusCode status) {
this(null, headers, status);
}
/**
* Create a {@code ResponseEntity} with a body, headers, and a raw status code.
* @param body the entity body
* @param headers the entity headers
* @param rawStatus the status code value
* @since 5.3.2
*/
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, int rawStatus) {
this(body, headers, HttpStatusCode.valueOf(rawStatus));
}
/**
* Create a {@code ResponseEntity} with a body, headers, and a status code.
* @param body the entity body
* @param headers the entity headers
* @param statusCode the status code
*/
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatusCode statusCode) {
super(body, headers);
Assert.notNull(statusCode, "HttpStatusCode must not be null");
this.status = statusCode;
}
/**
* Return the HTTP status code of the response.
* @return the HTTP status as an HttpStatus enum entry
*/
public HttpStatusCode getStatusCode() {
return this.status;
}
/**
* Return the HTTP status code of the response.
* @return the HTTP status as an int value
* @since 4.3
* @deprecated as of 6.0, in favor of {@link #getStatusCode()}; scheduled
* for removal in 7.0
*/
@Deprecated(since = "6.0")
public int getStatusCodeValue() {
return getStatusCode().value();
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (!super.equals(other)) {
return false;
}
return (other instanceof ResponseEntity<?> otherEntity && ObjectUtils.nullSafeEquals(this.status, otherEntity.status));
}
@Override
public int hashCode() {
return (29 * super.hashCode() + ObjectUtils.nullSafeHashCode(this.status));
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("<");
builder.append(this.status);
if (this.status instanceof HttpStatus httpStatus) {
builder.append(' ');
builder.append(httpStatus.getReasonPhrase());
}
builder.append(',');
T body = getBody();
HttpHeaders headers = getHeaders();
if (body != null) {
builder.append(body);
builder.append(',');
}
builder.append(headers);
builder.append('>');
return builder.toString();
}
// Static builder methods
/**
* Create a builder with the given status.
* @param status the response status
* @return the created builder
* @since 4.1
*/
public static BodyBuilder status(HttpStatusCode status) {
Assert.notNull(status, "HttpStatusCode must not be null");
return new DefaultBuilder(status);
}
/**
* Create a builder with the given status.
* @param status the response status
* @return the created builder
* @since 4.1
*/
public static BodyBuilder status(int status) {
return new DefaultBuilder(status);
}
/**
* Create a builder with the status set to {@linkplain HttpStatus#OK OK}.
* @return the created builder
* @since 4.1
*/
public static BodyBuilder ok() {
return status(HttpStatus.OK);
}
/**
* A shortcut for creating a {@code ResponseEntity} with the given body
* and the status set to {@linkplain HttpStatus#OK OK}.
* @param body the body of the response entity (possibly empty)
* @return the created {@code ResponseEntity}
* @since 4.1
*/
public static <T> ResponseEntity<T> ok(@Nullable T body) {
return ok().body(body);
}
/**
* A shortcut for creating a {@code ResponseEntity} with the given body
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of an
* {@linkplain Optional#empty()} parameter.
* @return the created {@code ResponseEntity}
* @since 5.1
*/
public static <T> ResponseEntity<T> of(Optional<T> body) {
Assert.notNull(body, "Body must not be null");
return body.map(ResponseEntity::ok).orElseGet(() -> notFound().build());
}
/**
* Create a new {@link HeadersBuilder} with its status set to
* {@link ProblemDetail#getStatus()} and its body is set to
* {@link ProblemDetail}.
* <p><strong>Note:</strong> If there are no headers to add, there is usually
* no need to create a {@link ResponseEntity} since {@code ProblemDetail}
* is also supported as a return value from controller methods.
* @param body the problem detail to use
* @return the created builder
* @since 6.0
*/
public static HeadersBuilder<?> of(ProblemDetail body) {
return new DefaultBuilder(body.getStatus()) {
@SuppressWarnings("unchecked")
@Override
public <T> ResponseEntity<T> build() {
return (ResponseEntity<T>) body(body);
}
};
}
/**
* A shortcut for creating a {@code ResponseEntity} with the given body
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of a
* {@code null} parameter.
* @return the created {@code ResponseEntity}
* @since 6.0.5
*/
public static <T> ResponseEntity<T> ofNullable(@Nullable T body) {
if (body == null) {
return notFound().build();
}
return ResponseEntity.ok(body);
}
/**
* Create a new builder with a {@linkplain HttpStatus#CREATED CREATED} status
* and a location header set to the given URI.
* @param location the location URI
* @return the created builder
* @since 4.1
*/
public static BodyBuilder created(URI location) {
return status(HttpStatus.CREATED).location(location);
}
/**
* Create a builder with an {@linkplain HttpStatus#ACCEPTED ACCEPTED} status.
* @return the created builder
* @since 4.1
*/
public static BodyBuilder accepted() {
return status(HttpStatus.ACCEPTED);
}
/**
* Create a builder with a {@linkplain HttpStatus#NO_CONTENT NO_CONTENT} status.
* @return the created builder
* @since 4.1
*/
public static HeadersBuilder<?> noContent() {
return status(HttpStatus.NO_CONTENT);
}
/**
* Create a builder with a {@linkplain HttpStatus#BAD_REQUEST BAD_REQUEST} status.
* @return the created builder
* @since 4.1
*/
public static BodyBuilder badRequest() {
return status(HttpStatus.BAD_REQUEST);
}
/**
* Create a builder with a {@linkplain HttpStatus#NOT_FOUND NOT_FOUND} status.
* @return the created builder
* @since 4.1
*/
public static HeadersBuilder<?> notFound() {
return status(HttpStatus.NOT_FOUND);
}
/**
* Create a builder with an
* {@linkplain HttpStatus#UNPROCESSABLE_ENTITY UNPROCESSABLE_ENTITY} status.
* @return the created builder
* @since 4.1.3
*/
public static BodyBuilder unprocessableEntity() {
return status(HttpStatus.UNPROCESSABLE_ENTITY);
}
/**
* Create a builder with an
* {@linkplain HttpStatus#INTERNAL_SERVER_ERROR INTERNAL_SERVER_ERROR} status.
* @return the created builder
* @since 5.3.8
*/
public static BodyBuilder internalServerError() {
return status(HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* Defines a builder that adds headers to the response entity.
* @since 4.1
* @param <B> the builder subclass
*/
public interface HeadersBuilder<B extends HeadersBuilder<B>> {
/**
* Add the given, single header value under the given name.
* @param headerName the header name
* @param headerValues the header value(s)
* @return this builder
* @see HttpHeaders#add(String, String)
*/
B header(String headerName, String... headerValues);
/**
* Copy the given headers into the entity's headers map.
* @param headers the existing HttpHeaders to copy from
* @return this builder
* @since 4.1.2
* @see HttpHeaders#add(String, String)
*/
B headers(@Nullable HttpHeaders headers);
/**
* Manipulate this entity's headers with the given consumer. The
* headers provided to the consumer are "live", so that the consumer can be used to
* {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
* {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
* {@link HttpHeaders} methods.
* @param headersConsumer a function that consumes the {@code HttpHeaders}
* @return this builder
* @since 5.2
*/
B headers(Consumer<HttpHeaders> headersConsumer);
/**
* Set the set of allowed {@link HttpMethod HTTP methods}, as specified
* by the {@code Allow} header.
* @param allowedMethods the allowed methods
* @return this builder
* @see HttpHeaders#setAllow(Set)
*/
B allow(HttpMethod... allowedMethods);
/**
* Set the entity tag of the body, as specified by the {@code ETag} header.
* @param etag the new entity tag
* @return this builder
* @see HttpHeaders#setETag(String)
*/
B eTag(@Nullable String etag);
/**
* Set the time the resource was last changed, as specified by the
* {@code Last-Modified} header.
* @param lastModified the last modified date
* @return this builder
* @since 5.1.4
* @see HttpHeaders#setLastModified(ZonedDateTime)
*/
B lastModified(ZonedDateTime lastModified);
/**
* Set the time the resource was last changed, as specified by the
* {@code Last-Modified} header.
* @param lastModified the last modified date
* @return this builder
* @since 5.1.4
* @see HttpHeaders#setLastModified(Instant)
*/
B lastModified(Instant lastModified);
/**
* Set the time the resource was last changed, as specified by the
* {@code Last-Modified} header.
* <p>The date should be specified as the number of milliseconds since
* January 1, 1970 GMT.
* @param lastModified the last modified date
* @return this builder
* @see HttpHeaders#setLastModified(long)
*/
B lastModified(long lastModified);
/**
* Set the location of a resource, as specified by the {@code Location} header.
* @param location the location
* @return this builder
* @see HttpHeaders#setLocation(URI)
*/
B location(URI location);
/**
* Set the caching directives for the resource, as specified by the HTTP 1.1
* {@code Cache-Control} header.
* <p>A {@code CacheControl} instance can be built like
* {@code CacheControl.maxAge(3600).cachePublic().noTransform()}.
* @param cacheControl a builder for cache-related HTTP response headers
* @return this builder
* @since 4.2
* @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2">RFC-7234 Section 5.2</a>
*/
B cacheControl(CacheControl cacheControl);
/**
* Configure one or more request header names (e.g. "Accept-Language") to
* add to the "Vary" response header to inform clients that the response is
* subject to content negotiation and variances based on the value of the
* given request headers. The configured request header names are added only
* if not already present in the response "Vary" header.
* @param requestHeaders request header names
* @since 4.3
*/
B varyBy(String... requestHeaders);
/**
* Build the response entity with no body.
* @return the response entity
* @see BodyBuilder#body(Object)
*/
<T> ResponseEntity<T> build();
}
/**
* Defines a builder that adds a body to the response entity.
* @since 4.1
*/
public interface BodyBuilder extends HeadersBuilder<BodyBuilder> {
/**
* Set the length of the body in bytes, as specified by the
* {@code Content-Length} header.
* @param contentLength the content length
* @return this builder
* @see HttpHeaders#setContentLength(long)
*/
BodyBuilder contentLength(long contentLength);
/**
* Set the {@linkplain MediaType media type} of the body, as specified by the
* {@code Content-Type} header.
* @param contentType the content type
* @return this builder
* @see HttpHeaders#setContentType(MediaType)
*/
BodyBuilder contentType(MediaType contentType);
/**
* Set the body of the response entity and returns it.
* @param <T> the type of the body
* @param body the body of the response entity
* @return the built response entity
*/
<T> ResponseEntity<T> body(@Nullable T body);
}
private static class DefaultBuilder implements BodyBuilder {
private final HttpStatusCode statusCode;
private final HttpHeaders headers = new HttpHeaders();
public DefaultBuilder(int statusCode) {
this(HttpStatusCode.valueOf(statusCode));
}
public DefaultBuilder(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
@Override
public BodyBuilder header(String headerName, String... headerValues) {
for (String headerValue : headerValues) {
this.headers.add(headerName, headerValue);
}
return this;
}
@Override
public BodyBuilder headers(@Nullable HttpHeaders headers) {
if (headers != null) {
this.headers.putAll(headers);
}
return this;
}
@Override
public BodyBuilder headers(Consumer<HttpHeaders> headersConsumer) {
headersConsumer.accept(this.headers);
return this;
}
@Override
public BodyBuilder allow(HttpMethod... allowedMethods) {
this.headers.setAllow(new LinkedHashSet<>(Arrays.asList(allowedMethods)));
return this;
}
@Override
public BodyBuilder contentLength(long contentLength) {
this.headers.setContentLength(contentLength);
return this;
}
@Override
public BodyBuilder contentType(MediaType contentType) {
this.headers.setContentType(contentType);
return this;
}
@Override
public BodyBuilder eTag(@Nullable String etag) {
if (etag != null) {
if (!etag.startsWith("\"") && !etag.startsWith("W/\"")) {
etag = "\"" + etag;
}
if (!etag.endsWith("\"")) {
etag = etag + "\"";
}
}
this.headers.setETag(etag);
return this;
}
@Override
public BodyBuilder lastModified(ZonedDateTime date) {
this.headers.setLastModified(date);
return this;
}
@Override
public BodyBuilder lastModified(Instant date) {
this.headers.setLastModified(date);
return this;
}
@Override
public BodyBuilder lastModified(long date) {
this.headers.setLastModified(date);
return this;
}
@Override
public BodyBuilder location(URI location) {
this.headers.setLocation(location);
return this;
}
@Override
public BodyBuilder cacheControl(CacheControl cacheControl) {
this.headers.setCacheControl(cacheControl);
return this;
}
@Override
public BodyBuilder varyBy(String... requestHeaders) {
this.headers.setVary(Arrays.asList(requestHeaders));
return this;
}
@Override
public <T> ResponseEntity<T> build() {
return body(null);
}
@Override
public <T> ResponseEntity<T> body(@Nullable T body) {
return new ResponseEntity<>(body, this.headers, this.statusCode);
}
}
}
| spring-projects/spring-framework | spring-web/src/main/java/org/springframework/http/ResponseEntity.java |
665 | /*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.build.bom;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import javax.inject.Inject;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.InvalidUserCodeException;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.plugins.JavaPlatformPlugin;
import org.gradle.api.publish.maven.tasks.GenerateMavenPom;
import org.gradle.api.tasks.Sync;
import org.gradle.api.tasks.TaskExecutionException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.springframework.boot.build.DeployedPlugin;
import org.springframework.boot.build.bom.Library.Exclusion;
import org.springframework.boot.build.bom.Library.Group;
import org.springframework.boot.build.bom.Library.LibraryVersion;
import org.springframework.boot.build.bom.Library.Module;
import org.springframework.boot.build.bom.Library.ProhibitedVersion;
import org.springframework.boot.build.bom.Library.VersionAlignment;
import org.springframework.boot.build.bom.bomr.version.DependencyVersion;
import org.springframework.boot.build.mavenplugin.MavenExec;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
/**
* DSL extensions for {@link BomPlugin}.
*
* @author Andy Wilkinson
* @author Phillip Webb
*/
public class BomExtension {
private final Map<String, DependencyVersion> properties = new LinkedHashMap<>();
private final Map<String, String> artifactVersionProperties = new HashMap<>();
private final List<Library> libraries = new ArrayList<>();
private final UpgradeHandler upgradeHandler;
private final DependencyHandler dependencyHandler;
private final Project project;
public BomExtension(DependencyHandler dependencyHandler, Project project) {
this.dependencyHandler = dependencyHandler;
this.upgradeHandler = project.getObjects().newInstance(UpgradeHandler.class);
this.project = project;
}
public List<Library> getLibraries() {
return this.libraries;
}
public void upgrade(Action<UpgradeHandler> action) {
action.execute(this.upgradeHandler);
}
public Upgrade getUpgrade() {
return new Upgrade(this.upgradeHandler.upgradePolicy, new GitHub(this.upgradeHandler.gitHub.organization,
this.upgradeHandler.gitHub.repository, this.upgradeHandler.gitHub.issueLabels));
}
public void library(String name, Action<LibraryHandler> action) {
library(name, null, action);
}
public void library(String name, String version, Action<LibraryHandler> action) {
ObjectFactory objects = this.project.getObjects();
LibraryHandler libraryHandler = objects.newInstance(LibraryHandler.class, this.project,
(version != null) ? version : "");
action.execute(libraryHandler);
LibraryVersion libraryVersion = new LibraryVersion(DependencyVersion.parse(libraryHandler.version));
VersionAlignment versionAlignment = (libraryHandler.alignWith.version != null)
? new VersionAlignment(libraryHandler.alignWith.version.from,
libraryHandler.alignWith.version.managedBy, this.project, this.libraries, libraryHandler.groups)
: null;
addLibrary(new Library(name, libraryHandler.calendarName, libraryVersion, libraryHandler.groups,
libraryHandler.prohibitedVersions, libraryHandler.considerSnapshots, versionAlignment,
libraryHandler.alignWith.dependencyManagementDeclaredIn, libraryHandler.linkRootName,
libraryHandler.links));
}
public void effectiveBomArtifact() {
Configuration effectiveBomConfiguration = this.project.getConfigurations().create("effectiveBom");
this.project.getTasks()
.matching((task) -> task.getName().equals(DeployedPlugin.GENERATE_POM_TASK_NAME))
.all((task) -> {
Sync syncBom = this.project.getTasks().create("syncBom", Sync.class);
syncBom.dependsOn(task);
File generatedBomDir = new File(this.project.getBuildDir(), "generated/bom");
syncBom.setDestinationDir(generatedBomDir);
syncBom.from(((GenerateMavenPom) task).getDestination(), (pom) -> pom.rename((name) -> "pom.xml"));
try {
String settingsXmlContent = FileCopyUtils
.copyToString(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("effective-bom-settings.xml"),
StandardCharsets.UTF_8))
.replace("localRepositoryPath",
new File(this.project.getBuildDir(), "local-m2-repository").getAbsolutePath());
syncBom.from(this.project.getResources().getText().fromString(settingsXmlContent),
(settingsXml) -> settingsXml.rename((name) -> "settings.xml"));
}
catch (IOException ex) {
throw new GradleException("Failed to prepare settings.xml", ex);
}
MavenExec generateEffectiveBom = this.project.getTasks()
.create("generateEffectiveBom", MavenExec.class);
generateEffectiveBom.setProjectDir(generatedBomDir);
File effectiveBom = new File(this.project.getBuildDir(),
"generated/effective-bom/" + this.project.getName() + "-effective-bom.xml");
generateEffectiveBom.args("--settings", "settings.xml", "help:effective-pom",
"-Doutput=" + effectiveBom);
generateEffectiveBom.dependsOn(syncBom);
generateEffectiveBom.getOutputs().file(effectiveBom);
generateEffectiveBom.doLast(new StripUnrepeatableOutputAction(effectiveBom));
this.project.getArtifacts()
.add(effectiveBomConfiguration.getName(), effectiveBom,
(artifact) -> artifact.builtBy(generateEffectiveBom));
});
}
private String createDependencyNotation(String groupId, String artifactId, DependencyVersion version) {
return groupId + ":" + artifactId + ":" + version;
}
Map<String, DependencyVersion> getProperties() {
return this.properties;
}
String getArtifactVersionProperty(String groupId, String artifactId, String classifier) {
String coordinates = groupId + ":" + artifactId + ":" + classifier;
return this.artifactVersionProperties.get(coordinates);
}
private void putArtifactVersionProperty(String groupId, String artifactId, String versionProperty) {
putArtifactVersionProperty(groupId, artifactId, null, versionProperty);
}
private void putArtifactVersionProperty(String groupId, String artifactId, String classifier,
String versionProperty) {
String coordinates = groupId + ":" + artifactId + ":" + ((classifier != null) ? classifier : "");
String existing = this.artifactVersionProperties.putIfAbsent(coordinates, versionProperty);
if (existing != null) {
throw new InvalidUserDataException("Cannot put version property for '" + coordinates
+ "'. Version property '" + existing + "' has already been stored.");
}
}
private void addLibrary(Library library) {
this.libraries.add(library);
String versionProperty = library.getVersionProperty();
if (versionProperty != null) {
this.properties.put(versionProperty, library.getVersion().getVersion());
}
for (Group group : library.getGroups()) {
for (Module module : group.getModules()) {
putArtifactVersionProperty(group.getId(), module.getName(), module.getClassifier(), versionProperty);
this.dependencyHandler.getConstraints()
.add(JavaPlatformPlugin.API_CONFIGURATION_NAME, createDependencyNotation(group.getId(),
module.getName(), library.getVersion().getVersion()));
}
for (String bomImport : group.getBoms()) {
putArtifactVersionProperty(group.getId(), bomImport, versionProperty);
String bomDependency = createDependencyNotation(group.getId(), bomImport,
library.getVersion().getVersion());
this.dependencyHandler.add(JavaPlatformPlugin.API_CONFIGURATION_NAME,
this.dependencyHandler.platform(bomDependency));
this.dependencyHandler.add(BomPlugin.API_ENFORCED_CONFIGURATION_NAME,
this.dependencyHandler.enforcedPlatform(bomDependency));
}
}
}
public static class LibraryHandler {
private final List<Group> groups = new ArrayList<>();
private final List<ProhibitedVersion> prohibitedVersions = new ArrayList<>();
private final AlignWithHandler alignWith;
private boolean considerSnapshots = false;
private String version;
private String calendarName;
private String linkRootName;
private final Map<String, Function<LibraryVersion, String>> links = new HashMap<>();
@Inject
public LibraryHandler(Project project, String version) {
this.version = version;
this.alignWith = project.getObjects().newInstance(AlignWithHandler.class);
}
public void version(String version) {
this.version = version;
}
public void considerSnapshots() {
this.considerSnapshots = true;
}
public void setCalendarName(String calendarName) {
this.calendarName = calendarName;
}
public void group(String id, Action<GroupHandler> action) {
GroupHandler groupHandler = new GroupHandler(id);
action.execute(groupHandler);
this.groups
.add(new Group(groupHandler.id, groupHandler.modules, groupHandler.plugins, groupHandler.imports));
}
public void prohibit(Action<ProhibitedHandler> action) {
ProhibitedHandler handler = new ProhibitedHandler();
action.execute(handler);
this.prohibitedVersions.add(new ProhibitedVersion(handler.versionRange, handler.startsWith,
handler.endsWith, handler.contains, handler.reason));
}
public void alignWith(Action<AlignWithHandler> action) {
action.execute(this.alignWith);
}
public void links(Action<LinksHandler> action) {
links(null, action);
}
public void links(String linkRootName, Action<LinksHandler> action) {
LinksHandler handler = new LinksHandler();
action.execute(handler);
this.linkRootName = linkRootName;
this.links.putAll(handler.links);
}
public static class ProhibitedHandler {
private String reason;
private final List<String> startsWith = new ArrayList<>();
private final List<String> endsWith = new ArrayList<>();
private final List<String> contains = new ArrayList<>();
private VersionRange versionRange;
public void versionRange(String versionRange) {
try {
this.versionRange = VersionRange.createFromVersionSpec(versionRange);
}
catch (InvalidVersionSpecificationException ex) {
throw new InvalidUserCodeException("Invalid version range", ex);
}
}
public void startsWith(String startsWith) {
this.startsWith.add(startsWith);
}
public void startsWith(Collection<String> startsWith) {
this.startsWith.addAll(startsWith);
}
public void endsWith(String endsWith) {
this.endsWith.add(endsWith);
}
public void endsWith(Collection<String> endsWith) {
this.endsWith.addAll(endsWith);
}
public void contains(String contains) {
this.contains.add(contains);
}
public void contains(List<String> contains) {
this.contains.addAll(contains);
}
public void because(String because) {
this.reason = because;
}
}
public class GroupHandler extends GroovyObjectSupport {
private final String id;
private List<Module> modules = new ArrayList<>();
private List<String> imports = new ArrayList<>();
private List<String> plugins = new ArrayList<>();
public GroupHandler(String id) {
this.id = id;
}
public void setModules(List<Object> modules) {
this.modules = modules.stream()
.map((input) -> (input instanceof Module module) ? module : new Module((String) input))
.toList();
}
public void setImports(List<String> imports) {
this.imports = imports;
}
public void setPlugins(List<String> plugins) {
this.plugins = plugins;
}
public Object methodMissing(String name, Object args) {
if (args instanceof Object[] && ((Object[]) args).length == 1) {
Object arg = ((Object[]) args)[0];
if (arg instanceof Closure<?> closure) {
ModuleHandler moduleHandler = new ModuleHandler();
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.setDelegate(moduleHandler);
closure.call(moduleHandler);
return new Module(name, moduleHandler.type, moduleHandler.classifier, moduleHandler.exclusions);
}
}
throw new InvalidUserDataException("Invalid configuration for module '" + name + "'");
}
public class ModuleHandler {
private final List<Exclusion> exclusions = new ArrayList<>();
private String type;
private String classifier;
public void exclude(Map<String, String> exclusion) {
this.exclusions.add(new Exclusion(exclusion.get("group"), exclusion.get("module")));
}
public void setType(String type) {
this.type = type;
}
public void setClassifier(String classifier) {
this.classifier = classifier;
}
}
}
public static class AlignWithHandler {
private VersionHandler version;
private String dependencyManagementDeclaredIn;
public void version(Action<VersionHandler> action) {
this.version = new VersionHandler();
action.execute(this.version);
}
public void dependencyManagementDeclaredIn(String bomCoordinates) {
this.dependencyManagementDeclaredIn = bomCoordinates;
}
public static class VersionHandler {
private String from;
private String managedBy;
public void from(String from) {
this.from = from;
}
public void managedBy(String managedBy) {
this.managedBy = managedBy;
}
}
}
}
public static class LinksHandler {
private final Map<String, Function<LibraryVersion, String>> links = new HashMap<>();
public void site(String linkTemplate) {
site(asFactory(linkTemplate));
}
public void site(Function<LibraryVersion, String> linkFactory) {
add("site", linkFactory);
}
public void github(String linkTemplate) {
github(asFactory(linkTemplate));
}
public void github(Function<LibraryVersion, String> linkFactory) {
add("github", linkFactory);
}
public void docs(String linkTemplate) {
docs(asFactory(linkTemplate));
}
public void docs(Function<LibraryVersion, String> linkFactory) {
add("docs", linkFactory);
}
public void javadoc(String linkTemplate) {
javadoc(asFactory(linkTemplate));
}
public void javadoc(Function<LibraryVersion, String> linkFactory) {
add("javadoc", linkFactory);
}
public void releaseNotes(String linkTemplate) {
releaseNotes(asFactory(linkTemplate));
}
public void releaseNotes(Function<LibraryVersion, String> linkFactory) {
add("releaseNotes", linkFactory);
}
public void add(String name, String linkTemplate) {
add(name, asFactory(linkTemplate));
}
public void add(String name, Function<LibraryVersion, String> linkFactory) {
this.links.put(name, linkFactory);
}
private Function<LibraryVersion, String> asFactory(String linkTemplate) {
return (version) -> {
PlaceholderResolver resolver = (name) -> "version".equals(name) ? version.toString() : null;
return new PropertyPlaceholderHelper("{", "}").replacePlaceholders(linkTemplate, resolver);
};
}
}
public static class UpgradeHandler {
private UpgradePolicy upgradePolicy;
private final GitHubHandler gitHub = new GitHubHandler();
public void setPolicy(UpgradePolicy upgradePolicy) {
this.upgradePolicy = upgradePolicy;
}
public void gitHub(Action<GitHubHandler> action) {
action.execute(this.gitHub);
}
}
public static final class Upgrade {
private final UpgradePolicy upgradePolicy;
private final GitHub gitHub;
private Upgrade(UpgradePolicy upgradePolicy, GitHub gitHub) {
this.upgradePolicy = upgradePolicy;
this.gitHub = gitHub;
}
public UpgradePolicy getPolicy() {
return this.upgradePolicy;
}
public GitHub getGitHub() {
return this.gitHub;
}
}
public static class GitHubHandler {
private String organization = "spring-projects";
private String repository = "spring-boot";
private List<String> issueLabels;
public void setOrganization(String organization) {
this.organization = organization;
}
public void setRepository(String repository) {
this.repository = repository;
}
public void setIssueLabels(List<String> issueLabels) {
this.issueLabels = issueLabels;
}
}
public static final class GitHub {
private String organization = "spring-projects";
private String repository = "spring-boot";
private final List<String> issueLabels;
private GitHub(String organization, String repository, List<String> issueLabels) {
this.organization = organization;
this.repository = repository;
this.issueLabels = issueLabels;
}
public String getOrganization() {
return this.organization;
}
public String getRepository() {
return this.repository;
}
public List<String> getIssueLabels() {
return this.issueLabels;
}
}
private static final class StripUnrepeatableOutputAction implements Action<Task> {
private final File effectiveBom;
private StripUnrepeatableOutputAction(File xmlFile) {
this.effectiveBom = xmlFile;
}
@Override
public void execute(Task task) {
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.effectiveBom);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList comments = (NodeList) xpath.evaluate("//comment()", document, XPathConstants.NODESET);
for (int i = 0; i < comments.getLength(); i++) {
org.w3c.dom.Node comment = comments.item(i);
comment.getParentNode().removeChild(comment);
}
org.w3c.dom.Node build = (org.w3c.dom.Node) xpath.evaluate("/project/build", document,
XPathConstants.NODE);
build.getParentNode().removeChild(build);
org.w3c.dom.Node reporting = (org.w3c.dom.Node) xpath.evaluate("/project/reporting", document,
XPathConstants.NODE);
reporting.getParentNode().removeChild(reporting);
TransformerFactory.newInstance()
.newTransformer()
.transform(new DOMSource(document), new StreamResult(this.effectiveBom));
}
catch (Exception ex) {
throw new TaskExecutionException(task, ex);
}
}
}
}
| spring-projects/spring-boot | buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java |
666 | /**
* File: n_queens.java
* Created Time: 2023-05-04
* Author: krahets ([email protected])
*/
package chapter_backtracking;
import java.util.*;
public class n_queens {
/* 回溯算法:n 皇后 */
public static void backtrack(int row, int n, List<List<String>> state, List<List<List<String>>> res,
boolean[] cols, boolean[] diags1, boolean[] diags2) {
// 当放置完所有行时,记录解
if (row == n) {
List<List<String>> copyState = new ArrayList<>();
for (List<String> sRow : state) {
copyState.add(new ArrayList<>(sRow));
}
res.add(copyState);
return;
}
// 遍历所有列
for (int col = 0; col < n; col++) {
// 计算该格子对应的主对角线和次对角线
int diag1 = row - col + n - 1;
int diag2 = row + col;
// 剪枝:不允许该格子所在列、主对角线、次对角线上存在皇后
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
// 尝试:将皇后放置在该格子
state.get(row).set(col, "Q");
cols[col] = diags1[diag1] = diags2[diag2] = true;
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state.get(row).set(col, "#");
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* 求解 n 皇后 */
public static List<List<List<String>>> nQueens(int n) {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
List<List<String>> state = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<String> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
row.add("#");
}
state.add(row);
}
boolean[] cols = new boolean[n]; // 记录列是否有皇后
boolean[] diags1 = new boolean[2 * n - 1]; // 记录主对角线上是否有皇后
boolean[] diags2 = new boolean[2 * n - 1]; // 记录次对角线上是否有皇后
List<List<List<String>>> res = new ArrayList<>();
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
public static void main(String[] args) {
int n = 4;
List<List<List<String>>> res = nQueens(n);
System.out.println("输入棋盘长宽为 " + n);
System.out.println("皇后放置方案共有 " + res.size() + " 种");
for (List<List<String>> state : res) {
System.out.println("--------------------");
for (List<String> row : state) {
System.out.println(row);
}
}
}
}
| krahets/hello-algo | codes/java/chapter_backtracking/n_queens.java |
667 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.CompactHashing.UNSET;
import static com.google.common.collect.Hashing.smearedHash;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.collect.NullnessCasts.unsafeNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* CompactHashMap is an implementation of a Map. All optional operations (put and remove) are
* supported. Null keys and values are supported.
*
* <p>{@code containsKey(k)}, {@code put(k, v)} and {@code remove(k)} are all (expected and
* amortized) constant time operations. Expected in the hashtable sense (depends on the hash
* function doing a good job of distributing the elements to the buckets to a distribution not far
* from uniform), and amortized since some operations can trigger a hash table resize.
*
* <p>Unlike {@code java.util.HashMap}, iteration is only proportional to the actual {@code size()},
* which is optimal, and <i>not</i> the size of the internal hashtable, which could be much larger
* than {@code size()}. Furthermore, this structure places significantly reduced load on the garbage
* collector by only using a constant number of internal objects.
*
* <p>If there are no removals, then iteration order for the {@link #entrySet}, {@link #keySet}, and
* {@link #values} views is the same as insertion order. Any removal invalidates any ordering
* guarantees.
*
* <p>This class should not be assumed to be universally superior to {@code java.util.HashMap}.
* Generally speaking, this class reduces object allocation and memory consumption at the price of
* moderately increased constant factors of CPU. Only use this class when there is a specific reason
* to prioritize memory over CPU.
*
* @author Louis Wasserman
* @author Jon Noack
*/
@GwtIncompatible // not worth using in GWT for now
@ElementTypesAreNonnullByDefault
class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMap<K, V> implements Serializable {
/*
* TODO: Make this a drop-in replacement for j.u. versions, actually drop them in, and test the
* world. Figure out what sort of space-time tradeoff we're actually going to get here with the
* *Map variants. This class is particularly hard to benchmark, because the benefit is not only in
* less allocation, but also having the GC do less work to scan the heap because of fewer
* references, which is particularly hard to quantify.
*/
/** Creates an empty {@code CompactHashMap} instance. */
public static <K extends @Nullable Object, V extends @Nullable Object>
CompactHashMap<K, V> create() {
return new CompactHashMap<>();
}
/**
* Creates a {@code CompactHashMap} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code CompactHashMap} with enough capacity to hold {@code expectedSize}
* elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
CompactHashMap<K, V> createWithExpectedSize(int expectedSize) {
return new CompactHashMap<>(expectedSize);
}
private static final Object NOT_FOUND = new Object();
/**
* Maximum allowed false positive probability of detecting a hash flooding attack given random
* input.
*/
@VisibleForTesting(
)
static final double HASH_FLOODING_FPP = 0.001;
/**
* Maximum allowed length of a hash table bucket before falling back to a j.u.LinkedHashMap-based
* implementation. Experimentally determined.
*/
private static final int MAX_HASH_BUCKET_LENGTH = 9;
// The way the `table`, `entries`, `keys`, and `values` arrays work together is as follows.
//
// The `table` array always has a size that is a power of 2. The hashcode of a key in the map
// is masked in order to correspond to the current table size. For example, if the table size
// is 128 then the mask is 127 == 0x7f, keeping the bottom 7 bits of the hash value.
// If a key hashes to 0x89abcdef the mask reduces it to 0x89abcdef & 0x7f == 0x6f. We'll call this
// the "short hash".
//
// The `keys`, `values`, and `entries` arrays always have the same size as each other. They can be
// seen as fields of an imaginary `Entry` object like this:
//
// class Entry {
// int hash;
// Entry next;
// K key;
// V value;
// }
//
// The imaginary `hash` and `next` values are combined into a single `int` value in the `entries`
// array. The top bits of this value are the remaining bits of the hash value that were not used
// in the short hash. We saw that a mask of 0x7f would keep the 7-bit value 0x6f from a full
// hashcode of 0x89abcdef. The imaginary `hash` value would then be the remaining top 25 bits,
// 0x89abcd80. To this is added (or'd) the `next` value, which is an index within `entries`
// (and therefore within `keys` and `values`) of another entry that has the same short hash
// value. In our example, it would be another entry for a key whose short hash is also 0x6f.
//
// Essentially, then, `table[h]` gives us the start of a linked list in `entries`, where every
// element of the list has the short hash value h.
//
// A wrinkle here is that the value 0 (called UNSET in the code) is used as the equivalent of a
// null pointer. If `table[h] == 0` that means there are no keys in the map whose short hash is h.
// If the `next` bits in `entries[i]` are 0 that means there are no further entries for the given
// short hash. But 0 is also a valid index in `entries`, so we add 1 to these indices before
// putting them in `table` or in `next` bits, and subtract 1 again when we need an index value.
//
// The elements of `keys`, `values`, and `entries` are added sequentially, so that elements 0 to
// `size() - 1` are used and remaining elements are not. This makes iteration straightforward.
// Removing an entry generally involves moving the last element of each array to where the removed
// entry was, and adjusting index links accordingly.
/**
* The hashtable object. This can be either:
*
* <ul>
* <li>a byte[], short[], or int[], with size a power of two, created by
* CompactHashing.createTable, whose values are either
* <ul>
* <li>UNSET, meaning "null pointer"
* <li>one plus an index into the keys, values, and entries arrays
* </ul>
* <li>another java.util.Map delegate implementation. In most modern JDKs, normal java.util hash
* collections intelligently fall back to a binary search tree if hash table collisions are
* detected. Rather than going to all the trouble of reimplementing this ourselves, we
* simply switch over to use the JDK implementation wholesale if probable hash flooding is
* detected, sacrificing the compactness guarantee in very rare cases in exchange for much
* more reliable worst-case behavior.
* <li>null, if no entries have yet been added to the map
* </ul>
*/
@CheckForNull private transient Object table;
/**
* Contains the logical entries, in the range of [0, size()). The high bits of each int are the
* part of the smeared hash of the key not covered by the hashtable mask, whereas the low bits are
* the "next" pointer (pointing to the next entry in the bucket chain), which will always be less
* than or equal to the hashtable mask.
*
* <pre>
* hash = aaaaaaaa
* mask = 00000fff
* next = 00000bbb
* entry = aaaaabbb
* </pre>
*
* <p>The pointers in [size(), entries.length) are all "null" (UNSET).
*/
@VisibleForTesting @CheckForNull transient int[] entries;
/**
* The keys of the entries in the map, in the range of [0, size()). The keys in [size(),
* keys.length) are all {@code null}.
*/
@VisibleForTesting @CheckForNull transient @Nullable Object[] keys;
/**
* The values of the entries in the map, in the range of [0, size()). The values in [size(),
* values.length) are all {@code null}.
*/
@VisibleForTesting @CheckForNull transient @Nullable Object[] values;
/**
* Keeps track of metadata like the number of hash table bits and modifications of this data
* structure (to make it possible to throw ConcurrentModificationException in the iterator). Note
* that we choose not to make this volatile, so we do less of a "best effort" to track such
* errors, for better performance.
*
* <p>For a new instance, where the arrays above have not yet been allocated, the value of {@code
* metadata} is the size that the arrays should be allocated with. Once the arrays have been
* allocated, the value of {@code metadata} combines the number of bits in the "short hash", in
* its bottom {@value CompactHashing#HASH_TABLE_BITS_MAX_BITS} bits, with a modification count in
* the remaining bits that is used to detect concurrent modification during iteration.
*/
private transient int metadata;
/** The number of elements contained in the set. */
private transient int size;
/** Constructs a new empty instance of {@code CompactHashMap}. */
CompactHashMap() {
init(CompactHashing.DEFAULT_SIZE);
}
/**
* Constructs a new instance of {@code CompactHashMap} with the specified capacity.
*
* @param expectedSize the initial capacity of this {@code CompactHashMap}.
*/
CompactHashMap(int expectedSize) {
init(expectedSize);
}
/** Pseudoconstructor for serialization support. */
void init(int expectedSize) {
Preconditions.checkArgument(expectedSize >= 0, "Expected size must be >= 0");
// Save expectedSize for use in allocArrays()
this.metadata = Ints.constrainToRange(expectedSize, 1, CompactHashing.MAX_SIZE);
}
/** Returns whether arrays need to be allocated. */
@VisibleForTesting
boolean needsAllocArrays() {
return table == null;
}
/** Handle lazy allocation of arrays. */
@CanIgnoreReturnValue
int allocArrays() {
Preconditions.checkState(needsAllocArrays(), "Arrays already allocated");
int expectedSize = metadata;
int buckets = CompactHashing.tableSize(expectedSize);
this.table = CompactHashing.createTable(buckets);
setHashTableMask(buckets - 1);
this.entries = new int[expectedSize];
this.keys = new Object[expectedSize];
this.values = new Object[expectedSize];
return expectedSize;
}
@SuppressWarnings("unchecked")
@VisibleForTesting
@CheckForNull
Map<K, V> delegateOrNull() {
if (table instanceof Map) {
return (Map<K, V>) table;
}
return null;
}
Map<K, V> createHashFloodingResistantDelegate(int tableSize) {
return new LinkedHashMap<>(tableSize, 1.0f);
}
@VisibleForTesting
@CanIgnoreReturnValue
Map<K, V> convertToHashFloodingResistantImplementation() {
Map<K, V> newDelegate = createHashFloodingResistantDelegate(hashTableMask() + 1);
for (int i = firstEntryIndex(); i >= 0; i = getSuccessor(i)) {
newDelegate.put(key(i), value(i));
}
this.table = newDelegate;
this.entries = null;
this.keys = null;
this.values = null;
incrementModCount();
return newDelegate;
}
/** Stores the hash table mask as the number of bits needed to represent an index. */
private void setHashTableMask(int mask) {
int hashTableBits = Integer.SIZE - Integer.numberOfLeadingZeros(mask);
metadata =
CompactHashing.maskCombine(metadata, hashTableBits, CompactHashing.HASH_TABLE_BITS_MASK);
}
/** Gets the hash table mask using the stored number of hash table bits. */
private int hashTableMask() {
return (1 << (metadata & CompactHashing.HASH_TABLE_BITS_MASK)) - 1;
}
void incrementModCount() {
metadata += CompactHashing.MODIFICATION_COUNT_INCREMENT;
}
/**
* Mark an access of the specified entry. Used only in {@code CompactLinkedHashMap} for LRU
* ordering.
*/
void accessEntry(int index) {
// no-op by default
}
@CanIgnoreReturnValue
@Override
@CheckForNull
public V put(@ParametricNullness K key, @ParametricNullness V value) {
if (needsAllocArrays()) {
allocArrays();
}
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.put(key, value);
}
int[] entries = requireEntries();
@Nullable Object[] keys = requireKeys();
@Nullable Object[] values = requireValues();
int newEntryIndex = this.size; // current size, and pointer to the entry to be appended
int newSize = newEntryIndex + 1;
int hash = smearedHash(key);
int mask = hashTableMask();
int tableIndex = hash & mask;
int next = CompactHashing.tableGet(requireTable(), tableIndex);
if (next == UNSET) { // uninitialized bucket
if (newSize > mask) {
// Resize and add new entry
mask = resizeTable(mask, CompactHashing.newCapacity(mask), hash, newEntryIndex);
} else {
CompactHashing.tableSet(requireTable(), tableIndex, newEntryIndex + 1);
}
} else {
int entryIndex;
int entry;
int hashPrefix = CompactHashing.getHashPrefix(hash, mask);
int bucketLength = 0;
do {
entryIndex = next - 1;
entry = entries[entryIndex];
if (CompactHashing.getHashPrefix(entry, mask) == hashPrefix
&& Objects.equal(key, keys[entryIndex])) {
@SuppressWarnings("unchecked") // known to be a V
V oldValue = (V) values[entryIndex];
values[entryIndex] = value;
accessEntry(entryIndex);
return oldValue;
}
next = CompactHashing.getNext(entry, mask);
bucketLength++;
} while (next != UNSET);
if (bucketLength >= MAX_HASH_BUCKET_LENGTH) {
return convertToHashFloodingResistantImplementation().put(key, value);
}
if (newSize > mask) {
// Resize and add new entry
mask = resizeTable(mask, CompactHashing.newCapacity(mask), hash, newEntryIndex);
} else {
entries[entryIndex] = CompactHashing.maskCombine(entry, newEntryIndex + 1, mask);
}
}
resizeMeMaybe(newSize);
insertEntry(newEntryIndex, key, value, hash, mask);
this.size = newSize;
incrementModCount();
return null;
}
/**
* Creates a fresh entry with the specified object at the specified position in the entry arrays.
*/
void insertEntry(
int entryIndex, @ParametricNullness K key, @ParametricNullness V value, int hash, int mask) {
this.setEntry(entryIndex, CompactHashing.maskCombine(hash, UNSET, mask));
this.setKey(entryIndex, key);
this.setValue(entryIndex, value);
}
/** Resizes the entries storage if necessary. */
private void resizeMeMaybe(int newSize) {
int entriesSize = requireEntries().length;
if (newSize > entriesSize) {
// 1.5x but round up to nearest odd (this is optimal for memory consumption on Android)
int newCapacity =
Math.min(CompactHashing.MAX_SIZE, (entriesSize + Math.max(1, entriesSize >>> 1)) | 1);
if (newCapacity != entriesSize) {
resizeEntries(newCapacity);
}
}
}
/**
* Resizes the internal entries array to the specified capacity, which may be greater or less than
* the current capacity.
*/
void resizeEntries(int newCapacity) {
this.entries = Arrays.copyOf(requireEntries(), newCapacity);
this.keys = Arrays.copyOf(requireKeys(), newCapacity);
this.values = Arrays.copyOf(requireValues(), newCapacity);
}
@CanIgnoreReturnValue
private int resizeTable(int oldMask, int newCapacity, int targetHash, int targetEntryIndex) {
Object newTable = CompactHashing.createTable(newCapacity);
int newMask = newCapacity - 1;
if (targetEntryIndex != UNSET) {
// Add target first; it must be last in the chain because its entry hasn't yet been created
CompactHashing.tableSet(newTable, targetHash & newMask, targetEntryIndex + 1);
}
Object oldTable = requireTable();
int[] entries = requireEntries();
// Loop over `oldTable` to construct its replacement, ``newTable`. The entries do not move, so
// the `keys` and `values` arrays do not need to change. But because the "short hash" now has a
// different number of bits, we must rewrite each element of `entries` so that its contribution
// to the full hashcode reflects the change, and so that its `next` link corresponds to the new
// linked list of entries with the new short hash.
for (int oldTableIndex = 0; oldTableIndex <= oldMask; oldTableIndex++) {
int oldNext = CompactHashing.tableGet(oldTable, oldTableIndex);
// Each element of `oldTable` is the head of a (possibly empty) linked list of elements in
// `entries`. The `oldNext` loop is going to traverse that linked list.
// We need to rewrite the `next` link of each of the elements so that it is in the appropriate
// linked list starting from `newTable`. In general, each element from the old linked list
// belongs to a different linked list from `newTable`. We insert each element in turn at the
// head of its appropriate `newTable` linked list.
while (oldNext != UNSET) {
int entryIndex = oldNext - 1;
int oldEntry = entries[entryIndex];
// Rebuild the full 32-bit hash using entry hashPrefix and oldTableIndex ("hashSuffix").
int hash = CompactHashing.getHashPrefix(oldEntry, oldMask) | oldTableIndex;
int newTableIndex = hash & newMask;
int newNext = CompactHashing.tableGet(newTable, newTableIndex);
CompactHashing.tableSet(newTable, newTableIndex, oldNext);
entries[entryIndex] = CompactHashing.maskCombine(hash, newNext, newMask);
oldNext = CompactHashing.getNext(oldEntry, oldMask);
}
}
this.table = newTable;
setHashTableMask(newMask);
return newMask;
}
private int indexOf(@CheckForNull Object key) {
if (needsAllocArrays()) {
return -1;
}
int hash = smearedHash(key);
int mask = hashTableMask();
int next = CompactHashing.tableGet(requireTable(), hash & mask);
if (next == UNSET) {
return -1;
}
int hashPrefix = CompactHashing.getHashPrefix(hash, mask);
do {
int entryIndex = next - 1;
int entry = entry(entryIndex);
if (CompactHashing.getHashPrefix(entry, mask) == hashPrefix
&& Objects.equal(key, key(entryIndex))) {
return entryIndex;
}
next = CompactHashing.getNext(entry, mask);
} while (next != UNSET);
return -1;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
Map<K, V> delegate = delegateOrNull();
return (delegate != null) ? delegate.containsKey(key) : indexOf(key) != -1;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.get(key);
}
int index = indexOf(key);
if (index == -1) {
return null;
}
accessEntry(index);
return value(index);
}
@CanIgnoreReturnValue
@SuppressWarnings("unchecked") // known to be a V
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.remove(key);
}
Object oldValue = removeHelper(key);
return (oldValue == NOT_FOUND) ? null : (V) oldValue;
}
private @Nullable Object removeHelper(@CheckForNull Object key) {
if (needsAllocArrays()) {
return NOT_FOUND;
}
int mask = hashTableMask();
int index =
CompactHashing.remove(
key,
/* value= */ null,
mask,
requireTable(),
requireEntries(),
requireKeys(),
/* values= */ null);
if (index == -1) {
return NOT_FOUND;
}
Object oldValue = value(index);
moveLastEntry(index, mask);
size--;
incrementModCount();
return oldValue;
}
/**
* Moves the last entry in the entry array into {@code dstIndex}, and nulls out its old position.
*/
void moveLastEntry(int dstIndex, int mask) {
Object table = requireTable();
int[] entries = requireEntries();
@Nullable Object[] keys = requireKeys();
@Nullable Object[] values = requireValues();
int srcIndex = size() - 1;
if (dstIndex < srcIndex) {
// move last entry to deleted spot
Object key = keys[srcIndex];
keys[dstIndex] = key;
values[dstIndex] = values[srcIndex];
keys[srcIndex] = null;
values[srcIndex] = null;
// move the last entry to the removed spot, just like we moved the element
entries[dstIndex] = entries[srcIndex];
entries[srcIndex] = 0;
// also need to update whoever's "next" pointer was pointing to the last entry place
int tableIndex = smearedHash(key) & mask;
int next = CompactHashing.tableGet(table, tableIndex);
int srcNext = srcIndex + 1;
if (next == srcNext) {
// we need to update the root pointer
CompactHashing.tableSet(table, tableIndex, dstIndex + 1);
} else {
// we need to update a pointer in an entry
int entryIndex;
int entry;
do {
entryIndex = next - 1;
entry = entries[entryIndex];
next = CompactHashing.getNext(entry, mask);
} while (next != srcNext);
// here, entries[entryIndex] points to the old entry location; update it
entries[entryIndex] = CompactHashing.maskCombine(entry, dstIndex + 1, mask);
}
} else {
keys[dstIndex] = null;
values[dstIndex] = null;
entries[dstIndex] = 0;
}
}
int firstEntryIndex() {
return isEmpty() ? -1 : 0;
}
int getSuccessor(int entryIndex) {
return (entryIndex + 1 < size) ? entryIndex + 1 : -1;
}
/**
* Updates the index an iterator is pointing to after a call to remove: returns the index of the
* entry that should be looked at after a removal on indexRemoved, with indexBeforeRemove as the
* index that *was* the next entry that would be looked at.
*/
int adjustAfterRemove(int indexBeforeRemove, @SuppressWarnings("unused") int indexRemoved) {
return indexBeforeRemove - 1;
}
private abstract class Itr<T extends @Nullable Object> implements Iterator<T> {
int expectedMetadata = metadata;
int currentIndex = firstEntryIndex();
int indexToRemove = -1;
@Override
public boolean hasNext() {
return currentIndex >= 0;
}
@ParametricNullness
abstract T getOutput(int entry);
@Override
@ParametricNullness
public T next() {
checkForConcurrentModification();
if (!hasNext()) {
throw new NoSuchElementException();
}
indexToRemove = currentIndex;
T result = getOutput(currentIndex);
currentIndex = getSuccessor(currentIndex);
return result;
}
@Override
public void remove() {
checkForConcurrentModification();
checkRemove(indexToRemove >= 0);
incrementExpectedModCount();
CompactHashMap.this.remove(key(indexToRemove));
currentIndex = adjustAfterRemove(currentIndex, indexToRemove);
indexToRemove = -1;
}
void incrementExpectedModCount() {
expectedMetadata += CompactHashing.MODIFICATION_COUNT_INCREMENT;
}
private void checkForConcurrentModification() {
if (metadata != expectedMetadata) {
throw new ConcurrentModificationException();
}
}
}
@LazyInit @CheckForNull private transient Set<K> keySetView;
@Override
public Set<K> keySet() {
return (keySetView == null) ? keySetView = createKeySet() : keySetView;
}
Set<K> createKeySet() {
return new KeySetView();
}
@WeakOuter
class KeySetView extends AbstractSet<K> {
@Override
public int size() {
return CompactHashMap.this.size();
}
@Override
public boolean contains(@CheckForNull Object o) {
return CompactHashMap.this.containsKey(o);
}
@Override
public boolean remove(@CheckForNull Object o) {
Map<K, V> delegate = delegateOrNull();
return (delegate != null)
? delegate.keySet().remove(o)
: CompactHashMap.this.removeHelper(o) != NOT_FOUND;
}
@Override
public Iterator<K> iterator() {
return keySetIterator();
}
@Override
public void clear() {
CompactHashMap.this.clear();
}
}
Iterator<K> keySetIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.keySet().iterator();
}
return new Itr<K>() {
@Override
@ParametricNullness
K getOutput(int entry) {
return key(entry);
}
};
}
@LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySetView;
@Override
public Set<Entry<K, V>> entrySet() {
return (entrySetView == null) ? entrySetView = createEntrySet() : entrySetView;
}
Set<Entry<K, V>> createEntrySet() {
return new EntrySetView();
}
@WeakOuter
class EntrySetView extends AbstractSet<Entry<K, V>> {
@Override
public int size() {
return CompactHashMap.this.size();
}
@Override
public void clear() {
CompactHashMap.this.clear();
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entrySetIterator();
}
@Override
public boolean contains(@CheckForNull Object o) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().contains(o);
} else if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
int index = indexOf(entry.getKey());
return index != -1 && Objects.equal(value(index), entry.getValue());
}
return false;
}
@Override
public boolean remove(@CheckForNull Object o) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().remove(o);
} else if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
if (needsAllocArrays()) {
return false;
}
int mask = hashTableMask();
int index =
CompactHashing.remove(
entry.getKey(),
entry.getValue(),
mask,
requireTable(),
requireEntries(),
requireKeys(),
requireValues());
if (index == -1) {
return false;
}
moveLastEntry(index, mask);
size--;
incrementModCount();
return true;
}
return false;
}
}
Iterator<Entry<K, V>> entrySetIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().iterator();
}
return new Itr<Entry<K, V>>() {
@Override
Entry<K, V> getOutput(int entry) {
return new MapEntry(entry);
}
};
}
final class MapEntry extends AbstractMapEntry<K, V> {
@ParametricNullness private final K key;
private int lastKnownIndex;
MapEntry(int index) {
this.key = key(index);
this.lastKnownIndex = index;
}
@Override
@ParametricNullness
public K getKey() {
return key;
}
private void updateLastKnownIndex() {
if (lastKnownIndex == -1
|| lastKnownIndex >= size()
|| !Objects.equal(key, key(lastKnownIndex))) {
lastKnownIndex = indexOf(key);
}
}
@Override
@ParametricNullness
public V getValue() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
/*
* The cast is safe because the entry is present in the map. Or, if it has been removed by a
* concurrent modification, behavior is undefined.
*/
return uncheckedCastNullableTToT(delegate.get(key));
}
updateLastKnownIndex();
/*
* If the entry has been removed from the map, we return null, even though that might not be a
* valid value. That's the best we can do, short of holding a reference to the most recently
* seen value. And while we *could* do that, we aren't required to: Map.Entry explicitly says
* that behavior is undefined when the backing map is modified through another API. (It even
* permits us to throw IllegalStateException. Maybe we should have done that, but we probably
* shouldn't change now for fear of breaking people.)
*/
return (lastKnownIndex == -1) ? unsafeNull() : value(lastKnownIndex);
}
@Override
@ParametricNullness
public V setValue(@ParametricNullness V value) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return uncheckedCastNullableTToT(delegate.put(key, value)); // See discussion in getValue().
}
updateLastKnownIndex();
if (lastKnownIndex == -1) {
put(key, value);
return unsafeNull(); // See discussion in getValue().
} else {
V old = value(lastKnownIndex);
CompactHashMap.this.setValue(lastKnownIndex, value);
return old;
}
}
}
@Override
public int size() {
Map<K, V> delegate = delegateOrNull();
return (delegate != null) ? delegate.size() : size;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsValue(@CheckForNull Object value) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.containsValue(value);
}
for (int i = 0; i < size; i++) {
if (Objects.equal(value, value(i))) {
return true;
}
}
return false;
}
@LazyInit @CheckForNull private transient Collection<V> valuesView;
@Override
public Collection<V> values() {
return (valuesView == null) ? valuesView = createValues() : valuesView;
}
Collection<V> createValues() {
return new ValuesView();
}
@WeakOuter
class ValuesView extends AbstractCollection<V> {
@Override
public int size() {
return CompactHashMap.this.size();
}
@Override
public void clear() {
CompactHashMap.this.clear();
}
@Override
public Iterator<V> iterator() {
return valuesIterator();
}
}
Iterator<V> valuesIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.values().iterator();
}
return new Itr<V>() {
@Override
@ParametricNullness
V getOutput(int entry) {
return value(entry);
}
};
}
/**
* Ensures that this {@code CompactHashMap} has the smallest representation in memory, given its
* current size.
*/
public void trimToSize() {
if (needsAllocArrays()) {
return;
}
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
Map<K, V> newDelegate = createHashFloodingResistantDelegate(size());
newDelegate.putAll(delegate);
this.table = newDelegate;
return;
}
int size = this.size;
if (size < requireEntries().length) {
resizeEntries(size);
}
int minimumTableSize = CompactHashing.tableSize(size);
int mask = hashTableMask();
if (minimumTableSize < mask) { // smaller table size will always be less than current mask
resizeTable(mask, minimumTableSize, UNSET, UNSET);
}
}
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
incrementModCount();
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
metadata =
Ints.constrainToRange(size(), CompactHashing.DEFAULT_SIZE, CompactHashing.MAX_SIZE);
delegate.clear(); // invalidate any iterators left over!
table = null;
size = 0;
} else {
Arrays.fill(requireKeys(), 0, size, null);
Arrays.fill(requireValues(), 0, size, null);
CompactHashing.tableClear(requireTable());
Arrays.fill(requireEntries(), 0, size, 0);
this.size = 0;
}
}
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
Iterator<Entry<K, V>> entryIterator = entrySetIterator();
while (entryIterator.hasNext()) {
Entry<K, V> e = entryIterator.next();
stream.writeObject(e.getKey());
stream.writeObject(e.getValue());
}
}
@SuppressWarnings("unchecked")
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
if (elementCount < 0) {
throw new InvalidObjectException("Invalid size: " + elementCount);
}
init(elementCount);
for (int i = 0; i < elementCount; i++) {
K key = (K) stream.readObject();
V value = (V) stream.readObject();
put(key, value);
}
}
/*
* The following methods are safe to call as long as both of the following hold:
*
* - allocArrays() has been called. Callers can confirm this by checking needsAllocArrays().
*
* - The map has not switched to delegating to a java.util implementation to mitigate hash
* flooding. Callers can confirm this by null-checking delegateOrNull().
*
* In an ideal world, we would document why we know those things are true every time we call these
* methods. But that is a bit too painful....
*/
private Object requireTable() {
return requireNonNull(table);
}
private int[] requireEntries() {
return requireNonNull(entries);
}
private @Nullable Object[] requireKeys() {
return requireNonNull(keys);
}
private @Nullable Object[] requireValues() {
return requireNonNull(values);
}
/*
* The following methods are safe to call as long as the conditions in the *previous* comment are
* met *and* the index is less than size().
*
* (The above explains when these methods are safe from a `nullness` perspective. From an
* `unchecked` perspective, they're safe because we put only K/V elements into each array.)
*/
@SuppressWarnings("unchecked")
private K key(int i) {
return (K) requireKeys()[i];
}
@SuppressWarnings("unchecked")
private V value(int i) {
return (V) requireValues()[i];
}
private int entry(int i) {
return requireEntries()[i];
}
private void setKey(int i, K key) {
requireKeys()[i] = key;
}
private void setValue(int i, V value) {
requireValues()[i] = value;
}
private void setEntry(int i, int value) {
requireEntries()[i] = value;
}
}
| google/guava | android/guava/src/com/google/common/collect/CompactHashMap.java |
668 | // ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package org.springframework.asm;
/**
* A {@link MethodVisitor} that generates a corresponding 'method_info' structure, as defined in the
* Java Virtual Machine Specification (JVMS).
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.6">JVMS
* 4.6</a>
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
final class MethodWriter extends MethodVisitor {
/** Indicates that nothing must be computed. */
static final int COMPUTE_NOTHING = 0;
/**
* Indicates that the maximum stack size and the maximum number of local variables must be
* computed, from scratch.
*/
static final int COMPUTE_MAX_STACK_AND_LOCAL = 1;
/**
* Indicates that the maximum stack size and the maximum number of local variables must be
* computed, from the existing stack map frames. This can be done more efficiently than with the
* control flow graph algorithm used for {@link #COMPUTE_MAX_STACK_AND_LOCAL}, by using a linear
* scan of the bytecode instructions.
*/
static final int COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES = 2;
/**
* Indicates that the stack map frames of type F_INSERT must be computed. The other frames are not
* computed. They should all be of type F_NEW and should be sufficient to compute the content of
* the F_INSERT frames, together with the bytecode instructions between a F_NEW and a F_INSERT
* frame - and without any knowledge of the type hierarchy (by definition of F_INSERT).
*/
static final int COMPUTE_INSERTED_FRAMES = 3;
/**
* Indicates that all the stack map frames must be computed. In this case the maximum stack size
* and the maximum number of local variables is also computed.
*/
static final int COMPUTE_ALL_FRAMES = 4;
/** Indicates that {@link #STACK_SIZE_DELTA} is not applicable (not constant or never used). */
private static final int NA = 0;
/**
* The stack size variation corresponding to each JVM opcode. The stack size variation for opcode
* 'o' is given by the array element at index 'o'.
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-6.html">JVMS 6</a>
*/
private static final int[] STACK_SIZE_DELTA = {
0, // nop = 0 (0x0)
1, // aconst_null = 1 (0x1)
1, // iconst_m1 = 2 (0x2)
1, // iconst_0 = 3 (0x3)
1, // iconst_1 = 4 (0x4)
1, // iconst_2 = 5 (0x5)
1, // iconst_3 = 6 (0x6)
1, // iconst_4 = 7 (0x7)
1, // iconst_5 = 8 (0x8)
2, // lconst_0 = 9 (0x9)
2, // lconst_1 = 10 (0xa)
1, // fconst_0 = 11 (0xb)
1, // fconst_1 = 12 (0xc)
1, // fconst_2 = 13 (0xd)
2, // dconst_0 = 14 (0xe)
2, // dconst_1 = 15 (0xf)
1, // bipush = 16 (0x10)
1, // sipush = 17 (0x11)
1, // ldc = 18 (0x12)
NA, // ldc_w = 19 (0x13)
NA, // ldc2_w = 20 (0x14)
1, // iload = 21 (0x15)
2, // lload = 22 (0x16)
1, // fload = 23 (0x17)
2, // dload = 24 (0x18)
1, // aload = 25 (0x19)
NA, // iload_0 = 26 (0x1a)
NA, // iload_1 = 27 (0x1b)
NA, // iload_2 = 28 (0x1c)
NA, // iload_3 = 29 (0x1d)
NA, // lload_0 = 30 (0x1e)
NA, // lload_1 = 31 (0x1f)
NA, // lload_2 = 32 (0x20)
NA, // lload_3 = 33 (0x21)
NA, // fload_0 = 34 (0x22)
NA, // fload_1 = 35 (0x23)
NA, // fload_2 = 36 (0x24)
NA, // fload_3 = 37 (0x25)
NA, // dload_0 = 38 (0x26)
NA, // dload_1 = 39 (0x27)
NA, // dload_2 = 40 (0x28)
NA, // dload_3 = 41 (0x29)
NA, // aload_0 = 42 (0x2a)
NA, // aload_1 = 43 (0x2b)
NA, // aload_2 = 44 (0x2c)
NA, // aload_3 = 45 (0x2d)
-1, // iaload = 46 (0x2e)
0, // laload = 47 (0x2f)
-1, // faload = 48 (0x30)
0, // daload = 49 (0x31)
-1, // aaload = 50 (0x32)
-1, // baload = 51 (0x33)
-1, // caload = 52 (0x34)
-1, // saload = 53 (0x35)
-1, // istore = 54 (0x36)
-2, // lstore = 55 (0x37)
-1, // fstore = 56 (0x38)
-2, // dstore = 57 (0x39)
-1, // astore = 58 (0x3a)
NA, // istore_0 = 59 (0x3b)
NA, // istore_1 = 60 (0x3c)
NA, // istore_2 = 61 (0x3d)
NA, // istore_3 = 62 (0x3e)
NA, // lstore_0 = 63 (0x3f)
NA, // lstore_1 = 64 (0x40)
NA, // lstore_2 = 65 (0x41)
NA, // lstore_3 = 66 (0x42)
NA, // fstore_0 = 67 (0x43)
NA, // fstore_1 = 68 (0x44)
NA, // fstore_2 = 69 (0x45)
NA, // fstore_3 = 70 (0x46)
NA, // dstore_0 = 71 (0x47)
NA, // dstore_1 = 72 (0x48)
NA, // dstore_2 = 73 (0x49)
NA, // dstore_3 = 74 (0x4a)
NA, // astore_0 = 75 (0x4b)
NA, // astore_1 = 76 (0x4c)
NA, // astore_2 = 77 (0x4d)
NA, // astore_3 = 78 (0x4e)
-3, // iastore = 79 (0x4f)
-4, // lastore = 80 (0x50)
-3, // fastore = 81 (0x51)
-4, // dastore = 82 (0x52)
-3, // aastore = 83 (0x53)
-3, // bastore = 84 (0x54)
-3, // castore = 85 (0x55)
-3, // sastore = 86 (0x56)
-1, // pop = 87 (0x57)
-2, // pop2 = 88 (0x58)
1, // dup = 89 (0x59)
1, // dup_x1 = 90 (0x5a)
1, // dup_x2 = 91 (0x5b)
2, // dup2 = 92 (0x5c)
2, // dup2_x1 = 93 (0x5d)
2, // dup2_x2 = 94 (0x5e)
0, // swap = 95 (0x5f)
-1, // iadd = 96 (0x60)
-2, // ladd = 97 (0x61)
-1, // fadd = 98 (0x62)
-2, // dadd = 99 (0x63)
-1, // isub = 100 (0x64)
-2, // lsub = 101 (0x65)
-1, // fsub = 102 (0x66)
-2, // dsub = 103 (0x67)
-1, // imul = 104 (0x68)
-2, // lmul = 105 (0x69)
-1, // fmul = 106 (0x6a)
-2, // dmul = 107 (0x6b)
-1, // idiv = 108 (0x6c)
-2, // ldiv = 109 (0x6d)
-1, // fdiv = 110 (0x6e)
-2, // ddiv = 111 (0x6f)
-1, // irem = 112 (0x70)
-2, // lrem = 113 (0x71)
-1, // frem = 114 (0x72)
-2, // drem = 115 (0x73)
0, // ineg = 116 (0x74)
0, // lneg = 117 (0x75)
0, // fneg = 118 (0x76)
0, // dneg = 119 (0x77)
-1, // ishl = 120 (0x78)
-1, // lshl = 121 (0x79)
-1, // ishr = 122 (0x7a)
-1, // lshr = 123 (0x7b)
-1, // iushr = 124 (0x7c)
-1, // lushr = 125 (0x7d)
-1, // iand = 126 (0x7e)
-2, // land = 127 (0x7f)
-1, // ior = 128 (0x80)
-2, // lor = 129 (0x81)
-1, // ixor = 130 (0x82)
-2, // lxor = 131 (0x83)
0, // iinc = 132 (0x84)
1, // i2l = 133 (0x85)
0, // i2f = 134 (0x86)
1, // i2d = 135 (0x87)
-1, // l2i = 136 (0x88)
-1, // l2f = 137 (0x89)
0, // l2d = 138 (0x8a)
0, // f2i = 139 (0x8b)
1, // f2l = 140 (0x8c)
1, // f2d = 141 (0x8d)
-1, // d2i = 142 (0x8e)
0, // d2l = 143 (0x8f)
-1, // d2f = 144 (0x90)
0, // i2b = 145 (0x91)
0, // i2c = 146 (0x92)
0, // i2s = 147 (0x93)
-3, // lcmp = 148 (0x94)
-1, // fcmpl = 149 (0x95)
-1, // fcmpg = 150 (0x96)
-3, // dcmpl = 151 (0x97)
-3, // dcmpg = 152 (0x98)
-1, // ifeq = 153 (0x99)
-1, // ifne = 154 (0x9a)
-1, // iflt = 155 (0x9b)
-1, // ifge = 156 (0x9c)
-1, // ifgt = 157 (0x9d)
-1, // ifle = 158 (0x9e)
-2, // if_icmpeq = 159 (0x9f)
-2, // if_icmpne = 160 (0xa0)
-2, // if_icmplt = 161 (0xa1)
-2, // if_icmpge = 162 (0xa2)
-2, // if_icmpgt = 163 (0xa3)
-2, // if_icmple = 164 (0xa4)
-2, // if_acmpeq = 165 (0xa5)
-2, // if_acmpne = 166 (0xa6)
0, // goto = 167 (0xa7)
1, // jsr = 168 (0xa8)
0, // ret = 169 (0xa9)
-1, // tableswitch = 170 (0xaa)
-1, // lookupswitch = 171 (0xab)
-1, // ireturn = 172 (0xac)
-2, // lreturn = 173 (0xad)
-1, // freturn = 174 (0xae)
-2, // dreturn = 175 (0xaf)
-1, // areturn = 176 (0xb0)
0, // return = 177 (0xb1)
NA, // getstatic = 178 (0xb2)
NA, // putstatic = 179 (0xb3)
NA, // getfield = 180 (0xb4)
NA, // putfield = 181 (0xb5)
NA, // invokevirtual = 182 (0xb6)
NA, // invokespecial = 183 (0xb7)
NA, // invokestatic = 184 (0xb8)
NA, // invokeinterface = 185 (0xb9)
NA, // invokedynamic = 186 (0xba)
1, // new = 187 (0xbb)
0, // newarray = 188 (0xbc)
0, // anewarray = 189 (0xbd)
0, // arraylength = 190 (0xbe)
NA, // athrow = 191 (0xbf)
0, // checkcast = 192 (0xc0)
0, // instanceof = 193 (0xc1)
-1, // monitorenter = 194 (0xc2)
-1, // monitorexit = 195 (0xc3)
NA, // wide = 196 (0xc4)
NA, // multianewarray = 197 (0xc5)
-1, // ifnull = 198 (0xc6)
-1, // ifnonnull = 199 (0xc7)
NA, // goto_w = 200 (0xc8)
NA // jsr_w = 201 (0xc9)
};
/** Where the constants used in this MethodWriter must be stored. */
private final SymbolTable symbolTable;
// Note: fields are ordered as in the method_info structure, and those related to attributes are
// ordered as in Section 4.7 of the JVMS.
/**
* The access_flags field of the method_info JVMS structure. This field can contain ASM specific
* access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the
* ClassFile structure.
*/
private final int accessFlags;
/** The name_index field of the method_info JVMS structure. */
private final int nameIndex;
/** The name of this method. */
private final String name;
/** The descriptor_index field of the method_info JVMS structure. */
private final int descriptorIndex;
/** The descriptor of this method. */
private final String descriptor;
// Code attribute fields and sub attributes:
/** The max_stack field of the Code attribute. */
private int maxStack;
/** The max_locals field of the Code attribute. */
private int maxLocals;
/** The 'code' field of the Code attribute. */
private final ByteVector code = new ByteVector();
/**
* The first element in the exception handler list (used to generate the exception_table of the
* Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May
* be {@literal null}.
*/
private Handler firstHandler;
/**
* The last element in the exception handler list (used to generate the exception_table of the
* Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May
* be {@literal null}.
*/
private Handler lastHandler;
/** The line_number_table_length field of the LineNumberTable code attribute. */
private int lineNumberTableLength;
/** The line_number_table array of the LineNumberTable code attribute, or {@literal null}. */
private ByteVector lineNumberTable;
/** The local_variable_table_length field of the LocalVariableTable code attribute. */
private int localVariableTableLength;
/**
* The local_variable_table array of the LocalVariableTable code attribute, or {@literal null}.
*/
private ByteVector localVariableTable;
/** The local_variable_type_table_length field of the LocalVariableTypeTable code attribute. */
private int localVariableTypeTableLength;
/**
* The local_variable_type_table array of the LocalVariableTypeTable code attribute, or {@literal
* null}.
*/
private ByteVector localVariableTypeTable;
/** The number_of_entries field of the StackMapTable code attribute. */
private int stackMapTableNumberOfEntries;
/** The 'entries' array of the StackMapTable code attribute. */
private ByteVector stackMapTableEntries;
/**
* The last runtime visible type annotation of the Code attribute. The previous ones can be
* accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
*/
private AnnotationWriter lastCodeRuntimeVisibleTypeAnnotation;
/**
* The last runtime invisible type annotation of the Code attribute. The previous ones can be
* accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
*/
private AnnotationWriter lastCodeRuntimeInvisibleTypeAnnotation;
/**
* The first non standard attribute of the Code attribute. The next ones can be accessed with the
* {@link Attribute#nextAttribute} field. May be {@literal null}.
*
* <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit.
* firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link
* #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the
* reverse order specified by the user.
*/
private Attribute firstCodeAttribute;
// Other method_info attributes:
/** The number_of_exceptions field of the Exceptions attribute. */
private final int numberOfExceptions;
/** The exception_index_table array of the Exceptions attribute, or {@literal null}. */
private final int[] exceptionIndexTable;
/** The signature_index field of the Signature attribute. */
private final int signatureIndex;
/**
* The last runtime visible annotation of this method. The previous ones can be accessed with the
* {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
*/
private AnnotationWriter lastRuntimeVisibleAnnotation;
/**
* The last runtime invisible annotation of this method. The previous ones can be accessed with
* the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
*/
private AnnotationWriter lastRuntimeInvisibleAnnotation;
/** The number of method parameters that can have runtime visible annotations, or 0. */
private int visibleAnnotableParameterCount;
/**
* The runtime visible parameter annotations of this method. Each array element contains the last
* annotation of a parameter (which can be {@literal null} - the previous ones can be accessed
* with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.
*/
private AnnotationWriter[] lastRuntimeVisibleParameterAnnotations;
/** The number of method parameters that can have runtime visible annotations, or 0. */
private int invisibleAnnotableParameterCount;
/**
* The runtime invisible parameter annotations of this method. Each array element contains the
* last annotation of a parameter (which can be {@literal null} - the previous ones can be
* accessed with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.
*/
private AnnotationWriter[] lastRuntimeInvisibleParameterAnnotations;
/**
* The last runtime visible type annotation of this method. The previous ones can be accessed with
* the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
*/
private AnnotationWriter lastRuntimeVisibleTypeAnnotation;
/**
* The last runtime invisible type annotation of this method. The previous ones can be accessed
* with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
*/
private AnnotationWriter lastRuntimeInvisibleTypeAnnotation;
/** The default_value field of the AnnotationDefault attribute, or {@literal null}. */
private ByteVector defaultValue;
/** The parameters_count field of the MethodParameters attribute. */
private int parametersCount;
/** The 'parameters' array of the MethodParameters attribute, or {@literal null}. */
private ByteVector parameters;
/**
* The first non standard attribute of this method. The next ones can be accessed with the {@link
* Attribute#nextAttribute} field. May be {@literal null}.
*
* <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit.
* firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link
* #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the
* reverse order specified by the user.
*/
private Attribute firstAttribute;
// -----------------------------------------------------------------------------------------------
// Fields used to compute the maximum stack size and number of locals, and the stack map frames
// -----------------------------------------------------------------------------------------------
/**
* Indicates what must be computed. Must be one of {@link #COMPUTE_ALL_FRAMES}, {@link
* #COMPUTE_INSERTED_FRAMES}, {@link COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link
* #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}.
*/
private final int compute;
/**
* The first basic block of the method. The next ones (in bytecode offset order) can be accessed
* with the {@link Label#nextBasicBlock} field.
*/
private Label firstBasicBlock;
/**
* The last basic block of the method (in bytecode offset order). This field is updated each time
* a basic block is encountered, and is used to append it at the end of the basic block list.
*/
private Label lastBasicBlock;
/**
* The current basic block, i.e. the basic block of the last visited instruction. When {@link
* #compute} is equal to {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_ALL_FRAMES}, this
* field is {@literal null} for unreachable code. When {@link #compute} is equal to {@link
* #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES} or {@link #COMPUTE_INSERTED_FRAMES}, this field stays
* unchanged throughout the whole method (i.e. the whole code is seen as a single basic block;
* indeed, the existing frames are sufficient by hypothesis to compute any intermediate frame -
* and the maximum stack size as well - without using any control flow graph).
*/
private Label currentBasicBlock;
/**
* The relative stack size after the last visited instruction. This size is relative to the
* beginning of {@link #currentBasicBlock}, i.e. the true stack size after the last visited
* instruction is equal to the {@link Label#inputStackSize} of the current basic block plus {@link
* #relativeStackSize}. When {@link #compute} is equal to {@link
* #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of
* the method, so this relative size is also equal to the absolute stack size after the last
* visited instruction.
*/
private int relativeStackSize;
/**
* The maximum relative stack size after the last visited instruction. This size is relative to
* the beginning of {@link #currentBasicBlock}, i.e. the true maximum stack size after the last
* visited instruction is equal to the {@link Label#inputStackSize} of the current basic block
* plus {@link #maxRelativeStackSize}.When {@link #compute} is equal to {@link
* #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of
* the method, so this relative size is also equal to the absolute maximum stack size after the
* last visited instruction.
*/
private int maxRelativeStackSize;
/** The number of local variables in the last visited stack map frame. */
private int currentLocals;
/** The bytecode offset of the last frame that was written in {@link #stackMapTableEntries}. */
private int previousFrameOffset;
/**
* The last frame that was written in {@link #stackMapTableEntries}. This field has the same
* format as {@link #currentFrame}.
*/
private int[] previousFrame;
/**
* The current stack map frame. The first element contains the bytecode offset of the instruction
* to which the frame corresponds, the second element is the number of locals and the third one is
* the number of stack elements. The local variables start at index 3 and are followed by the
* operand stack elements. In summary frame[0] = offset, frame[1] = numLocal, frame[2] = numStack.
* Local variables and operand stack entries contain abstract types, as defined in {@link Frame},
* but restricted to {@link Frame#CONSTANT_KIND}, {@link Frame#REFERENCE_KIND}, {@link
* Frame#UNINITIALIZED_KIND} or {@link Frame#FORWARD_UNINITIALIZED_KIND} abstract types. Long and
* double types use only one array entry.
*/
private int[] currentFrame;
/** Whether this method contains subroutines. */
private boolean hasSubroutines;
// -----------------------------------------------------------------------------------------------
// Other miscellaneous status fields
// -----------------------------------------------------------------------------------------------
/** Whether the bytecode of this method contains ASM specific instructions. */
private boolean hasAsmInstructions;
/**
* The start offset of the last visited instruction. Used to set the offset field of type
* annotations of type 'offset_target' (see <a
* href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.1">JVMS
* 4.7.20.1</a>).
*/
private int lastBytecodeOffset;
/**
* The offset in bytes in {@link SymbolTable#getSource} from which the method_info for this method
* (excluding its first 6 bytes) must be copied, or 0.
*/
private int sourceOffset;
/**
* The length in bytes in {@link SymbolTable#getSource} which must be copied to get the
* method_info for this method (excluding its first 6 bytes for access_flags, name_index and
* descriptor_index).
*/
private int sourceLength;
// -----------------------------------------------------------------------------------------------
// Constructor and accessors
// -----------------------------------------------------------------------------------------------
/**
* Constructs a new {@link MethodWriter}.
*
* @param symbolTable where the constants used in this AnnotationWriter must be stored.
* @param access the method's access flags (see {@link Opcodes}).
* @param name the method's name.
* @param descriptor the method's descriptor (see {@link Type}).
* @param signature the method's signature. May be {@literal null}.
* @param exceptions the internal names of the method's exceptions. May be {@literal null}.
* @param compute indicates what must be computed (see #compute).
*/
MethodWriter(
final SymbolTable symbolTable,
final int access,
final String name,
final String descriptor,
final String signature,
final String[] exceptions,
final int compute) {
super(/* latest api = */ Opcodes.ASM9);
this.symbolTable = symbolTable;
this.accessFlags = "<init>".equals(name) ? access | Constants.ACC_CONSTRUCTOR : access;
this.nameIndex = symbolTable.addConstantUtf8(name);
this.name = name;
this.descriptorIndex = symbolTable.addConstantUtf8(descriptor);
this.descriptor = descriptor;
this.signatureIndex = signature == null ? 0 : symbolTable.addConstantUtf8(signature);
if (exceptions != null && exceptions.length > 0) {
numberOfExceptions = exceptions.length;
this.exceptionIndexTable = new int[numberOfExceptions];
for (int i = 0; i < numberOfExceptions; ++i) {
this.exceptionIndexTable[i] = symbolTable.addConstantClass(exceptions[i]).index;
}
} else {
numberOfExceptions = 0;
this.exceptionIndexTable = null;
}
this.compute = compute;
if (compute != COMPUTE_NOTHING) {
// Update maxLocals and currentLocals.
int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;
if ((access & Opcodes.ACC_STATIC) != 0) {
--argumentsSize;
}
maxLocals = argumentsSize;
currentLocals = argumentsSize;
// Create and visit the label for the first basic block.
firstBasicBlock = new Label();
visitLabel(firstBasicBlock);
}
}
boolean hasFrames() {
return stackMapTableNumberOfEntries > 0;
}
boolean hasAsmInstructions() {
return hasAsmInstructions;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the MethodVisitor abstract class
// -----------------------------------------------------------------------------------------------
@Override
public void visitParameter(final String name, final int access) {
if (parameters == null) {
parameters = new ByteVector();
}
++parametersCount;
parameters.putShort((name == null) ? 0 : symbolTable.addConstantUtf8(name)).putShort(access);
}
@Override
public AnnotationVisitor visitAnnotationDefault() {
defaultValue = new ByteVector();
return new AnnotationWriter(symbolTable, /* useNamedValues= */ false, defaultValue, null);
}
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
if (visible) {
return lastRuntimeVisibleAnnotation =
AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation);
} else {
return lastRuntimeInvisibleAnnotation =
AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation);
}
}
@Override
public AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (visible) {
return lastRuntimeVisibleTypeAnnotation =
AnnotationWriter.create(
symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation);
} else {
return lastRuntimeInvisibleTypeAnnotation =
AnnotationWriter.create(
symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation);
}
}
@Override
public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) {
if (visible) {
visibleAnnotableParameterCount = parameterCount;
} else {
invisibleAnnotableParameterCount = parameterCount;
}
}
@Override
public AnnotationVisitor visitParameterAnnotation(
final int parameter, final String annotationDescriptor, final boolean visible) {
if (visible) {
if (lastRuntimeVisibleParameterAnnotations == null) {
lastRuntimeVisibleParameterAnnotations =
new AnnotationWriter[Type.getArgumentCount(descriptor)];
}
return lastRuntimeVisibleParameterAnnotations[parameter] =
AnnotationWriter.create(
symbolTable, annotationDescriptor, lastRuntimeVisibleParameterAnnotations[parameter]);
} else {
if (lastRuntimeInvisibleParameterAnnotations == null) {
lastRuntimeInvisibleParameterAnnotations =
new AnnotationWriter[Type.getArgumentCount(descriptor)];
}
return lastRuntimeInvisibleParameterAnnotations[parameter] =
AnnotationWriter.create(
symbolTable,
annotationDescriptor,
lastRuntimeInvisibleParameterAnnotations[parameter]);
}
}
@Override
public void visitAttribute(final Attribute attribute) {
// Store the attributes in the <i>reverse</i> order of their visit by this method.
if (attribute.isCodeAttribute()) {
attribute.nextAttribute = firstCodeAttribute;
firstCodeAttribute = attribute;
} else {
attribute.nextAttribute = firstAttribute;
firstAttribute = attribute;
}
}
@Override
public void visitCode() {
// Nothing to do.
}
@Override
public void visitFrame(
final int type,
final int numLocal,
final Object[] local,
final int numStack,
final Object[] stack) {
if (compute == COMPUTE_ALL_FRAMES) {
return;
}
if (compute == COMPUTE_INSERTED_FRAMES) {
if (currentBasicBlock.frame == null) {
// This should happen only once, for the implicit first frame (which is explicitly visited
// in ClassReader if the EXPAND_ASM_INSNS option is used - and COMPUTE_INSERTED_FRAMES
// can't be set if EXPAND_ASM_INSNS is not used).
currentBasicBlock.frame = new CurrentFrame(currentBasicBlock);
currentBasicBlock.frame.setInputFrameFromDescriptor(
symbolTable, accessFlags, descriptor, numLocal);
currentBasicBlock.frame.accept(this);
} else {
if (type == Opcodes.F_NEW) {
currentBasicBlock.frame.setInputFrameFromApiFormat(
symbolTable, numLocal, local, numStack, stack);
}
// If type is not F_NEW then it is F_INSERT by hypothesis, and currentBlock.frame contains
// the stack map frame at the current instruction, computed from the last F_NEW frame and
// the bytecode instructions in between (via calls to CurrentFrame#execute).
currentBasicBlock.frame.accept(this);
}
} else if (type == Opcodes.F_NEW) {
if (previousFrame == null) {
int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;
Frame implicitFirstFrame = new Frame(new Label());
implicitFirstFrame.setInputFrameFromDescriptor(
symbolTable, accessFlags, descriptor, argumentsSize);
implicitFirstFrame.accept(this);
}
currentLocals = numLocal;
int frameIndex = visitFrameStart(code.length, numLocal, numStack);
for (int i = 0; i < numLocal; ++i) {
currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, local[i]);
}
for (int i = 0; i < numStack; ++i) {
currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, stack[i]);
}
visitFrameEnd();
} else {
if (symbolTable.getMajorVersion() < Opcodes.V1_6) {
throw new IllegalArgumentException("Class versions V1_5 or less must use F_NEW frames.");
}
int offsetDelta;
if (stackMapTableEntries == null) {
stackMapTableEntries = new ByteVector();
offsetDelta = code.length;
} else {
offsetDelta = code.length - previousFrameOffset - 1;
if (offsetDelta < 0) {
if (type == Opcodes.F_SAME) {
return;
} else {
throw new IllegalStateException();
}
}
}
switch (type) {
case Opcodes.F_FULL:
currentLocals = numLocal;
stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);
for (int i = 0; i < numLocal; ++i) {
putFrameType(local[i]);
}
stackMapTableEntries.putShort(numStack);
for (int i = 0; i < numStack; ++i) {
putFrameType(stack[i]);
}
break;
case Opcodes.F_APPEND:
currentLocals += numLocal;
stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocal).putShort(offsetDelta);
for (int i = 0; i < numLocal; ++i) {
putFrameType(local[i]);
}
break;
case Opcodes.F_CHOP:
currentLocals -= numLocal;
stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED - numLocal).putShort(offsetDelta);
break;
case Opcodes.F_SAME:
if (offsetDelta < 64) {
stackMapTableEntries.putByte(offsetDelta);
} else {
stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);
}
break;
case Opcodes.F_SAME1:
if (offsetDelta < 64) {
stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);
} else {
stackMapTableEntries
.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
.putShort(offsetDelta);
}
putFrameType(stack[0]);
break;
default:
throw new IllegalArgumentException();
}
previousFrameOffset = code.length;
++stackMapTableNumberOfEntries;
}
if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
relativeStackSize = numStack;
for (int i = 0; i < numStack; ++i) {
if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {
relativeStackSize++;
}
}
if (relativeStackSize > maxRelativeStackSize) {
maxRelativeStackSize = relativeStackSize;
}
}
maxStack = Math.max(maxStack, numStack);
maxLocals = Math.max(maxLocals, currentLocals);
}
@Override
public void visitInsn(final int opcode) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
code.putByte(opcode);
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, 0, null, null);
} else {
int size = relativeStackSize + STACK_SIZE_DELTA[opcode];
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {
endCurrentBasicBlockWithNoSuccessor();
}
}
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
if (opcode == Opcodes.SIPUSH) {
code.put12(opcode, operand);
} else { // BIPUSH or NEWARRAY
code.put11(opcode, operand);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, operand, null, null);
} else if (opcode != Opcodes.NEWARRAY) {
// The stack size delta is 1 for BIPUSH or SIPUSH, and 0 for NEWARRAY.
int size = relativeStackSize + 1;
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
@Override
public void visitVarInsn(final int opcode, final int varIndex) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
if (varIndex < 4 && opcode != Opcodes.RET) {
int optimizedOpcode;
if (opcode < Opcodes.ISTORE) {
optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + varIndex;
} else {
optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + varIndex;
}
code.putByte(optimizedOpcode);
} else if (varIndex >= 256) {
code.putByte(Constants.WIDE).put12(opcode, varIndex);
} else {
code.put11(opcode, varIndex);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, varIndex, null, null);
} else {
if (opcode == Opcodes.RET) {
// No stack size delta.
currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_END;
currentBasicBlock.outputStackSize = (short) relativeStackSize;
endCurrentBasicBlockWithNoSuccessor();
} else { // xLOAD or xSTORE
int size = relativeStackSize + STACK_SIZE_DELTA[opcode];
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
if (compute != COMPUTE_NOTHING) {
int currentMaxLocals;
if (opcode == Opcodes.LLOAD
|| opcode == Opcodes.DLOAD
|| opcode == Opcodes.LSTORE
|| opcode == Opcodes.DSTORE) {
currentMaxLocals = varIndex + 2;
} else {
currentMaxLocals = varIndex + 1;
}
if (currentMaxLocals > maxLocals) {
maxLocals = currentMaxLocals;
}
}
if (opcode >= Opcodes.ISTORE && compute == COMPUTE_ALL_FRAMES && firstHandler != null) {
// If there are exception handler blocks, each instruction within a handler range is, in
// theory, a basic block (since execution can jump from this instruction to the exception
// handler). As a consequence, the local variable types at the beginning of the handler
// block should be the merge of the local variable types at all the instructions within the
// handler range. However, instead of creating a basic block for each instruction, we can
// get the same result in a more efficient way. Namely, by starting a new basic block after
// each xSTORE instruction, which is what we do here.
visitLabel(new Label());
}
}
@Override
public void visitTypeInsn(final int opcode, final String type) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
Symbol typeSymbol = symbolTable.addConstantClass(type);
code.put12(opcode, typeSymbol.index);
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, lastBytecodeOffset, typeSymbol, symbolTable);
} else if (opcode == Opcodes.NEW) {
// The stack size delta is 1 for NEW, and 0 for ANEWARRAY, CHECKCAST, or INSTANCEOF.
int size = relativeStackSize + 1;
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
@Override
public void visitFieldInsn(
final int opcode, final String owner, final String name, final String descriptor) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
Symbol fieldrefSymbol = symbolTable.addConstantFieldref(owner, name, descriptor);
code.put12(opcode, fieldrefSymbol.index);
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, 0, fieldrefSymbol, symbolTable);
} else {
int size;
char firstDescChar = descriptor.charAt(0);
switch (opcode) {
case Opcodes.GETSTATIC:
size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 2 : 1);
break;
case Opcodes.PUTSTATIC:
size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -2 : -1);
break;
case Opcodes.GETFIELD:
size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 1 : 0);
break;
case Opcodes.PUTFIELD:
default:
size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -3 : -2);
break;
}
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
@Override
public void visitMethodInsn(
final int opcode,
final String owner,
final String name,
final String descriptor,
final boolean isInterface) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
Symbol methodrefSymbol = symbolTable.addConstantMethodref(owner, name, descriptor, isInterface);
if (opcode == Opcodes.INVOKEINTERFACE) {
code.put12(Opcodes.INVOKEINTERFACE, methodrefSymbol.index)
.put11(methodrefSymbol.getArgumentsAndReturnSizes() >> 2, 0);
} else {
code.put12(opcode, methodrefSymbol.index);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, 0, methodrefSymbol, symbolTable);
} else {
int argumentsAndReturnSize = methodrefSymbol.getArgumentsAndReturnSizes();
int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2);
int size;
if (opcode == Opcodes.INVOKESTATIC) {
size = relativeStackSize + stackSizeDelta + 1;
} else {
size = relativeStackSize + stackSizeDelta;
}
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
@Override
public void visitInvokeDynamicInsn(
final String name,
final String descriptor,
final Handle bootstrapMethodHandle,
final Object... bootstrapMethodArguments) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
Symbol invokeDynamicSymbol =
symbolTable.addConstantInvokeDynamic(
name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
code.put12(Opcodes.INVOKEDYNAMIC, invokeDynamicSymbol.index);
code.putShort(0);
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, invokeDynamicSymbol, symbolTable);
} else {
int argumentsAndReturnSize = invokeDynamicSymbol.getArgumentsAndReturnSizes();
int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2) + 1;
int size = relativeStackSize + stackSizeDelta;
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
// Compute the 'base' opcode, i.e. GOTO or JSR if opcode is GOTO_W or JSR_W, otherwise opcode.
int baseOpcode =
opcode >= Constants.GOTO_W ? opcode - Constants.WIDE_JUMP_OPCODE_DELTA : opcode;
boolean nextInsnIsJumpTarget = false;
if ((label.flags & Label.FLAG_RESOLVED) != 0
&& label.bytecodeOffset - code.length < Short.MIN_VALUE) {
// Case of a backward jump with an offset < -32768. In this case we automatically replace GOTO
// with GOTO_W, JSR with JSR_W and IFxxx <l> with IFNOTxxx <L> GOTO_W <l> L:..., where
// IFNOTxxx is the "opposite" opcode of IFxxx (e.g. IFNE for IFEQ) and where <L> designates
// the instruction just after the GOTO_W.
if (baseOpcode == Opcodes.GOTO) {
code.putByte(Constants.GOTO_W);
} else if (baseOpcode == Opcodes.JSR) {
code.putByte(Constants.JSR_W);
} else {
// Put the "opposite" opcode of baseOpcode. This can be done by flipping the least
// significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ (with a
// pre and post offset by 1). The jump offset is 8 bytes (3 for IFNOTxxx, 5 for GOTO_W).
code.putByte(baseOpcode >= Opcodes.IFNULL ? baseOpcode ^ 1 : ((baseOpcode + 1) ^ 1) - 1);
code.putShort(8);
// Here we could put a GOTO_W in theory, but if ASM specific instructions are used in this
// method or another one, and if the class has frames, we will need to insert a frame after
// this GOTO_W during the additional ClassReader -> ClassWriter round trip to remove the ASM
// specific instructions. To not miss this additional frame, we need to use an ASM_GOTO_W
// here, which has the unfortunate effect of forcing this additional round trip (which in
// some case would not have been really necessary, but we can't know this at this point).
code.putByte(Constants.ASM_GOTO_W);
hasAsmInstructions = true;
// The instruction after the GOTO_W becomes the target of the IFNOT instruction.
nextInsnIsJumpTarget = true;
}
label.put(code, code.length - 1, true);
} else if (baseOpcode != opcode) {
// Case of a GOTO_W or JSR_W specified by the user (normally ClassReader when used to remove
// ASM specific instructions). In this case we keep the original instruction.
code.putByte(opcode);
label.put(code, code.length - 1, true);
} else {
// Case of a jump with an offset >= -32768, or of a jump with an unknown offset. In these
// cases we store the offset in 2 bytes (which will be increased via a ClassReader ->
// ClassWriter round trip if it turns out that 2 bytes are not sufficient).
code.putByte(baseOpcode);
label.put(code, code.length - 1, false);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
Label nextBasicBlock = null;
if (compute == COMPUTE_ALL_FRAMES) {
currentBasicBlock.frame.execute(baseOpcode, 0, null, null);
// Record the fact that 'label' is the target of a jump instruction.
label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
// Add 'label' as a successor of the current basic block.
addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
if (baseOpcode != Opcodes.GOTO) {
// The next instruction starts a new basic block (except for GOTO: by default the code
// following a goto is unreachable - unless there is an explicit label for it - and we
// should not compute stack frame types for its instructions).
nextBasicBlock = new Label();
}
} else if (compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(baseOpcode, 0, null, null);
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
// No need to update maxRelativeStackSize (the stack size delta is always negative).
relativeStackSize += STACK_SIZE_DELTA[baseOpcode];
} else {
if (baseOpcode == Opcodes.JSR) {
// Record the fact that 'label' designates a subroutine, if not already done.
if ((label.flags & Label.FLAG_SUBROUTINE_START) == 0) {
label.flags |= Label.FLAG_SUBROUTINE_START;
hasSubroutines = true;
}
currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_CALLER;
// Note that, by construction in this method, a block which calls a subroutine has at
// least two successors in the control flow graph: the first one (added below) leads to
// the instruction after the JSR, while the second one (added here) leads to the JSR
// target. Note that the first successor is virtual (it does not correspond to a possible
// execution path): it is only used to compute the successors of the basic blocks ending
// with a ret, in {@link Label#addSubroutineRetSuccessors}.
addSuccessorToCurrentBasicBlock(relativeStackSize + 1, label);
// The instruction after the JSR starts a new basic block.
nextBasicBlock = new Label();
} else {
// No need to update maxRelativeStackSize (the stack size delta is always negative).
relativeStackSize += STACK_SIZE_DELTA[baseOpcode];
addSuccessorToCurrentBasicBlock(relativeStackSize, label);
}
}
// If the next instruction starts a new basic block, call visitLabel to add the label of this
// instruction as a successor of the current block, and to start a new basic block.
if (nextBasicBlock != null) {
if (nextInsnIsJumpTarget) {
nextBasicBlock.flags |= Label.FLAG_JUMP_TARGET;
}
visitLabel(nextBasicBlock);
}
if (baseOpcode == Opcodes.GOTO) {
endCurrentBasicBlockWithNoSuccessor();
}
}
}
@Override
public void visitLabel(final Label label) {
// Resolve the forward references to this label, if any.
hasAsmInstructions |= label.resolve(code.data, stackMapTableEntries, code.length);
// visitLabel starts a new basic block (except for debug only labels), so we need to update the
// previous and current block references and list of successors.
if ((label.flags & Label.FLAG_DEBUG_ONLY) != 0) {
return;
}
if (compute == COMPUTE_ALL_FRAMES) {
if (currentBasicBlock != null) {
if (label.bytecodeOffset == currentBasicBlock.bytecodeOffset) {
// We use {@link Label#getCanonicalInstance} to store the state of a basic block in only
// one place, but this does not work for labels which have not been visited yet.
// Therefore, when we detect here two labels having the same bytecode offset, we need to
// - consolidate the state scattered in these two instances into the canonical instance:
currentBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);
// - make sure the two instances share the same Frame instance (the implementation of
// {@link Label#getCanonicalInstance} relies on this property; here label.frame should be
// null):
label.frame = currentBasicBlock.frame;
// - and make sure to NOT assign 'label' into 'currentBasicBlock' or 'lastBasicBlock', so
// that they still refer to the canonical instance for this bytecode offset.
return;
}
// End the current basic block (with one new successor).
addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
}
// Append 'label' at the end of the basic block list.
if (lastBasicBlock != null) {
if (label.bytecodeOffset == lastBasicBlock.bytecodeOffset) {
// Same comment as above.
lastBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);
// Here label.frame should be null.
label.frame = lastBasicBlock.frame;
currentBasicBlock = lastBasicBlock;
return;
}
lastBasicBlock.nextBasicBlock = label;
}
lastBasicBlock = label;
// Make it the new current basic block.
currentBasicBlock = label;
// Here label.frame should be null.
label.frame = new Frame(label);
} else if (compute == COMPUTE_INSERTED_FRAMES) {
if (currentBasicBlock == null) {
// This case should happen only once, for the visitLabel call in the constructor. Indeed, if
// compute is equal to COMPUTE_INSERTED_FRAMES, currentBasicBlock stays unchanged.
currentBasicBlock = label;
} else {
// Update the frame owner so that a correct frame offset is computed in Frame.accept().
currentBasicBlock.frame.owner = label;
}
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
if (currentBasicBlock != null) {
// End the current basic block (with one new successor).
currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;
addSuccessorToCurrentBasicBlock(relativeStackSize, label);
}
// Start a new current basic block, and reset the current and maximum relative stack sizes.
currentBasicBlock = label;
relativeStackSize = 0;
maxRelativeStackSize = 0;
// Append the new basic block at the end of the basic block list.
if (lastBasicBlock != null) {
lastBasicBlock.nextBasicBlock = label;
}
lastBasicBlock = label;
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES && currentBasicBlock == null) {
// This case should happen only once, for the visitLabel call in the constructor. Indeed, if
// compute is equal to COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES, currentBasicBlock stays
// unchanged.
currentBasicBlock = label;
}
}
@Override
public void visitLdcInsn(final Object value) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
Symbol constantSymbol = symbolTable.addConstant(value);
int constantIndex = constantSymbol.index;
char firstDescriptorChar;
boolean isLongOrDouble =
constantSymbol.tag == Symbol.CONSTANT_LONG_TAG
|| constantSymbol.tag == Symbol.CONSTANT_DOUBLE_TAG
|| (constantSymbol.tag == Symbol.CONSTANT_DYNAMIC_TAG
&& ((firstDescriptorChar = constantSymbol.value.charAt(0)) == 'J'
|| firstDescriptorChar == 'D'));
if (isLongOrDouble) {
code.put12(Constants.LDC2_W, constantIndex);
} else if (constantIndex >= 256) {
code.put12(Constants.LDC_W, constantIndex);
} else {
code.put11(Opcodes.LDC, constantIndex);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);
} else {
int size = relativeStackSize + (isLongOrDouble ? 2 : 1);
if (size > maxRelativeStackSize) {
maxRelativeStackSize = size;
}
relativeStackSize = size;
}
}
}
@Override
public void visitIincInsn(final int varIndex, final int increment) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
if ((varIndex > 255) || (increment > 127) || (increment < -128)) {
code.putByte(Constants.WIDE).put12(Opcodes.IINC, varIndex).putShort(increment);
} else {
code.putByte(Opcodes.IINC).put11(varIndex, increment);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null
&& (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES)) {
currentBasicBlock.frame.execute(Opcodes.IINC, varIndex, null, null);
}
if (compute != COMPUTE_NOTHING) {
int currentMaxLocals = varIndex + 1;
if (currentMaxLocals > maxLocals) {
maxLocals = currentMaxLocals;
}
}
}
@Override
public void visitTableSwitchInsn(
final int min, final int max, final Label dflt, final Label... labels) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
code.putByte(Opcodes.TABLESWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);
dflt.put(code, lastBytecodeOffset, true);
code.putInt(min).putInt(max);
for (Label label : labels) {
label.put(code, lastBytecodeOffset, true);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
visitSwitchInsn(dflt, labels);
}
@Override
public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
code.putByte(Opcodes.LOOKUPSWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);
dflt.put(code, lastBytecodeOffset, true);
code.putInt(labels.length);
for (int i = 0; i < labels.length; ++i) {
code.putInt(keys[i]);
labels[i].put(code, lastBytecodeOffset, true);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
visitSwitchInsn(dflt, labels);
}
private void visitSwitchInsn(final Label dflt, final Label[] labels) {
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES) {
currentBasicBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null);
// Add all the labels as successors of the current basic block.
addSuccessorToCurrentBasicBlock(Edge.JUMP, dflt);
dflt.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
for (Label label : labels) {
addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
}
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
// No need to update maxRelativeStackSize (the stack size delta is always negative).
--relativeStackSize;
// Add all the labels as successors of the current basic block.
addSuccessorToCurrentBasicBlock(relativeStackSize, dflt);
for (Label label : labels) {
addSuccessorToCurrentBasicBlock(relativeStackSize, label);
}
}
// End the current basic block.
endCurrentBasicBlockWithNoSuccessor();
}
}
@Override
public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
Symbol descSymbol = symbolTable.addConstantClass(descriptor);
code.put12(Opcodes.MULTIANEWARRAY, descSymbol.index).putByte(numDimensions);
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(
Opcodes.MULTIANEWARRAY, numDimensions, descSymbol, symbolTable);
} else {
// No need to update maxRelativeStackSize (the stack size delta is always negative).
relativeStackSize += 1 - numDimensions;
}
}
}
@Override
public AnnotationVisitor visitInsnAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (visible) {
return lastCodeRuntimeVisibleTypeAnnotation =
AnnotationWriter.create(
symbolTable,
(typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8),
typePath,
descriptor,
lastCodeRuntimeVisibleTypeAnnotation);
} else {
return lastCodeRuntimeInvisibleTypeAnnotation =
AnnotationWriter.create(
symbolTable,
(typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8),
typePath,
descriptor,
lastCodeRuntimeInvisibleTypeAnnotation);
}
}
@Override
public void visitTryCatchBlock(
final Label start, final Label end, final Label handler, final String type) {
Handler newHandler =
new Handler(
start, end, handler, type != null ? symbolTable.addConstantClass(type).index : 0, type);
if (firstHandler == null) {
firstHandler = newHandler;
} else {
lastHandler.nextHandler = newHandler;
}
lastHandler = newHandler;
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (visible) {
return lastCodeRuntimeVisibleTypeAnnotation =
AnnotationWriter.create(
symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeVisibleTypeAnnotation);
} else {
return lastCodeRuntimeInvisibleTypeAnnotation =
AnnotationWriter.create(
symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeInvisibleTypeAnnotation);
}
}
@Override
public void visitLocalVariable(
final String name,
final String descriptor,
final String signature,
final Label start,
final Label end,
final int index) {
if (signature != null) {
if (localVariableTypeTable == null) {
localVariableTypeTable = new ByteVector();
}
++localVariableTypeTableLength;
localVariableTypeTable
.putShort(start.bytecodeOffset)
.putShort(end.bytecodeOffset - start.bytecodeOffset)
.putShort(symbolTable.addConstantUtf8(name))
.putShort(symbolTable.addConstantUtf8(signature))
.putShort(index);
}
if (localVariableTable == null) {
localVariableTable = new ByteVector();
}
++localVariableTableLength;
localVariableTable
.putShort(start.bytecodeOffset)
.putShort(end.bytecodeOffset - start.bytecodeOffset)
.putShort(symbolTable.addConstantUtf8(name))
.putShort(symbolTable.addConstantUtf8(descriptor))
.putShort(index);
if (compute != COMPUTE_NOTHING) {
char firstDescChar = descriptor.charAt(0);
int currentMaxLocals = index + (firstDescChar == 'J' || firstDescChar == 'D' ? 2 : 1);
if (currentMaxLocals > maxLocals) {
maxLocals = currentMaxLocals;
}
}
}
@Override
public AnnotationVisitor visitLocalVariableAnnotation(
final int typeRef,
final TypePath typePath,
final Label[] start,
final Label[] end,
final int[] index,
final String descriptor,
final boolean visible) {
// Create a ByteVector to hold a 'type_annotation' JVMS structure.
// See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.
ByteVector typeAnnotation = new ByteVector();
// Write target_type, target_info, and target_path.
typeAnnotation.putByte(typeRef >>> 24).putShort(start.length);
for (int i = 0; i < start.length; ++i) {
typeAnnotation
.putShort(start[i].bytecodeOffset)
.putShort(end[i].bytecodeOffset - start[i].bytecodeOffset)
.putShort(index[i]);
}
TypePath.put(typePath, typeAnnotation);
// Write type_index and reserve space for num_element_value_pairs.
typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0);
if (visible) {
return lastCodeRuntimeVisibleTypeAnnotation =
new AnnotationWriter(
symbolTable,
/* useNamedValues= */ true,
typeAnnotation,
lastCodeRuntimeVisibleTypeAnnotation);
} else {
return lastCodeRuntimeInvisibleTypeAnnotation =
new AnnotationWriter(
symbolTable,
/* useNamedValues= */ true,
typeAnnotation,
lastCodeRuntimeInvisibleTypeAnnotation);
}
}
@Override
public void visitLineNumber(final int line, final Label start) {
if (lineNumberTable == null) {
lineNumberTable = new ByteVector();
}
++lineNumberTableLength;
lineNumberTable.putShort(start.bytecodeOffset);
lineNumberTable.putShort(line);
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
if (compute == COMPUTE_ALL_FRAMES) {
computeAllFrames();
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
computeMaxStackAndLocal();
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
this.maxStack = maxRelativeStackSize;
} else {
this.maxStack = maxStack;
this.maxLocals = maxLocals;
}
}
/** Computes all the stack map frames of the method, from scratch. */
private void computeAllFrames() {
// Complete the control flow graph with exception handler blocks.
Handler handler = firstHandler;
while (handler != null) {
String catchTypeDescriptor =
handler.catchTypeDescriptor == null ? "java/lang/Throwable" : handler.catchTypeDescriptor;
int catchType = Frame.getAbstractTypeFromInternalName(symbolTable, catchTypeDescriptor);
// Mark handlerBlock as an exception handler.
Label handlerBlock = handler.handlerPc.getCanonicalInstance();
handlerBlock.flags |= Label.FLAG_JUMP_TARGET;
// Add handlerBlock as a successor of all the basic blocks in the exception handler range.
Label handlerRangeBlock = handler.startPc.getCanonicalInstance();
Label handlerRangeEnd = handler.endPc.getCanonicalInstance();
while (handlerRangeBlock != handlerRangeEnd) {
handlerRangeBlock.outgoingEdges =
new Edge(catchType, handlerBlock, handlerRangeBlock.outgoingEdges);
handlerRangeBlock = handlerRangeBlock.nextBasicBlock;
}
handler = handler.nextHandler;
}
// Create and visit the first (implicit) frame.
Frame firstFrame = firstBasicBlock.frame;
firstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, this.maxLocals);
firstFrame.accept(this);
// Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks
// whose stack map frame has changed) and, while there are blocks to process, remove one from
// the list and update the stack map frames of its successor blocks in the control flow graph
// (which might change them, in which case these blocks must be processed too, and are thus
// added to the list of blocks to process). Also compute the maximum stack size of the method,
// as a by-product.
Label listOfBlocksToProcess = firstBasicBlock;
listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;
int maxStackSize = 0;
while (listOfBlocksToProcess != Label.EMPTY_LIST) {
// Remove a basic block from the list of blocks to process.
Label basicBlock = listOfBlocksToProcess;
listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;
basicBlock.nextListElement = null;
// By definition, basicBlock is reachable.
basicBlock.flags |= Label.FLAG_REACHABLE;
// Update the (absolute) maximum stack size.
int maxBlockStackSize = basicBlock.frame.getInputStackSize() + basicBlock.outputStackMax;
if (maxBlockStackSize > maxStackSize) {
maxStackSize = maxBlockStackSize;
}
// Update the successor blocks of basicBlock in the control flow graph.
Edge outgoingEdge = basicBlock.outgoingEdges;
while (outgoingEdge != null) {
Label successorBlock = outgoingEdge.successor.getCanonicalInstance();
boolean successorBlockChanged =
basicBlock.frame.merge(symbolTable, successorBlock.frame, outgoingEdge.info);
if (successorBlockChanged && successorBlock.nextListElement == null) {
// If successorBlock has changed it must be processed. Thus, if it is not already in the
// list of blocks to process, add it to this list.
successorBlock.nextListElement = listOfBlocksToProcess;
listOfBlocksToProcess = successorBlock;
}
outgoingEdge = outgoingEdge.nextEdge;
}
}
// Loop over all the basic blocks and visit the stack map frames that must be stored in the
// StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from
// exception handler ranges.
Label basicBlock = firstBasicBlock;
while (basicBlock != null) {
if ((basicBlock.flags & (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE))
== (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) {
basicBlock.frame.accept(this);
}
if ((basicBlock.flags & Label.FLAG_REACHABLE) == 0) {
// Find the start and end bytecode offsets of this unreachable block.
Label nextBasicBlock = basicBlock.nextBasicBlock;
int startOffset = basicBlock.bytecodeOffset;
int endOffset = (nextBasicBlock == null ? code.length : nextBasicBlock.bytecodeOffset) - 1;
if (endOffset >= startOffset) {
// Replace its instructions with NOP ... NOP ATHROW.
for (int i = startOffset; i < endOffset; ++i) {
code.data[i] = Opcodes.NOP;
}
code.data[endOffset] = (byte) Opcodes.ATHROW;
// Emit a frame for this unreachable block, with no local and a Throwable on the stack
// (so that the ATHROW could consume this Throwable if it were reachable).
int frameIndex = visitFrameStart(startOffset, /* numLocal = */ 0, /* numStack = */ 1);
currentFrame[frameIndex] =
Frame.getAbstractTypeFromInternalName(symbolTable, "java/lang/Throwable");
visitFrameEnd();
// Remove this unreachable basic block from the exception handler ranges.
firstHandler = Handler.removeRange(firstHandler, basicBlock, nextBasicBlock);
// The maximum stack size is now at least one, because of the Throwable declared above.
maxStackSize = Math.max(maxStackSize, 1);
}
}
basicBlock = basicBlock.nextBasicBlock;
}
this.maxStack = maxStackSize;
}
/** Computes the maximum stack size of the method. */
private void computeMaxStackAndLocal() {
// Complete the control flow graph with exception handler blocks.
Handler handler = firstHandler;
while (handler != null) {
Label handlerBlock = handler.handlerPc;
Label handlerRangeBlock = handler.startPc;
Label handlerRangeEnd = handler.endPc;
// Add handlerBlock as a successor of all the basic blocks in the exception handler range.
while (handlerRangeBlock != handlerRangeEnd) {
if ((handlerRangeBlock.flags & Label.FLAG_SUBROUTINE_CALLER) == 0) {
handlerRangeBlock.outgoingEdges =
new Edge(Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges);
} else {
// If handlerRangeBlock is a JSR block, add handlerBlock after the first two outgoing
// edges to preserve the hypothesis about JSR block successors order (see
// {@link #visitJumpInsn}).
handlerRangeBlock.outgoingEdges.nextEdge.nextEdge =
new Edge(
Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges.nextEdge.nextEdge);
}
handlerRangeBlock = handlerRangeBlock.nextBasicBlock;
}
handler = handler.nextHandler;
}
// Complete the control flow graph with the successor blocks of subroutines, if needed.
if (hasSubroutines) {
// First step: find the subroutines. This step determines, for each basic block, to which
// subroutine(s) it belongs. Start with the main "subroutine":
short numSubroutines = 1;
firstBasicBlock.markSubroutine(numSubroutines);
// Then, mark the subroutines called by the main subroutine, then the subroutines called by
// those called by the main subroutine, etc.
for (short currentSubroutine = 1; currentSubroutine <= numSubroutines; ++currentSubroutine) {
Label basicBlock = firstBasicBlock;
while (basicBlock != null) {
if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0
&& basicBlock.subroutineId == currentSubroutine) {
Label jsrTarget = basicBlock.outgoingEdges.nextEdge.successor;
if (jsrTarget.subroutineId == 0) {
// If this subroutine has not been marked yet, find its basic blocks.
jsrTarget.markSubroutine(++numSubroutines);
}
}
basicBlock = basicBlock.nextBasicBlock;
}
}
// Second step: find the successors in the control flow graph of each subroutine basic block
// 'r' ending with a RET instruction. These successors are the virtual successors of the basic
// blocks ending with JSR instructions (see {@link #visitJumpInsn)} that can reach 'r'.
Label basicBlock = firstBasicBlock;
while (basicBlock != null) {
if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {
// By construction, jsr targets are stored in the second outgoing edge of basic blocks
// that ends with a jsr instruction (see {@link #FLAG_SUBROUTINE_CALLER}).
Label subroutine = basicBlock.outgoingEdges.nextEdge.successor;
subroutine.addSubroutineRetSuccessors(basicBlock);
}
basicBlock = basicBlock.nextBasicBlock;
}
}
// Data flow algorithm: put the first basic block in a list of blocks to process (i.e. blocks
// whose input stack size has changed) and, while there are blocks to process, remove one
// from the list, update the input stack size of its successor blocks in the control flow
// graph, and add these blocks to the list of blocks to process (if not already done).
Label listOfBlocksToProcess = firstBasicBlock;
listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;
int maxStackSize = maxStack;
while (listOfBlocksToProcess != Label.EMPTY_LIST) {
// Remove a basic block from the list of blocks to process. Note that we don't reset
// basicBlock.nextListElement to null on purpose, to make sure we don't reprocess already
// processed basic blocks.
Label basicBlock = listOfBlocksToProcess;
listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;
// Compute the (absolute) input stack size and maximum stack size of this block.
int inputStackTop = basicBlock.inputStackSize;
int maxBlockStackSize = inputStackTop + basicBlock.outputStackMax;
// Update the absolute maximum stack size of the method.
if (maxBlockStackSize > maxStackSize) {
maxStackSize = maxBlockStackSize;
}
// Update the input stack size of the successor blocks of basicBlock in the control flow
// graph, and add these blocks to the list of blocks to process, if not already done.
Edge outgoingEdge = basicBlock.outgoingEdges;
if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {
// Ignore the first outgoing edge of the basic blocks ending with a jsr: these are virtual
// edges which lead to the instruction just after the jsr, and do not correspond to a
// possible execution path (see {@link #visitJumpInsn} and
// {@link Label#FLAG_SUBROUTINE_CALLER}).
outgoingEdge = outgoingEdge.nextEdge;
}
while (outgoingEdge != null) {
Label successorBlock = outgoingEdge.successor;
if (successorBlock.nextListElement == null) {
successorBlock.inputStackSize =
(short) (outgoingEdge.info == Edge.EXCEPTION ? 1 : inputStackTop + outgoingEdge.info);
successorBlock.nextListElement = listOfBlocksToProcess;
listOfBlocksToProcess = successorBlock;
}
outgoingEdge = outgoingEdge.nextEdge;
}
}
this.maxStack = maxStackSize;
}
@Override
public void visitEnd() {
// Nothing to do.
}
// -----------------------------------------------------------------------------------------------
// Utility methods: control flow analysis algorithm
// -----------------------------------------------------------------------------------------------
/**
* Adds a successor to {@link #currentBasicBlock} in the control flow graph.
*
* @param info information about the control flow edge to be added.
* @param successor the successor block to be added to the current basic block.
*/
private void addSuccessorToCurrentBasicBlock(final int info, final Label successor) {
currentBasicBlock.outgoingEdges = new Edge(info, successor, currentBasicBlock.outgoingEdges);
}
/**
* Ends the current basic block. This method must be used in the case where the current basic
* block does not have any successor.
*
* <p>WARNING: this method must be called after the currently visited instruction has been put in
* {@link #code} (if frames are computed, this method inserts a new Label to start a new basic
* block after the current instruction).
*/
private void endCurrentBasicBlockWithNoSuccessor() {
if (compute == COMPUTE_ALL_FRAMES) {
Label nextBasicBlock = new Label();
nextBasicBlock.frame = new Frame(nextBasicBlock);
nextBasicBlock.resolve(code.data, stackMapTableEntries, code.length);
lastBasicBlock.nextBasicBlock = nextBasicBlock;
lastBasicBlock = nextBasicBlock;
currentBasicBlock = null;
} else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;
currentBasicBlock = null;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods: stack map frames
// -----------------------------------------------------------------------------------------------
/**
* Starts the visit of a new stack map frame, stored in {@link #currentFrame}.
*
* @param offset the bytecode offset of the instruction to which the frame corresponds.
* @param numLocal the number of local variables in the frame.
* @param numStack the number of stack elements in the frame.
* @return the index of the next element to be written in this frame.
*/
int visitFrameStart(final int offset, final int numLocal, final int numStack) {
int frameLength = 3 + numLocal + numStack;
if (currentFrame == null || currentFrame.length < frameLength) {
currentFrame = new int[frameLength];
}
currentFrame[0] = offset;
currentFrame[1] = numLocal;
currentFrame[2] = numStack;
return 3;
}
/**
* Sets an abstract type in {@link #currentFrame}.
*
* @param frameIndex the index of the element to be set in {@link #currentFrame}.
* @param abstractType an abstract type.
*/
void visitAbstractType(final int frameIndex, final int abstractType) {
currentFrame[frameIndex] = abstractType;
}
/**
* Ends the visit of {@link #currentFrame} by writing it in the StackMapTable entries and by
* updating the StackMapTable number_of_entries (except if the current frame is the first one,
* which is implicit in StackMapTable). Then resets {@link #currentFrame} to {@literal null}.
*/
void visitFrameEnd() {
if (previousFrame != null) {
if (stackMapTableEntries == null) {
stackMapTableEntries = new ByteVector();
}
putFrame();
++stackMapTableNumberOfEntries;
}
previousFrame = currentFrame;
currentFrame = null;
}
/** Compresses and writes {@link #currentFrame} in a new StackMapTable entry. */
private void putFrame() {
final int numLocal = currentFrame[1];
final int numStack = currentFrame[2];
if (symbolTable.getMajorVersion() < Opcodes.V1_6) {
// Generate a StackMap attribute entry, which are always uncompressed.
stackMapTableEntries.putShort(currentFrame[0]).putShort(numLocal);
putAbstractTypes(3, 3 + numLocal);
stackMapTableEntries.putShort(numStack);
putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);
return;
}
final int offsetDelta =
stackMapTableNumberOfEntries == 0
? currentFrame[0]
: currentFrame[0] - previousFrame[0] - 1;
final int previousNumlocal = previousFrame[1];
final int numLocalDelta = numLocal - previousNumlocal;
int type = Frame.FULL_FRAME;
if (numStack == 0) {
switch (numLocalDelta) {
case -3:
case -2:
case -1:
type = Frame.CHOP_FRAME;
break;
case 0:
type = offsetDelta < 64 ? Frame.SAME_FRAME : Frame.SAME_FRAME_EXTENDED;
break;
case 1:
case 2:
case 3:
type = Frame.APPEND_FRAME;
break;
default:
// Keep the FULL_FRAME type.
break;
}
} else if (numLocalDelta == 0 && numStack == 1) {
type =
offsetDelta < 63
? Frame.SAME_LOCALS_1_STACK_ITEM_FRAME
: Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;
}
if (type != Frame.FULL_FRAME) {
// Verify if locals are the same as in the previous frame.
int frameIndex = 3;
for (int i = 0; i < previousNumlocal && i < numLocal; i++) {
if (currentFrame[frameIndex] != previousFrame[frameIndex]) {
type = Frame.FULL_FRAME;
break;
}
frameIndex++;
}
}
switch (type) {
case Frame.SAME_FRAME:
stackMapTableEntries.putByte(offsetDelta);
break;
case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME:
stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);
putAbstractTypes(3 + numLocal, 4 + numLocal);
break;
case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED:
stackMapTableEntries
.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
.putShort(offsetDelta);
putAbstractTypes(3 + numLocal, 4 + numLocal);
break;
case Frame.SAME_FRAME_EXTENDED:
stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);
break;
case Frame.CHOP_FRAME:
stackMapTableEntries
.putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)
.putShort(offsetDelta);
break;
case Frame.APPEND_FRAME:
stackMapTableEntries
.putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)
.putShort(offsetDelta);
putAbstractTypes(3 + previousNumlocal, 3 + numLocal);
break;
case Frame.FULL_FRAME:
default:
stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);
putAbstractTypes(3, 3 + numLocal);
stackMapTableEntries.putShort(numStack);
putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);
break;
}
}
/**
* Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using the
* JVMS verification_type_info format used in StackMapTable attributes.
*
* @param start index of the first type in {@link #currentFrame} to write.
* @param end index of last type in {@link #currentFrame} to write (exclusive).
*/
private void putAbstractTypes(final int start, final int end) {
for (int i = start; i < end; ++i) {
Frame.putAbstractType(symbolTable, currentFrame[i], stackMapTableEntries);
}
}
/**
* Puts the given public API frame element type in {@link #stackMapTableEntries} , using the JVMS
* verification_type_info format used in StackMapTable attributes.
*
* @param type a frame element type described using the same format as in {@link
* MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link
* Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or
* {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating
* a NEW instruction (for uninitialized types).
*/
private void putFrameType(final Object type) {
if (type instanceof Integer) {
stackMapTableEntries.putByte(((Integer) type).intValue());
} else if (type instanceof String) {
stackMapTableEntries
.putByte(Frame.ITEM_OBJECT)
.putShort(symbolTable.addConstantClass((String) type).index);
} else {
stackMapTableEntries.putByte(Frame.ITEM_UNINITIALIZED);
((Label) type).put(stackMapTableEntries);
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns whether the attributes of this method can be copied from the attributes of the given
* method (assuming there is no method visitor between the given ClassReader and this
* MethodWriter). This method should only be called just after this MethodWriter has been created,
* and before any content is visited. It returns true if the attributes corresponding to the
* constructor arguments (at most a Signature, an Exception, a Deprecated and a Synthetic
* attribute) are the same as the corresponding attributes in the given method.
*
* @param source the source ClassReader from which the attributes of this method might be copied.
* @param hasSyntheticAttribute whether the method_info JVMS structure from which the attributes
* of this method might be copied contains a Synthetic attribute.
* @param hasDeprecatedAttribute whether the method_info JVMS structure from which the attributes
* of this method might be copied contains a Deprecated attribute.
* @param descriptorIndex the descriptor_index field of the method_info JVMS structure from which
* the attributes of this method might be copied.
* @param signatureIndex the constant pool index contained in the Signature attribute of the
* method_info JVMS structure from which the attributes of this method might be copied, or 0.
* @param exceptionsOffset the offset in 'source.b' of the Exceptions attribute of the method_info
* JVMS structure from which the attributes of this method might be copied, or 0.
* @return whether the attributes of this method can be copied from the attributes of the
* method_info JVMS structure in 'source.b', between 'methodInfoOffset' and 'methodInfoOffset'
* + 'methodInfoLength'.
*/
boolean canCopyMethodAttributes(
final ClassReader source,
final boolean hasSyntheticAttribute,
final boolean hasDeprecatedAttribute,
final int descriptorIndex,
final int signatureIndex,
final int exceptionsOffset) {
// If the method descriptor has changed, with more locals than the max_locals field of the
// original Code attribute, if any, then the original method attributes can't be copied. A
// conservative check on the descriptor changes alone ensures this (being more precise is not
// worth the additional complexity, because these cases should be rare -- if a transform changes
// a method descriptor, most of the time it needs to change the method's code too).
if (source != symbolTable.getSource()
|| descriptorIndex != this.descriptorIndex
|| signatureIndex != this.signatureIndex
|| hasDeprecatedAttribute != ((accessFlags & Opcodes.ACC_DEPRECATED) != 0)) {
return false;
}
boolean needSyntheticAttribute =
symbolTable.getMajorVersion() < Opcodes.V1_5 && (accessFlags & Opcodes.ACC_SYNTHETIC) != 0;
if (hasSyntheticAttribute != needSyntheticAttribute) {
return false;
}
if (exceptionsOffset == 0) {
if (numberOfExceptions != 0) {
return false;
}
} else if (source.readUnsignedShort(exceptionsOffset) == numberOfExceptions) {
int currentExceptionOffset = exceptionsOffset + 2;
for (int i = 0; i < numberOfExceptions; ++i) {
if (source.readUnsignedShort(currentExceptionOffset) != exceptionIndexTable[i]) {
return false;
}
currentExceptionOffset += 2;
}
}
return true;
}
/**
* Sets the source from which the attributes of this method will be copied.
*
* @param methodInfoOffset the offset in 'symbolTable.getSource()' of the method_info JVMS
* structure from which the attributes of this method will be copied.
* @param methodInfoLength the length in 'symbolTable.getSource()' of the method_info JVMS
* structure from which the attributes of this method will be copied.
*/
void setMethodAttributesSource(final int methodInfoOffset, final int methodInfoLength) {
// Don't copy the attributes yet, instead store their location in the source class reader so
// they can be copied later, in {@link #putMethodInfo}. Note that we skip the 6 header bytes
// of the method_info JVMS structure.
this.sourceOffset = methodInfoOffset + 6;
this.sourceLength = methodInfoLength - 6;
}
/**
* Returns the size of the method_info JVMS structure generated by this MethodWriter. Also add the
* names of the attributes of this method in the constant pool.
*
* @return the size in bytes of the method_info JVMS structure.
*/
int computeMethodInfoSize() {
// If this method_info must be copied from an existing one, the size computation is trivial.
if (sourceOffset != 0) {
// sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index.
return 6 + sourceLength;
}
// 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.
int size = 8;
// For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
if (code.length > 0) {
if (code.length > 65535) {
throw new MethodTooLargeException(
symbolTable.getClassName(), name, descriptor, code.length);
}
symbolTable.addConstantUtf8(Constants.CODE);
// The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,
// max_locals, code_length and attributes_count, plus the bytecode and the exception table.
size += 16 + code.length + Handler.getExceptionTableSize(firstHandler);
if (stackMapTableEntries != null) {
boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap");
// 6 header bytes and 2 bytes for number_of_entries.
size += 8 + stackMapTableEntries.length;
}
if (lineNumberTable != null) {
symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE);
// 6 header bytes and 2 bytes for line_number_table_length.
size += 8 + lineNumberTable.length;
}
if (localVariableTable != null) {
symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE);
// 6 header bytes and 2 bytes for local_variable_table_length.
size += 8 + localVariableTable.length;
}
if (localVariableTypeTable != null) {
symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE);
// 6 header bytes and 2 bytes for local_variable_type_table_length.
size += 8 + localVariableTypeTable.length;
}
if (lastCodeRuntimeVisibleTypeAnnotation != null) {
size +=
lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(
Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);
}
if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
size +=
lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(
Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);
}
if (firstCodeAttribute != null) {
size +=
firstCodeAttribute.computeAttributesSize(
symbolTable, code.data, code.length, maxStack, maxLocals);
}
}
if (numberOfExceptions > 0) {
symbolTable.addConstantUtf8(Constants.EXCEPTIONS);
size += 8 + 2 * numberOfExceptions;
}
size += Attribute.computeAttributesSize(symbolTable, accessFlags, signatureIndex);
size +=
AnnotationWriter.computeAnnotationsSize(
lastRuntimeVisibleAnnotation,
lastRuntimeInvisibleAnnotation,
lastRuntimeVisibleTypeAnnotation,
lastRuntimeInvisibleTypeAnnotation);
if (lastRuntimeVisibleParameterAnnotations != null) {
size +=
AnnotationWriter.computeParameterAnnotationsSize(
Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS,
lastRuntimeVisibleParameterAnnotations,
visibleAnnotableParameterCount == 0
? lastRuntimeVisibleParameterAnnotations.length
: visibleAnnotableParameterCount);
}
if (lastRuntimeInvisibleParameterAnnotations != null) {
size +=
AnnotationWriter.computeParameterAnnotationsSize(
Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS,
lastRuntimeInvisibleParameterAnnotations,
invisibleAnnotableParameterCount == 0
? lastRuntimeInvisibleParameterAnnotations.length
: invisibleAnnotableParameterCount);
}
if (defaultValue != null) {
symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT);
size += 6 + defaultValue.length;
}
if (parameters != null) {
symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS);
// 6 header bytes and 1 byte for parameters_count.
size += 7 + parameters.length;
}
if (firstAttribute != null) {
size += firstAttribute.computeAttributesSize(symbolTable);
}
return size;
}
/**
* Puts the content of the method_info JVMS structure generated by this MethodWriter into the
* given ByteVector.
*
* @param output where the method_info structure must be put.
*/
void putMethodInfo(final ByteVector output) {
boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5;
int mask = useSyntheticAttribute ? Opcodes.ACC_SYNTHETIC : 0;
output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex);
// If this method_info must be copied from an existing one, copy it now and return early.
if (sourceOffset != 0) {
output.putByteArray(symbolTable.getSource().classFileBuffer, sourceOffset, sourceLength);
return;
}
// For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
int attributeCount = 0;
if (code.length > 0) {
++attributeCount;
}
if (numberOfExceptions > 0) {
++attributeCount;
}
if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) {
++attributeCount;
}
if (signatureIndex != 0) {
++attributeCount;
}
if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) {
++attributeCount;
}
if (lastRuntimeVisibleAnnotation != null) {
++attributeCount;
}
if (lastRuntimeInvisibleAnnotation != null) {
++attributeCount;
}
if (lastRuntimeVisibleParameterAnnotations != null) {
++attributeCount;
}
if (lastRuntimeInvisibleParameterAnnotations != null) {
++attributeCount;
}
if (lastRuntimeVisibleTypeAnnotation != null) {
++attributeCount;
}
if (lastRuntimeInvisibleTypeAnnotation != null) {
++attributeCount;
}
if (defaultValue != null) {
++attributeCount;
}
if (parameters != null) {
++attributeCount;
}
if (firstAttribute != null) {
attributeCount += firstAttribute.getAttributeCount();
}
// For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
output.putShort(attributeCount);
if (code.length > 0) {
// 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and
// attributes_count, plus the bytecode and the exception table.
int size = 10 + code.length + Handler.getExceptionTableSize(firstHandler);
int codeAttributeCount = 0;
if (stackMapTableEntries != null) {
// 6 header bytes and 2 bytes for number_of_entries.
size += 8 + stackMapTableEntries.length;
++codeAttributeCount;
}
if (lineNumberTable != null) {
// 6 header bytes and 2 bytes for line_number_table_length.
size += 8 + lineNumberTable.length;
++codeAttributeCount;
}
if (localVariableTable != null) {
// 6 header bytes and 2 bytes for local_variable_table_length.
size += 8 + localVariableTable.length;
++codeAttributeCount;
}
if (localVariableTypeTable != null) {
// 6 header bytes and 2 bytes for local_variable_type_table_length.
size += 8 + localVariableTypeTable.length;
++codeAttributeCount;
}
if (lastCodeRuntimeVisibleTypeAnnotation != null) {
size +=
lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(
Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);
++codeAttributeCount;
}
if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
size +=
lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(
Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);
++codeAttributeCount;
}
if (firstCodeAttribute != null) {
size +=
firstCodeAttribute.computeAttributesSize(
symbolTable, code.data, code.length, maxStack, maxLocals);
codeAttributeCount += firstCodeAttribute.getAttributeCount();
}
output
.putShort(symbolTable.addConstantUtf8(Constants.CODE))
.putInt(size)
.putShort(maxStack)
.putShort(maxLocals)
.putInt(code.length)
.putByteArray(code.data, 0, code.length);
Handler.putExceptionTable(firstHandler, output);
output.putShort(codeAttributeCount);
if (stackMapTableEntries != null) {
boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
output
.putShort(
symbolTable.addConstantUtf8(
useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap"))
.putInt(2 + stackMapTableEntries.length)
.putShort(stackMapTableNumberOfEntries)
.putByteArray(stackMapTableEntries.data, 0, stackMapTableEntries.length);
}
if (lineNumberTable != null) {
output
.putShort(symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE))
.putInt(2 + lineNumberTable.length)
.putShort(lineNumberTableLength)
.putByteArray(lineNumberTable.data, 0, lineNumberTable.length);
}
if (localVariableTable != null) {
output
.putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE))
.putInt(2 + localVariableTable.length)
.putShort(localVariableTableLength)
.putByteArray(localVariableTable.data, 0, localVariableTable.length);
}
if (localVariableTypeTable != null) {
output
.putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE))
.putInt(2 + localVariableTypeTable.length)
.putShort(localVariableTypeTableLength)
.putByteArray(localVariableTypeTable.data, 0, localVariableTypeTable.length);
}
if (lastCodeRuntimeVisibleTypeAnnotation != null) {
lastCodeRuntimeVisibleTypeAnnotation.putAnnotations(
symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output);
}
if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
lastCodeRuntimeInvisibleTypeAnnotation.putAnnotations(
symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output);
}
if (firstCodeAttribute != null) {
firstCodeAttribute.putAttributes(
symbolTable, code.data, code.length, maxStack, maxLocals, output);
}
}
if (numberOfExceptions > 0) {
output
.putShort(symbolTable.addConstantUtf8(Constants.EXCEPTIONS))
.putInt(2 + 2 * numberOfExceptions)
.putShort(numberOfExceptions);
for (int exceptionIndex : exceptionIndexTable) {
output.putShort(exceptionIndex);
}
}
Attribute.putAttributes(symbolTable, accessFlags, signatureIndex, output);
AnnotationWriter.putAnnotations(
symbolTable,
lastRuntimeVisibleAnnotation,
lastRuntimeInvisibleAnnotation,
lastRuntimeVisibleTypeAnnotation,
lastRuntimeInvisibleTypeAnnotation,
output);
if (lastRuntimeVisibleParameterAnnotations != null) {
AnnotationWriter.putParameterAnnotations(
symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS),
lastRuntimeVisibleParameterAnnotations,
visibleAnnotableParameterCount == 0
? lastRuntimeVisibleParameterAnnotations.length
: visibleAnnotableParameterCount,
output);
}
if (lastRuntimeInvisibleParameterAnnotations != null) {
AnnotationWriter.putParameterAnnotations(
symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS),
lastRuntimeInvisibleParameterAnnotations,
invisibleAnnotableParameterCount == 0
? lastRuntimeInvisibleParameterAnnotations.length
: invisibleAnnotableParameterCount,
output);
}
if (defaultValue != null) {
output
.putShort(symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT))
.putInt(defaultValue.length)
.putByteArray(defaultValue.data, 0, defaultValue.length);
}
if (parameters != null) {
output
.putShort(symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS))
.putInt(1 + parameters.length)
.putByte(parametersCount)
.putByteArray(parameters.data, 0, parameters.length);
}
if (firstAttribute != null) {
firstAttribute.putAttributes(symbolTable, output);
}
}
/**
* Collects the attributes of this method into the given set of attribute prototypes.
*
* @param attributePrototypes a set of attribute prototypes.
*/
final void collectAttributePrototypes(final Attribute.Set attributePrototypes) {
attributePrototypes.addAttributes(firstAttribute);
attributePrototypes.addAttributes(firstCodeAttribute);
}
}
| spring-projects/spring-framework | spring-core/src/main/java/org/springframework/asm/MethodWriter.java |
669 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.CheckReturnValue;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.model.TaskListener;
import hudson.util.QuotedStringTokenizer;
import hudson.util.VariableResolver;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.CopyOption;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.SimpleTimeZone;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import jenkins.model.Jenkins;
import jenkins.util.MemoryReductionUtil;
import jenkins.util.SystemProperties;
import jenkins.util.io.PathRemover;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerRequest;
/**
* Various utility methods that don't have more proper home.
*
* @author Kohsuke Kawaguchi
*/
public class Util {
// Constant number of milliseconds in various time units.
private static final long ONE_SECOND_MS = 1000;
private static final long ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
private static final long ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
private static final long ONE_DAY_MS = 24 * ONE_HOUR_MS;
private static final long ONE_MONTH_MS = 30 * ONE_DAY_MS;
private static final long ONE_YEAR_MS = 365 * ONE_DAY_MS;
/**
* Creates a filtered sublist.
* @since 1.176
*/
@NonNull
public static <T> List<T> filter(@NonNull Iterable<?> base, @NonNull Class<T> type) {
List<T> r = new ArrayList<>();
for (Object i : base) {
if (type.isInstance(i))
r.add(type.cast(i));
}
return r;
}
/**
* Creates a filtered sublist.
*/
@NonNull
public static <T> List<T> filter(@NonNull List<?> base, @NonNull Class<T> type) {
return filter((Iterable) base, type);
}
/**
* Pattern for capturing variables. Either $xyz, ${xyz} or ${a.b} but not $a.b, while ignoring "$$"
*/
private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_.]+\\}|\\$)");
/**
* Replaces the occurrence of '$key' by {@code properties.get('key')}.
*
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*
*/
@Nullable
public static String replaceMacro(@CheckForNull String s, @NonNull Map<String, String> properties) {
return replaceMacro(s, new VariableResolver.ByMap<>(properties));
}
/**
* Replaces the occurrence of '$key' by {@code resolver.get('key')}.
*
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*/
@Nullable
public static String replaceMacro(@CheckForNull String s, @NonNull VariableResolver<String> resolver) {
if (s == null) {
return null;
}
int idx = 0;
while (true) {
Matcher m = VARIABLE.matcher(s);
if (!m.find(idx)) return s;
String key = m.group().substring(1);
// escape the dollar sign or get the key to resolve
String value;
if (key.charAt(0) == '$') {
value = "$";
} else {
if (key.charAt(0) == '{') key = key.substring(1, key.length() - 1);
value = resolver.resolve(key);
}
if (value == null)
idx = m.end(); // skip this
else {
s = s.substring(0, m.start()) + value + s.substring(m.end());
idx = m.start() + value.length();
}
}
}
/**
* Reads the entire contents of the text file at {@code logfile} into a
* string using the {@link Charset#defaultCharset() default charset} for
* decoding. If no such file exists, an empty string is returned.
* @param logfile The text file to read in its entirety.
* @return The entire text content of {@code logfile}.
* @throws IOException If an error occurs while reading the file.
* @deprecated call {@link #loadFile(java.io.File, java.nio.charset.Charset)}
* instead to specify the charset to use for decoding (preferably
* {@link java.nio.charset.StandardCharsets#UTF_8}).
*/
@NonNull
@Deprecated
public static String loadFile(@NonNull File logfile) throws IOException {
return loadFile(logfile, Charset.defaultCharset());
}
/**
* Reads the entire contents of the text file at {@code logfile} into a
* string using {@code charset} for decoding. If no such file exists,
* an empty string is returned.
* @param logfile The text file to read in its entirety.
* @param charset The charset to use for decoding the bytes in {@code logfile}.
* @return The entire text content of {@code logfile}.
* @throws IOException If an error occurs while reading the file.
*/
@NonNull
public static String loadFile(@NonNull File logfile, @NonNull Charset charset) throws IOException {
// Note: Until charset handling is resolved (e.g. by implementing
// https://issues.jenkins.io/browse/JENKINS-48923 ), this method
// must be able to handle character encoding errors. As reported at
// https://issues.jenkins.io/browse/JENKINS-49112 Run.getLog() calls
// loadFile() to fully read the generated log file. This file might
// contain unmappable and/or malformed byte sequences. We need to make
// sure that in such cases, no CharacterCodingException is thrown.
//
// One approach that cannot be used is Files.newBufferedReader, which
// creates its CharsetDecoder with the default behavior of reporting
// malformed input and unmappable character errors. The implementation
// of InputStreamReader(InputStream, Charset) has the desired behavior
// of replacing malformed input and unmappable character errors, but
// this implementation is not specified in the API contract. Therefore,
// we explicitly use a decoder with the desired behavior.
// See: https://issues.jenkins.io/browse/JENKINS-49060?focusedCommentId=325989&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325989
CharsetDecoder decoder = charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
try (InputStream is = Files.newInputStream(Util.fileToPath(logfile));
Reader isr = new InputStreamReader(is, decoder);
Reader br = new BufferedReader(isr)) {
return IOUtils.toString(br);
} catch (NoSuchFileException e) {
return "";
} catch (Exception e) {
throw new IOException("Failed to fully read " + logfile, e);
}
}
/**
* Deletes the contents of the given directory (but not the directory itself)
* recursively.
* It does not take no for an answer - if necessary, it will have multiple
* attempts at deleting things.
*
* @throws IOException
* if the operation fails.
*/
public static void deleteContentsRecursive(@NonNull File file) throws IOException {
deleteContentsRecursive(fileToPath(file), PathRemover.PathChecker.ALLOW_ALL);
}
/**
* Deletes the given directory contents (but not the directory itself) recursively using a PathChecker.
* @param path a directory to delete
* @param pathChecker a security check to validate a path before deleting
* @throws IOException if the operation fails
*/
@Restricted(NoExternalUse.class)
public static void deleteContentsRecursive(@NonNull Path path, @NonNull PathRemover.PathChecker pathChecker) throws IOException {
newPathRemover(pathChecker).forceRemoveDirectoryContents(path);
}
/**
* Deletes this file (and does not take no for an answer).
* If necessary, it will have multiple attempts at deleting things.
*
* @param f a file to delete
* @throws IOException if it exists but could not be successfully deleted
*/
public static void deleteFile(@NonNull File f) throws IOException {
newPathRemover(PathRemover.PathChecker.ALLOW_ALL).forceRemoveFile(fileToPath(f));
}
/**
* Deletes the given directory (including its contents) recursively.
* It does not take no for an answer - if necessary, it will have multiple
* attempts at deleting things.
*
* @throws IOException
* if the operation fails.
*/
public static void deleteRecursive(@NonNull File dir) throws IOException {
deleteRecursive(fileToPath(dir), PathRemover.PathChecker.ALLOW_ALL);
}
/**
* Deletes the given directory and contents recursively using a filter.
* @param dir a directory to delete
* @param pathChecker a security check to validate a path before deleting
* @throws IOException if the operation fails
*/
@Restricted(NoExternalUse.class)
public static void deleteRecursive(@NonNull Path dir, @NonNull PathRemover.PathChecker pathChecker) throws IOException {
newPathRemover(pathChecker).forceRemoveRecursive(dir);
}
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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.
*/
/**
* Checks if the given file represents a symlink. Unlike {@link Files#isSymbolicLink(Path)}, this method also
* considers <a href="https://en.wikipedia.org/wiki/NTFS_junction_point">NTFS junction points</a> as symbolic
* links.
*/
public static boolean isSymlink(@NonNull File file) throws IOException {
return isSymlink(fileToPath(file));
}
@Restricted(NoExternalUse.class)
public static boolean isSymlink(@NonNull Path path) {
/*
* Windows Directory Junctions are effectively the same as Linux symlinks to directories.
* Unfortunately, the Java 7 NIO2 API function isSymbolicLink does not treat them as such.
* It thinks of them as normal directories. To use the NIO2 API & treat it like a symlink,
* you have to go through BasicFileAttributes and do the following check:
* isSymbolicLink() || isOther()
* The isOther() call will include Windows reparse points, of which a directory junction is.
* It also includes includes devices, but reading the attributes of a device with NIO fails
* or returns false for isOther(). (i.e. named pipes such as \\.\pipe\JenkinsTestPipe return
* false for isOther(), and drives such as \\.\PhysicalDrive0 throw an exception when
* calling readAttributes.
*/
try {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
return attrs.isSymbolicLink() || (attrs instanceof DosFileAttributes && attrs.isOther());
} catch (IOException ignored) {
return false;
}
}
/**
* A mostly accurate check of whether a path is a relative path or not. This is designed to take a path against
* an unknown operating system so may give invalid results.
*
* @param path the path.
* @return {@code true} if the path looks relative.
* @since 1.606
*/
public static boolean isRelativePath(String path) {
if (path.startsWith("/"))
return false;
if (path.startsWith("\\\\") && path.length() > 3 && path.indexOf('\\', 3) != -1)
return false; // a UNC path which is the most absolute you can get on windows
if (path.length() >= 3 && ':' == path.charAt(1)) {
// never mind that the drive mappings can be changed between sessions, we just want to
// know if the 3rd character is a `\` (or a '/' is acceptable too)
char p = path.charAt(0);
if (('A' <= p && p <= 'Z') || ('a' <= p && p <= 'z')) {
return path.charAt(2) != '\\' && path.charAt(2) != '/';
}
}
return true;
}
/**
* A check if a file path is a descendant of a parent path
* @param forParent the parent the child should be a descendant of
* @param potentialChild the path to check
* @return true if so
* @throws IOException for invalid paths
* @since 2.80
* @see InvalidPathException
*/
public static boolean isDescendant(File forParent, File potentialChild) throws IOException {
Path child = fileToPath(potentialChild.getAbsoluteFile()).normalize();
Path parent = fileToPath(forParent.getAbsoluteFile()).normalize();
return child.startsWith(parent);
}
/**
* Creates a new temporary directory.
*/
public static File createTempDir() throws IOException {
// The previously used approach of creating a temporary file, deleting
// it, and making a new directory having the same name in its place is
// potentially problematic:
// https://stackoverflow.com/questions/617414/how-to-create-a-temporary-directory-folder-in-java
// We can use the Java 7 Files.createTempDirectory() API, but note that
// by default, the permissions of the created directory are 0700&(~umask)
// whereas the old approach created a temporary directory with permissions
// 0777&(~umask).
// To avoid permissions problems like https://issues.jenkins.io/browse/JENKINS-48407
// we can pass POSIX file permissions as an attribute (see, for example,
// https://github.com/jenkinsci/jenkins/pull/3161 )
final Path tempPath;
final String tempDirNamePrefix = "jenkins";
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
tempPath = Files.createTempDirectory(tempDirNamePrefix,
PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class)));
} else {
tempPath = Files.createTempDirectory(tempDirNamePrefix);
}
return tempPath.toFile();
}
private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
/**
* On Windows, error messages for IOException aren't very helpful.
* This method generates additional user-friendly error message to the listener
*/
public static void displayIOException(@NonNull IOException e, @NonNull TaskListener listener) {
String msg = getWin32ErrorMessage(e);
if (msg != null)
listener.getLogger().println(msg);
}
@CheckForNull
public static String getWin32ErrorMessage(@NonNull IOException e) {
return getWin32ErrorMessage((Throwable) e);
}
/**
* Extracts the Win32 error message from {@link Throwable} if possible.
*
* @return
* null if there seems to be no error code or if the platform is not Win32.
*/
@CheckForNull
public static String getWin32ErrorMessage(Throwable e) {
String msg = e.getMessage();
if (msg != null) {
Matcher m = errorCodeParser.matcher(msg);
if (m.matches()) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
return rb.getString("error" + m.group(1));
} catch (RuntimeException ignored) {
// silently recover from resource related failures
}
}
}
if (e.getCause() != null)
return getWin32ErrorMessage(e.getCause());
return null; // no message
}
/**
* Gets a human readable message for the given Win32 error code.
*
* @return
* null if no such message is available.
*/
@CheckForNull
public static String getWin32ErrorMessage(int n) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
return rb.getString("error" + n);
} catch (MissingResourceException e) {
LOGGER.log(Level.WARNING, "Failed to find resource bundle", e);
return null;
}
}
/**
* Guesses the current host name.
*/
@NonNull
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
/**
* @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)}
*/
@Deprecated
public static void copyStream(@NonNull InputStream in, @NonNull OutputStream out) throws IOException {
IOUtils.copy(in, out);
}
/**
* @deprecated Use {@link IOUtils#copy(Reader, Writer)}
*/
@Deprecated
public static void copyStream(@NonNull Reader in, @NonNull Writer out) throws IOException {
IOUtils.copy(in, out);
}
/**
* @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)} in a {@code try}-with-resources block
*/
@Deprecated
public static void copyStreamAndClose(@NonNull InputStream in, @NonNull OutputStream out) throws IOException {
try (InputStream _in = in; OutputStream _out = out) { // make sure both are closed, and use Throwable.addSuppressed
IOUtils.copy(_in, _out);
}
}
/**
* @deprecated Use {@link IOUtils#copy(Reader, Writer)} in a {@code try}-with-resources block
*/
@Deprecated
public static void copyStreamAndClose(@NonNull Reader in, @NonNull Writer out) throws IOException {
try (Reader _in = in; Writer _out = out) {
IOUtils.copy(_in, _out);
}
}
/**
* Tokenizes the text separated by delimiters.
*
* <p>
* In 1.210, this method was changed to handle quotes like Unix shell does.
* Before that, this method just used {@link StringTokenizer}.
*
* @since 1.145
* @see QuotedStringTokenizer
*/
@NonNull
public static String[] tokenize(@NonNull String s, @CheckForNull String delimiter) {
return QuotedStringTokenizer.tokenize(s, delimiter);
}
@NonNull
public static String[] tokenize(@NonNull String s) {
return tokenize(s, " \t\n\r\f");
}
/**
* Converts the map format of the environment variables to the K=V format in the array.
*/
@NonNull
public static String[] mapToEnv(@NonNull Map<String, String> m) {
String[] r = new String[m.size()];
int idx = 0;
for (final Map.Entry<String, String> e : m.entrySet()) {
r[idx++] = e.getKey() + '=' + e.getValue();
}
return r;
}
public static int min(int x, @NonNull int... values) {
for (int i : values) {
if (i < x)
x = i;
}
return x;
}
@CheckForNull
public static String nullify(@CheckForNull String v) {
return fixEmpty(v);
}
@NonNull
public static String removeTrailingSlash(@NonNull String s) {
if (s.endsWith("/")) return s.substring(0, s.length() - 1);
else return s;
}
/**
* Ensure string ends with suffix
*
* @param subject Examined string
* @param suffix Desired suffix
* @return Original subject in case it already ends with suffix, null in
* case subject was null and subject + suffix otherwise.
* @since 1.505
*/
@Nullable
public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix) {
if (subject == null) return null;
if (subject.endsWith(suffix)) return subject;
return subject + suffix;
}
/**
* Computes MD5 digest of the given input stream.
*
* This method should only be used for non-security applications where the MD5 weakness is not a problem.
*
* @param source
* The stream will be closed by this method at the end of this method.
* @return
* 32-char wide string
* @see DigestUtils#md5Hex(InputStream)
*/
@NonNull
public static String getDigestOf(@NonNull InputStream source) throws IOException {
try (source) {
MessageDigest md5 = getMd5();
try (InputStream in = new DigestInputStream(source, md5); OutputStream out = OutputStream.nullOutputStream()) {
// Note: IOUtils.copy() buffers the input internally, so there is no
// need to use a BufferedInputStream.
IOUtils.copy(in, out);
}
return toHexString(md5.digest());
} catch (NoSuchAlgorithmException e) {
throw new IOException("MD5 not installed", e); // impossible
}
/* JENKINS-18178: confuses Maven 2 runner
try {
return DigestUtils.md5Hex(source);
} finally {
source.close();
}
*/
}
// TODO JENKINS-60563 remove MD5 from all usages in Jenkins
@SuppressFBWarnings(value = "WEAK_MESSAGE_DIGEST_MD5", justification =
"This method should only be used for non-security applications where the MD5 weakness is not a problem.")
@Deprecated
private static MessageDigest getMd5() throws NoSuchAlgorithmException {
return MessageDigest.getInstance("MD5");
}
@NonNull
public static String getDigestOf(@NonNull String text) {
try {
return getDigestOf(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
} catch (IOException e) {
throw new Error(e);
}
}
/**
* Computes the MD5 digest of a file.
* @param file a file
* @return a 32-character string
* @throws IOException in case reading fails
* @since 1.525
*/
@NonNull
public static String getDigestOf(@NonNull File file) throws IOException {
// Note: getDigestOf() closes the input stream.
return getDigestOf(Files.newInputStream(fileToPath(file)));
}
/**
* Converts a string into 128-bit AES key.
* @since 1.308
*/
@NonNull
public static SecretKey toAes128Key(@NonNull String s) {
try {
// turn secretKey into 256 bit hash
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(s.getBytes(StandardCharsets.UTF_8));
// Due to the stupid US export restriction JDK only ships 128bit version.
return new SecretKeySpec(digest.digest(), 0, 128 / 8, "AES");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
}
}
@NonNull
public static String toHexString(@NonNull byte[] data, int start, int len) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < len; i++) {
int b = data[start + i] & 0xFF;
if (b < 16) buf.append('0');
buf.append(Integer.toHexString(b));
}
return buf.toString();
}
@NonNull
public static String toHexString(@NonNull byte[] bytes) {
return toHexString(bytes, 0, bytes.length);
}
@NonNull
public static byte[] fromHexString(@NonNull String data) {
if (data.length() % 2 != 0)
throw new IllegalArgumentException("data must have an even number of hexadecimal digits");
byte[] r = new byte[data.length() / 2];
for (int i = 0; i < data.length(); i += 2)
r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
return r;
}
/**
* Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
* This version should be used for representing a duration of some activity (like build)
*
* @param duration
* number of milliseconds.
*/
@NonNull
@SuppressFBWarnings(value = "ICAST_IDIV_CAST_TO_DOUBLE", justification = "We want to truncate here.")
public static String getTimeSpanString(long duration) {
// Break the duration up in to units.
long years = duration / ONE_YEAR_MS;
duration %= ONE_YEAR_MS;
long months = duration / ONE_MONTH_MS;
duration %= ONE_MONTH_MS;
long days = duration / ONE_DAY_MS;
duration %= ONE_DAY_MS;
long hours = duration / ONE_HOUR_MS;
duration %= ONE_HOUR_MS;
long minutes = duration / ONE_MINUTE_MS;
duration %= ONE_MINUTE_MS;
long seconds = duration / ONE_SECOND_MS;
duration %= ONE_SECOND_MS;
long millisecs = duration;
if (years > 0)
return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
else if (months > 0)
return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
else if (days > 0)
return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
else if (hours > 0)
return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
else if (minutes > 0)
return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
else if (seconds >= 10)
return Messages.Util_second(seconds);
else if (seconds >= 1)
return Messages.Util_second(seconds + (float) (millisecs / 100) / 10); // render "1.2 sec"
else if (millisecs >= 100)
return Messages.Util_second((float) (millisecs / 10) / 100); // render "0.12 sec".
else
return Messages.Util_millisecond(millisecs);
}
/**
* Create a string representation of a time duration. If the quantity of
* the most significant unit is big (>=10), then we use only that most
* significant unit in the string representation. If the quantity of the
* most significant unit is small (a single-digit value), then we also
* use a secondary, smaller unit for increased precision.
* So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
* and 43 seconds is "3 minutes 43 seconds".
*/
@NonNull
private static String makeTimeSpanString(long bigUnit,
@NonNull String bigLabel,
long smallUnit,
@NonNull String smallLabel) {
String text = bigLabel;
if (bigUnit < 10)
text += ' ' + smallLabel;
return text;
}
/**
* Get a human readable string representing strings like "xxx days ago",
* which should be used to point to the occurrence of an event in the past.
* @deprecated Actually identical to {@link #getTimeSpanString}, does not add {@code ago}.
*/
@Deprecated
@NonNull
public static String getPastTimeString(long duration) {
return getTimeSpanString(duration);
}
/**
* Combines number and unit, with a plural suffix if needed.
*
* @deprecated
* Use individual localization methods instead.
* See {@link Messages#Util_year(Object)} for an example.
* Deprecated since 2009-06-24, remove method after 2009-12-24.
*/
@NonNull
@Deprecated
public static String combine(long n, @NonNull String suffix) {
String s = Long.toString(n) + ' ' + suffix;
if (n != 1)
// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
s += "s";
return s;
}
/**
* Create a sub-list by only picking up instances of the specified type.
*/
@NonNull
public static <T> List<T> createSubList(@NonNull Collection<?> source, @NonNull Class<T> type) {
List<T> r = new ArrayList<>();
for (Object item : source) {
if (type.isInstance(item))
r.add(type.cast(item));
}
return r;
}
/**
* Escapes non-ASCII characters in URL.
*
* <p>
* Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
* such as '#'.
* {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
* a single path component to that method (it will encode /, but this method does not).
*/
@NonNull
public static String encode(@NonNull String s) {
try {
boolean escaped = false;
StringBuilder out = new StringBuilder(s.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter w = new OutputStreamWriter(buf, StandardCharsets.UTF_8);
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
if (c < 128 && c != ' ') {
out.append((char) c);
} else {
// 1 char -> UTF8
w.write(c);
w.flush();
for (byte b : buf.toByteArray()) {
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
buf.reset();
escaped = true;
}
}
return escaped ? out.toString() : s;
} catch (IOException e) {
throw new Error(e); // impossible
}
}
private static final boolean[] uriMap = new boolean[123];
static {
String raw =
"! $ &'()*+,-. 0123456789 = @ABCDEFGHIJKLMNOPQRSTUVWXYZ _ abcdefghijklmnopqrstuvwxyz";
// "# % / :;< >? [\]^ ` {|}~
// ^--so these are encoded
int i;
// Encode control chars and space
for (i = 0; i < 33; i++) uriMap[i] = true;
for (int j = 0; j < raw.length(); i++, j++)
uriMap[i] = raw.charAt(j) == ' ';
// If we add encodeQuery() just add a 2nd map to encode &+=
// queryMap[38] = queryMap[43] = queryMap[61] = true;
}
private static final boolean[] fullUriMap = new boolean[123];
static {
String raw = " 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz";
// !"#$%&'()*+,-./0123456789:;<=>?@ [\]^_` {|}~
// ^--so these are encoded
int i;
// Encode control chars and space
for (i = 0; i < 33; i++) fullUriMap[i] = true;
for (int j = 0; j < raw.length(); i++, j++)
fullUriMap[i] = raw.charAt(j) == ' ';
// If we add encodeQuery() just add a 2nd map to encode &+=
// queryMap[38] = queryMap[43] = queryMap[61] = true;
}
/**
* Encode a single path component for use in an HTTP URL.
* Escapes all non-ASCII, general unsafe (space and {@code "#%<>[\]^`{|}~})
* and HTTP special characters ({@code /;:?}) as specified in RFC1738.
* (so alphanumeric and {@code !@$&*()-_=+',.} are not encoded)
* Note that slash ({@code /}) is encoded, so the given string should be a
* single path component used in constructing a URL.
* Method name inspired by PHP's rawurlencode.
*/
@NonNull
public static String rawEncode(@NonNull String s) {
return encode(s, uriMap);
}
/**
* Encode a single path component for use in an HTTP URL.
* Escapes all special characters including those outside
* of the characters specified in RFC1738.
* All characters outside numbers and letters without diacritic are encoded.
* Note that slash ({@code /}) is encoded, so the given string should be a
* single path component used in constructing a URL.
*
* @since 2.308
*/
@NonNull
public static String fullEncode(@NonNull String s) {
return encode(s, fullUriMap);
}
private static String encode(String s, boolean[] map) {
boolean escaped = false;
StringBuilder out = null;
CharsetEncoder enc = null;
CharBuffer buf = null;
char c;
for (int i = 0, m = s.length(); i < m; i++) {
int codePoint = Character.codePointAt(s, i);
if ((codePoint & 0xffffff80) == 0) { // 1 byte
c = s.charAt(i);
if (c > 122 || map[c]) {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s, 0, i);
escaped = true;
}
if (enc == null || buf == null) {
enc = StandardCharsets.UTF_8.newEncoder();
buf = CharBuffer.allocate(1);
}
// 1 char -> UTF8
buf.put(0, c);
buf.rewind();
try {
ByteBuffer bytes = enc.encode(buf);
while (bytes.hasRemaining()) {
byte b = bytes.get();
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
} catch (CharacterCodingException ex) {
}
} else if (escaped) {
out.append(c);
}
} else {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s, 0, i);
escaped = true;
}
byte[] bytes = new String(new int[] { codePoint }, 0, 1).getBytes(StandardCharsets.UTF_8);
for (byte aByte : bytes) {
out.append('%');
out.append(toDigit((aByte >> 4) & 0xF));
out.append(toDigit(aByte & 0xF));
}
if (Character.charCount(codePoint) > 1) {
i++; // we processed two characters
}
}
}
return escaped ? out.toString() : s;
}
private static char toDigit(int n) {
return (char) (n < 10 ? '0' + n : 'A' + n - 10);
}
/**
* Surrounds by a single-quote.
*/
public static String singleQuote(String s) {
return '\'' + s + '\'';
}
/**
* Escapes HTML unsafe characters like <, & to the respective character entities.
*/
@Nullable
public static String escape(@CheckForNull String text) {
if (text == null) return null;
StringBuilder buf = new StringBuilder(text.length() + 64);
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '\n')
buf.append("<br>");
else
if (ch == '<')
buf.append("<");
else
if (ch == '>')
buf.append(">");
else
if (ch == '&')
buf.append("&");
else
if (ch == '"')
buf.append(""");
else
if (ch == '\'')
buf.append("'");
else
if (ch == ' ') {
// All spaces in a block of consecutive spaces are converted to
// non-breaking space ( ) except for the last one. This allows
// significant whitespace to be retained without prohibiting wrapping.
char nextCh = i + 1 < text.length() ? text.charAt(i + 1) : 0;
buf.append(nextCh == ' ' ? " " : " ");
}
else
buf.append(ch);
}
return buf.toString();
}
@NonNull
public static String xmlEscape(@NonNull String text) {
StringBuilder buf = new StringBuilder(text.length() + 64);
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '<')
buf.append("<");
else
if (ch == '>')
buf.append(">");
else
if (ch == '&')
buf.append("&");
else
buf.append(ch);
}
return buf.toString();
}
/**
* Creates an empty file if nonexistent or truncates the existing file.
* Note: The behavior of this method in the case where the file already
* exists is unlike the POSIX {@code touch} utility which merely
* updates the file's access and/or modification time.
*/
public static void touch(@NonNull File file) throws IOException {
Files.newOutputStream(fileToPath(file)).close();
}
/**
* Copies a single file by using Ant.
*
* @deprecated since 2.335; use {@link Files#copy(Path, Path, CopyOption...)} directly
*/
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.335")
public static void copyFile(@NonNull File src, @NonNull File dst) throws BuildException {
Copy cp = new Copy();
cp.setProject(new Project());
cp.setTofile(dst);
cp.setFile(src);
cp.setOverwrite(true);
cp.execute();
}
/**
* Convert null to "".
*/
@NonNull
public static String fixNull(@CheckForNull String s) {
return fixNull(s, "");
}
/**
* Convert {@code null} to a default value.
* @param defaultValue Default value. It may be immutable or not, depending on the implementation.
* @since 2.144
*/
@NonNull
public static <T> T fixNull(@CheckForNull T s, @NonNull T defaultValue) {
return s != null ? s : defaultValue;
}
/**
* Convert empty string to null.
*/
@CheckForNull
public static String fixEmpty(@CheckForNull String s) {
if (s == null || s.isEmpty()) return null;
return s;
}
/**
* Convert empty string to null, and trim whitespace.
*
* @since 1.154
*/
@CheckForNull
public static String fixEmptyAndTrim(@CheckForNull String s) {
if (s == null) return null;
return fixEmpty(s.trim());
}
/**
*
* @param l list to check.
* @param <T>
* Type of the list.
* @return
* {@code l} if l is not {@code null}.
* An empty <b>immutable list</b> if l is {@code null}.
*/
@NonNull
public static <T> List<T> fixNull(@CheckForNull List<T> l) {
return fixNull(l, Collections.emptyList());
}
/**
*
* @param l set to check.
* @param <T>
* Type of the set.
* @return
* {@code l} if l is not {@code null}.
* An empty <b>immutable set</b> if l is {@code null}.
*/
@NonNull
public static <T> Set<T> fixNull(@CheckForNull Set<T> l) {
return fixNull(l, Collections.emptySet());
}
/**
*
* @param l collection to check.
* @param <T>
* Type of the collection.
* @return
* {@code l} if l is not {@code null}.
* An empty <b>immutable set</b> if l is {@code null}.
*/
@NonNull
public static <T> Collection<T> fixNull(@CheckForNull Collection<T> l) {
return fixNull(l, Collections.emptySet());
}
/**
*
* @param l iterable to check.
* @param <T>
* Type of the iterable.
* @return
* {@code l} if l is not {@code null}.
* An empty <b>immutable set</b> if l is {@code null}.
*/
@NonNull
public static <T> Iterable<T> fixNull(@CheckForNull Iterable<T> l) {
return fixNull(l, Collections.emptySet());
}
/**
* Cuts all the leading path portion and get just the file name.
*/
@NonNull
public static String getFileName(@NonNull String filePath) {
int idx = filePath.lastIndexOf('\\');
if (idx >= 0)
return getFileName(filePath.substring(idx + 1));
idx = filePath.lastIndexOf('/');
if (idx >= 0)
return getFileName(filePath.substring(idx + 1));
return filePath;
}
/**
* Concatenate multiple strings by inserting a separator.
* @deprecated since 2.292; use {@link String#join(CharSequence, Iterable)}
*/
@Deprecated
@NonNull
public static String join(@NonNull Collection<?> strings, @NonNull String separator) {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Object s : strings) {
if (first) first = false;
else buf.append(separator);
buf.append(s);
}
return buf.toString();
}
/**
* Combines all the given collections into a single list.
*/
@NonNull
public static <T> List<T> join(@NonNull Collection<? extends T>... items) {
int size = 0;
for (Collection<? extends T> item : items)
size += item.size();
List<T> r = new ArrayList<>(size);
for (Collection<? extends T> item : items)
r.addAll(item);
return r;
}
/**
* Creates Ant {@link FileSet} with the base dir and include pattern.
*
* <p>
* The difference with this and using {@link FileSet#setIncludes(String)}
* is that this method doesn't treat whitespace as a pattern separator,
* which makes it impossible to use space in the file path.
*
* @param includes
* String like "foo/bar/*.xml" Multiple patterns can be separated
* by ',', and whitespace can surround ',' (so that you can write
* "abc, def" and "abc,def" to mean the same thing.
* @param excludes
* Exclusion pattern. Follows the same format as the 'includes' parameter.
* Can be null.
* @since 1.172
*/
@NonNull
public static FileSet createFileSet(@NonNull File baseDir, @NonNull String includes, @CheckForNull String excludes) {
FileSet fs = new FileSet();
fs.setDir(baseDir);
fs.setProject(new Project());
StringTokenizer tokens;
tokens = new StringTokenizer(includes, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
fs.createInclude().setName(token);
}
if (excludes != null) {
tokens = new StringTokenizer(excludes, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
fs.createExclude().setName(token);
}
}
return fs;
}
@NonNull
public static FileSet createFileSet(@NonNull File baseDir, @NonNull String includes) {
return createFileSet(baseDir, includes, null);
}
private static void tryToDeleteSymlink(@NonNull File symlink) {
if (!symlink.delete()) {
LogRecord record = new LogRecord(Level.FINE, "Failed to delete temporary symlink {0}");
record.setParameters(new Object[]{symlink.getAbsolutePath()});
LOGGER.log(record);
}
}
private static void reportAtomicFailure(@NonNull Path pathForSymlink, @NonNull Exception ex) {
LogRecord record = new LogRecord(Level.FINE, "Failed to atomically create/replace symlink {0}");
record.setParameters(new Object[]{pathForSymlink.toAbsolutePath().toString()});
record.setThrown(ex);
LOGGER.log(record);
}
/**
* Creates a symlink to targetPath at baseDir+symlinkPath.
*
* @param pathForSymlink
* The absolute path of the symlink itself as a path object.
* @param fileForSymlink
* The absolute path of the symlink itself as a file object.
* @param target
* The path that the symlink should point to. Usually relative to the directory of the symlink but may instead be an absolute path.
* @param symlinkPath
* Where to create a symlink in (relative to {@code baseDir})
*
* Returns true on success
*/
@CheckReturnValue
private static boolean createSymlinkAtomic(@NonNull Path pathForSymlink, @NonNull File fileForSymlink, @NonNull Path target, @NonNull String symlinkPath) {
try {
File symlink = File.createTempFile("symtmp", null, fileForSymlink);
tryToDeleteSymlink(symlink);
Path tempSymlinkPath = symlink.toPath();
Files.createSymbolicLink(tempSymlinkPath, target);
try {
Files.move(tempSymlinkPath, pathForSymlink, StandardCopyOption.ATOMIC_MOVE);
return true;
} catch (
UnsupportedOperationException |
SecurityException |
IOException ex) {
// If we couldn't perform an atomic move or the setup, we fall through to another approach
reportAtomicFailure(pathForSymlink, ex);
}
// If we didn't return after our atomic move, then we want to clean up our symlink
tryToDeleteSymlink(symlink);
} catch (
SecurityException |
InvalidPathException |
UnsupportedOperationException |
IOException ex) {
// We couldn't perform an atomic move or the setup.
reportAtomicFailure(pathForSymlink, ex);
}
return false;
}
/**
* Creates a symlink to targetPath at baseDir+symlinkPath.
* <p>
* If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
*
* @param baseDir
* Base directory to resolve the 'symlinkPath' parameter.
* @param targetPath
* The file that the symlink should point to. Usually relative to the directory of the symlink but may instead be an absolute path.
* @param symlinkPath
* Where to create a symlink in (relative to {@code baseDir})
*/
public static void createSymlink(@NonNull File baseDir, @NonNull String targetPath,
@NonNull String symlinkPath, @NonNull TaskListener listener) throws InterruptedException {
File fileForSymlink = new File(baseDir, symlinkPath);
try {
Path pathForSymlink = fileToPath(fileForSymlink);
Path target = Paths.get(targetPath, MemoryReductionUtil.EMPTY_STRING_ARRAY);
if (createSymlinkAtomic(pathForSymlink, fileForSymlink, target, symlinkPath)) {
return;
}
final int maxNumberOfTries = 4;
final int timeInMillis = 100;
for (int tryNumber = 1; tryNumber <= maxNumberOfTries; tryNumber++) {
Files.deleteIfExists(pathForSymlink);
try {
Files.createSymbolicLink(pathForSymlink, target);
break;
} catch (FileAlreadyExistsException fileAlreadyExistsException) {
if (tryNumber < maxNumberOfTries) {
TimeUnit.MILLISECONDS.sleep(timeInMillis); //trying to defeat likely ongoing race condition
continue;
}
LOGGER.log(Level.WARNING, "symlink FileAlreadyExistsException thrown {0} times => cannot createSymbolicLink", maxNumberOfTries);
throw fileAlreadyExistsException;
}
}
} catch (UnsupportedOperationException e) {
PrintStream log = listener.getLogger();
log.print("Symbolic links are not supported on this platform");
Functions.printStackTrace(e, log);
} catch (IOException e) {
if (Functions.isWindows() && e instanceof FileSystemException) {
warnWindowsSymlink();
return;
}
PrintStream log = listener.getLogger();
log.printf("ln %s %s failed%n", targetPath, fileForSymlink);
Functions.printStackTrace(e, log);
}
}
private static final AtomicBoolean warnedSymlinks = new AtomicBoolean();
private static void warnWindowsSymlink() {
if (warnedSymlinks.compareAndSet(false, true)) {
LOGGER.warning("Symbolic links enabled on this platform but disabled for this user; run as administrator or use Local Security Policy > Security Settings > Local Policies > User Rights Assignment > Create symbolic links");
}
}
/**
* @deprecated as of 1.456
* Use {@link #resolveSymlink(File)}
*/
@Deprecated
public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
return resolveSymlink(link);
}
/**
* Resolves a symlink to the {@link File} that points to.
*
* @return null
* if the specified file is not a symlink.
*/
@CheckForNull
public static File resolveSymlinkToFile(@NonNull File link) throws InterruptedException, IOException {
String target = resolveSymlink(link);
if (target == null) return null;
File f = new File(target);
if (f.isAbsolute()) return f; // absolute symlink
return new File(link.getParentFile(), target); // relative symlink
}
/**
* Resolves symlink, if the given file is a symlink. Otherwise return null.
* <p>
* If the resolution fails, report an error.
*
* @return
* null if the given file is not a symlink.
* If the symlink is absolute, the returned string is an absolute path.
* If the symlink is relative, the returned string is that relative representation.
* The relative path is meant to be resolved from the location of the symlink.
*/
@CheckForNull
public static String resolveSymlink(@NonNull File link) throws IOException {
try {
Path path = fileToPath(link);
return Files.readSymbolicLink(path).toString();
} catch (UnsupportedOperationException | FileSystemException x) {
// no symlinks on this platform (windows?),
// or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink,
// rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ?
return null;
} catch (IOException x) {
throw x;
} catch (RuntimeException x) {
throw new IOException(x);
}
}
/**
* Encodes the URL by RFC 2396.
*
* I thought there's another spec that refers to UTF-8 as the encoding,
* but don't remember it right now.
*
* @since 1.204
* @deprecated since 2008-05-13. This method is broken (see JENKINS-1666). It should probably
* be removed but I'm not sure if it is considered part of the public API
* that needs to be maintained for backwards compatibility.
* Use {@link #encode(String)} instead.
*/
@Deprecated
public static String encodeRFC2396(String url) {
try {
return new URI(null, url, null).toASCIIString();
} catch (URISyntaxException e) {
LOGGER.log(Level.WARNING, "Failed to encode {0}", url); // could this ever happen?
return url;
}
}
/**
* Wraps with the error icon and the CSS class to render error message.
* @since 1.173
*/
@NonNull
public static String wrapToErrorSpan(@NonNull String s) {
s = "<span class=error style='display:inline-block'>" + s + "</span>";
return s;
}
/**
* Returns the parsed string if parsed successful; otherwise returns the default number.
* If the string is null, empty or a ParseException is thrown then the defaultNumber
* is returned.
* @param numberStr string to parse
* @param defaultNumber number to return if the string can not be parsed
* @return returns the parsed string; otherwise the default number
*/
@CheckForNull
public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber) {
if (numberStr == null || numberStr.isEmpty()) {
return defaultNumber;
}
try {
return NumberFormat.getNumberInstance().parse(numberStr);
} catch (ParseException e) {
return defaultNumber;
}
}
/**
* Checks whether the method defined on the base type with the given arguments is overridden in the given derived
* type.
*
* @param base The base type.
* @param derived The derived type.
* @param methodName The name of the method.
* @param types The types of the arguments for the method.
* @return {@code true} when {@code derived} provides the specified method other than as inherited from {@code base}.
* @throws IllegalArgumentException When {@code derived} does not derive from {@code base}, or when {@code base}
* does not contain the specified method.
*/
public static boolean isOverridden(@NonNull Class<?> base, @NonNull Class<?> derived, @NonNull String methodName, @NonNull Class<?>... types) {
// If derived is not a subclass or implementor of base, it can't override any method
// Technically this should also be triggered when base == derived, because it can't override its own method, but
// the unit tests explicitly test for that as working.
if (!base.isAssignableFrom(derived)) {
throw new IllegalArgumentException("The specified derived class (" + derived.getCanonicalName() + ") does not derive from the specified base class (" + base.getCanonicalName() + ").");
}
final Method baseMethod = Util.getMethod(base, null, methodName, types);
if (baseMethod == null) {
throw new IllegalArgumentException("The specified method is not declared by the specified base class (" + base.getCanonicalName() + "), or it is private, static or final.");
}
final Method derivedMethod = Util.getMethod(derived, base, methodName, types);
// the lookup will either return null or the base method when no override has been found (depending on whether
// the base is an interface)
return derivedMethod != null && derivedMethod != baseMethod;
}
/**
* Calls the given supplier if the method defined on the base type with the given arguments is overridden in the
* given derived type.
*
* @param supplier The supplier to call if the method is indeed overridden.
* @param base The base type.
* @param derived The derived type.
* @param methodName The name of the method.
* @param types The types of the arguments for the method.
* @return {@code true} when {@code derived} provides the specified method other than as inherited from {@code base}.
* @throws IllegalArgumentException When {@code derived} does not derive from {@code base}, or when {@code base}
* does not contain the specified method.
* @throws AbstractMethodError If the derived class doesn't override the given method.
* @since 2.259
*/
public static <T> T ifOverridden(Supplier<T> supplier, @NonNull Class<?> base, @NonNull Class<?> derived, @NonNull String methodName, @NonNull Class<?>... types) {
if (isOverridden(base, derived, methodName, types)) {
return supplier.get();
} else {
throw new AbstractMethodError("The class " + derived.getName() + " must override at least one of the "
+ base.getSimpleName() + "." + methodName + " methods");
}
}
private static Method getMethod(@NonNull Class<?> clazz, @Nullable Class<?> base, @NonNull String methodName, @NonNull Class<?>... types) {
try {
final Method res = clazz.getDeclaredMethod(methodName, types);
final int mod = res.getModifiers();
// private and static methods are never ok, and end the search
if (Modifier.isPrivate(mod) || Modifier.isStatic(mod)) {
return null;
}
// when looking for the base/declaring method, final is not ok
if (base == null && Modifier.isFinal(mod)) {
return null;
}
// when looking for the overriding method, abstract is not ok
if (base != null && Modifier.isAbstract(mod)) {
return null;
}
return res;
} catch (NoSuchMethodException e) {
// If the base is an interface, the implementation may come from a default implementation on a derived
// interface. So look at interfaces too.
if (base != null && Modifier.isInterface(base.getModifiers())) {
for (Class<?> iface : clazz.getInterfaces()) {
if (base.equals(iface) || !base.isAssignableFrom(iface)) {
continue;
}
final Method defaultImpl = Util.getMethod(iface, base, methodName, types);
if (defaultImpl != null) {
return defaultImpl;
}
}
}
// Method not found in clazz, let's search in superclasses
Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
// if the superclass doesn't derive from base anymore (or IS base), stop looking
if (base != null && (base.equals(superclass) || !base.isAssignableFrom(superclass))) {
return null;
}
return getMethod(superclass, base, methodName, types);
}
return null;
} catch (SecurityException e) {
throw new AssertionError(e);
}
}
/**
* Returns a file name by changing its extension.
*
* @param ext
* For example, ".zip"
*/
@NonNull
public static File changeExtension(@NonNull File dst, @NonNull String ext) {
String p = dst.getPath();
int pos = p.lastIndexOf('.');
if (pos < 0) return new File(p + ext);
else return new File(p.substring(0, pos) + ext);
}
/**
* Null-safe String intern method.
* @return A canonical representation for the string object. Null for null input strings
*/
@Nullable
public static String intern(@CheckForNull String s) {
return s == null ? s : s.intern();
}
/**
* Return true if the systemId denotes an absolute URI .
*
* The same algorithm can be seen in {@link URI}, but
* implementing this by ourselves allow it to be more lenient about
* escaping of URI.
*
* @deprecated Use {@link #isSafeToRedirectTo} instead if your goal is to prevent open redirects
*/
@Deprecated
@RestrictedSince("1.651.2 / 2.3")
@Restricted(NoExternalUse.class)
public static boolean isAbsoluteUri(@NonNull String uri) {
int idx = uri.indexOf(':');
if (idx < 0) return false; // no ':'. can't be absolute
// #, ?, and / must not be before ':'
return idx < _indexOf(uri, '#') && idx < _indexOf(uri, '?') && idx < _indexOf(uri, '/');
}
/**
* Return true iff the parameter does not denote an absolute URI and not a scheme-relative URI.
* @since 2.3 / 1.651.2
*/
public static boolean isSafeToRedirectTo(@NonNull String uri) {
return !isAbsoluteUri(uri) && !uri.startsWith("//");
}
/**
* Works like {@link String#indexOf(int)} but 'not found' is returned as s.length(), not -1.
* This enables more straight-forward comparison.
*/
private static int _indexOf(@NonNull String s, char ch) {
int idx = s.indexOf(ch);
if (idx < 0) return s.length();
return idx;
}
/**
* Loads a key/value pair string as {@link Properties}
* @since 1.392
*/
@NonNull
public static Properties loadProperties(@NonNull String properties) throws IOException {
Properties p = new Properties();
p.load(new StringReader(properties));
return p;
}
/**
* Closes the item and logs error to the log in the case of error.
* Logging will be performed on the {@code WARNING} level.
* @param toClose Item to close. Nothing will happen if it is {@code null}
* @param logger Logger, which receives the error
* @param closeableName Name of the closeable item
* @param closeableOwner String representation of the closeable holder
* @since 2.19, but TODO update once un-restricted
*/
@Restricted(NoExternalUse.class)
public static void closeAndLogFailures(@CheckForNull Closeable toClose, @NonNull Logger logger,
@NonNull String closeableName, @NonNull String closeableOwner) {
if (toClose == null) {
return;
}
try {
toClose.close();
} catch (IOException ex) {
LogRecord record = new LogRecord(Level.WARNING, "Failed to close {0} of {1}");
record.setParameters(new Object[] { closeableName, closeableOwner });
record.setThrown(ex);
logger.log(record);
}
}
@Restricted(NoExternalUse.class)
public static int permissionsToMode(Set<PosixFilePermission> permissions) {
PosixFilePermission[] allPermissions = PosixFilePermission.values();
int result = 0;
for (PosixFilePermission allPermission : allPermissions) {
result <<= 1;
result |= permissions.contains(allPermission) ? 1 : 0;
}
return result;
}
@Restricted(NoExternalUse.class)
public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException {
// Anything larger is a file type, not a permission.
int PERMISSIONS_MASK = 07777;
// setgid/setuid/sticky are not supported.
int MAX_SUPPORTED_MODE = 0777;
mode = mode & PERMISSIONS_MASK;
if ((mode & MAX_SUPPORTED_MODE) != mode) {
throw new IOException("Invalid mode: " + mode);
}
PosixFilePermission[] allPermissions = PosixFilePermission.values();
Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class);
for (int i = 0; i < allPermissions.length; i++) {
if ((mode & 1) == 1) {
result.add(allPermissions[allPermissions.length - i - 1]);
}
mode >>= 1;
}
return result;
}
/**
* Converts a {@link File} into a {@link Path} and checks runtime exceptions.
* @throws IOException if {@code f.toPath()} throws {@link InvalidPathException}.
*/
@Restricted(NoExternalUse.class)
public static @NonNull Path fileToPath(@NonNull File file) throws IOException {
try {
return file.toPath();
} catch (InvalidPathException e) {
throw new IOException(e);
}
}
/**
* Create a directory by creating all nonexistent parent directories first.
*
* <p>Unlike {@link Files#createDirectory}, an exception is not thrown
* if the directory could not be created because it already exists.
* Unlike {@link Files#createDirectories}, an exception is not thrown
* if the directory (or one of its parents) is a symbolic link.
*
* <p>The {@code attrs} parameter contains optional {@link FileAttribute file attributes}
* to set atomically when creating the nonexistent directories.
* Each file attribute is identified by its {@link FileAttribute#name}.
* If more than one attribute of the same name is included in the array,
* then all but the last occurrence is ignored.
*
* <p>If this method fails,
* then it may do so after creating some, but not all, of the parent directories.
*
* @param dir The directory to create.
* @param attrs An optional list of file attributes to set atomically
* when creating the directory.
* @return The directory.
* @throws UnsupportedOperationException If the array contains an attribute
* that cannot be set atomically when creating the directory.
* @throws FileAlreadyExistsException If {@code dir} exists but is not a directory.
* @throws IOException If an I/O error occurs.
* @see Files#createDirectories(Path, FileAttribute[])
*/
@Restricted(NoExternalUse.class)
public static Path createDirectories(@NonNull Path dir, FileAttribute<?>... attrs) throws IOException {
dir = dir.toAbsolutePath();
Path parent;
for (parent = dir.getParent(); parent != null; parent = parent.getParent()) {
if (Files.exists(parent)) {
break;
}
}
if (parent == null) {
if (Files.isDirectory(dir)) {
return dir;
} else {
try {
return Files.createDirectory(dir, attrs);
} catch (FileAlreadyExistsException e) {
if (Files.isDirectory(dir)) {
// a concurrent caller won the race
return dir;
} else {
throw e;
}
}
}
}
Path child = parent;
for (Path name : parent.relativize(dir)) {
child = child.resolve(name);
if (!Files.isDirectory(child)) {
try {
Files.createDirectory(child, attrs);
} catch (FileAlreadyExistsException e) {
if (Files.isDirectory(child)) {
// a concurrent caller won the race
} else {
throw e;
}
}
}
}
return dir;
}
/**
* Compute the number of calendar days elapsed since the given date.
* As it's only the calendar days difference that matter, "11.00pm" to "2.00am the day after" returns 1,
* even if there are only 3 hours between. As well as "10am" to "2pm" both on the same day, returns 0.
*/
@Restricted(NoExternalUse.class)
public static long daysBetween(@NonNull Date a, @NonNull Date b) {
LocalDate aLocal = a.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate bLocal = b.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return ChronoUnit.DAYS.between(aLocal, bLocal);
}
/**
* @return positive number of days between the given date and now
* @see #daysBetween(Date, Date)
*/
@Restricted(NoExternalUse.class)
public static long daysElapsedSince(@NonNull Date date) {
return Math.max(0, daysBetween(date, new Date()));
}
/**
* Find the specific ancestor, or throw an exception.
* Useful for an ancestor we know is inside the URL to ease readability
*/
@Restricted(NoExternalUse.class)
public static @NonNull <T> T getNearestAncestorOfTypeOrThrow(@NonNull StaplerRequest request, @NonNull Class<T> clazz) {
T t = request.findAncestorObject(clazz);
if (t == null) {
throw new IllegalArgumentException("No ancestor of type " + clazz.getName() + " in the request");
}
return t;
}
@Restricted(NoExternalUse.class)
public static void printRedirect(String contextPath, String redirectUrl, String message, PrintWriter out) {
out.printf(
"<html><head>" +
"<meta http-equiv='refresh' content='1;url=%1$s'/>" +
"<script id='redirect' data-redirect-url='%1$s' src='" +
contextPath + Jenkins.RESOURCE_PATH +
"/scripts/redirect.js'></script>" +
"</head>" +
"<body style='background-color:white; color:white;'>%n" +
"%2$s%n" +
"<!--%n", Functions.htmlAttributeEscape(redirectUrl), message);
}
/**
* @deprecated use {@link #XS_DATETIME_FORMATTER2}
*/
@Deprecated
public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'", new SimpleTimeZone(0, "GMT"));
public static final DateTimeFormatter XS_DATETIME_FORMATTER2 =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);
// Note: RFC822 dates must not be localized!
/**
* @deprecated use {@link DateTimeFormatter#RFC_1123_DATE_TIME}
*/
@Deprecated
public static final FastDateFormat RFC822_DATETIME_FORMATTER
= FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
private static final Logger LOGGER = Logger.getLogger(Util.class.getName());
/**
* On Unix environment that cannot run "ln", set this to true.
*/
public static boolean NO_SYMLINK = SystemProperties.getBoolean(Util.class.getName() + ".noSymLink");
public static boolean SYMLINK_ESCAPEHATCH = SystemProperties.getBoolean(Util.class.getName() + ".symlinkEscapeHatch");
/**
* The number of additional times we will attempt to delete files/directory trees
* before giving up and throwing an exception.<br/>
* Specifying a value less than 0 is invalid and will be treated as if
* a value of 0 (i.e. one attempt, no retries) was specified.
* <p>
* e.g. if some of the child directories are big, it might take long enough
* to delete that it allows others to create new files in the directory we
* are trying to empty, causing problems like JENKINS-10113.
* Or, if we're on Windows, then deletes can fail for transient reasons
* regardless of external activity; see JENKINS-15331.
* Whatever the reason, this allows us to do multiple attempts before we
* give up, thus improving build reliability.
*/
@Restricted(value = NoExternalUse.class)
static int DELETION_RETRIES = Math.max(0, SystemProperties.getInteger(Util.class.getName() + ".maxFileDeletionRetries", 2));
/**
* The time (in milliseconds) that we will wait between attempts to
* delete files when retrying.<br>
* This has no effect unless {@link #DELETION_RETRIES} is non-zero.
* <p>
* If zero, we will not delay between attempts.<br>
* If negative, we will wait an (linearly) increasing multiple of this value
* between attempts.
*/
@Restricted(value = NoExternalUse.class)
static int WAIT_BETWEEN_DELETION_RETRIES = SystemProperties.getInteger(Util.class.getName() + ".deletionRetryWait", 100);
/**
* If this flag is set to true then we will request a garbage collection
* after a deletion failure before we next retry the delete.<br>
* It defaults to {@code false} and is ignored unless
* {@link #DELETION_RETRIES} is non zero.
* <p>
* Setting this flag to true <i>may</i> resolve some problems on Windows,
* and also for directory trees residing on an NFS share, <b>but</b> it can
* have a negative impact on performance and may have no effect at all (GC
* behavior is JVM-specific).
* <p>
* Warning: This should only ever be used if you find that your builds are
* failing because Jenkins is unable to delete files, that this failure is
* because Jenkins itself has those files locked "open", and even then it
* should only be used on agents with relatively few executors (because the
* garbage collection can impact the performance of all job executors on
* that agent).<br/>
* i.e. Setting this flag is a act of last resort - it is <em>not</em>
* recommended, and should not be used on the main Jenkins server
* unless you can tolerate the performance impact.
*/
@Restricted(value = NoExternalUse.class)
static boolean GC_AFTER_FAILED_DELETE = SystemProperties.getBoolean(Util.class.getName() + ".performGCOnFailedDelete");
private static PathRemover newPathRemover(@NonNull PathRemover.PathChecker pathChecker) {
return PathRemover.newFilteredRobustRemover(pathChecker, DELETION_RETRIES, GC_AFTER_FAILED_DELETE, WAIT_BETWEEN_DELETION_RETRIES);
}
/**
* Returns SHA-256 Digest of input bytes
*/
@Restricted(NoExternalUse.class)
public static byte[] getSHA256DigestOf(@NonNull byte[] input) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(input);
return messageDigest.digest();
} catch (NoSuchAlgorithmException noSuchAlgorithmException) {
throw new IllegalStateException("SHA-256 could not be instantiated, but is required to" +
" be implemented by the language specification", noSuchAlgorithmException);
}
}
/**
* Returns Hex string of SHA-256 Digest of passed input
*/
@Restricted(NoExternalUse.class)
public static String getHexOfSHA256DigestOf(byte[] input) throws IOException {
//get hex string of sha 256 of payload
byte[] payloadDigest = Util.getSHA256DigestOf(input);
return (payloadDigest != null) ? Util.toHexString(payloadDigest) : null;
}
}
| Dohbedoh/jenkins | core/src/main/java/hudson/Util.java |
670 | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.cache;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.cache.CacheBuilder.NULL_TICKER;
import static com.google.common.cache.CacheBuilder.UNSET_INT;
import static com.google.common.util.concurrent.Futures.transform;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.util.Collections.unmodifiableSet;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.cache.CacheBuilder.NullListener;
import com.google.common.cache.CacheBuilder.OneWeigher;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.cache.CacheLoader.UnsupportedLoadingOperationException;
import com.google.common.cache.LocalCache.AbstractCacheSet;
import com.google.common.collect.AbstractSequentialIterator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractQueue;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* The concurrent hash map implementation built by {@link CacheBuilder}.
*
* <p>This implementation is heavily derived from revision 1.96 of <a
* href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>.
*
* @author Charles Fry
* @author Bob Lee ({@code com.google.common.collect.MapMaker})
* @author Doug Lea ({@code ConcurrentHashMap})
*/
@SuppressWarnings({
"GoodTime", // lots of violations (nanosecond math)
"nullness", // too much trouble for the payoff
})
@GwtCompatible(emulated = true)
// TODO(cpovirk): Annotate for nullness.
class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> {
/*
* The basic strategy is to subdivide the table among Segments, each of which itself is a
* concurrently readable hash table. The map supports non-blocking reads and concurrent writes
* across different segments.
*
* If a maximum size is specified, a best-effort bounding is performed per segment, using a
* page-replacement algorithm to determine which entries to evict when the capacity has been
* exceeded.
*
* The page replacement algorithm's data structures are kept casually consistent with the map. The
* ordering of writes to a segment is sequentially consistent. An update to the map and recording
* of reads may not be immediately reflected on the algorithm's data structures. These structures
* are guarded by a lock and operations are applied in batches to avoid lock contention. The
* penalty of applying the batches is spread across threads so that the amortized cost is slightly
* higher than performing just the operation without enforcing the capacity constraint.
*
* This implementation uses a per-segment queue to record a memento of the additions, removals,
* and accesses that were performed on the map. The queue is drained on writes and when it exceeds
* its capacity threshold.
*
* The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit
* rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation
* operates per-segment rather than globally for increased implementation simplicity. We expect
* the cache hit rate to be similar to that of a global LRU algorithm.
*/
// Constants
/**
* The maximum capacity, used if a higher value is implicitly specified by either of the
* constructors with arguments. MUST be a power of two {@code <= 1<<30} to ensure that entries are
* indexable using ints.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/** The maximum number of segments to allow; used to bound constructor arguments. */
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
/** Number of (unsynchronized) retries in the containsValue method. */
static final int CONTAINS_VALUE_RETRIES = 3;
/**
* Number of cache access operations that can be buffered per segment before the cache's recency
* ordering information is updated. This is used to avoid lock contention by recording a memento
* of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs.
*
* <p>This must be a (2^n)-1 as it is used as a mask.
*/
static final int DRAIN_THRESHOLD = 0x3F;
/**
* Maximum number of entries to be drained in a single cleanup run. This applies independently to
* the cleanup queue and both reference queues.
*/
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
// Fields
static final Logger logger = Logger.getLogger(LocalCache.class.getName());
/**
* Mask value for indexing into segments. The upper bits of a key's hash code are used to choose
* the segment.
*/
final int segmentMask;
/**
* Shift value for indexing within segments. Helps prevent entries that end up in the same segment
* from also ending up in the same bucket.
*/
final int segmentShift;
/** The segments, each of which is a specialized hash table. */
final Segment<K, V>[] segments;
/** The concurrency level. */
final int concurrencyLevel;
/** Strategy for comparing keys. */
final Equivalence<Object> keyEquivalence;
/** Strategy for comparing values. */
final Equivalence<Object> valueEquivalence;
/** Strategy for referencing keys. */
final Strength keyStrength;
/** Strategy for referencing values. */
final Strength valueStrength;
/** The maximum weight of this map. UNSET_INT if there is no maximum. */
final long maxWeight;
/** Weigher to weigh cache entries. */
final Weigher<K, V> weigher;
/** How long after the last access to an entry the map will retain that entry. */
final long expireAfterAccessNanos;
/** How long after the last write to an entry the map will retain that entry. */
final long expireAfterWriteNanos;
/** How long after the last write an entry becomes a candidate for refresh. */
final long refreshNanos;
/** Entries waiting to be consumed by the removal listener. */
// TODO(fry): define a new type which creates event objects and automates the clear logic
final Queue<RemovalNotification<K, V>> removalNotificationQueue;
/**
* A listener that is invoked when an entry is removed due to expiration or garbage collection of
* soft/weak entries.
*/
final RemovalListener<K, V> removalListener;
/** Measures time in a testable way. */
final Ticker ticker;
/** Factory used to create new entries. */
final EntryFactory entryFactory;
/**
* Accumulates global cache statistics. Note that there are also per-segments stats counters which
* must be aggregated to obtain a global stats view.
*/
final StatsCounter globalStatsCounter;
/** The default cache loader to use on loading operations. */
@CheckForNull final CacheLoader<? super K, V> defaultLoader;
/**
* Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
*/
LocalCache(
CacheBuilder<? super K, ? super V> builder, @CheckForNull CacheLoader<? super K, V> loader) {
concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS);
keyStrength = builder.getKeyStrength();
valueStrength = builder.getValueStrength();
keyEquivalence = builder.getKeyEquivalence();
valueEquivalence = builder.getValueEquivalence();
maxWeight = builder.getMaximumWeight();
weigher = builder.getWeigher();
expireAfterAccessNanos = builder.getExpireAfterAccessNanos();
expireAfterWriteNanos = builder.getExpireAfterWriteNanos();
refreshNanos = builder.getRefreshNanos();
removalListener = builder.getRemovalListener();
removalNotificationQueue =
(removalListener == NullListener.INSTANCE)
? LocalCache.discardingQueue()
: new ConcurrentLinkedQueue<>();
ticker = builder.getTicker(recordsTime());
entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries());
globalStatsCounter = builder.getStatsCounterSupplier().get();
defaultLoader = loader;
int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY);
if (evictsBySize() && !customWeigher()) {
initialCapacity = (int) Math.min(initialCapacity, maxWeight);
}
// Find the lowest power-of-two segmentCount that exceeds concurrencyLevel, unless
// maximumSize/Weight is specified in which case ensure that each segment gets at least 10
// entries. The special casing for size-based eviction is only necessary because that eviction
// happens per segment instead of globally, so too many segments compared to the maximum size
// will result in random eviction behavior.
int segmentShift = 0;
int segmentCount = 1;
while (segmentCount < concurrencyLevel
&& (!evictsBySize() || segmentCount * 20L <= maxWeight)) {
++segmentShift;
segmentCount <<= 1;
}
this.segmentShift = 32 - segmentShift;
segmentMask = segmentCount - 1;
this.segments = newSegmentArray(segmentCount);
int segmentCapacity = initialCapacity / segmentCount;
if (segmentCapacity * segmentCount < initialCapacity) {
++segmentCapacity;
}
int segmentSize = 1;
while (segmentSize < segmentCapacity) {
segmentSize <<= 1;
}
if (evictsBySize()) {
// Ensure sum of segment max weights = overall max weights
long maxSegmentWeight = maxWeight / segmentCount + 1;
long remainder = maxWeight % segmentCount;
for (int i = 0; i < this.segments.length; ++i) {
if (i == remainder) {
maxSegmentWeight--;
}
this.segments[i] =
createSegment(segmentSize, maxSegmentWeight, builder.getStatsCounterSupplier().get());
}
} else {
for (int i = 0; i < this.segments.length; ++i) {
this.segments[i] =
createSegment(segmentSize, UNSET_INT, builder.getStatsCounterSupplier().get());
}
}
}
boolean evictsBySize() {
return maxWeight >= 0;
}
boolean customWeigher() {
return weigher != OneWeigher.INSTANCE;
}
boolean expires() {
return expiresAfterWrite() || expiresAfterAccess();
}
boolean expiresAfterWrite() {
return expireAfterWriteNanos > 0;
}
boolean expiresAfterAccess() {
return expireAfterAccessNanos > 0;
}
boolean refreshes() {
return refreshNanos > 0;
}
boolean usesAccessQueue() {
return expiresAfterAccess() || evictsBySize();
}
boolean usesWriteQueue() {
return expiresAfterWrite();
}
boolean recordsWrite() {
return expiresAfterWrite() || refreshes();
}
boolean recordsAccess() {
return expiresAfterAccess();
}
boolean recordsTime() {
return recordsWrite() || recordsAccess();
}
boolean usesWriteEntries() {
return usesWriteQueue() || recordsWrite();
}
boolean usesAccessEntries() {
return usesAccessQueue() || recordsAccess();
}
boolean usesKeyReferences() {
return keyStrength != Strength.STRONG;
}
boolean usesValueReferences() {
return valueStrength != Strength.STRONG;
}
enum Strength {
/*
* TODO(kevinb): If we strongly reference the value and aren't loading, we needn't wrap the
* value. This could save ~8 bytes per entry.
*/
STRONG {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new StrongValueReference<K, V>(value)
: new WeightedStrongValueReference<K, V>(value, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.equals();
}
},
SOFT {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry)
: new WeightedSoftValueReference<K, V>(
segment.valueReferenceQueue, value, entry, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
},
WEAK {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry)
: new WeightedWeakValueReference<K, V>(
segment.valueReferenceQueue, value, entry, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
};
/** Creates a reference for the given value according to this value strength. */
abstract <K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight);
/**
* Returns the default equivalence strategy used to compare and hash keys or values referenced
* at this strength. This strategy will be used unless the user explicitly specifies an
* alternate strategy.
*/
abstract Equivalence<Object> defaultEquivalence();
}
/** Creates new entries. */
enum EntryFactory {
STRONG {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongEntry<>(key, hash, next);
}
},
STRONG_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongAccessEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
},
STRONG_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongWriteEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
STRONG_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongAccessWriteEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
WEAK {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakEntry<>(segment.keyReferenceQueue, key, hash, next);
}
},
WEAK_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakAccessEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
},
WEAK_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakWriteEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
WEAK_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakAccessWriteEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
}
};
// Masks used to compute indices in the following table.
static final int ACCESS_MASK = 1;
static final int WRITE_MASK = 2;
static final int WEAK_MASK = 4;
/** Look-up table for factories. */
static final EntryFactory[] factories = {
STRONG,
STRONG_ACCESS,
STRONG_WRITE,
STRONG_ACCESS_WRITE,
WEAK,
WEAK_ACCESS,
WEAK_WRITE,
WEAK_ACCESS_WRITE,
};
static EntryFactory getFactory(
Strength keyStrength, boolean usesAccessQueue, boolean usesWriteQueue) {
int flags =
((keyStrength == Strength.WEAK) ? WEAK_MASK : 0)
| (usesAccessQueue ? ACCESS_MASK : 0)
| (usesWriteQueue ? WRITE_MASK : 0);
return factories[flags];
}
/**
* Creates a new entry.
*
* @param segment to create the entry for
* @param key of the entry
* @param hash of the key
* @param next entry in the same bucket
*/
abstract <K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next);
/**
* Copies an entry, assigning it a new {@code next} entry.
*
* @param original the entry to copy. But avoid calling {@code getKey} on it: Instead, use the
* {@code key} parameter. That way, we prevent the key from being garbage collected in the
* case of weak keys. If we create a new entry with a key that is null at construction time,
* we're not sure if entry will necessarily ever be garbage collected.
* @param newNext entry in the same bucket
* @param key the key to copy from the original entry to the new one. Use this in preference to
* {@code original.getKey()}.
*/
// Guarded By Segment.this
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) {
return newEntry(segment, key, original.getHash(), newNext);
}
// Guarded By Segment.this
<K, V> void copyAccessEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectAccessOrder, nullifyAccessOrder.
newEntry.setAccessTime(original.getAccessTime());
connectAccessOrder(original.getPreviousInAccessQueue(), newEntry);
connectAccessOrder(newEntry, original.getNextInAccessQueue());
nullifyAccessOrder(original);
}
// Guarded By Segment.this
<K, V> void copyWriteEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectWriteOrder, nullifyWriteOrder.
newEntry.setWriteTime(original.getWriteTime());
connectWriteOrder(original.getPreviousInWriteQueue(), newEntry);
connectWriteOrder(newEntry, original.getNextInWriteQueue());
nullifyWriteOrder(original);
}
}
/** A reference to a value. */
interface ValueReference<K, V> {
/** Returns the value. Does not block or throw exceptions. */
@CheckForNull
V get();
/**
* Waits for a value that may still be loading. Unlike get(), this method can block (in the case
* of FutureValueReference).
*
* @throws ExecutionException if the loading thread throws an exception
* @throws ExecutionError if the loading thread throws an error
*/
V waitForValue() throws ExecutionException;
/** Returns the weight of this entry. This is assumed to be static between calls to setValue. */
int getWeight();
/**
* Returns the entry associated with this value reference, or {@code null} if this value
* reference is independent of any entry.
*/
@CheckForNull
ReferenceEntry<K, V> getEntry();
/**
* Creates a copy of this reference for the given entry.
*
* <p>{@code value} may be null only for a loading reference.
*/
ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry);
/**
* Notify pending loads that a new value was set. This is only relevant to loading value
* references.
*/
void notifyNewValue(@CheckForNull V newValue);
/**
* Returns true if a new value is currently loading, regardless of whether there is an existing
* value. It is assumed that the return value of this method is constant for any given
* ValueReference instance.
*/
boolean isLoading();
/**
* Returns true if this reference contains an active value, meaning one that is still considered
* present in the cache. Active values consist of live values, which are returned by cache
* lookups, and dead values, which have been evicted but awaiting removal. Non-active values
* consist strictly of loading values, though during refresh a value may be both active and
* loading.
*/
boolean isActive();
}
/** Placeholder. Indicates that the value hasn't been set yet. */
static final ValueReference<Object, Object> UNSET =
new ValueReference<Object, Object>() {
@CheckForNull
@Override
public Object get() {
return null;
}
@Override
public int getWeight() {
return 0;
}
@CheckForNull
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
}
@Override
public ValueReference<Object, Object> copyFor(
ReferenceQueue<Object> queue,
@CheckForNull Object value,
ReferenceEntry<Object, Object> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return false;
}
@CheckForNull
@Override
public Object waitForValue() {
return null;
}
@Override
public void notifyNewValue(Object newValue) {}
};
/** Singleton placeholder that indicates a value is being loaded. */
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ValueReference<K, V> unset() {
return (ValueReference<K, V>) UNSET;
}
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
@CheckForNull
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
}
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
@CheckForNull
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
}
@Override
public int getHash() {
return 0;
}
@CheckForNull
@Override
public Object getKey() {
return null;
}
@Override
public long getAccessTime() {
return 0;
}
@Override
public void setAccessTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextInAccessQueue() {
return this;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousInAccessQueue() {
return this;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<Object, Object> previous) {}
@Override
public long getWriteTime() {
return 0;
}
@Override
public void setWriteTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextInWriteQueue() {
return this;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousInWriteQueue() {
return this;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<Object, Object> previous) {}
}
abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> {
@Override
public ValueReference<K, V> getValueReference() {
throw new UnsupportedOperationException();
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNext() {
throw new UnsupportedOperationException();
}
@Override
public int getHash() {
throw new UnsupportedOperationException();
}
@Override
public K getKey() {
throw new UnsupportedOperationException();
}
@Override
public long getAccessTime() {
throw new UnsupportedOperationException();
}
@Override
public void setAccessTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
@Override
public long getWriteTime() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ReferenceEntry<K, V> nullEntry() {
return (ReferenceEntry<K, V>) NullEntry.INSTANCE;
}
static final Queue<?> DISCARDING_QUEUE =
new AbstractQueue<Object>() {
@Override
public boolean offer(Object o) {
return true;
}
@CheckForNull
@Override
public Object peek() {
return null;
}
@CheckForNull
@Override
public Object poll() {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Object> iterator() {
return ImmutableSet.of().iterator();
}
};
/** Queue that discards all elements. */
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <E> Queue<E> discardingQueue() {
return (Queue) DISCARDING_QUEUE;
}
/*
* Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins!
* To maintain this code, make a change for the strong reference type. Then, cut and paste, and
* replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that
* strong entries store the key reference directly while soft and weak entries delegate to their
* respective superclasses.
*/
/** Used for strongly-referenced keys. */
static class StrongEntry<K, V> extends AbstractReferenceEntry<K, V> {
final K key;
StrongEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
this.key = key;
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return this.key;
}
// The code below is exactly the same for each entry type.
final int hash;
@CheckForNull final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
this.valueReference = valueReference;
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class StrongAccessEntry<K, V> extends StrongEntry<K, V> {
StrongAccessEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
}
static final class StrongWriteEntry<K, V> extends StrongEntry<K, V> {
StrongWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
static final class StrongAccessWriteEntry<K, V> extends StrongEntry<K, V> {
StrongAccessWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
/** Used for weakly-referenced keys. */
static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> {
WeakEntry(ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
/*
* It'd be nice to get these for free from AbstractReferenceEntry, but we're already extending
* WeakReference<K>.
*/
// null access
@Override
public long getAccessTime() {
throw new UnsupportedOperationException();
}
@Override
public void setAccessTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null write
@Override
public long getWriteTime() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
@CheckForNull final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
this.valueReference = valueReference;
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class WeakAccessEntry<K, V> extends WeakEntry<K, V> {
WeakAccessEntry(
ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
}
static final class WeakWriteEntry<K, V> extends WeakEntry<K, V> {
WeakWriteEntry(
ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
static final class WeakAccessWriteEntry<K, V> extends WeakEntry<K, V> {
WeakAccessWriteEntry(
ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
/** References a weak value. */
static class WeakValueReference<K, V> extends WeakReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void notifyNewValue(V newValue) {}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeakValueReference<>(queue, value, entry);
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
}
/** References a soft value. */
static class SoftValueReference<K, V> extends SoftReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void notifyNewValue(V newValue) {}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new SoftValueReference<>(queue, value, entry);
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
}
/** References a strong value. */
static class StrongValueReference<K, V> implements ValueReference<K, V> {
final V referent;
StrongValueReference(V referent) {
this.referent = referent;
}
@Override
public V get() {
return referent;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void notifyNewValue(V newValue) {}
}
/** References a weak value. */
static final class WeightedWeakValueReference<K, V> extends WeakValueReference<K, V> {
final int weight;
WeightedWeakValueReference(
ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedWeakValueReference<>(queue, value, entry, weight);
}
}
/** References a soft value. */
static final class WeightedSoftValueReference<K, V> extends SoftValueReference<K, V> {
final int weight;
WeightedSoftValueReference(
ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedSoftValueReference<>(queue, value, entry, weight);
}
}
/** References a strong value. */
static final class WeightedStrongValueReference<K, V> extends StrongValueReference<K, V> {
final int weight;
WeightedStrongValueReference(V referent, int weight) {
super(referent);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
}
/**
* Applies a supplemental hash function to a given hash code, which defends against poor quality
* hash functions. This is critical when the concurrent hash map uses power-of-two length hash
* tables, that otherwise encounter collisions for hash codes that do not differ in lower or upper
* bits.
*
* @param h hash code
*/
static int rehash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
// TODO(kevinb): use Hashing/move this to Hashing?
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#newEntry} directly.
*/
@VisibleForTesting
ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
Segment<K, V> segment = segmentFor(hash);
segment.lock();
try {
return segment.newEntry(key, hash, next);
} finally {
segment.unlock();
}
}
/**
* This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly.
*/
// Guarded By Segment.this
@SuppressWarnings("GuardedBy")
@VisibleForTesting
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
int hash = original.getHash();
return segmentFor(hash).copyEntry(original, newNext);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#setValue} instead.
*/
// Guarded By Segment.this
@VisibleForTesting
ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value, int weight) {
int hash = entry.getHash();
return valueStrength.referenceValue(segmentFor(hash), entry, checkNotNull(value), weight);
}
int hash(@CheckForNull Object key) {
int h = keyEquivalence.hash(key);
return rehash(h);
}
void reclaimValue(ValueReference<K, V> valueReference) {
ReferenceEntry<K, V> entry = valueReference.getEntry();
int hash = entry.getHash();
segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference);
}
void reclaimKey(ReferenceEntry<K, V> entry) {
int hash = entry.getHash();
segmentFor(hash).reclaimKey(entry, hash);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#getLiveValue}
* instead.
*/
@VisibleForTesting
boolean isLive(ReferenceEntry<K, V> entry, long now) {
return segmentFor(entry.getHash()).getLiveValue(entry, now) != null;
}
/**
* Returns the segment that should be used for a key with the given hash.
*
* @param hash the hash code for the key
* @return the segment
*/
Segment<K, V> segmentFor(int hash) {
// TODO(fry): Lazily create segments?
return segments[(hash >>> segmentShift) & segmentMask];
}
Segment<K, V> createSegment(
int initialCapacity, long maxSegmentWeight, StatsCounter statsCounter) {
return new Segment<>(this, initialCapacity, maxSegmentWeight, statsCounter);
}
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
* loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean
* up stale entries. As such it should only be called outside a segment context, such as during
* iteration.
*/
@CheckForNull
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
return null;
}
if (isExpired(entry, now)) {
return null;
}
return value;
}
// expiration
/** Returns true if the entry has expired. */
boolean isExpired(ReferenceEntry<K, V> entry, long now) {
checkNotNull(entry);
if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) {
return true;
}
if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) {
return true;
}
return false;
}
// queues
// Guarded By Segment.this
static <K, V> void connectAccessOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextInAccessQueue(next);
next.setPreviousInAccessQueue(previous);
}
// Guarded By Segment.this
static <K, V> void nullifyAccessOrder(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextInAccessQueue(nullEntry);
nulled.setPreviousInAccessQueue(nullEntry);
}
// Guarded By Segment.this
static <K, V> void connectWriteOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextInWriteQueue(next);
next.setPreviousInWriteQueue(previous);
}
// Guarded By Segment.this
static <K, V> void nullifyWriteOrder(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextInWriteQueue(nullEntry);
nulled.setPreviousInWriteQueue(nullEntry);
}
/**
* Notifies listeners that an entry has been automatically removed due to expiration, eviction, or
* eligibility for garbage collection. This should be called every time expireEntries or
* evictEntry is called (once the lock is released).
*/
void processPendingNotifications() {
RemovalNotification<K, V> notification;
while ((notification = removalNotificationQueue.poll()) != null) {
try {
removalListener.onRemoval(notification);
} catch (Throwable e) {
logger.log(Level.WARNING, "Exception thrown by removal listener", e);
}
}
}
@SuppressWarnings("unchecked")
final Segment<K, V>[] newSegmentArray(int ssize) {
return (Segment<K, V>[]) new Segment<?, ?>[ssize];
}
// Inner Classes
/**
* Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock
* opportunistically, just to simplify some locking and avoid separate construction.
*/
@SuppressWarnings("serial") // This class is never serialized.
static class Segment<K, V> extends ReentrantLock {
/*
* TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class.
* It will require more memory but will reduce indirection.
*/
/*
* Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can
* be read without locking. Next fields of nodes are immutable (final). All list additions are
* performed at the front of each bin. This makes it easy to check changes, and also fast to
* traverse. When nodes would otherwise be changed, new nodes are created to replace them. This
* works well for hash tables since the bin lists tend to be short. (The average length is less
* than two.)
*
* Read operations can thus proceed without locking, but rely on selected uses of volatiles to
* ensure that completed write operations performed by other threads are noticed. For most
* purposes, the "count" field, tracking the number of elements, serves as that volatile
* variable ensuring visibility. This is convenient because this field needs to be read in many
* read operations anyway:
*
* - All (unsynchronized) read operations must first read the "count" field, and should not look
* at table entries if it is 0.
*
* - All (synchronized) write operations should write to the "count" field after structurally
* changing any bin. The operations must not take any action that could even momentarily cause a
* concurrent read operation to see inconsistent data. This is made easier by the nature of the
* read operations in Map. For example, no operation can reveal that the table has grown but the
* threshold has not yet been updated, so there are no atomicity requirements for this with
* respect to reads.
*
* As a guide, all critical volatile reads and writes to the count field are marked in code
* comments.
*/
@Weak final LocalCache<K, V> map;
/** The number of live elements in this segment's region. */
volatile int count;
/** The weight of the live elements in this segment's region. */
@GuardedBy("this")
long totalWeight;
/**
* Number of updates that alter the size of the table. This is used during bulk-read methods to
* make sure they see a consistent snapshot: If modCounts change during a traversal of segments
* loading size or checking containsValue, then we might have an inconsistent view of state so
* (usually) must retry.
*/
int modCount;
/**
* The table is expanded when its size exceeds this threshold. (The value of this field is
* always {@code (int) (capacity * 0.75)}.)
*/
int threshold;
/** The per-segment table. */
@CheckForNull volatile AtomicReferenceArray<ReferenceEntry<K, V>> table;
/** The maximum weight of this segment. UNSET_INT if there is no maximum. */
final long maxSegmentWeight;
/**
* The key reference queue contains entries whose keys have been garbage collected, and which
* need to be cleaned up internally.
*/
@CheckForNull final ReferenceQueue<K> keyReferenceQueue;
/**
* The value reference queue contains value references whose values have been garbage collected,
* and which need to be cleaned up internally.
*/
@CheckForNull final ReferenceQueue<V> valueReferenceQueue;
/**
* The recency queue is used to record which entries were accessed for updating the access
* list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is
* crossed or a write occurs on the segment.
*/
final Queue<ReferenceEntry<K, V>> recencyQueue;
/**
* A counter of the number of reads since the last write, used to drain queues on a small
* fraction of read operations.
*/
final AtomicInteger readCount = new AtomicInteger();
/**
* A queue of elements currently in the map, ordered by write time. Elements are added to the
* tail of the queue on write.
*/
@GuardedBy("this")
final Queue<ReferenceEntry<K, V>> writeQueue;
/**
* A queue of elements currently in the map, ordered by access time. Elements are added to the
* tail of the queue on access (note that writes count as accesses).
*/
@GuardedBy("this")
final Queue<ReferenceEntry<K, V>> accessQueue;
/** Accumulates cache statistics. */
final StatsCounter statsCounter;
Segment(
LocalCache<K, V> map,
int initialCapacity,
long maxSegmentWeight,
StatsCounter statsCounter) {
this.map = map;
this.maxSegmentWeight = maxSegmentWeight;
this.statsCounter = checkNotNull(statsCounter);
initTable(newEntryArray(initialCapacity));
keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null;
valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null;
recencyQueue =
map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue();
writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue();
accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
return new AtomicReferenceArray<>(size);
}
void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
if (!map.customWeigher() && this.threshold == maxSegmentWeight) {
// prevent spurious expansion before eviction
this.threshold++;
}
this.table = newTable;
}
@GuardedBy("this")
ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return map.entryFactory.newEntry(this, checkNotNull(key), hash, next);
}
/**
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
@CheckForNull
@GuardedBy("this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
K key = original.getKey();
if (key == null) {
// key collected
return null;
}
ValueReference<K, V> valueReference = original.getValueReference();
V value = valueReference.get();
if ((value == null) && valueReference.isActive()) {
// value collected
return null;
}
ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext, key);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
/** Sets a new value of an entry. Adds newly created entries at the end of the access queue. */
@GuardedBy("this")
void setValue(ReferenceEntry<K, V> entry, K key, V value, long now) {
ValueReference<K, V> previous = entry.getValueReference();
int weight = map.weigher.weigh(key, value);
checkState(weight >= 0, "Weights must be non-negative");
ValueReference<K, V> valueReference =
map.valueStrength.referenceValue(this, entry, value, weight);
entry.setValueReference(valueReference);
recordWrite(entry, weight, now);
previous.notifyNewValue(value);
}
// loading
@CanIgnoreReturnValue
V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
checkNotNull(key);
checkNotNull(loader);
try {
if (count != 0) { // read-volatile
// don't call getLiveEntry, which would ignore loading values
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e != null) {
long now = map.ticker.read();
V value = getLiveValue(e, now);
if (value != null) {
recordRead(e, now);
statsCounter.recordHits(1);
return scheduleRefresh(e, key, hash, value, now, loader);
}
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isLoading()) {
return waitForLoadingValue(e, key, valueReference);
}
}
}
// at this point e is either null or expired;
return lockedGetOrLoad(key, hash, loader);
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
} else if (cause instanceof RuntimeException) {
throw new UncheckedExecutionException(cause);
}
throw ee;
} finally {
postReadCleanup();
}
}
@CheckForNull
V get(Object key, int hash) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
ReferenceEntry<K, V> e = getLiveEntry(key, hash, now);
if (e == null) {
return null;
}
V value = e.getValueReference().get();
if (value != null) {
recordRead(e, now);
return scheduleRefresh(e, e.getKey(), hash, value, now, map.defaultLoader);
}
tryDrainReferenceQueues();
}
return null;
} finally {
postReadCleanup();
}
}
V lockedGetOrLoad(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
ReferenceEntry<K, V> e;
ValueReference<K, V> valueReference = null;
LoadingValueReference<K, V> loadingValueReference = null;
boolean createNewEntry = true;
lock();
try {
// re-read ticker once inside the lock
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
valueReference = e.getValueReference();
if (valueReference.isLoading()) {
createNewEntry = false;
} else {
V value = valueReference.get();
if (value == null) {
enqueueNotification(
entryKey, hash, value, valueReference.getWeight(), RemovalCause.COLLECTED);
} else if (map.isExpired(e, now)) {
// This is a duplicate check, as preWriteCleanup already purged expired
// entries, but let's accommodate an incorrect expiration queue.
enqueueNotification(
entryKey, hash, value, valueReference.getWeight(), RemovalCause.EXPIRED);
} else {
recordLockedRead(e, now);
statsCounter.recordHits(1);
// we were concurrent with loading; don't consider refresh
return value;
}
// immediately reuse invalid entries
writeQueue.remove(e);
accessQueue.remove(e);
this.count = newCount; // write-volatile
}
break;
}
}
if (createNewEntry) {
loadingValueReference = new LoadingValueReference<>();
if (e == null) {
e = newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
} else {
e.setValueReference(loadingValueReference);
}
}
} finally {
unlock();
postWriteCleanup();
}
if (createNewEntry) {
try {
// Synchronizes on the entry to allow failing fast when a recursive load is
// detected. This may be circumvented when an entry is copied, but will fail fast most
// of the time.
synchronized (e) {
return loadSync(key, hash, loadingValueReference, loader);
}
} finally {
statsCounter.recordMisses(1);
}
} else {
// The entry already exists. Wait for loading.
return waitForLoadingValue(e, key, valueReference);
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference)
throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
// at most one of loadSync/loadAsync may be called for any given LoadingValueReference
V loadSync(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
CacheLoader<? super K, V> loader)
throws ExecutionException {
ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
return getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
}
ListenableFuture<V> loadAsync(
final K key,
final int hash,
final LoadingValueReference<K, V> loadingValueReference,
CacheLoader<? super K, V> loader) {
final ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
loadingFuture.addListener(
() -> {
try {
getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
} catch (Throwable t) {
logger.log(Level.WARNING, "Exception thrown during refresh", t);
loadingValueReference.setException(t);
}
},
directExecutor());
return loadingFuture;
}
/** Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats. */
@CanIgnoreReturnValue
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue)
throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V scheduleRefresh(
ReferenceEntry<K, V> entry,
K key,
int hash,
V oldValue,
long now,
CacheLoader<? super K, V> loader) {
if (map.refreshes()
&& (now - entry.getWriteTime() > map.refreshNanos)
&& !entry.getValueReference().isLoading()) {
V newValue = refresh(key, hash, loader, true);
if (newValue != null) {
return newValue;
}
}
return oldValue;
}
/**
* Refreshes the value associated with {@code key}, unless another thread is already doing so.
* Returns the newly refreshed value associated with {@code key} if it was refreshed inline, or
* {@code null} if another thread is performing the refresh or if an error occurs during
* refresh.
*/
@CanIgnoreReturnValue
@CheckForNull
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
final LoadingValueReference<K, V> loadingValueReference =
insertLoadingValueReference(key, hash, checkTime);
if (loadingValueReference == null) {
return null;
}
ListenableFuture<V> result = loadAsync(key, hash, loadingValueReference, loader);
if (result.isDone()) {
try {
return Uninterruptibles.getUninterruptibly(result);
} catch (Throwable t) {
// don't let refresh exceptions propagate; error was already logged
}
}
return null;
}
/**
* Returns a newly inserted {@code LoadingValueReference}, or null if the live value reference
* is already loading.
*/
@CheckForNull
LoadingValueReference<K, V> insertLoadingValueReference(
final K key, final int hash, boolean checkTime) {
ReferenceEntry<K, V> e = null;
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isLoading()
|| (checkTime && (now - e.getWriteTime() < map.refreshNanos))) {
// refresh is a no-op if loading is pending
// if checkTime, we want to check *after* acquiring the lock if refresh still needs
// to be scheduled
return null;
}
// continue returning old value while loading
++modCount;
LoadingValueReference<K, V> loadingValueReference =
new LoadingValueReference<>(valueReference);
e.setValueReference(loadingValueReference);
return loadingValueReference;
}
}
++modCount;
LoadingValueReference<K, V> loadingValueReference = new LoadingValueReference<>();
e = newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
return loadingValueReference;
} finally {
unlock();
postWriteCleanup();
}
}
// reference queues, for garbage collection cleanup
/** Cleanup collected entries when the lock is available. */
void tryDrainReferenceQueues() {
if (tryLock()) {
try {
drainReferenceQueues();
} finally {
unlock();
}
}
}
/**
* Drain the key and value reference queues, cleaning up internal entries containing garbage
* collected keys or values.
*/
@GuardedBy("this")
void drainReferenceQueues() {
if (map.usesKeyReferences()) {
drainKeyReferenceQueue();
}
if (map.usesValueReferences()) {
drainValueReferenceQueue();
}
}
@GuardedBy("this")
void drainKeyReferenceQueue() {
Reference<? extends K> ref;
int i = 0;
while ((ref = keyReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref;
map.reclaimKey(entry);
if (++i == DRAIN_MAX) {
break;
}
}
}
@GuardedBy("this")
void drainValueReferenceQueue() {
Reference<? extends V> ref;
int i = 0;
while ((ref = valueReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ValueReference<K, V> valueReference = (ValueReference<K, V>) ref;
map.reclaimValue(valueReference);
if (++i == DRAIN_MAX) {
break;
}
}
}
/** Clears all entries from the key and value reference queues. */
void clearReferenceQueues() {
if (map.usesKeyReferences()) {
clearKeyReferenceQueue();
}
if (map.usesValueReferences()) {
clearValueReferenceQueue();
}
}
void clearKeyReferenceQueue() {
while (keyReferenceQueue.poll() != null) {}
}
void clearValueReferenceQueue() {
while (valueReferenceQueue.poll() != null) {}
}
// recency queue, shared by expiration and eviction
/**
* Records the relative order in which this read was performed by adding {@code entry} to the
* recency queue. At write-time, or when the queue is full past the threshold, the queue will be
* drained and the entries therein processed.
*
* <p>Note: locked reads should use {@link #recordLockedRead}.
*/
void recordRead(ReferenceEntry<K, V> entry, long now) {
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
recencyQueue.add(entry);
}
/**
* Updates the eviction metadata that {@code entry} was just read. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*
* <p>Note: this method should only be called under lock, as it directly manipulates the
* eviction queues. Unlocked reads should use {@link #recordRead}.
*/
@GuardedBy("this")
void recordLockedRead(ReferenceEntry<K, V> entry, long now) {
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
accessQueue.add(entry);
}
/**
* Updates eviction metadata that {@code entry} was just written. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*/
@GuardedBy("this")
void recordWrite(ReferenceEntry<K, V> entry, int weight, long now) {
// we are already under lock, so drain the recency queue immediately
drainRecencyQueue();
totalWeight += weight;
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
if (map.recordsWrite()) {
entry.setWriteTime(now);
}
accessQueue.add(entry);
writeQueue.add(entry);
}
/**
* Drains the recency queue, updating eviction metadata that the entries therein were read in
* the specified relative order. This currently amounts to adding them to relevant eviction
* lists (accounting for the fact that they could have been removed from the map since being
* added to the recency queue).
*/
@GuardedBy("this")
void drainRecencyQueue() {
ReferenceEntry<K, V> e;
while ((e = recencyQueue.poll()) != null) {
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
// all the segment's entries.
if (accessQueue.contains(e)) {
accessQueue.add(e);
}
}
}
// expiration
/** Cleanup expired entries when the lock is available. */
void tryExpireEntries(long now) {
if (tryLock()) {
try {
expireEntries(now);
} finally {
unlock();
// don't call postWriteCleanup as we're in a read
}
}
}
@GuardedBy("this")
void expireEntries(long now) {
drainRecencyQueue();
ReferenceEntry<K, V> e;
while ((e = writeQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
while ((e = accessQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
}
// eviction
@GuardedBy("this")
void enqueueNotification(
@CheckForNull K key, int hash, @CheckForNull V value, int weight, RemovalCause cause) {
totalWeight -= weight;
if (cause.wasEvicted()) {
statsCounter.recordEviction();
}
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
RemovalNotification<K, V> notification = RemovalNotification.create(key, value, cause);
map.removalNotificationQueue.offer(notification);
}
}
/**
* Performs eviction if the segment is over capacity. Avoids flushing the entire cache if the
* newest entry exceeds the maximum weight all on its own.
*
* @param newest the most recently added entry
*/
@GuardedBy("this")
void evictEntries(ReferenceEntry<K, V> newest) {
if (!map.evictsBySize()) {
return;
}
drainRecencyQueue();
// If the newest entry by itself is too heavy for the segment, don't bother evicting
// anything else, just that
if (newest.getValueReference().getWeight() > maxSegmentWeight) {
if (!removeEntry(newest, newest.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
}
while (totalWeight > maxSegmentWeight) {
ReferenceEntry<K, V> e = getNextEvictable();
if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
}
}
// TODO(fry): instead implement this with an eviction head
@GuardedBy("this")
ReferenceEntry<K, V> getNextEvictable() {
for (ReferenceEntry<K, V> e : accessQueue) {
int weight = e.getValueReference().getWeight();
if (weight > 0) {
return e;
}
}
throw new AssertionError();
}
/** Returns first entry of bin for given hash. */
ReferenceEntry<K, V> getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
return table.get(hash & (table.length() - 1));
}
// Specialized implementations of map methods
@CheckForNull
ReferenceEntry<K, V> getEntry(Object key, int hash) {
for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) {
if (e.getHash() != hash) {
continue;
}
K entryKey = e.getKey();
if (entryKey == null) {
tryDrainReferenceQueues();
continue;
}
if (map.keyEquivalence.equivalent(key, entryKey)) {
return e;
}
}
return null;
}
@CheckForNull
ReferenceEntry<K, V> getLiveEntry(Object key, int hash, long now) {
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e == null) {
return null;
} else if (map.isExpired(e, now)) {
tryExpireEntries(now);
return null;
}
return e;
}
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
* loading, or expired.
*/
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
tryDrainReferenceQueues();
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
tryDrainReferenceQueues();
return null;
}
if (map.isExpired(entry, now)) {
tryExpireEntries(now);
return null;
}
return value;
}
boolean containsKey(Object key, int hash) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
ReferenceEntry<K, V> e = getLiveEntry(key, hash, now);
if (e == null) {
return false;
}
return e.getValueReference().get() != null;
}
return false;
} finally {
postReadCleanup();
}
}
/**
* This method is a convenience for testing. Code should call {@link LocalCache#containsValue}
* directly.
*/
@VisibleForTesting
boolean containsValue(Object value) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int length = table.length();
for (int i = 0; i < length; ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
V entryValue = getLiveValue(e, now);
if (entryValue == null) {
continue;
}
if (map.valueEquivalence.equivalent(value, entryValue)) {
return true;
}
}
}
}
return false;
} finally {
postReadCleanup();
}
}
@CanIgnoreReturnValue
@CheckForNull
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
++modCount;
if (valueReference.isActive()) {
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.COLLECTED);
setValue(e, key, value, now);
newCount = this.count; // count remains unchanged
} else {
setValue(e, key, value, now);
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
evictEntries(e);
return null;
} else if (onlyIfAbsent) {
// Mimic
// "if (!map.containsKey(key)) ...
// else return map.get(key);
recordLockedRead(e, now);
return entryValue;
} else {
// clobber existing entry, count remains unchanged
++modCount;
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, value, now);
evictEntries(e);
return entryValue;
}
}
}
// Create a new entry.
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, key, value, now);
table.set(index, newEntry);
newCount = this.count + 1;
this.count = newCount; // write-volatile
evictEntries(newEntry);
return null;
} finally {
unlock();
postWriteCleanup();
}
}
/** Expands the table if possible. */
@GuardedBy("this")
void expand() {
AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table;
int oldCapacity = oldTable.length();
if (oldCapacity >= MAXIMUM_CAPACITY) {
return;
}
/*
* Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move with a power of two offset.
* We eliminate unnecessary node creation by catching cases where old nodes can be reused
* because their next fields won't change. Statistically, at the default threshold, only about
* one-sixth of them need cloning when a table doubles. The nodes they replace will be garbage
* collectable as soon as they are no longer referenced by any reader thread that may be in
* the midst of traversing table right now.
*/
int newCount = count;
AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1);
threshold = newTable.length() * 3 / 4;
int newMask = newTable.length() - 1;
for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
ReferenceEntry<K, V> head = oldTable.get(oldIndex);
if (head != null) {
ReferenceEntry<K, V> next = head.getNext();
int headIndex = head.getHash() & newMask;
// Single node on list
if (next == null) {
newTable.set(headIndex, head);
} else {
// Reuse the consecutive sequence of nodes with the same target
// index from the end of the list. tail points to the first
// entry in the reusable list.
ReferenceEntry<K, V> tail = head;
int tailIndex = headIndex;
for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
if (newIndex != tailIndex) {
// The index changed. We'll need to copy the previous entry.
tailIndex = newIndex;
tail = e;
}
}
newTable.set(tailIndex, tail);
// Clone nodes leading up to the tail.
for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
ReferenceEntry<K, V> newNext = newTable.get(newIndex);
ReferenceEntry<K, V> newFirst = copyEntry(e, newNext);
if (newFirst != null) {
newTable.set(newIndex, newFirst);
} else {
removeCollectedEntry(e);
newCount--;
}
}
}
}
}
table = newTable;
this.count = newCount;
}
boolean replace(K key, int hash, V oldValue, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (valueReference.isActive()) {
// If the value disappeared, this entry is partially collected.
int newCount = this.count - 1;
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
entryKey,
hash,
entryValue,
valueReference,
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return false;
}
if (map.valueEquivalence.equivalent(oldValue, entryValue)) {
++modCount;
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, newValue, now);
evictEntries(e);
return true;
} else {
// Mimic
// "if (map.containsKey(key) && map.get(key).equals(oldValue))..."
recordLockedRead(e, now);
return false;
}
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@CheckForNull
V replace(K key, int hash, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (valueReference.isActive()) {
// If the value disappeared, this entry is partially collected.
int newCount = this.count - 1;
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
entryKey,
hash,
entryValue,
valueReference,
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return null;
}
++modCount;
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, newValue, now);
evictEntries(e);
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
@CheckForNull
V remove(Object key, int hash) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (entryValue != null) {
cause = RemovalCause.EXPLICIT;
} else if (valueReference.isActive()) {
cause = RemovalCause.COLLECTED;
} else {
// currently loading
return null;
}
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(first, e, entryKey, hash, entryValue, valueReference, cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
boolean remove(Object key, int hash, Object value) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (map.valueEquivalence.equivalent(value, entryValue)) {
cause = RemovalCause.EXPLICIT;
} else if (entryValue == null && valueReference.isActive()) {
cause = RemovalCause.COLLECTED;
} else {
// currently loading
return false;
}
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(first, e, entryKey, hash, entryValue, valueReference, cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return (cause == RemovalCause.EXPLICIT);
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@CanIgnoreReturnValue
boolean storeLoadedValue(
K key, int hash, LoadingValueReference<K, V> oldValueReference, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
// replace the old LoadingValueReference if it's live, otherwise
// perform a putIfAbsent
if (oldValueReference == valueReference
|| (entryValue == null && valueReference != UNSET)) {
++modCount;
if (oldValueReference.isActive()) {
RemovalCause cause =
(entryValue == null) ? RemovalCause.COLLECTED : RemovalCause.REPLACED;
enqueueNotification(key, hash, entryValue, oldValueReference.getWeight(), cause);
newCount--;
}
setValue(e, key, newValue, now);
this.count = newCount; // write-volatile
evictEntries(e);
return true;
}
// the loaded value was already clobbered
enqueueNotification(key, hash, newValue, 0, RemovalCause.REPLACED);
return false;
}
}
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, key, newValue, now);
table.set(index, newEntry);
this.count = newCount; // write-volatile
evictEntries(newEntry);
return true;
} finally {
unlock();
postWriteCleanup();
}
}
void clear() {
if (count != 0) { // read-volatile
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
for (int i = 0; i < table.length(); ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
// Loading references aren't actually in the map yet.
if (e.getValueReference().isActive()) {
K key = e.getKey();
V value = e.getValueReference().get();
RemovalCause cause =
(key == null || value == null) ? RemovalCause.COLLECTED : RemovalCause.EXPLICIT;
enqueueNotification(
key, e.getHash(), value, e.getValueReference().getWeight(), cause);
}
}
}
for (int i = 0; i < table.length(); ++i) {
table.set(i, null);
}
clearReferenceQueues();
writeQueue.clear();
accessQueue.clear();
readCount.set(0);
++modCount;
count = 0; // write-volatile
} finally {
unlock();
postWriteCleanup();
}
}
}
@GuardedBy("this")
@CheckForNull
ReferenceEntry<K, V> removeValueFromChain(
ReferenceEntry<K, V> first,
ReferenceEntry<K, V> entry,
@CheckForNull K key,
int hash,
V value,
ValueReference<K, V> valueReference,
RemovalCause cause) {
enqueueNotification(key, hash, value, valueReference.getWeight(), cause);
writeQueue.remove(entry);
accessQueue.remove(entry);
if (valueReference.isLoading()) {
valueReference.notifyNewValue(null);
return first;
} else {
return removeEntryFromChain(first, entry);
}
}
@GuardedBy("this")
@CheckForNull
ReferenceEntry<K, V> removeEntryFromChain(
ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) {
int newCount = count;
ReferenceEntry<K, V> newFirst = entry.getNext();
for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) {
ReferenceEntry<K, V> next = copyEntry(e, newFirst);
if (next != null) {
newFirst = next;
} else {
removeCollectedEntry(e);
newCount--;
}
}
this.count = newCount;
return newFirst;
}
@GuardedBy("this")
void removeCollectedEntry(ReferenceEntry<K, V> entry) {
enqueueNotification(
entry.getKey(),
entry.getHash(),
entry.getValueReference().get(),
entry.getValueReference().getWeight(),
RemovalCause.COLLECTED);
writeQueue.remove(entry);
accessQueue.remove(entry);
}
/** Removes an entry whose key has been garbage collected. */
@CanIgnoreReturnValue
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
int newCount = count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
e.getKey(),
hash,
e.getValueReference().get(),
e.getValueReference(),
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
/** Removes an entry whose value has been garbage collected. */
@CanIgnoreReturnValue
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
entryKey,
hash,
valueReference.get(),
valueReference,
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
return false;
}
}
return false;
} finally {
unlock();
if (!isHeldByCurrentThread()) { // don't clean up inside of put
postWriteCleanup();
}
}
}
@CanIgnoreReturnValue
boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
if (valueReference.isActive()) {
e.setValueReference(valueReference.getOldValue());
} else {
ReferenceEntry<K, V> newFirst = removeEntryFromChain(first, e);
table.set(index, newFirst);
}
return true;
}
return false;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@VisibleForTesting
@GuardedBy("this")
@CanIgnoreReturnValue
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
e.getKey(),
hash,
e.getValueReference().get(),
e.getValueReference(),
cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
}
/**
* Performs routine cleanup following a read. Normally cleanup happens during writes. If cleanup
* is not observed after a sufficient number of reads, try cleaning up from the read thread.
*/
void postReadCleanup() {
if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) {
cleanUp();
}
}
/**
* Performs routine cleanup prior to executing a write. This should be called every time a write
* thread acquires the segment lock, immediately after acquiring the lock.
*
* <p>Post-condition: expireEntries has been run.
*/
@GuardedBy("this")
void preWriteCleanup(long now) {
runLockedCleanup(now);
}
/** Performs routine cleanup following a write. */
void postWriteCleanup() {
runUnlockedCleanup();
}
void cleanUp() {
long now = map.ticker.read();
runLockedCleanup(now);
runUnlockedCleanup();
}
void runLockedCleanup(long now) {
if (tryLock()) {
try {
drainReferenceQueues();
expireEntries(now); // calls drainRecencyQueue
readCount.set(0);
} finally {
unlock();
}
}
}
void runUnlockedCleanup() {
// locked cleanup may generate notifications we can send unlocked
if (!isHeldByCurrentThread()) {
map.processPendingNotifications();
}
}
}
static class LoadingValueReference<K, V> implements ValueReference<K, V> {
volatile ValueReference<K, V> oldValue;
// TODO(fry): rename get, then extend AbstractFuture instead of containing SettableFuture
final SettableFuture<V> futureValue = SettableFuture.create();
final Stopwatch stopwatch = Stopwatch.createUnstarted();
public LoadingValueReference() {
this(LocalCache.<K, V>unset());
}
/*
* TODO(cpovirk): Consider making this implementation closer to the mainline implementation.
* (The difference was introduced as part of Java-8-specific changes in cl/132882204, but we
* could probably make *some* of those changes here in the backport, too.)
*/
public LoadingValueReference(ValueReference<K, V> oldValue) {
this.oldValue = oldValue;
}
@Override
public boolean isLoading() {
return true;
}
@Override
public boolean isActive() {
return oldValue.isActive();
}
@Override
public int getWeight() {
return oldValue.getWeight();
}
@CanIgnoreReturnValue
public boolean set(@CheckForNull V newValue) {
return futureValue.set(newValue);
}
@CanIgnoreReturnValue
public boolean setException(Throwable t) {
return futureValue.setException(t);
}
private ListenableFuture<V> fullyFailedFuture(Throwable t) {
return Futures.immediateFailedFuture(t);
}
@Override
public void notifyNewValue(@CheckForNull V newValue) {
if (newValue != null) {
// The pending load was clobbered by a manual write.
// Unblock all pending gets, and have them return the new value.
set(newValue);
} else {
// The pending load was removed. Delay notifications until loading completes.
oldValue = unset();
}
// TODO(fry): could also cancel loading if we had a handle on its future
}
public ListenableFuture<V> loadFuture(K key, CacheLoader<? super K, V> loader) {
try {
stopwatch.start();
V previousValue = oldValue.get();
if (previousValue == null) {
V newValue = loader.load(key);
return set(newValue) ? futureValue : Futures.immediateFuture(newValue);
}
ListenableFuture<V> newValue = loader.reload(key, previousValue);
if (newValue == null) {
return Futures.immediateFuture(null);
}
// To avoid a race, make sure the refreshed value is set into loadingValueReference
// *before* returning newValue from the cache query.
return transform(
newValue,
newResult -> {
LoadingValueReference.this.set(newResult);
return newResult;
},
directExecutor());
} catch (Throwable t) {
ListenableFuture<V> result = setException(t) ? futureValue : fullyFailedFuture(t);
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
return result;
}
}
public long elapsedNanos() {
return stopwatch.elapsed(NANOSECONDS);
}
@Override
public V waitForValue() throws ExecutionException {
return getUninterruptibly(futureValue);
}
@Override
public V get() {
return oldValue.get();
}
public ValueReference<K, V> getOldValue() {
return oldValue;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry) {
return this;
}
}
// Queues
/**
* A custom queue for managing eviction order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in the
* map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of
* the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the
* current model.
*/
static final class WriteQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head =
new AbstractReferenceEntry<K, V>() {
@Override
public long getWriteTime() {
return Long.MAX_VALUE;
}
@Override
public void setWriteTime(long time) {}
@Weak ReferenceEntry<K, V> nextWrite = this;
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
@Weak ReferenceEntry<K, V> previousWrite = this;
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectWriteOrder(entry.getPreviousInWriteQueue(), entry.getNextInWriteQueue());
// add to tail
connectWriteOrder(head.getPreviousInWriteQueue(), entry);
connectWriteOrder(entry, head);
return true;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
return (next == head) ? null : next;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
@CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInWriteQueue();
ReferenceEntry<K, V> next = e.getNextInWriteQueue();
connectWriteOrder(previous, next);
nullifyWriteOrder(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
return e.getNextInWriteQueue() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextInWriteQueue() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextInWriteQueue();
e != head;
e = e.getNextInWriteQueue()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextInWriteQueue();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextInWriteQueue();
nullifyWriteOrder(e);
e = next;
}
head.setNextInWriteQueue(head);
head.setPreviousInWriteQueue(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInWriteQueue();
return (next == head) ? null : next;
}
};
}
}
/**
* A custom queue for managing access order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in the
* map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of
* the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the
* current model.
*/
static final class AccessQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head =
new AbstractReferenceEntry<K, V>() {
@Override
public long getAccessTime() {
return Long.MAX_VALUE;
}
@Override
public void setAccessTime(long time) {}
@Weak ReferenceEntry<K, V> nextAccess = this;
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
@Weak ReferenceEntry<K, V> previousAccess = this;
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectAccessOrder(entry.getPreviousInAccessQueue(), entry.getNextInAccessQueue());
// add to tail
connectAccessOrder(head.getPreviousInAccessQueue(), entry);
connectAccessOrder(entry, head);
return true;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
return (next == head) ? null : next;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
@CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInAccessQueue();
ReferenceEntry<K, V> next = e.getNextInAccessQueue();
connectAccessOrder(previous, next);
nullifyAccessOrder(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
return e.getNextInAccessQueue() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextInAccessQueue() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextInAccessQueue();
e != head;
e = e.getNextInAccessQueue()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextInAccessQueue();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextInAccessQueue();
nullifyAccessOrder(e);
e = next;
}
head.setNextInAccessQueue(head);
head.setPreviousInAccessQueue(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInAccessQueue();
return (next == head) ? null : next;
}
};
}
}
// Cache support
public void cleanUp() {
for (Segment<?, ?> segment : segments) {
segment.cleanUp();
}
}
// ConcurrentMap methods
@Override
public boolean isEmpty() {
/*
* Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and
* removed in one segment while checking another, in which case the table was never actually
* empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment
* modifications before recheck.) Method containsValue() uses similar constructions for
* stability checks.
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
for (Segment<K, V> segment : segments) {
if (segment.count != 0) {
return false;
}
sum += segment.modCount;
}
if (sum != 0L) { // recheck unless no modifications
for (Segment<K, V> segment : segments) {
if (segment.count != 0) {
return false;
}
sum -= segment.modCount;
}
return sum == 0L;
}
return true;
}
long longSize() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
for (Segment<K, V> segment : segments) {
sum += Math.max(0, segment.count); // see https://github.com/google/guava/issues/2108
}
return sum;
}
@Override
public int size() {
return Ints.saturatedCast(longSize());
}
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).get(key, hash);
}
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).get(key, hash, loader);
}
@CheckForNull
public V getIfPresent(Object key) {
int hash = hash(checkNotNull(key));
V value = segmentFor(hash).get(key, hash);
if (value == null) {
globalStatsCounter.recordMisses(1);
} else {
globalStatsCounter.recordHits(1);
}
return value;
}
@Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
V result = get(key);
return (result != null) ? result : defaultValue;
}
V getOrLoad(K key) throws ExecutionException {
return get(key, defaultLoader);
}
ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
int hits = 0;
int misses = 0;
ImmutableMap.Builder<K, V> result = ImmutableMap.builder();
for (Object key : keys) {
V value = get(key);
if (value == null) {
misses++;
} else {
// TODO(fry): store entry key instead of query key
@SuppressWarnings("unchecked")
K castKey = (K) key;
result.put(castKey, value);
hits++;
}
}
globalStatsCounter.recordHits(hits);
globalStatsCounter.recordMisses(misses);
return result.buildKeepingLast();
}
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
int hits = 0;
int misses = 0;
Map<K, V> result = Maps.newLinkedHashMap();
Set<K> keysToLoad = Sets.newLinkedHashSet();
for (K key : keys) {
V value = get(key);
if (!result.containsKey(key)) {
result.put(key, value);
if (value == null) {
misses++;
keysToLoad.add(key);
} else {
hits++;
}
}
}
try {
if (!keysToLoad.isEmpty()) {
try {
Map<K, V> newEntries = loadAll(unmodifiableSet(keysToLoad), defaultLoader);
for (K key : keysToLoad) {
V value = newEntries.get(key);
if (value == null) {
throw new InvalidCacheLoadException("loadAll failed to return a value for " + key);
}
result.put(key, value);
}
} catch (UnsupportedLoadingOperationException e) {
// loadAll not implemented, fallback to load
for (K key : keysToLoad) {
misses--; // get will count this miss
result.put(key, get(key, defaultLoader));
}
}
}
return ImmutableMap.copyOf(result);
} finally {
globalStatsCounter.recordHits(hits);
globalStatsCounter.recordMisses(misses);
}
}
/**
* Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't
* implement {@code loadAll}.
*/
@CheckForNull
Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader)
throws ExecutionException {
checkNotNull(loader);
checkNotNull(keys);
Stopwatch stopwatch = Stopwatch.createStarted();
Map<K, V> result;
boolean success = false;
try {
@SuppressWarnings("unchecked") // safe since all keys extend K
Map<K, V> map = (Map<K, V>) loader.loadAll(keys);
result = map;
success = true;
} catch (UnsupportedLoadingOperationException e) {
success = true;
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ExecutionException(e);
} catch (RuntimeException e) {
throw new UncheckedExecutionException(e);
} catch (Exception e) {
throw new ExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
} finally {
if (!success) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
}
}
if (result == null) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
throw new InvalidCacheLoadException(loader + " returned null map from loadAll");
}
stopwatch.stop();
// TODO(fry): batch by segment
boolean nullsPresent = false;
for (Entry<K, V> entry : result.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
if (key == null || value == null) {
// delay failure until non-null entries are stored
nullsPresent = true;
} else {
put(key, value);
}
}
if (nullsPresent) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
throw new InvalidCacheLoadException(loader + " returned null keys or values from loadAll");
}
// TODO(fry): record count of loaded entries
globalStatsCounter.recordLoadSuccess(stopwatch.elapsed(NANOSECONDS));
return result;
}
/**
* Returns the internal entry for the specified key. The entry may be loading, expired, or
* partially collected.
*/
@CheckForNull
ReferenceEntry<K, V> getEntry(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).getEntry(key, hash);
}
void refresh(K key) {
int hash = hash(checkNotNull(key));
segmentFor(hash).refresh(key, hash, defaultLoader, false);
}
@Override
public boolean containsKey(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).containsKey(key, hash);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
// does not impact recency ordering
if (value == null) {
return false;
}
// This implementation is patterned after ConcurrentHashMap, but without the locking. The only
// way for it to return a false negative would be for the target value to jump around in the map
// such that none of the subsequent iterations observed it, despite the fact that at every point
// in time it was present somewhere int the map. This becomes increasingly unlikely as
// CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible.
long now = ticker.read();
final Segment<K, V>[] segments = this.segments;
long last = -1L;
for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
long sum = 0L;
for (Segment<K, V> segment : segments) {
// ensure visibility of most recent completed write
int unused = segment.count; // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
for (int j = 0; j < table.length(); j++) {
for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
V v = segment.getLiveValue(e, now);
if (v != null && valueEquivalence.equivalent(value, v)) {
return true;
}
}
}
sum += segment.modCount;
}
if (sum == last) {
break;
}
last = sum;
}
return false;
}
@CheckForNull
@CanIgnoreReturnValue
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, false);
}
@CheckForNull
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, true);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@CheckForNull
@CanIgnoreReturnValue
@Override
public V remove(@CheckForNull Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash);
}
@CanIgnoreReturnValue
@Override
public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
if (key == null || value == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash, value);
}
@CanIgnoreReturnValue
@Override
public boolean replace(K key, @CheckForNull V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
@CheckForNull
@CanIgnoreReturnValue
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).replace(key, hash, value);
}
@Override
public void clear() {
for (Segment<K, V> segment : segments) {
segment.clear();
}
}
void invalidateAll(Iterable<?> keys) {
// TODO(fry): batch by segment
for (Object key : keys) {
remove(key);
}
}
@LazyInit @RetainedWith @CheckForNull Set<K> keySet;
@Override
public Set<K> keySet() {
// does not impact recency ordering
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
}
@LazyInit @RetainedWith @CheckForNull Collection<V> values;
@Override
public Collection<V> values() {
// does not impact recency ordering
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
@LazyInit @RetainedWith @CheckForNull Set<Entry<K, V>> entrySet;
@Override
@GwtIncompatible // Not supported.
public Set<Entry<K, V>> entrySet() {
// does not impact recency ordering
Set<Entry<K, V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
// Iterator Support
abstract class HashIterator<T> implements Iterator<T> {
int nextSegmentIndex;
int nextTableIndex;
@CheckForNull Segment<K, V> currentSegment;
@CheckForNull AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
@CheckForNull ReferenceEntry<K, V> nextEntry;
@CheckForNull WriteThroughEntry nextExternal;
@CheckForNull WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
nextTableIndex = -1;
advance();
}
@Override
public abstract T next();
final void advance() {
nextExternal = null;
if (nextInChain()) {
return;
}
if (nextInTable()) {
return;
}
while (nextSegmentIndex >= 0) {
currentSegment = segments[nextSegmentIndex--];
if (currentSegment.count != 0) {
currentTable = currentSegment.table;
nextTableIndex = currentTable.length() - 1;
if (nextInTable()) {
return;
}
}
}
}
/** Finds the next entry in the current chain. Returns true if an entry was found. */
boolean nextInChain() {
if (nextEntry != null) {
for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) {
if (advanceTo(nextEntry)) {
return true;
}
}
}
return false;
}
/** Finds the next entry in the current table. Returns true if an entry was found. */
boolean nextInTable() {
while (nextTableIndex >= 0) {
if ((nextEntry = currentTable.get(nextTableIndex--)) != null) {
if (advanceTo(nextEntry) || nextInChain()) {
return true;
}
}
}
return false;
}
/**
* Advances to the given entry. Returns true if the entry was valid, false if it should be
* skipped.
*/
boolean advanceTo(ReferenceEntry<K, V> entry) {
try {
long now = ticker.read();
K key = entry.getKey();
V value = getLiveValue(entry, now);
if (value != null) {
nextExternal = new WriteThroughEntry(key, value);
return true;
} else {
// Skip stale entry.
return false;
}
} finally {
currentSegment.postReadCleanup();
}
}
@Override
public boolean hasNext() {
return nextExternal != null;
}
WriteThroughEntry nextEntry() {
if (nextExternal == null) {
throw new NoSuchElementException();
}
lastReturned = nextExternal;
advance();
return lastReturned;
}
@Override
public void remove() {
checkState(lastReturned != null);
LocalCache.this.remove(lastReturned.getKey());
lastReturned = null;
}
}
final class KeyIterator extends HashIterator<K> {
@Override
public K next() {
return nextEntry().getKey();
}
}
final class ValueIterator extends HashIterator<V> {
@Override
public V next() {
return nextEntry().getValue();
}
}
/**
* Custom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying
* map.
*/
final class WriteThroughEntry implements Entry<K, V> {
final K key; // non-null
V value; // non-null
WriteThroughEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public boolean equals(@CheckForNull Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return key.equals(that.getKey()) && value.equals(that.getValue());
}
return false;
}
@Override
public int hashCode() {
// Cannot use key and value equivalence
return key.hashCode() ^ value.hashCode();
}
@Override
public V setValue(V newValue) {
V oldValue = put(key, newValue);
value = newValue; // only if put succeeds
return oldValue;
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
}
final class EntryIterator extends HashIterator<Entry<K, V>> {
@Override
public Entry<K, V> next() {
return nextEntry();
}
}
abstract class AbstractCacheSet<T> extends AbstractSet<T> {
@Override
public int size() {
return LocalCache.this.size();
}
@Override
public boolean isEmpty() {
return LocalCache.this.isEmpty();
}
@Override
public void clear() {
LocalCache.this.clear();
}
// super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android.
// https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508
@Override
public Object[] toArray() {
return toArrayList(this).toArray();
}
@Override
public <E> E[] toArray(E[] a) {
return toArrayList(this).toArray(a);
}
}
private static <E> ArrayList<E> toArrayList(Collection<E> c) {
// Avoid calling ArrayList(Collection), which may call back into toArray.
ArrayList<E> result = new ArrayList<>(c.size());
Iterators.addAll(result, c.iterator());
return result;
}
final class KeySet extends AbstractCacheSet<K> {
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public boolean contains(Object o) {
return LocalCache.this.containsKey(o);
}
@Override
public boolean remove(Object o) {
return LocalCache.this.remove(o) != null;
}
}
final class Values extends AbstractCollection<V> {
@Override
public int size() {
return LocalCache.this.size();
}
@Override
public boolean isEmpty() {
return LocalCache.this.isEmpty();
}
@Override
public void clear() {
LocalCache.this.clear();
}
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public boolean contains(Object o) {
return LocalCache.this.containsValue(o);
}
// super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android.
// https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508
@Override
public Object[] toArray() {
return toArrayList(this).toArray();
}
@Override
public <E> E[] toArray(E[] a) {
return toArrayList(this).toArray(a);
}
}
final class EntrySet extends AbstractCacheSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
if (key == null) {
return false;
}
V v = LocalCache.this.get(key);
return v != null && valueEquivalence.equivalent(e.getValue(), v);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
return key != null && LocalCache.this.remove(key, e.getValue());
}
}
// Serialization Support
/**
* Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder
* upon deserialization. An instance of this class is fit for use by the writeReplace of
* LocalManualCache.
*
* <p>Unfortunately, readResolve() doesn't get called when a circular dependency is present, so
* the proxy must be able to behave as the cache itself.
*/
static class ManualSerializationProxy<K, V> extends ForwardingCache<K, V>
implements Serializable {
private static final long serialVersionUID = 1;
final Strength keyStrength;
final Strength valueStrength;
final Equivalence<Object> keyEquivalence;
final Equivalence<Object> valueEquivalence;
final long expireAfterWriteNanos;
final long expireAfterAccessNanos;
final long maxWeight;
final Weigher<K, V> weigher;
final int concurrencyLevel;
final RemovalListener<? super K, ? super V> removalListener;
@CheckForNull final Ticker ticker;
final CacheLoader<? super K, V> loader;
@CheckForNull transient Cache<K, V> delegate;
ManualSerializationProxy(LocalCache<K, V> cache) {
this(
cache.keyStrength,
cache.valueStrength,
cache.keyEquivalence,
cache.valueEquivalence,
cache.expireAfterWriteNanos,
cache.expireAfterAccessNanos,
cache.maxWeight,
cache.weigher,
cache.concurrencyLevel,
cache.removalListener,
cache.ticker,
cache.defaultLoader);
}
private ManualSerializationProxy(
Strength keyStrength,
Strength valueStrength,
Equivalence<Object> keyEquivalence,
Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos,
long expireAfterAccessNanos,
long maxWeight,
Weigher<K, V> weigher,
int concurrencyLevel,
RemovalListener<? super K, ? super V> removalListener,
Ticker ticker,
CacheLoader<? super K, V> loader) {
this.keyStrength = keyStrength;
this.valueStrength = valueStrength;
this.keyEquivalence = keyEquivalence;
this.valueEquivalence = valueEquivalence;
this.expireAfterWriteNanos = expireAfterWriteNanos;
this.expireAfterAccessNanos = expireAfterAccessNanos;
this.maxWeight = maxWeight;
this.weigher = weigher;
this.concurrencyLevel = concurrencyLevel;
this.removalListener = removalListener;
this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER) ? null : ticker;
this.loader = loader;
}
CacheBuilder<K, V> recreateCacheBuilder() {
CacheBuilder<K, V> builder =
CacheBuilder.newBuilder()
.setKeyStrength(keyStrength)
.setValueStrength(valueStrength)
.keyEquivalence(keyEquivalence)
.valueEquivalence(valueEquivalence)
.concurrencyLevel(concurrencyLevel)
.removalListener(removalListener);
builder.strictParsing = false;
if (expireAfterWriteNanos > 0) {
builder.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS);
}
if (expireAfterAccessNanos > 0) {
builder.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (weigher != OneWeigher.INSTANCE) {
Object unused = builder.weigher(weigher);
if (maxWeight != UNSET_INT) {
builder.maximumWeight(maxWeight);
}
} else {
if (maxWeight != UNSET_INT) {
builder.maximumSize(maxWeight);
}
}
if (ticker != null) {
builder.ticker(ticker);
}
return builder;
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
CacheBuilder<K, V> builder = recreateCacheBuilder();
this.delegate = builder.build();
}
private Object readResolve() {
return delegate;
}
@Override
protected Cache<K, V> delegate() {
return delegate;
}
}
/**
* Serializes the configuration of a LocalCache, reconstituting it as an LoadingCache using
* CacheBuilder upon deserialization. An instance of this class is fit for use by the writeReplace
* of LocalLoadingCache.
*
* <p>Unfortunately, readResolve() doesn't get called when a circular dependency is present, so
* the proxy must be able to behave as the cache itself.
*/
static final class LoadingSerializationProxy<K, V> extends ManualSerializationProxy<K, V>
implements LoadingCache<K, V>, Serializable {
private static final long serialVersionUID = 1;
@CheckForNull transient LoadingCache<K, V> autoDelegate;
LoadingSerializationProxy(LocalCache<K, V> cache) {
super(cache);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
CacheBuilder<K, V> builder = recreateCacheBuilder();
this.autoDelegate = builder.build(loader);
}
@Override
public V get(K key) throws ExecutionException {
return autoDelegate.get(key);
}
@Override
public V getUnchecked(K key) {
return autoDelegate.getUnchecked(key);
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return autoDelegate.getAll(keys);
}
@Override
public V apply(K key) {
return autoDelegate.apply(key);
}
@Override
public void refresh(K key) {
autoDelegate.refresh(key);
}
private Object readResolve() {
return autoDelegate;
}
}
static class LocalManualCache<K, V> implements Cache<K, V>, Serializable {
final LocalCache<K, V> localCache;
LocalManualCache(CacheBuilder<? super K, ? super V> builder) {
this(new LocalCache<>(builder, null));
}
private LocalManualCache(LocalCache<K, V> localCache) {
this.localCache = localCache;
}
// Cache methods
@Override
@CheckForNull
public V getIfPresent(Object key) {
return localCache.getIfPresent(key);
}
@Override
public V get(K key, final Callable<? extends V> valueLoader) throws ExecutionException {
checkNotNull(valueLoader);
return localCache.get(
key,
new CacheLoader<Object, V>() {
@Override
public V load(Object key) throws Exception {
return valueLoader.call();
}
});
}
@Override
public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
return localCache.getAllPresent(keys);
}
@Override
public void put(K key, V value) {
localCache.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
localCache.putAll(m);
}
@Override
public void invalidate(Object key) {
checkNotNull(key);
localCache.remove(key);
}
@Override
public void invalidateAll(Iterable<?> keys) {
localCache.invalidateAll(keys);
}
@Override
public void invalidateAll() {
localCache.clear();
}
@Override
public long size() {
return localCache.longSize();
}
@Override
public ConcurrentMap<K, V> asMap() {
return localCache;
}
@Override
public CacheStats stats() {
SimpleStatsCounter aggregator = new SimpleStatsCounter();
aggregator.incrementBy(localCache.globalStatsCounter);
for (Segment<K, V> segment : localCache.segments) {
aggregator.incrementBy(segment.statsCounter);
}
return aggregator.snapshot();
}
@Override
public void cleanUp() {
localCache.cleanUp();
}
// Serialization Support
private static final long serialVersionUID = 1;
Object writeReplace() {
return new ManualSerializationProxy<>(localCache);
}
private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("Use ManualSerializationProxy");
}
}
static class LocalLoadingCache<K, V> extends LocalManualCache<K, V>
implements LoadingCache<K, V> {
LocalLoadingCache(
CacheBuilder<? super K, ? super V> builder, CacheLoader<? super K, V> loader) {
super(new LocalCache<>(builder, checkNotNull(loader)));
}
// LoadingCache methods
@Override
public V get(K key) throws ExecutionException {
return localCache.getOrLoad(key);
}
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V getUnchecked(K key) {
try {
return get(key);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e.getCause());
}
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return localCache.getAll(keys);
}
@Override
public void refresh(K key) {
localCache.refresh(key);
}
@Override
public final V apply(K key) {
return getUnchecked(key);
}
// Serialization Support
private static final long serialVersionUID = 1;
@Override
Object writeReplace() {
return new LoadingSerializationProxy<>(localCache);
}
private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("Use LoadingSerializationProxy");
}
}
}
| google/guava | android/guava/src/com/google/common/cache/LocalCache.java |
671 | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.EnumSet;
import javax.annotation.CheckForNull;
/**
* Implementation of {@link ImmutableSet} backed by a non-empty {@link java.util.EnumSet}.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
static <E extends Enum<E>> ImmutableSet<E> asImmutable(EnumSet<E> set) {
switch (set.size()) {
case 0:
return ImmutableSet.of();
case 1:
return ImmutableSet.of(Iterables.getOnlyElement(set));
default:
return new ImmutableEnumSet<>(set);
}
}
/*
* Notes on EnumSet and <E extends Enum<E>>:
*
* This class isn't an arbitrary ForwardingImmutableSet because we need to
* know that calling {@code clone()} during deserialization will return an
* object that no one else has a reference to, allowing us to guarantee
* immutability. Hence, we support only {@link EnumSet}.
*/
private final transient EnumSet<E> delegate;
private ImmutableEnumSet(EnumSet<E> delegate) {
this.delegate = delegate;
}
@Override
boolean isPartialView() {
return false;
}
@Override
public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean contains(@CheckForNull Object object) {
return delegate.contains(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
if (collection instanceof ImmutableEnumSet<?>) {
collection = ((ImmutableEnumSet<?>) collection).delegate;
}
return delegate.containsAll(collection);
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof ImmutableEnumSet) {
object = ((ImmutableEnumSet<?>) object).delegate;
}
return delegate.equals(object);
}
@Override
boolean isHashCodeFast() {
return true;
}
@LazyInit private transient int hashCode;
@Override
public int hashCode() {
int result = hashCode;
return (result == 0) ? hashCode = delegate.hashCode() : result;
}
@Override
public String toString() {
return delegate.toString();
}
// All callers of the constructor are restricted to <E extends Enum<E>>.
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return new EnumSerializedForm<E>(delegate);
}
@J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
@J2ktIncompatible // serialization
private static class EnumSerializedForm<E extends Enum<E>> implements Serializable {
final EnumSet<E> delegate;
EnumSerializedForm(EnumSet<E> delegate) {
this.delegate = delegate;
}
Object readResolve() {
// EJ2 #76: Write readObject() methods defensively.
return new ImmutableEnumSet<E>(delegate.clone());
}
private static final long serialVersionUID = 0;
}
}
| google/guava | android/guava/src/com/google/common/collect/ImmutableEnumSet.java |
672 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
import java.util.stream.Collector;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to {@link Set} instances. Also see this class's counterparts
* {@link Lists}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#sets">{@code Sets}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Chris Povirk
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Sets {
private Sets() {}
/**
* {@link AbstractSet} substitute without the potentially-quadratic {@code removeAll}
* implementation.
*/
abstract static class ImprovedAbstractSet<E extends @Nullable Object> extends AbstractSet<E> {
@Override
public boolean removeAll(Collection<?> c) {
return removeAllImpl(this, c);
}
@Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(checkNotNull(c)); // GWT compatibility
}
}
/**
* Returns an immutable set instance containing the given enum elements. Internally, the returned
* set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration order, not the order in
* which the elements are provided to the method.
*
* @param anElement one of the elements the set should contain
* @param otherElements the rest of the elements the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
E anElement, E... otherElements) {
return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
}
/**
* Returns an immutable set instance containing the given enum elements. Internally, the returned
* set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration order, not the order in
* which the elements appear in the given collection.
*
* @param elements the elements, all of the same {@code enum} type, that the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(Iterable<E> elements) {
if (elements instanceof ImmutableEnumSet) {
return (ImmutableEnumSet<E>) elements;
} else if (elements instanceof Collection) {
Collection<E> collection = (Collection<E>) elements;
if (collection.isEmpty()) {
return ImmutableSet.of();
} else {
return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
}
} else {
Iterator<E> itr = elements.iterator();
if (itr.hasNext()) {
EnumSet<E> enumSet = EnumSet.of(itr.next());
Iterators.addAll(enumSet, itr);
return ImmutableEnumSet.asImmutable(enumSet);
} else {
return ImmutableSet.of();
}
}
}
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code ImmutableSet}
* with an implementation specialized for enums. Unlike {@link ImmutableSet#toImmutableSet}, the
* resulting set will iterate over elements in their enum definition order, not encounter order.
*
* @since 21.0
*/
public static <E extends Enum<E>> Collector<E, ?, ImmutableSet<E>> toImmutableEnumSet() {
return CollectCollectors.toImmutableEnumSet();
}
/**
* Returns a new, <i>mutable</i> {@code EnumSet} instance containing the given elements in their
* natural order. This method behaves identically to {@link EnumSet#copyOf(Collection)}, but also
* accepts non-{@code Collection} iterables and empty iterables.
*/
public static <E extends Enum<E>> EnumSet<E> newEnumSet(
Iterable<E> iterable, Class<E> elementType) {
EnumSet<E> set = EnumSet.noneOf(elementType);
Iterables.addAll(set, iterable);
return set;
}
// HashSet
/**
* Creates a <i>mutable</i>, initially empty {@code HashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead. If {@code
* E} is an {@link Enum} type, use {@link EnumSet#noneOf} instead. Otherwise, strongly consider
* using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get
* deterministic iteration behavior.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code HashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
public static <E extends @Nullable Object> HashSet<E> newHashSet() {
return new HashSet<>();
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance initially containing the given elements.
*
* <p><b>Note:</b> if elements are non-null and won't be added or removed after this point, use
* {@link ImmutableSet#of()} or {@link ImmutableSet#copyOf(Object[])} instead. If {@code E} is an
* {@link Enum} type, use {@link EnumSet#of(Enum, Enum[])} instead. Otherwise, strongly consider
* using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get
* deterministic iteration behavior.
*
* <p>This method is just a small convenience, either for {@code newHashSet(}{@link Arrays#asList
* asList}{@code (...))}, or for creating an empty set then calling {@link Collections#addAll}.
* This method is not actually very useful and will likely be deprecated in the future.
*/
@SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix.
public static <E extends @Nullable Object> HashSet<E> newHashSet(E... elements) {
HashSet<E> set = newHashSetWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
* convenience for creating an empty set then calling {@link Collection#addAll} or {@link
* Iterables#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableSet#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
* FluentIterable} and call {@code elements.toSet()}.)
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link #newEnumSet(Iterable, Class)}
* instead.
*
* <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method.
* Instead, use the {@code HashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* <p>Overall, this method is not very useful and will likely be deprecated in the future.
*/
public static <E extends @Nullable Object> HashSet<E> newHashSet(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? new HashSet<E>((Collection<? extends E>) elements)
: newHashSet(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
* convenience for creating an empty set and then calling {@link Iterators#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableSet#copyOf(Iterator)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an {@link EnumSet}
* instead.
*
* <p>Overall, this method is not very useful and will likely be deprecated in the future.
*/
public static <E extends @Nullable Object> HashSet<E> newHashSet(Iterator<? extends E> elements) {
HashSet<E> set = newHashSet();
Iterators.addAll(set, elements);
return set;
}
/**
* Returns a new hash set using the smallest initial table size that can hold {@code expectedSize}
* elements without resizing. Note that this is not what {@link HashSet#HashSet(int)} does, but it
* is what most users want and expect it to do.
*
* <p>This behavior can't be broadly guaranteed, but has been tested with OpenJDK 1.7 and 1.8.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty hash set with enough capacity to hold {@code expectedSize} elements
* without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E extends @Nullable Object> HashSet<E> newHashSetWithExpectedSize(
int expectedSize) {
return new HashSet<>(Maps.capacity(expectedSize));
}
/**
* Creates a thread-safe set backed by a hash map. The set is backed by a {@link
* ConcurrentHashMap} instance, and thus carries the same concurrency guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The
* set is serializable.
*
* @return a new, empty thread-safe {@code Set}
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet() {
return Platform.newConcurrentHashSet();
}
/**
* Creates a thread-safe set backed by a hash map and containing the given elements. The set is
* backed by a {@link ConcurrentHashMap} instance, and thus carries the same concurrency
* guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The
* set is serializable.
*
* @param elements the elements that the set should contain
* @return a new thread-safe set containing those elements (minus duplicates)
* @throws NullPointerException if {@code elements} or any of its contents is null
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet(Iterable<? extends E> elements) {
Set<E> set = newConcurrentHashSet();
Iterables.addAll(set, elements);
return set;
}
// LinkedHashSet
/**
* Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedHashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code LinkedHashSet}
*/
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet() {
return new LinkedHashSet<>();
}
/**
* Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the given elements in order.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method.
* Instead, use the {@code LinkedHashSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* <p>Overall, this method is not very useful and will likely be deprecated in the future.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code LinkedHashSet} containing those elements (minus duplicates)
*/
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<>((Collection<? extends E>) elements);
}
LinkedHashSet<E> set = newLinkedHashSet();
Iterables.addAll(set, elements);
return set;
}
/**
* Creates a {@code LinkedHashSet} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
* broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
* that the method isn't inadvertently <i>oversizing</i> the returned set.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize}
* elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 11.0
*/
public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
int expectedSize) {
return new LinkedHashSet<>(Maps.capacity(expectedSize));
}
// TreeSet
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the natural sort ordering of
* its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code TreeSet}
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <E extends Comparable> TreeSet<E> newTreeSet() {
return new TreeSet<>();
}
/**
* Creates a <i>mutable</i> {@code TreeSet} instance containing the given elements sorted by their
* natural ordering.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#copyOf(Iterable)}
* instead.
*
* <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit comparator, this
* method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code
* TreeSet} with that comparator.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* <p>This method is just a small convenience for creating an empty set and then calling {@link
* Iterables#addAll}. This method is not very useful and will likely be deprecated in the future.
*
* @param elements the elements that the set should contain
* @return a new {@code TreeSet} containing those elements (minus duplicates)
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
Iterables.addAll(set, elements);
return set;
}
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedSet.orderedBy(comparator).build()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeSet} constructor directly, taking advantage of <a
* href="http://goo.gl/iz2Wi">"diamond" syntax</a>. One caveat to this is that the {@code TreeSet}
* constructor uses a null {@code Comparator} to mean "natural ordering," whereas this factory
* rejects null. Clean your code accordingly.
*
* @param comparator the comparator to use to sort the set
* @return a new, empty {@code TreeSet}
* @throws NullPointerException if {@code comparator} is null
*/
public static <E extends @Nullable Object> TreeSet<E> newTreeSet(
Comparator<? super E> comparator) {
return new TreeSet<>(checkNotNull(comparator));
}
/**
* Creates an empty {@code Set} that uses identity to determine equality. It compares object
* references, instead of calling {@code equals}, to determine whether a provided object matches
* an element in the set. For example, {@code contains} returns {@code false} when passed an
* object that equals a set member, but isn't the same instance. This behavior is similar to the
* way {@code IdentityHashMap} handles key lookups.
*
* @since 8.0
*/
public static <E extends @Nullable Object> Set<E> newIdentityHashSet() {
return Collections.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
}
/**
* Creates an empty {@code CopyOnWriteArraySet} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link Set}, use {@link Collections#emptySet}
* instead.
*
* @return a new, empty {@code CopyOnWriteArraySet}
* @since 12.0
*/
@J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
return new CopyOnWriteArraySet<>();
}
/**
* Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code CopyOnWriteArraySet} containing those elements
* @since 12.0
*/
@J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
Iterable<? extends E> elements) {
// We copy elements to an ArrayList first, rather than incurring the
// quadratic cost of adding them to the COWAS directly.
Collection<? extends E> elementsCollection =
(elements instanceof Collection)
? (Collection<? extends E>) elements
: Lists.newArrayList(elements);
return new CopyOnWriteArraySet<>(elementsCollection);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in the specified
* collection. If the collection is an {@link EnumSet}, this method has the same behavior as
* {@link EnumSet#complementOf}. Otherwise, the specified collection must contain at least one
* element, in order to determine the element type. If the collection could be empty, use {@link
* #complementOf(Collection, Class)} instead of this method.
*
* @param collection the collection whose complement should be stored in the enum set
* @return a new, modifiable {@code EnumSet} containing all values of the enum that aren't present
* in the given collection
* @throws IllegalArgumentException if {@code collection} is not an {@code EnumSet} instance and
* contains no elements
*/
@J2ktIncompatible
@GwtIncompatible // EnumSet.complementOf
public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) {
if (collection instanceof EnumSet) {
return EnumSet.complementOf((EnumSet<E>) collection);
}
checkArgument(
!collection.isEmpty(), "collection is empty; use the other version of this method");
Class<E> type = collection.iterator().next().getDeclaringClass();
return makeComplementByHand(collection, type);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in the specified
* collection. This is equivalent to {@link EnumSet#complementOf}, but can act on any input
* collection, as long as the elements are of enum type.
*
* @param collection the collection whose complement should be stored in the {@code EnumSet}
* @param type the type of the elements in the set
* @return a new, modifiable {@code EnumSet} initially containing all the values of the enum not
* present in the given collection
*/
@J2ktIncompatible
@GwtIncompatible // EnumSet.complementOf
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection, Class<E> type) {
checkNotNull(collection);
return (collection instanceof EnumSet)
? EnumSet.complementOf((EnumSet<E>) collection)
: makeComplementByHand(collection, type);
}
@J2ktIncompatible
@GwtIncompatible
private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
Collection<E> collection, Class<E> type) {
EnumSet<E> result = EnumSet.allOf(type);
result.removeAll(collection);
return result;
}
/**
* Returns a set backed by the specified map. The resulting set displays the same ordering,
* concurrency, and performance characteristics as the backing map. In essence, this factory
* method provides a {@link Set} implementation corresponding to any {@link Map} implementation.
* There is no need to use this method on a {@link Map} implementation that already has a
* corresponding {@link Set} implementation (such as {@link java.util.HashMap} or {@link
* java.util.TreeMap}).
*
* <p>Each method invocation on the set returned by this method results in exactly one method
* invocation on the backing map or its {@code keySet} view, with one exception. The {@code
* addAll} method is implemented as a sequence of {@code put} invocations on the backing map.
*
* <p>The specified map must be empty at the time this method is invoked, and should not be
* accessed directly after this method returns. These conditions are ensured if the map is created
* empty, passed directly to this method, and no reference to the map is retained, as illustrated
* in the following code fragment:
*
* <pre>{@code
* Set<Object> identityHashSet = Sets.newSetFromMap(
* new IdentityHashMap<Object, Boolean>());
* }</pre>
*
* <p>The returned set is serializable if the backing map is.
*
* @param map the backing map
* @return the set backed by the map
* @throws IllegalArgumentException if {@code map} is not empty
* @deprecated Use {@link Collections#newSetFromMap} instead.
*/
@Deprecated
public static <E extends @Nullable Object> Set<E> newSetFromMap(
Map<E, Boolean> map) {
return Collections.newSetFromMap(map);
}
/**
* An unmodifiable view of a set which may be backed by other sets; this view will change as the
* backing sets do. Contains methods to copy the data into a new set which will then remain
* stable. There is usually no reason to retain a reference of type {@code SetView}; typically,
* you either use it as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
* {@link #copyInto} and forget the {@code SetView} itself.
*
* @since 2.0
*/
public abstract static class SetView<E extends @Nullable Object> extends AbstractSet<E> {
private SetView() {} // no subclasses but our own
/**
* Returns an immutable copy of the current contents of this set view. Does not support null
* elements.
*
* <p><b>Warning:</b> this may have unexpected results if a backing set of this view uses a
* nonstandard notion of equivalence, for example if it is a {@link TreeSet} using a comparator
* that is inconsistent with {@link Object#equals(Object)}.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't fix it now.
public ImmutableSet<@NonNull E> immutableCopy() {
return ImmutableSet.copyOf((SetView<@NonNull E>) this);
}
/**
* Copies the current contents of this set view into an existing set. This method has equivalent
* behavior to {@code set.addAll(this)}, assuming that all the sets involved are based on the
* same notion of equivalence.
*
* @return a reference to {@code set}, for convenience
*/
// Note: S should logically extend Set<? super E> but can't due to either
// some javac bug or some weirdness in the spec, not sure which.
@CanIgnoreReturnValue
public <S extends Set<E>> S copyInto(S set) {
set.addAll(this);
return set;
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean add(@ParametricNullness E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean remove(@CheckForNull Object object) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean addAll(Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean removeIf(java.util.function.Predicate<? super E> filter) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Scope the return type to {@link UnmodifiableIterator} to ensure this is an unmodifiable view.
*
* @since 20.0 (present with return type {@link Iterator} since 2.0)
*/
@Override
public abstract UnmodifiableIterator<E> iterator();
}
/**
* Returns an unmodifiable <b>view</b> of the union of two sets. The returned set contains all
* elements that are contained in either backing set. Iterating over the returned set iterates
* first over all the elements of {@code set1}, then over each element of {@code set2}, in order,
* that is not contained in {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*/
public static <E extends @Nullable Object> SetView<E> union(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public int size() {
int size = set1.size();
for (E e : set2) {
if (!set1.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return set1.isEmpty() && set2.isEmpty();
}
@Override
public UnmodifiableIterator<E> iterator() {
return new AbstractIterator<E>() {
final Iterator<? extends E> itr1 = set1.iterator();
final Iterator<? extends E> itr2 = set2.iterator();
@Override
@CheckForNull
protected E computeNext() {
if (itr1.hasNext()) {
return itr1.next();
}
while (itr2.hasNext()) {
E e = itr2.next();
if (!set1.contains(e)) {
return e;
}
}
return endOfData();
}
};
}
@Override
public Stream<E> stream() {
return Stream.concat(set1.stream(), set2.stream().filter((E e) -> !set1.contains(e)));
}
@Override
public Stream<E> parallelStream() {
return stream().parallel();
}
@Override
public boolean contains(@CheckForNull Object object) {
return set1.contains(object) || set2.contains(object);
}
@Override
public <S extends Set<E>> S copyInto(S set) {
set.addAll(set1);
set.addAll(set2);
return set;
}
@Override
@SuppressWarnings({"nullness", "unchecked"}) // see supertype
public ImmutableSet<@NonNull E> immutableCopy() {
ImmutableSet.Builder<@NonNull E> builder =
new ImmutableSet.Builder<@NonNull E>()
.addAll((Iterable<@NonNull E>) set1)
.addAll((Iterable<@NonNull E>) set2);
return (ImmutableSet<@NonNull E>) builder.build();
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the intersection of two sets. The returned set contains
* all elements that are contained by both backing sets. The iteration order of the returned set
* matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*
* <p><b>Note:</b> The returned view performs slightly better when {@code set1} is the smaller of
* the two sets. If you have reason to believe one of your sets will generally be smaller than the
* other, pass it first. Unfortunately, since this method sets the generic type of the returned
* set based on the type of the first set passed, this could in rare cases force you to make a
* cast, for example:
*
* <pre>{@code
* Set<Object> aFewBadObjects = ...
* Set<String> manyBadStrings = ...
*
* // impossible for a non-String to be in the intersection
* SuppressWarnings("unchecked")
* Set<String> badStrings = (Set) Sets.intersection(
* aFewBadObjects, manyBadStrings);
* }</pre>
*
* <p>This is unfortunate, but should come up only very rarely.
*/
public static <E extends @Nullable Object> SetView<E> intersection(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public UnmodifiableIterator<E> iterator() {
return new AbstractIterator<E>() {
final Iterator<E> itr = set1.iterator();
@Override
@CheckForNull
protected E computeNext() {
while (itr.hasNext()) {
E e = itr.next();
if (set2.contains(e)) {
return e;
}
}
return endOfData();
}
};
}
@Override
public Stream<E> stream() {
return set1.stream().filter(set2::contains);
}
@Override
public Stream<E> parallelStream() {
return set1.parallelStream().filter(set2::contains);
}
@Override
public int size() {
int size = 0;
for (E e : set1) {
if (set2.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return Collections.disjoint(set2, set1);
}
@Override
public boolean contains(@CheckForNull Object object) {
return set1.contains(object) && set2.contains(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return set1.containsAll(collection) && set2.containsAll(collection);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the difference of two sets. The returned set contains
* all elements that are contained by {@code set1} and not contained by {@code set2}. {@code set2}
* may also contain elements not present in {@code set1}; these are simply ignored. The iteration
* order of the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*/
public static <E extends @Nullable Object> SetView<E> difference(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public UnmodifiableIterator<E> iterator() {
return new AbstractIterator<E>() {
final Iterator<E> itr = set1.iterator();
@Override
@CheckForNull
protected E computeNext() {
while (itr.hasNext()) {
E e = itr.next();
if (!set2.contains(e)) {
return e;
}
}
return endOfData();
}
};
}
@Override
public Stream<E> stream() {
return set1.stream().filter(e -> !set2.contains(e));
}
@Override
public Stream<E> parallelStream() {
return set1.parallelStream().filter(e -> !set2.contains(e));
}
@Override
public int size() {
int size = 0;
for (E e : set1) {
if (!set2.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return set2.containsAll(set1);
}
@Override
public boolean contains(@CheckForNull Object element) {
return set1.contains(element) && !set2.contains(element);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the symmetric difference of two sets. The returned set
* contains all elements that are contained in either {@code set1} or {@code set2} but not in
* both. The iteration order of the returned set is undefined.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on different
* equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a
* {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}.
*
* @since 3.0
*/
public static <E extends @Nullable Object> SetView<E> symmetricDifference(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
return new SetView<E>() {
@Override
public UnmodifiableIterator<E> iterator() {
final Iterator<? extends E> itr1 = set1.iterator();
final Iterator<? extends E> itr2 = set2.iterator();
return new AbstractIterator<E>() {
@Override
@CheckForNull
public E computeNext() {
while (itr1.hasNext()) {
E elem1 = itr1.next();
if (!set2.contains(elem1)) {
return elem1;
}
}
while (itr2.hasNext()) {
E elem2 = itr2.next();
if (!set1.contains(elem2)) {
return elem2;
}
}
return endOfData();
}
};
}
@Override
public int size() {
int size = 0;
for (E e : set1) {
if (!set2.contains(e)) {
size++;
}
}
for (E e : set2) {
if (!set1.contains(e)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return set1.equals(set2);
}
@Override
public boolean contains(@CheckForNull Object element) {
return set1.contains(element) ^ set2.contains(element);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The returned set is a live
* view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all other set methods
* are supported. When given an element that doesn't satisfy the predicate, the set's {@code
* add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements
* that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in
* the underlying set and determine which elements satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and
* use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link
* java.util.stream.Stream#filter}. This method is not being deprecated, but we gently encourage
* you to migrate to streams.
*/
// TODO(kevinb): how to omit that last sentence when building GWT javadoc?
public static <E extends @Nullable Object> Set<E> filter(
Set<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof SortedSet) {
return filter((SortedSet<E>) unfiltered, predicate);
}
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
return new FilteredSet<>((Set<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSet<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy a predicate. The
* returned set is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all other set methods
* are supported. When given an element that doesn't satisfy the predicate, the set's {@code
* add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements
* that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in
* the underlying set and determine which elements satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and
* use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* @since 11.0
*/
public static <E extends @Nullable Object> SortedSet<E> filter(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
return new FilteredSortedSet<>((SortedSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSortedSet<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that satisfy a predicate.
* The returned set is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all other set methods
* are supported. When given an element that doesn't satisfy the predicate, the set's {@code
* add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements
* that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in
* the underlying set and determine which elements satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and
* use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* @since 14.0
*/
@GwtIncompatible // NavigableSet
public static <E extends @Nullable Object> NavigableSet<E> filter(
NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
return new FilteredNavigableSet<>((NavigableSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredNavigableSet<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSet<E extends @Nullable Object> extends FilteredCollection<E>
implements Set<E> {
FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override
public boolean equals(@CheckForNull Object object) {
return equalsImpl(this, object);
}
@Override
public int hashCode() {
return hashCodeImpl(this);
}
}
private static class FilteredSortedSet<E extends @Nullable Object> extends FilteredSet<E>
implements SortedSet<E> {
FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override
@CheckForNull
public Comparator<? super E> comparator() {
return ((SortedSet<E>) unfiltered).comparator();
}
@Override
public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return new FilteredSortedSet<>(
((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate);
}
@Override
public SortedSet<E> headSet(@ParametricNullness E toElement) {
return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
}
@Override
public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
}
@Override
@ParametricNullness
public E first() {
return Iterators.find(unfiltered.iterator(), predicate);
}
@Override
@ParametricNullness
public E last() {
SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
while (true) {
E element = sortedUnfiltered.last();
if (predicate.apply(element)) {
return element;
}
sortedUnfiltered = sortedUnfiltered.headSet(element);
}
}
}
@GwtIncompatible // NavigableSet
private static class FilteredNavigableSet<E extends @Nullable Object> extends FilteredSortedSet<E>
implements NavigableSet<E> {
FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
NavigableSet<E> unfiltered() {
return (NavigableSet<E>) unfiltered;
}
@Override
@CheckForNull
public E lower(@ParametricNullness E e) {
return Iterators.find(unfiltered().headSet(e, false).descendingIterator(), predicate, null);
}
@Override
@CheckForNull
public E floor(@ParametricNullness E e) {
return Iterators.find(unfiltered().headSet(e, true).descendingIterator(), predicate, null);
}
@Override
@CheckForNull
public E ceiling(@ParametricNullness E e) {
return Iterables.find(unfiltered().tailSet(e, true), predicate, null);
}
@Override
@CheckForNull
public E higher(@ParametricNullness E e) {
return Iterables.find(unfiltered().tailSet(e, false), predicate, null);
}
@Override
@CheckForNull
public E pollFirst() {
return Iterables.removeFirstMatching(unfiltered(), predicate);
}
@Override
@CheckForNull
public E pollLast() {
return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate);
}
@Override
public NavigableSet<E> descendingSet() {
return Sets.filter(unfiltered().descendingSet(), predicate);
}
@Override
public Iterator<E> descendingIterator() {
return Iterators.filter(unfiltered().descendingIterator(), predicate);
}
@Override
@ParametricNullness
public E last() {
return Iterators.find(unfiltered().descendingIterator(), predicate);
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return filter(
unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate);
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return filter(unfiltered().headSet(toElement, inclusive), predicate);
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return filter(unfiltered().tailSet(fromElement, inclusive), predicate);
}
}
/**
* Returns every possible list that can be formed by choosing one element from each of the given
* sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example:
*
* <pre>{@code
* Sets.cartesianProduct(ImmutableList.of(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C")))
* }</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
* products that you would get from nesting for loops:
*
* <pre>{@code
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }
* }</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at
* all are provided (an empty list), the resulting Cartesian product has one element, an empty
* list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a
* set of size {@code m x n x p}, its actual memory consumption is much smaller. When the
* cartesian set is constructed, the input sets are merely copied. Only as the resulting set is
* iterated are the individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that the elements chosen from those
* sets should appear in the resulting lists
* @param <B> any common base class shared by all axes (often just {@link Object})
* @return the Cartesian product, as an immutable set containing immutable lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a
* provided set is null
* @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets) {
return CartesianSet.create(sets);
}
/**
* Returns every possible list that can be formed by choosing one element from each of the given
* sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example:
*
* <pre>{@code
* Sets.cartesianProduct(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C"))
* }</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
* products that you would get from nesting for loops:
*
* <pre>{@code
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }
* }</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at
* all are provided (an empty list), the resulting Cartesian product has one element, an empty
* list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a
* set of size {@code m x n x p}, its actual memory consumption is much smaller. When the
* cartesian set is constructed, the input sets are merely copied. Only as the resulting set is
* iterated are the individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that the elements chosen from those
* sets should appear in the resulting lists
* @param <B> any common base class shared by all axes (often just {@link Object})
* @return the Cartesian product, as an immutable set containing immutable lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a
* provided set is null
* @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range
* @since 2.0
*/
@SafeVarargs
public static <B> Set<List<B>> cartesianProduct(Set<? extends B>... sets) {
return cartesianProduct(Arrays.asList(sets));
}
private static final class CartesianSet<E> extends ForwardingCollection<List<E>>
implements Set<List<E>> {
private final transient ImmutableList<ImmutableSet<E>> axes;
private final transient CartesianList<E> delegate;
static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<>(sets.size());
for (Set<? extends E> set : sets) {
ImmutableSet<E> copy = ImmutableSet.copyOf(set);
if (copy.isEmpty()) {
return ImmutableSet.of();
}
axesBuilder.add(copy);
}
final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
ImmutableList<List<E>> listAxes =
new ImmutableList<List<E>>() {
@Override
public int size() {
return axes.size();
}
@Override
public List<E> get(int index) {
return axes.get(index).asList();
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
}
private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
this.axes = axes;
this.delegate = delegate;
}
@Override
protected Collection<List<E>> delegate() {
return delegate;
}
@Override
public boolean contains(@CheckForNull Object object) {
if (!(object instanceof List)) {
return false;
}
List<?> list = (List<?>) object;
if (list.size() != axes.size()) {
return false;
}
int i = 0;
for (Object o : list) {
if (!axes.get(i).contains(o)) {
return false;
}
i++;
}
return true;
}
@Override
public boolean equals(@CheckForNull Object object) {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
if (object instanceof CartesianSet) {
CartesianSet<?> that = (CartesianSet<?>) object;
return this.axes.equals(that.axes);
}
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return this.size() == that.size() && this.containsAll(that);
}
return false;
}
@Override
public int hashCode() {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
// It's a weird formula, but tests prove it works.
int adjust = size() - 1;
for (int i = 0; i < axes.size(); i++) {
adjust *= 31;
adjust = ~~adjust;
// in GWT, we have to deal with integer overflow carefully
}
int hash = 1;
for (Set<E> axis : axes) {
hash = 31 * hash + (size() / axis.size() * axis.hashCode());
hash = ~~hash;
}
hash += adjust;
return ~~hash;
}
}
/**
* Returns the set of all possible subsets of {@code set}. For example, {@code
* powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, {1}, {2}, {1, 2}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they appeared in the input
* set. The order in which these subsets appear in the outer set is undefined. Note that the power
* set of the empty set is not the empty set, but a one-element set containing the empty set.
*
* <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
* are identical, even if the input set uses a different concept of equivalence.
*
* <p><i>Performance notes:</i> while the power set of a set with size {@code n} is of size {@code
* 2^n}, its memory usage is only {@code O(n)}. When the power set is constructed, the input set
* is merely copied. Only as the power set is iterated are the individual subsets created, and
* these subsets themselves occupy only a small constant amount of memory.
*
* @param set the set of elements to construct a power set from
* @return the power set, as an immutable set of immutable sets
* @throws IllegalArgumentException if {@code set} has more than 30 unique elements (causing the
* power set size to exceed the {@code int} range)
* @throws NullPointerException if {@code set} is or contains {@code null}
* @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at Wikipedia</a>
* @since 4.0
*/
@GwtCompatible(serializable = false)
public static <E> Set<Set<E>> powerSet(Set<E> set) {
return new PowerSet<E>(set);
}
private static final class SubSet<E> extends AbstractSet<E> {
private final ImmutableMap<E, Integer> inputSet;
private final int mask;
SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
this.inputSet = inputSet;
this.mask = mask;
}
@Override
public Iterator<E> iterator() {
return new UnmodifiableIterator<E>() {
final ImmutableList<E> elements = inputSet.keySet().asList();
int remainingSetBits = mask;
@Override
public boolean hasNext() {
return remainingSetBits != 0;
}
@Override
public E next() {
int index = Integer.numberOfTrailingZeros(remainingSetBits);
if (index == 32) {
throw new NoSuchElementException();
}
remainingSetBits &= ~(1 << index);
return elements.get(index);
}
};
}
@Override
public int size() {
return Integer.bitCount(mask);
}
@Override
public boolean contains(@CheckForNull Object o) {
Integer index = inputSet.get(o);
return index != null && (mask & (1 << index)) != 0;
}
}
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableMap<E, Integer> inputSet;
PowerSet(Set<E> input) {
checkArgument(
input.size() <= 30, "Too many elements to create power set: %s > 30", input.size());
this.inputSet = Maps.indexMap(input);
}
@Override
public int size() {
return 1 << inputSet.size();
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<Set<E>> iterator() {
return new AbstractIndexedListIterator<Set<E>>(size()) {
@Override
protected Set<E> get(final int setBits) {
return new SubSet<>(inputSet, setBits);
}
};
}
@Override
public boolean contains(@CheckForNull Object obj) {
if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
return inputSet.keySet().containsAll(set);
}
return false;
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof PowerSet) {
PowerSet<?> that = (PowerSet<?>) obj;
return inputSet.keySet().equals(that.inputSet.keySet());
}
return super.equals(obj);
}
@Override
public int hashCode() {
/*
* The sum of the sums of the hash codes in each subset is just the sum of
* each input element's hash code times the number of sets that element
* appears in. Each element appears in exactly half of the 2^n sets, so:
*/
return inputSet.keySet().hashCode() << (inputSet.size() - 1);
}
@Override
public String toString() {
return "powerSet(" + inputSet + ")";
}
}
/**
* Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code
* combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they appeared in the input
* set. The order in which these subsets appear in the outer set is undefined.
*
* <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
* are identical, even if the input set uses a different concept of equivalence.
*
* <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When
* the result set is constructed, the input set is merely copied. Only as the result set is
* iterated are the individual subsets created. Each of these subsets occupies an additional O(n)
* memory but only for as long as the user retains a reference to it. That is, the set returned by
* {@code combinations} does not retain the individual subsets.
*
* @param set the set of elements to take combinations of
* @param size the number of elements per combination
* @return the set of all combinations of {@code size} elements from {@code set}
* @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()}
* inclusive
* @throws NullPointerException if {@code set} is or contains {@code null}
* @since 23.0
*/
public static <E> Set<Set<E>> combinations(Set<E> set, final int size) {
final ImmutableMap<E, Integer> index = Maps.indexMap(set);
checkNonnegative(size, "size");
checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size());
if (size == 0) {
return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of());
} else if (size == index.size()) {
return ImmutableSet.<Set<E>>of(index.keySet());
}
return new AbstractSet<Set<E>>() {
@Override
public boolean contains(@CheckForNull Object o) {
if (o instanceof Set) {
Set<?> s = (Set<?>) o;
return s.size() == size && index.keySet().containsAll(s);
}
return false;
}
@Override
public Iterator<Set<E>> iterator() {
return new AbstractIterator<Set<E>>() {
final BitSet bits = new BitSet(index.size());
@Override
@CheckForNull
protected Set<E> computeNext() {
if (bits.isEmpty()) {
bits.set(0, size);
} else {
int firstSetBit = bits.nextSetBit(0);
int bitToFlip = bits.nextClearBit(firstSetBit);
if (bitToFlip == index.size()) {
return endOfData();
}
/*
* The current set in sorted order looks like
* {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...}
* where it does *not* contain bitToFlip.
*
* The next combination is
*
* {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...}
*
* This is lexicographically next if you look at the combinations in descending order
* e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}...
*/
bits.set(0, bitToFlip - firstSetBit - 1);
bits.clear(bitToFlip - firstSetBit - 1, bitToFlip);
bits.set(bitToFlip);
}
final BitSet copy = (BitSet) bits.clone();
return new AbstractSet<E>() {
@Override
public boolean contains(@CheckForNull Object o) {
Integer i = index.get(o);
return i != null && copy.get(i);
}
@Override
public Iterator<E> iterator() {
return new AbstractIterator<E>() {
int i = -1;
@Override
@CheckForNull
protected E computeNext() {
i = copy.nextSetBit(i + 1);
if (i == -1) {
return endOfData();
}
return index.keySet().asList().get(i);
}
};
}
@Override
public int size() {
return size;
}
};
}
};
}
@Override
public int size() {
return IntMath.binomial(index.size(), size);
}
@Override
public String toString() {
return "Sets.combinations(" + index.keySet() + ", " + size + ")";
}
};
}
/** An implementation for {@link Set#hashCode()}. */
static int hashCodeImpl(Set<?> s) {
int hashCode = 0;
for (Object o : s) {
hashCode += o != null ? o.hashCode() : 0;
hashCode = ~~hashCode;
// Needed to deal with unusual integer overflow in GWT.
}
return hashCode;
}
/** An implementation for {@link Set#equals(Object)}. */
static boolean equalsImpl(Set<?> s, @CheckForNull Object object) {
if (s == object) {
return true;
}
if (object instanceof Set) {
Set<?> o = (Set<?>) object;
try {
return s.size() == o.size() && s.containsAll(o);
} catch (NullPointerException | ClassCastException ignored) {
return false;
}
}
return false;
}
/**
* Returns an unmodifiable view of the specified navigable set. This method allows modules to
* provide users with "read-only" access to internal navigable sets. Query operations on the
* returned set "read through" to the specified set, and attempts to modify the returned set,
* whether direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
* <p><b>Java 8+ users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}.
*
* @param set the navigable set for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable set
* @since 12.0
*/
public static <E extends @Nullable Object> NavigableSet<E> unmodifiableNavigableSet(
NavigableSet<E> set) {
if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) {
return set;
}
return new UnmodifiableNavigableSet<>(set);
}
static final class UnmodifiableNavigableSet<E extends @Nullable Object>
extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable {
private final NavigableSet<E> delegate;
private final SortedSet<E> unmodifiableDelegate;
UnmodifiableNavigableSet(NavigableSet<E> delegate) {
this.delegate = checkNotNull(delegate);
this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate);
}
@Override
protected SortedSet<E> delegate() {
return unmodifiableDelegate;
}
// default methods not forwarded by ForwardingSortedSet
@Override
public boolean removeIf(java.util.function.Predicate<? super E> filter) {
throw new UnsupportedOperationException();
}
@Override
public Stream<E> stream() {
return delegate.stream();
}
@Override
public Stream<E> parallelStream() {
return delegate.parallelStream();
}
@Override
public void forEach(Consumer<? super E> action) {
delegate.forEach(action);
}
@Override
@CheckForNull
public E lower(@ParametricNullness E e) {
return delegate.lower(e);
}
@Override
@CheckForNull
public E floor(@ParametricNullness E e) {
return delegate.floor(e);
}
@Override
@CheckForNull
public E ceiling(@ParametricNullness E e) {
return delegate.ceiling(e);
}
@Override
@CheckForNull
public E higher(@ParametricNullness E e) {
return delegate.higher(e);
}
@Override
@CheckForNull
public E pollFirst() {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public E pollLast() {
throw new UnsupportedOperationException();
}
@LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
@Override
public NavigableSet<E> descendingSet() {
UnmodifiableNavigableSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = new UnmodifiableNavigableSet<>(delegate.descendingSet());
result.descendingSet = this;
}
return result;
}
@Override
public Iterator<E> descendingIterator() {
return Iterators.unmodifiableIterator(delegate.descendingIterator());
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return unmodifiableNavigableSet(
delegate.subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive));
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In
* order to guarantee serial access, it is critical that <b>all</b> access to the backing
* navigable set is accomplished through the returned navigable set (or its views).
*
* <p>It is imperative that the user manually synchronize on the returned sorted set when
* iterating over it or any of its {@code descendingSet}, {@code subSet}, {@code headSet}, or
* {@code tailSet} views.
*
* <pre>{@code
* NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
* ...
* synchronized (set) {
* // Must be in the synchronized block
* Iterator<E> it = set.iterator();
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>or:
*
* <pre>{@code
* NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
* NavigableSet<E> set2 = set.descendingSet().headSet(foo);
* ...
* synchronized (set) { // Note: set, not set2!!!
* // Must be in the synchronized block
* Iterator<E> it = set2.descendingIterator();
* while (it.hasNext())
* foo(it.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
* <p><b>Java 8+ users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}.
*
* @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set.
* @return a synchronized view of the specified navigable set.
* @since 13.0
*/
@GwtIncompatible // NavigableSet
public static <E extends @Nullable Object> NavigableSet<E> synchronizedNavigableSet(
NavigableSet<E> navigableSet) {
return Synchronized.navigableSet(navigableSet);
}
/** Remove each element in an iterable from a set. */
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
boolean changed = false;
while (iterator.hasNext()) {
changed |= set.remove(iterator.next());
}
return changed;
}
static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
checkNotNull(collection); // for GWT
if (collection instanceof Multiset) {
collection = ((Multiset<?>) collection).elementSet();
}
/*
* AbstractSet.removeAll(List) has quadratic behavior if the list size
* is just more than the set's size. We augment the test by
* assuming that sets have fast contains() performance, and other
* collections don't. See
* http://code.google.com/p/guava-libraries/issues/detail?id=1013
*/
if (collection instanceof Set && collection.size() > set.size()) {
return Iterators.removeAll(set.iterator(), collection);
} else {
return removeAllImpl(set, collection.iterator());
}
}
@GwtIncompatible // NavigableSet
static class DescendingSet<E extends @Nullable Object> extends ForwardingNavigableSet<E> {
private final NavigableSet<E> forward;
DescendingSet(NavigableSet<E> forward) {
this.forward = forward;
}
@Override
protected NavigableSet<E> delegate() {
return forward;
}
@Override
@CheckForNull
public E lower(@ParametricNullness E e) {
return forward.higher(e);
}
@Override
@CheckForNull
public E floor(@ParametricNullness E e) {
return forward.ceiling(e);
}
@Override
@CheckForNull
public E ceiling(@ParametricNullness E e) {
return forward.floor(e);
}
@Override
@CheckForNull
public E higher(@ParametricNullness E e) {
return forward.lower(e);
}
@Override
@CheckForNull
public E pollFirst() {
return forward.pollLast();
}
@Override
@CheckForNull
public E pollLast() {
return forward.pollFirst();
}
@Override
public NavigableSet<E> descendingSet() {
return forward;
}
@Override
public Iterator<E> descendingIterator() {
return forward.iterator();
}
@Override
public NavigableSet<E> subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
}
@Override
public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return standardSubSet(fromElement, toElement);
}
@Override
public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
return forward.tailSet(toElement, inclusive).descendingSet();
}
@Override
public SortedSet<E> headSet(@ParametricNullness E toElement) {
return standardHeadSet(toElement);
}
@Override
public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return forward.headSet(fromElement, inclusive).descendingSet();
}
@Override
public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
return standardTailSet(fromElement);
}
@SuppressWarnings("unchecked")
@Override
public Comparator<? super E> comparator() {
Comparator<? super E> forwardComparator = forward.comparator();
if (forwardComparator == null) {
return (Comparator) Ordering.natural().reverse();
} else {
return reverse(forwardComparator);
}
}
// If we inline this, we get a javac error.
private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) {
return Ordering.from(forward).reverse();
}
@Override
@ParametricNullness
public E first() {
return forward.last();
}
@Override
@ParametricNullness
public E last() {
return forward.first();
}
@Override
public Iterator<E> iterator() {
return forward.descendingIterator();
}
@Override
public @Nullable Object[] toArray() {
return standardToArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override
public String toString() {
return standardToString();
}
}
/**
* Returns a view of the portion of {@code set} whose elements are contained by {@code range}.
*
* <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely {@link
* NavigableSet#subSet(Object, boolean, Object, boolean) subSet()}, {@link
* NavigableSet#tailSet(Object, boolean) tailSet()}, and {@link NavigableSet#headSet(Object,
* boolean) headSet()}) to actually construct the view. Consult these methods for a full
* description of the returned view's behavior.
*
* <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
* ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a {@link
* Comparator}, which can violate the natural ordering. Using this method (or in general using
* {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined behavior.
*
* @since 20.0
*/
@GwtIncompatible // NavigableSet
public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
NavigableSet<K> set, Range<K> range) {
if (set.comparator() != null
&& set.comparator() != Ordering.natural()
&& range.hasLowerBound()
&& range.hasUpperBound()) {
checkArgument(
set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
"set is using a custom comparator which is inconsistent with the natural ordering.");
}
if (range.hasLowerBound() && range.hasUpperBound()) {
return set.subSet(
range.lowerEndpoint(),
range.lowerBoundType() == BoundType.CLOSED,
range.upperEndpoint(),
range.upperBoundType() == BoundType.CLOSED);
} else if (range.hasLowerBound()) {
return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
} else if (range.hasUpperBound()) {
return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
}
return checkNotNull(set);
}
}
| google/guava | guava/src/com/google/common/collect/Sets.java |
673 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractSequentialList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code ListMultimap} that supports deterministic iteration order for both
* keys and values. The iteration order is preserved across non-distinct key values. For example,
* for the following multimap definition:
*
* <pre>{@code
* Multimap<K, V> multimap = LinkedListMultimap.create();
* multimap.put(key1, foo);
* multimap.put(key2, bar);
* multimap.put(key1, baz);
* }</pre>
*
* ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]}, and similarly for
* {@link #entries()}. Unlike {@link LinkedHashMultimap}, the iteration order is kept consistent
* between keys, entries and values. For example, calling:
*
* <pre>{@code
* multimap.remove(key1, foo);
* }</pre>
*
* <p>changes the entries iteration order to {@code [key2=bar, key1=baz]} and the key iteration
* order to {@code [key2, key1]}. The {@link #entries()} iterator returns mutable map entries, and
* {@link #replaceValues} attempts to preserve iteration order as much as possible.
*
* <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate through the keys in
* the order they were first added to the multimap. Similarly, {@link #get}, {@link #removeAll}, and
* {@link #replaceValues} return collections that iterate through the values in the order they were
* added. The collections generated by {@link #entries()}, {@link #keys()}, and {@link #values}
* iterate across the key-value mappings in the order they were added to the multimap.
*
* <p>The {@link #values()} and {@link #entries()} methods both return a {@code List}, instead of
* the {@code Collection} specified by the {@link ListMultimap} interface.
*
* <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()}, {@link #values}, {@link
* #entries()}, and {@link #asMap} return collections that are views of the multimap. If the
* multimap is modified while an iteration over any of those collections is in progress, except
* through the iterator's methods, the results of the iteration are undefined.
*
* <p>Keys and values may be null. All optional multimap methods are supported, and all returned
* views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent
* read operations will work correctly. To allow concurrent update operations, wrap your multimap
* with a call to {@link Multimaps#synchronizedListMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap">{@code Multimap}</a>.
*
* @author Mike Bostock
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@ElementTypesAreNonnullByDefault
public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMultimap<K, V> implements ListMultimap<K, V>, Serializable {
/*
* Order is maintained using a linked list containing all key-value pairs. In
* addition, a series of disjoint linked lists of "siblings", each containing
* the values for a specific key, is used to implement {@link
* ValueForKeyIterator} in constant time.
*/
static final class Node<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMapEntry<K, V> {
@ParametricNullness final K key;
@ParametricNullness V value;
@CheckForNull Node<K, V> next; // the next node (with any key)
@CheckForNull Node<K, V> previous; // the previous node (with any key)
@CheckForNull Node<K, V> nextSibling; // the next node with the same key
@CheckForNull Node<K, V> previousSibling; // the previous node with the same key
Node(@ParametricNullness K key, @ParametricNullness V value) {
this.key = key;
this.value = value;
}
@Override
@ParametricNullness
public K getKey() {
return key;
}
@Override
@ParametricNullness
public V getValue() {
return value;
}
@Override
@ParametricNullness
public V setValue(@ParametricNullness V newValue) {
V result = value;
this.value = newValue;
return result;
}
}
private static class KeyList<K extends @Nullable Object, V extends @Nullable Object> {
Node<K, V> head;
Node<K, V> tail;
int count;
KeyList(Node<K, V> firstNode) {
this.head = firstNode;
this.tail = firstNode;
firstNode.previousSibling = null;
firstNode.nextSibling = null;
this.count = 1;
}
}
@CheckForNull private transient Node<K, V> head; // the head for all keys
@CheckForNull private transient Node<K, V> tail; // the tail for all keys
private transient Map<K, KeyList<K, V>> keyToKeyList;
private transient int size;
/*
* Tracks modifications to keyToKeyList so that addition or removal of keys invalidates
* preexisting iterators. This does *not* track simple additions and removals of values
* that are not the first to be added or last to be removed for their key.
*/
private transient int modCount;
/** Creates a new, empty {@code LinkedListMultimap} with the default initial capacity. */
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedListMultimap<K, V> create() {
return new LinkedListMultimap<>();
}
/**
* Constructs an empty {@code LinkedListMultimap} with enough capacity to hold the specified
* number of keys without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @throws IllegalArgumentException if {@code expectedKeys} is negative
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedListMultimap<K, V> create(int expectedKeys) {
return new LinkedListMultimap<>(expectedKeys);
}
/**
* Constructs a {@code LinkedListMultimap} with the same mappings as the specified {@code
* Multimap}. The new multimap has the same {@link Multimap#entries()} iteration order as the
* input multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedListMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
return new LinkedListMultimap<>(multimap);
}
LinkedListMultimap() {
this(12);
}
private LinkedListMultimap(int expectedKeys) {
keyToKeyList = Platform.newHashMapWithExpectedSize(expectedKeys);
}
private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size());
putAll(multimap);
}
/**
* Adds a new node for the specified key-value pair before the specified {@code nextSibling}
* element, or at the end of the list if {@code nextSibling} is null. Note: if {@code nextSibling}
* is specified, it MUST be for a node for the same {@code key}!
*/
@CanIgnoreReturnValue
private Node<K, V> addNode(
@ParametricNullness K key,
@ParametricNullness V value,
@CheckForNull Node<K, V> nextSibling) {
Node<K, V> node = new Node<>(key, value);
if (head == null) { // empty list
head = tail = node;
keyToKeyList.put(key, new KeyList<K, V>(node));
modCount++;
} else if (nextSibling == null) { // non-empty list, add to tail
// requireNonNull is safe because the list is non-empty.
requireNonNull(tail).next = node;
node.previous = tail;
tail = node;
KeyList<K, V> keyList = keyToKeyList.get(key);
if (keyList == null) {
keyToKeyList.put(key, keyList = new KeyList<>(node));
modCount++;
} else {
keyList.count++;
Node<K, V> keyTail = keyList.tail;
keyTail.nextSibling = node;
node.previousSibling = keyTail;
keyList.tail = node;
}
} else { // non-empty list, insert before nextSibling
/*
* requireNonNull is safe as long as callers pass a nextSibling that (a) has the same key and
* (b) is present in the multimap. (And they do, except maybe in case of concurrent
* modification, in which case all bets are off.)
*/
KeyList<K, V> keyList = requireNonNull(keyToKeyList.get(key));
keyList.count++;
node.previous = nextSibling.previous;
node.previousSibling = nextSibling.previousSibling;
node.next = nextSibling;
node.nextSibling = nextSibling;
if (nextSibling.previousSibling == null) { // nextSibling was key head
keyList.head = node;
} else {
nextSibling.previousSibling.nextSibling = node;
}
if (nextSibling.previous == null) { // nextSibling was head
head = node;
} else {
nextSibling.previous.next = node;
}
nextSibling.previous = node;
nextSibling.previousSibling = node;
}
size++;
return node;
}
/**
* Removes the specified node from the linked list. This method is only intended to be used from
* the {@code Iterator} classes. See also {@link LinkedListMultimap#removeAllNodes(Object)}.
*/
private void removeNode(Node<K, V> node) {
if (node.previous != null) {
node.previous.next = node.next;
} else { // node was head
head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else { // node was tail
tail = node.previous;
}
if (node.previousSibling == null && node.nextSibling == null) {
/*
* requireNonNull is safe as long as we call removeNode only for nodes that are still in the
* Multimap. This should be the case (except in case of concurrent modification, when all bets
* are off).
*/
KeyList<K, V> keyList = requireNonNull(keyToKeyList.remove(node.key));
keyList.count = 0;
modCount++;
} else {
// requireNonNull is safe (under the conditions listed in the comment in the branch above).
KeyList<K, V> keyList = requireNonNull(keyToKeyList.get(node.key));
keyList.count--;
if (node.previousSibling == null) {
// requireNonNull is safe because we checked that not *both* siblings were null.
keyList.head = requireNonNull(node.nextSibling);
} else {
node.previousSibling.nextSibling = node.nextSibling;
}
if (node.nextSibling == null) {
// requireNonNull is safe because we checked that not *both* siblings were null.
keyList.tail = requireNonNull(node.previousSibling);
} else {
node.nextSibling.previousSibling = node.previousSibling;
}
}
size--;
}
/** Removes all nodes for the specified key. */
private void removeAllNodes(@ParametricNullness K key) {
Iterators.clear(new ValueForKeyIterator(key));
}
/** An {@code Iterator} over all nodes. */
private class NodeIterator implements ListIterator<Entry<K, V>> {
int nextIndex;
@CheckForNull Node<K, V> next;
@CheckForNull Node<K, V> current;
@CheckForNull Node<K, V> previous;
int expectedModCount = modCount;
NodeIterator(int index) {
int size = size();
checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = head;
while (index-- > 0) {
next();
}
}
current = null;
}
private void checkForConcurrentModification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForConcurrentModification();
return next != null;
}
@CanIgnoreReturnValue
@Override
public Node<K, V> next() {
checkForConcurrentModification();
if (next == null) {
throw new NoSuchElementException();
}
previous = current = next;
next = next.next;
nextIndex++;
return current;
}
@Override
public void remove() {
checkForConcurrentModification();
checkState(current != null, "no calls to next() since the last call to remove()");
if (current != next) { // after call to next()
previous = current.previous;
nextIndex--;
} else { // after call to previous()
next = current.next;
}
removeNode(current);
current = null;
expectedModCount = modCount;
}
@Override
public boolean hasPrevious() {
checkForConcurrentModification();
return previous != null;
}
@CanIgnoreReturnValue
@Override
public Node<K, V> previous() {
checkForConcurrentModification();
if (previous == null) {
throw new NoSuchElementException();
}
next = current = previous;
previous = previous.previous;
nextIndex--;
return current;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void set(Entry<K, V> e) {
throw new UnsupportedOperationException();
}
@Override
public void add(Entry<K, V> e) {
throw new UnsupportedOperationException();
}
void setValue(@ParametricNullness V value) {
checkState(current != null);
current.value = value;
}
}
/** An {@code Iterator} over distinct keys in key head order. */
private class DistinctKeyIterator implements Iterator<K> {
final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size());
@CheckForNull Node<K, V> next = head;
@CheckForNull Node<K, V> current;
int expectedModCount = modCount;
private void checkForConcurrentModification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForConcurrentModification();
return next != null;
}
@Override
@ParametricNullness
public K next() {
checkForConcurrentModification();
if (next == null) {
throw new NoSuchElementException();
}
current = next;
seenKeys.add(current.key);
do { // skip ahead to next unseen key
next = next.next;
} while ((next != null) && !seenKeys.add(next.key));
return current.key;
}
@Override
public void remove() {
checkForConcurrentModification();
checkState(current != null, "no calls to next() since the last call to remove()");
removeAllNodes(current.key);
current = null;
expectedModCount = modCount;
}
}
/** A {@code ListIterator} over values for a specified key. */
private class ValueForKeyIterator implements ListIterator<V> {
@ParametricNullness final K key;
int nextIndex;
@CheckForNull Node<K, V> next;
@CheckForNull Node<K, V> current;
@CheckForNull Node<K, V> previous;
/** Constructs a new iterator over all values for the specified key. */
ValueForKeyIterator(@ParametricNullness K key) {
this.key = key;
KeyList<K, V> keyList = keyToKeyList.get(key);
next = (keyList == null) ? null : keyList.head;
}
/**
* Constructs a new iterator over all values for the specified key starting at the specified
* index. This constructor is optimized so that it starts at either the head or the tail,
* depending on which is closer to the specified index. This allows adds to the tail to be done
* in constant time.
*
* @throws IndexOutOfBoundsException if index is invalid
*/
public ValueForKeyIterator(@ParametricNullness K key, int index) {
KeyList<K, V> keyList = keyToKeyList.get(key);
int size = (keyList == null) ? 0 : keyList.count;
checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = (keyList == null) ? null : keyList.tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = (keyList == null) ? null : keyList.head;
while (index-- > 0) {
next();
}
}
this.key = key;
current = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@CanIgnoreReturnValue
@Override
@ParametricNullness
public V next() {
if (next == null) {
throw new NoSuchElementException();
}
previous = current = next;
next = next.nextSibling;
nextIndex++;
return current.value;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@CanIgnoreReturnValue
@Override
@ParametricNullness
public V previous() {
if (previous == null) {
throw new NoSuchElementException();
}
next = current = previous;
previous = previous.previousSibling;
nextIndex--;
return current.value;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void remove() {
checkState(current != null, "no calls to next() since the last call to remove()");
if (current != next) { // after call to next()
previous = current.previousSibling;
nextIndex--;
} else { // after call to previous()
next = current.nextSibling;
}
removeNode(current);
current = null;
}
@Override
public void set(@ParametricNullness V value) {
checkState(current != null);
current.value = value;
}
@Override
public void add(@ParametricNullness V value) {
previous = addNode(key, value, next);
nextIndex++;
current = null;
}
}
// Query Operations
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return keyToKeyList.containsKey(key);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return values().contains(value);
}
// Modification Operations
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} always
*/
@CanIgnoreReturnValue
@Override
public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
addNode(key, value, null);
return true;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>If any entries for the specified {@code key} already exist in the multimap, their values are
* changed in-place without affecting the iteration order.
*
* <p>The returned list is immutable and implements {@link java.util.RandomAccess}.
*/
@CanIgnoreReturnValue
@Override
public List<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
List<V> oldValues = getCopy(key);
ListIterator<V> keyValues = new ValueForKeyIterator(key);
Iterator<? extends V> newValues = values.iterator();
// Replace existing values, if any.
while (keyValues.hasNext() && newValues.hasNext()) {
keyValues.next();
keyValues.set(newValues.next());
}
// Remove remaining old values, if any.
while (keyValues.hasNext()) {
keyValues.next();
keyValues.remove();
}
// Add remaining new values, if any.
while (newValues.hasNext()) {
keyValues.add(newValues.next());
}
return oldValues;
}
private List<V> getCopy(@ParametricNullness K key) {
return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key)));
}
/**
* {@inheritDoc}
*
* <p>The returned list is immutable and implements {@link java.util.RandomAccess}.
*/
@CanIgnoreReturnValue
@Override
public List<V> removeAll(@CheckForNull Object key) {
/*
* Safe because all we do is remove values for the key, not add them. (If we wanted to make sure
* to call getCopy and removeAllNodes only with a true K, then we could check containsKey first.
* But that check wouldn't eliminate the warnings.)
*/
@SuppressWarnings({"unchecked", "nullness"})
K castKey = (K) key;
List<V> oldValues = getCopy(castKey);
removeAllNodes(castKey);
return oldValues;
}
@Override
public void clear() {
head = null;
tail = null;
keyToKeyList.clear();
size = 0;
modCount++;
}
// Views
/**
* {@inheritDoc}
*
* <p>If the multimap is modified while an iteration over the list is in progress (except through
* the iterator's own {@code add}, {@code set} or {@code remove} operations) the results of the
* iteration are undefined.
*
* <p>The returned list is not serializable and does not have random access.
*/
@Override
public List<V> get(@ParametricNullness final K key) {
return new AbstractSequentialList<V>() {
@Override
public int size() {
KeyList<K, V> keyList = keyToKeyList.get(key);
return (keyList == null) ? 0 : keyList.count;
}
@Override
public ListIterator<V> listIterator(int index) {
return new ValueForKeyIterator(key, index);
}
};
}
@Override
Set<K> createKeySet() {
@WeakOuter
class KeySetImpl extends Sets.ImprovedAbstractSet<K> {
@Override
public int size() {
return keyToKeyList.size();
}
@Override
public Iterator<K> iterator() {
return new DistinctKeyIterator();
}
@Override
public boolean contains(@CheckForNull Object key) { // for performance
return containsKey(key);
}
@Override
public boolean remove(@CheckForNull Object o) { // for performance
return !LinkedListMultimap.this.removeAll(o).isEmpty();
}
}
return new KeySetImpl();
}
@Override
Multiset<K> createKeys() {
return new Multimaps.Keys<K, V>(this);
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values in the order they
* were added to the multimap. Because the values may have duplicates and follow the insertion
* ordering, this method returns a {@link List}, instead of the {@link Collection} specified in
* the {@link ListMultimap} interface.
*/
@Override
public List<V> values() {
return (List<V>) super.values();
}
@Override
List<V> createValues() {
@WeakOuter
class ValuesImpl extends AbstractSequentialList<V> {
@Override
public int size() {
return size;
}
@Override
public ListIterator<V> listIterator(int index) {
final NodeIterator nodeItr = new NodeIterator(index);
return new TransformedListIterator<Entry<K, V>, V>(nodeItr) {
@Override
@ParametricNullness
V transform(Entry<K, V> entry) {
return entry.getValue();
}
@Override
public void set(@ParametricNullness V value) {
nodeItr.setValue(value);
}
};
}
}
return new ValuesImpl();
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the entries in the order they
* were added to the multimap. Because the entries may have duplicates and follow the insertion
* ordering, this method returns a {@link List}, instead of the {@link Collection} specified in
* the {@link ListMultimap} interface.
*
* <p>An entry's {@link Entry#getKey} method always returns the same key, regardless of what
* happens subsequently. As long as the corresponding key-value mapping is not removed from the
* multimap, {@link Entry#getValue} returns the value from the multimap, which may change over
* time, and {@link Entry#setValue} modifies that value. Removing the mapping from the multimap
* does not alter the value returned by {@code getValue()}, though a subsequent {@code setValue()}
* call won't update the multimap but will lead to a revised value being returned by {@code
* getValue()}.
*/
@Override
public List<Entry<K, V>> entries() {
return (List<Entry<K, V>>) super.entries();
}
@Override
List<Entry<K, V>> createEntries() {
@WeakOuter
class EntriesImpl extends AbstractSequentialList<Entry<K, V>> {
@Override
public int size() {
return size;
}
@Override
public ListIterator<Entry<K, V>> listIterator(int index) {
return new NodeIterator(index);
}
@Override
public void forEach(Consumer<? super Entry<K, V>> action) {
checkNotNull(action);
for (Node<K, V> node = head; node != null; node = node.next) {
action.accept(node);
}
}
}
return new EntriesImpl();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
Map<K, Collection<V>> createAsMap() {
return new Multimaps.AsMap<>(this);
}
/**
* @serialData the number of distinct keys, and then for each distinct key: the first key, the
* number of values for that key, and the key's values, followed by successive keys and values
* from the entries() ordering
*/
@GwtIncompatible // java.io.ObjectOutputStream
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
for (Entry<K, V> entry : entries()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
@GwtIncompatible // java.io.ObjectInputStream
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyToKeyList = Maps.newLinkedHashMap();
int size = stream.readInt();
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeObject
K key = (K) stream.readObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
V value = (V) stream.readObject();
put(key, value);
}
}
@GwtIncompatible // java serialization not supported
@J2ktIncompatible
private static final long serialVersionUID = 0;
}
| google/guava | guava/src/com/google/common/collect/LinkedListMultimap.java |
675 | package com.alibaba.druid;
import com.alibaba.druid.util.FnvHash;
public enum DbType {
other(1 << 0),
jtds(1 << 1),
hsql(1 << 2),
db2(1 << 3),
postgresql(1 << 4),
sqlserver(1 << 5),
oracle(1 << 6),
mysql(1 << 7),
mariadb(1 << 8),
derby(1 << 9),
hive(1 << 10),
h2(1 << 11),
dm(1 << 12), // dm.jdbc.driver.DmDriver
kingbase(1 << 13),
gbase(1 << 14),
oceanbase(1 << 15),
informix(1 << 16),
odps(1 << 17),
teradata(1 << 18),
phoenix(1 << 19),
edb(1 << 20),
kylin(1 << 21), // org.apache.kylin.jdbc.Driver
sqlite(1 << 22),
ads(1 << 23),
presto(1 << 24),
elastic_search(1 << 25), // com.alibaba.xdriver.elastic.jdbc.ElasticDriver
hbase(1 << 26),
drds(1 << 27),
clickhouse(1 << 28),
blink(1 << 29),
antspark(1 << 30),
oceanbase_oracle(1 << 31),
polardb(1L << 32),
ali_oracle(1L << 33),
mock(1L << 34),
sybase(1L << 35),
highgo(1L << 36),
/**
* 非常成熟的开源mpp数据库
*/
greenplum(1L << 37),
/**
* 华为的mpp数据库
*/
gaussdb(1L << 38),
trino(1L << 39),
oscar(1L << 40),
tidb(1L << 41),
tydb(1L << 42),
starrocks(1L << 43),
goldendb(1L << 44),
ingres(0),
cloudscape(0),
timesten(0),
as400(0),
sapdb(0),
kdb(0),
log4jdbc(0),
xugu(0),
firebirdsql(0),
JSQLConnect(0),
JTurbo(0),
interbase(0),
pointbase(0),
edbc(0),
mimer(0),
taosdata(0);
public final long mask;
public final long hashCode64;
private DbType(long mask) {
this.mask = mask;
this.hashCode64 = FnvHash.hashCode64(name());
}
public static long of(DbType... types) {
long value = 0;
for (DbType type : types) {
value |= type.mask;
}
return value;
}
public static DbType of(String name) {
if (name == null || name.isEmpty()) {
return null;
}
if ("aliyun_ads".equalsIgnoreCase(name)) {
return ads;
}
try {
return valueOf(name);
} catch (Exception e) {
return null;
}
}
public static boolean isPostgreSQLDbStyle(DbType dbType) {
return dbType == DbType.postgresql || dbType == DbType.edb || dbType == DbType.greenplum;
}
public final boolean equals(String other) {
return this == of(other);
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/DbType.java |
676 | /*
* @notice
*
* Copyright 2020 Adrien Grand and the lz4-java contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.elasticsearch.lz4;
import net.jpountz.util.Utils;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
/**
* This file is forked from https://github.com/lz4/lz4-java. In particular, it forks the following file
* net.jpountz.lz4.SafeUtils.
*
* It modifies the original implementation to use Java9 varhandle performance improvements. Comments
* are included to mark the changes.
*/
public enum SafeUtils {
;
// Added VarHandle
private static final VarHandle intPlatformNative = MethodHandles.byteArrayViewVarHandle(int[].class, Utils.NATIVE_BYTE_ORDER);
private static final VarHandle shortLittleEndian = MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.LITTLE_ENDIAN);
public static void checkRange(byte[] buf, int off) {
if (off < 0 || off >= buf.length) {
throw new ArrayIndexOutOfBoundsException(off);
}
}
public static void checkRange(byte[] buf, int off, int len) {
checkLength(len);
if (len > 0) {
checkRange(buf, off);
checkRange(buf, off + len - 1);
}
}
public static void checkLength(int len) {
if (len < 0) {
throw new IllegalArgumentException("lengths must be >= 0");
}
}
public static byte readByte(byte[] buf, int i) {
return buf[i];
}
// Deleted unused dedicated LE/BE readInt methods
// Modified to use VarHandle
public static int readInt(byte[] buf, int i) {
return (int) intPlatformNative.get(buf, i);
}
// Unused in forked instance, no need to optimize
public static long readLongLE(byte[] buf, int i) {
return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) | ((buf[i + 4]
& 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56);
}
// Modified to use VarHandle
public static void writeShortLE(byte[] buf, int off, int v) {
shortLittleEndian.set(buf, off, (short) v);
}
public static void writeInt(int[] buf, int off, int v) {
buf[off] = v;
}
public static int readInt(int[] buf, int off) {
return buf[off];
}
public static void writeByte(byte[] dest, int off, int i) {
dest[off] = (byte) i;
}
public static void writeShort(short[] buf, int off, int v) {
buf[off] = (short) v;
}
// Modified to use VarHandle
public static int readShortLE(byte[] buf, int i) {
return Short.toUnsignedInt((short) shortLittleEndian.get(buf, i));
}
public static int readShort(short[] buf, int off) {
return buf[off] & 0xFFFF;
}
}
| elastic/elasticsearch | libs/lz4/src/main/java/org/elasticsearch/lz4/SafeUtils.java |
677 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.inference;
import java.util.Objects;
public class Model {
public static String documentId(String modelId) {
return "model_" + modelId;
}
private final ModelConfigurations configurations;
private final ModelSecrets secrets;
public Model(ModelConfigurations configurations, ModelSecrets secrets) {
this.configurations = Objects.requireNonNull(configurations);
this.secrets = Objects.requireNonNull(secrets);
}
public Model(Model model, TaskSettings taskSettings) {
Objects.requireNonNull(model);
configurations = ModelConfigurations.of(model, taskSettings);
secrets = model.getSecrets();
}
public Model(Model model, ServiceSettings serviceSettings) {
Objects.requireNonNull(model);
configurations = ModelConfigurations.of(model, serviceSettings);
secrets = model.getSecrets();
}
public Model(ModelConfigurations configurations) {
this(configurations, new ModelSecrets());
}
public String getInferenceEntityId() {
return configurations.getInferenceEntityId();
}
public TaskType getTaskType() {
return configurations.getTaskType();
}
/**
* Returns the model's non-sensitive configurations (e.g. service name).
*/
public ModelConfigurations getConfigurations() {
return configurations;
}
/**
* Returns the model's sensitive configurations (e.g. api key).
*
* This returns an object that in json would look like:
*
* <pre>
* {@code
* {
* "secret_settings": { "api_key": "abc" }
* }
* }
* </pre>
*/
public ModelSecrets getSecrets() {
return secrets;
}
public ServiceSettings getServiceSettings() {
return configurations.getServiceSettings();
}
public TaskSettings getTaskSettings() {
return configurations.getTaskSettings();
}
/**
* Returns the inner sensitive data defined by a particular service.
*
* This returns an object that in json would look like:
*
* <pre>
* {@code
* {
* "api_key": "abc"
* }
* }
* </pre>
*/
public SecretSettings getSecretSettings() {
return secrets.getSecretSettings();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Model model = (Model) o;
return Objects.equals(configurations, model.configurations) && Objects.equals(secrets, model.secrets);
}
@Override
public int hashCode() {
return Objects.hash(configurations, secrets);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/inference/Model.java |
678 | /*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.alwaysTrue;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Maps.safeContainsKey;
import static com.google.common.collect.Maps.safeGet;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.common.collect.Maps.ViewCachingAbstractMap;
import com.google.common.collect.Sets.ImprovedAbstractSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckForNull;
/**
* {@link Table} implementation backed by a map that associates row keys with column key / value
* secondary maps. This class provides rapid access to records by the row key alone or by both keys,
* but not by just the column key.
*
* <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link #columnMap()} have
* iterators that don't support {@code remove()}. Otherwise, all optional operations are supported.
* Null row keys, columns keys, and values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because the data is stored in
* a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still runs
* quickly, since the row key is provided. However, {@code column(columnKey).size()} takes longer,
* since an iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads access this table
* concurrently and one of the threads modifies the table, it must be synchronized externally.
*
* @author Jared Levy
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable {
@GwtTransient final Map<R, Map<C, V>> backingMap;
@GwtTransient final Supplier<? extends Map<C, V>> factory;
StandardTable(Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
this.backingMap = backingMap;
this.factory = factory;
}
// Accessors
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return rowKey != null && columnKey != null && super.contains(rowKey, columnKey);
}
@Override
public boolean containsColumn(@CheckForNull Object columnKey) {
if (columnKey == null) {
return false;
}
for (Map<C, V> map : backingMap.values()) {
if (safeContainsKey(map, columnKey)) {
return true;
}
}
return false;
}
@Override
public boolean containsRow(@CheckForNull Object rowKey) {
return rowKey != null && safeContainsKey(backingMap, rowKey);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return value != null && super.containsValue(value);
}
@Override
@CheckForNull
public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return (rowKey == null || columnKey == null) ? null : super.get(rowKey, columnKey);
}
@Override
public boolean isEmpty() {
return backingMap.isEmpty();
}
@Override
public int size() {
int size = 0;
for (Map<C, V> map : backingMap.values()) {
size += map.size();
}
return size;
}
// Mutators
@Override
public void clear() {
backingMap.clear();
}
private Map<C, V> getOrCreate(R rowKey) {
Map<C, V> map = backingMap.get(rowKey);
if (map == null) {
map = factory.get();
backingMap.put(rowKey, map);
}
return map;
}
@CanIgnoreReturnValue
@Override
@CheckForNull
public V put(R rowKey, C columnKey, V value) {
checkNotNull(rowKey);
checkNotNull(columnKey);
checkNotNull(value);
return getOrCreate(rowKey).put(columnKey, value);
}
@CanIgnoreReturnValue
@Override
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
if ((rowKey == null) || (columnKey == null)) {
return null;
}
Map<C, V> map = safeGet(backingMap, rowKey);
if (map == null) {
return null;
}
V value = map.remove(columnKey);
if (map.isEmpty()) {
backingMap.remove(rowKey);
}
return value;
}
@CanIgnoreReturnValue
private Map<R, V> removeColumn(@CheckForNull Object column) {
Map<R, V> output = new LinkedHashMap<>();
Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<R, Map<C, V>> entry = iterator.next();
V value = entry.getValue().remove(column);
if (value != null) {
output.put(entry.getKey(), value);
if (entry.getValue().isEmpty()) {
iterator.remove();
}
}
}
return output;
}
private boolean containsMapping(
@CheckForNull Object rowKey, @CheckForNull Object columnKey, @CheckForNull Object value) {
return value != null && value.equals(get(rowKey, columnKey));
}
/** Remove a row key / column key / value mapping, if present. */
private boolean removeMapping(
@CheckForNull Object rowKey, @CheckForNull Object columnKey, @CheckForNull Object value) {
if (containsMapping(rowKey, columnKey, value)) {
remove(rowKey, columnKey);
return true;
}
return false;
}
// Views
/**
* Abstract set whose {@code isEmpty()} returns whether the table is empty and whose {@code
* clear()} clears all table mappings.
*/
@WeakOuter
private abstract class TableSet<T> extends ImprovedAbstractSet<T> {
@Override
public boolean isEmpty() {
return backingMap.isEmpty();
}
@Override
public void clear() {
backingMap.clear();
}
}
/**
* {@inheritDoc}
*
* <p>The set's iterator traverses the mappings for the first row, the mappings for the second
* row, and so on.
*
* <p>Each cell is an immutable snapshot of a row key / column key / value mapping, taken at the
* time the cell is returned by a method call to the set or its iterator.
*/
@Override
public Set<Cell<R, C, V>> cellSet() {
return super.cellSet();
}
@Override
Iterator<Cell<R, C, V>> cellIterator() {
return new CellIterator();
}
private class CellIterator implements Iterator<Cell<R, C, V>> {
final Iterator<Entry<R, Map<C, V>>> rowIterator = backingMap.entrySet().iterator();
@CheckForNull Entry<R, Map<C, V>> rowEntry;
Iterator<Entry<C, V>> columnIterator = Iterators.emptyModifiableIterator();
@Override
public boolean hasNext() {
return rowIterator.hasNext() || columnIterator.hasNext();
}
@Override
public Cell<R, C, V> next() {
if (!columnIterator.hasNext()) {
rowEntry = rowIterator.next();
columnIterator = rowEntry.getValue().entrySet().iterator();
}
/*
* requireNonNull is safe because:
*
* - columnIterator started off pointing to an empty iterator, so we must have entered the
* `if` body above at least once. Thus, if we got this far, that `if` body initialized
* rowEntry at least once.
*
* - The only case in which rowEntry is cleared (during remove() below) happens only if the
* caller removed every element from columnIterator. During that process, we would have had
* to iterate it to exhaustion. Then we can apply the logic above about an empty
* columnIterator. (This assumes no concurrent modification, but behavior under concurrent
* modification is undefined, anyway.)
*/
requireNonNull(rowEntry);
Entry<C, V> columnEntry = columnIterator.next();
return Tables.immutableCell(rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue());
}
@Override
public void remove() {
columnIterator.remove();
/*
* requireNonNull is safe because:
*
* - columnIterator.remove() succeeded, so it must have returned a value, so it must have been
* initialized by next() -- which initializes rowEntry, too.
*
* - rowEntry isn't cleared except below. If it was cleared below, then either
* columnIterator.remove() would have failed above (if the user hasn't called next() since
* then) or rowEntry would have been initialized by next() (as discussed above).
*/
if (requireNonNull(rowEntry).getValue().isEmpty()) {
rowIterator.remove();
rowEntry = null;
}
}
}
@Override
public Map<C, V> row(R rowKey) {
return new Row(rowKey);
}
class Row extends IteratorBasedAbstractMap<C, V> {
final R rowKey;
Row(R rowKey) {
this.rowKey = checkNotNull(rowKey);
}
@CheckForNull Map<C, V> backingRowMap;
final void updateBackingRowMapField() {
if (backingRowMap == null || (backingRowMap.isEmpty() && backingMap.containsKey(rowKey))) {
backingRowMap = computeBackingRowMap();
}
}
@CheckForNull
Map<C, V> computeBackingRowMap() {
return backingMap.get(rowKey);
}
// Call this every time we perform a removal.
void maintainEmptyInvariant() {
updateBackingRowMapField();
if (backingRowMap != null && backingRowMap.isEmpty()) {
backingMap.remove(rowKey);
backingRowMap = null;
}
}
@Override
public boolean containsKey(@CheckForNull Object key) {
updateBackingRowMapField();
return (key != null && backingRowMap != null) && Maps.safeContainsKey(backingRowMap, key);
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
updateBackingRowMapField();
return (key != null && backingRowMap != null) ? Maps.safeGet(backingRowMap, key) : null;
}
@Override
@CheckForNull
public V put(C key, V value) {
checkNotNull(key);
checkNotNull(value);
if (backingRowMap != null && !backingRowMap.isEmpty()) {
return backingRowMap.put(key, value);
}
return StandardTable.this.put(rowKey, key, value);
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
updateBackingRowMapField();
if (backingRowMap == null) {
return null;
}
V result = Maps.safeRemove(backingRowMap, key);
maintainEmptyInvariant();
return result;
}
@Override
public void clear() {
updateBackingRowMapField();
if (backingRowMap != null) {
backingRowMap.clear();
}
maintainEmptyInvariant();
}
@Override
public int size() {
updateBackingRowMapField();
return (backingRowMap == null) ? 0 : backingRowMap.size();
}
@Override
Iterator<Entry<C, V>> entryIterator() {
updateBackingRowMapField();
if (backingRowMap == null) {
return Iterators.emptyModifiableIterator();
}
final Iterator<Entry<C, V>> iterator = backingRowMap.entrySet().iterator();
return new Iterator<Entry<C, V>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry<C, V> next() {
return wrapEntry(iterator.next());
}
@Override
public void remove() {
iterator.remove();
maintainEmptyInvariant();
}
};
}
Entry<C, V> wrapEntry(final Entry<C, V> entry) {
return new ForwardingMapEntry<C, V>() {
@Override
protected Entry<C, V> delegate() {
return entry;
}
@Override
public V setValue(V value) {
return super.setValue(checkNotNull(value));
}
@Override
public boolean equals(@CheckForNull Object object) {
// TODO(lowasser): identify why this affects GWT tests
return standardEquals(object);
}
};
}
}
/**
* {@inheritDoc}
*
* <p>The returned map's views have iterators that don't support {@code remove()}.
*/
@Override
public Map<R, V> column(C columnKey) {
return new Column(columnKey);
}
private class Column extends ViewCachingAbstractMap<R, V> {
final C columnKey;
Column(C columnKey) {
this.columnKey = checkNotNull(columnKey);
}
@Override
@CheckForNull
public V put(R key, V value) {
return StandardTable.this.put(key, columnKey, value);
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return StandardTable.this.get(key, columnKey);
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return StandardTable.this.contains(key, columnKey);
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
return StandardTable.this.remove(key, columnKey);
}
/** Removes all {@code Column} mappings whose row key and value satisfy the given predicate. */
@CanIgnoreReturnValue
boolean removeFromColumnIf(Predicate<? super Entry<R, V>> predicate) {
boolean changed = false;
Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<R, Map<C, V>> entry = iterator.next();
Map<C, V> map = entry.getValue();
V value = map.get(columnKey);
if (value != null && predicate.apply(Maps.immutableEntry(entry.getKey(), value))) {
map.remove(columnKey);
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override
Set<Entry<R, V>> createEntrySet() {
return new EntrySet();
}
@WeakOuter
private class EntrySet extends ImprovedAbstractSet<Entry<R, V>> {
@Override
public Iterator<Entry<R, V>> iterator() {
return new EntrySetIterator();
}
@Override
public int size() {
int size = 0;
for (Map<C, V> map : backingMap.values()) {
if (map.containsKey(columnKey)) {
size++;
}
}
return size;
}
@Override
public boolean isEmpty() {
return !containsColumn(columnKey);
}
@Override
public void clear() {
removeFromColumnIf(alwaysTrue());
}
@Override
public boolean contains(@CheckForNull Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return containsMapping(entry.getKey(), columnKey, entry.getValue());
}
return false;
}
@Override
public boolean remove(@CheckForNull Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return removeMapping(entry.getKey(), columnKey, entry.getValue());
}
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeFromColumnIf(not(in(c)));
}
}
private class EntrySetIterator extends AbstractIterator<Entry<R, V>> {
final Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator();
@Override
@CheckForNull
protected Entry<R, V> computeNext() {
while (iterator.hasNext()) {
final Entry<R, Map<C, V>> entry = iterator.next();
if (entry.getValue().containsKey(columnKey)) {
@WeakOuter
class EntryImpl extends AbstractMapEntry<R, V> {
@Override
public R getKey() {
return entry.getKey();
}
@Override
public V getValue() {
return entry.getValue().get(columnKey);
}
@Override
public V setValue(V value) {
/*
* The cast is safe because of the containsKey check above. (Well, it's possible for
* the map to change between that call and this one. But if that happens, the
* behavior is undefined because of the concurrent mutation.)
*
* (Our prototype checker happens to be "smart" enough to understand this for the
* *get* call in getValue but not for the *put* call here.)
*
* (Arguably we should use requireNonNull rather than uncheckedCastNullableTToT: We
* know that V is a non-null type because that's the only kind of value type that
* StandardTable supports. Thus, requireNonNull is safe as long as the cell is still
* present. (And if it's not present, behavior is undefined.) However, that's a
* behavior change relative to the old code, so it didn't seem worth risking.)
*/
return uncheckedCastNullableTToT(
entry.getValue().put(columnKey, checkNotNull(value)));
}
}
return new EntryImpl();
}
}
return endOfData();
}
}
@Override
Set<R> createKeySet() {
return new KeySet();
}
@WeakOuter
private class KeySet extends Maps.KeySet<R, V> {
KeySet() {
super(Column.this);
}
@Override
public boolean contains(@CheckForNull Object obj) {
return StandardTable.this.contains(obj, columnKey);
}
@Override
public boolean remove(@CheckForNull Object obj) {
return StandardTable.this.remove(obj, columnKey) != null;
}
@Override
public boolean retainAll(final Collection<?> c) {
return removeFromColumnIf(Maps.<R>keyPredicateOnEntries(not(in(c))));
}
}
@Override
Collection<V> createValues() {
return new Values();
}
@WeakOuter
private class Values extends Maps.Values<R, V> {
Values() {
super(Column.this);
}
@Override
public boolean remove(@CheckForNull Object obj) {
return obj != null && removeFromColumnIf(Maps.<V>valuePredicateOnEntries(equalTo(obj)));
}
@Override
public boolean removeAll(final Collection<?> c) {
return removeFromColumnIf(Maps.<V>valuePredicateOnEntries(in(c)));
}
@Override
public boolean retainAll(final Collection<?> c) {
return removeFromColumnIf(Maps.<V>valuePredicateOnEntries(not(in(c))));
}
}
}
@Override
public Set<R> rowKeySet() {
return rowMap().keySet();
}
@LazyInit @CheckForNull private transient Set<C> columnKeySet;
/**
* {@inheritDoc}
*
* <p>The returned set has an iterator that does not support {@code remove()}.
*
* <p>The set's iterator traverses the columns of the first row, the columns of the second row,
* etc., skipping any columns that have appeared previously.
*/
@Override
public Set<C> columnKeySet() {
Set<C> result = columnKeySet;
return (result == null) ? columnKeySet = new ColumnKeySet() : result;
}
@WeakOuter
private class ColumnKeySet extends TableSet<C> {
@Override
public Iterator<C> iterator() {
return createColumnKeyIterator();
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean remove(@CheckForNull Object obj) {
if (obj == null) {
return false;
}
boolean changed = false;
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
if (map.keySet().remove(obj)) {
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override
public boolean removeAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
// map.keySet().removeAll(c) can throw a NPE when map is a TreeMap with
// natural ordering and c contains a null.
if (Iterators.removeAll(map.keySet().iterator(), c)) {
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override
public boolean retainAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
Iterator<Map<C, V>> iterator = backingMap.values().iterator();
while (iterator.hasNext()) {
Map<C, V> map = iterator.next();
if (map.keySet().retainAll(c)) {
changed = true;
if (map.isEmpty()) {
iterator.remove();
}
}
}
return changed;
}
@Override
public boolean contains(@CheckForNull Object obj) {
return containsColumn(obj);
}
}
/** Creates an iterator that returns each column value with duplicates omitted. */
Iterator<C> createColumnKeyIterator() {
return new ColumnKeyIterator();
}
private class ColumnKeyIterator extends AbstractIterator<C> {
// Use the same map type to support TreeMaps with comparators that aren't
// consistent with equals().
final Map<C, V> seen = factory.get();
final Iterator<Map<C, V>> mapIterator = backingMap.values().iterator();
Iterator<Entry<C, V>> entryIterator = Iterators.emptyIterator();
@Override
@CheckForNull
protected C computeNext() {
while (true) {
if (entryIterator.hasNext()) {
Entry<C, V> entry = entryIterator.next();
if (!seen.containsKey(entry.getKey())) {
seen.put(entry.getKey(), entry.getValue());
return entry.getKey();
}
} else if (mapIterator.hasNext()) {
entryIterator = mapIterator.next().entrySet().iterator();
} else {
return endOfData();
}
}
}
}
/**
* {@inheritDoc}
*
* <p>The collection's iterator traverses the values for the first row, the values for the second
* row, and so on.
*/
@Override
public Collection<V> values() {
return super.values();
}
@LazyInit @CheckForNull private transient Map<R, Map<C, V>> rowMap;
@Override
public Map<R, Map<C, V>> rowMap() {
Map<R, Map<C, V>> result = rowMap;
return (result == null) ? rowMap = createRowMap() : result;
}
Map<R, Map<C, V>> createRowMap() {
return new RowMap();
}
@WeakOuter
class RowMap extends ViewCachingAbstractMap<R, Map<C, V>> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return containsRow(key);
}
// performing cast only when key is in backing map and has the correct type
@SuppressWarnings("unchecked")
@Override
@CheckForNull
public Map<C, V> get(@CheckForNull Object key) {
// requireNonNull is safe because of the containsRow check.
return containsRow(key) ? row((R) requireNonNull(key)) : null;
}
@Override
@CheckForNull
public Map<C, V> remove(@CheckForNull Object key) {
return (key == null) ? null : backingMap.remove(key);
}
@Override
protected Set<Entry<R, Map<C, V>>> createEntrySet() {
return new EntrySet();
}
@WeakOuter
private final class EntrySet extends TableSet<Entry<R, Map<C, V>>> {
@Override
public Iterator<Entry<R, Map<C, V>>> iterator() {
return Maps.asMapEntryIterator(
backingMap.keySet(),
new Function<R, Map<C, V>>() {
@Override
public Map<C, V> apply(R rowKey) {
return row(rowKey);
}
});
}
@Override
public int size() {
return backingMap.size();
}
@Override
public boolean contains(@CheckForNull Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return entry.getKey() != null
&& entry.getValue() instanceof Map
&& Collections2.safeContains(backingMap.entrySet(), entry);
}
return false;
}
@Override
public boolean remove(@CheckForNull Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return entry.getKey() != null
&& entry.getValue() instanceof Map
&& backingMap.entrySet().remove(entry);
}
return false;
}
}
}
@LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, V>> columnMap() {
ColumnMap result = columnMap;
return (result == null) ? columnMap = new ColumnMap() : result;
}
@WeakOuter
private class ColumnMap extends ViewCachingAbstractMap<C, Map<R, V>> {
// The cast to C occurs only when the key is in the map, implying that it
// has the correct type.
@SuppressWarnings("unchecked")
@Override
@CheckForNull
public Map<R, V> get(@CheckForNull Object key) {
// requireNonNull is safe because of the containsColumn check.
return containsColumn(key) ? column((C) requireNonNull(key)) : null;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return containsColumn(key);
}
@Override
@CheckForNull
public Map<R, V> remove(@CheckForNull Object key) {
return containsColumn(key) ? removeColumn(key) : null;
}
@Override
public Set<Entry<C, Map<R, V>>> createEntrySet() {
return new ColumnMapEntrySet();
}
@Override
public Set<C> keySet() {
return columnKeySet();
}
@Override
Collection<Map<R, V>> createValues() {
return new ColumnMapValues();
}
@WeakOuter
private final class ColumnMapEntrySet extends TableSet<Entry<C, Map<R, V>>> {
@Override
public Iterator<Entry<C, Map<R, V>>> iterator() {
return Maps.asMapEntryIterator(
columnKeySet(),
new Function<C, Map<R, V>>() {
@Override
public Map<R, V> apply(C columnKey) {
return column(columnKey);
}
});
}
@Override
public int size() {
return columnKeySet().size();
}
@Override
public boolean contains(@CheckForNull Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
if (containsColumn(entry.getKey())) {
// requireNonNull is safe because of the containsColumn check.
return requireNonNull(get(entry.getKey())).equals(entry.getValue());
}
}
return false;
}
@Override
public boolean remove(@CheckForNull Object obj) {
/*
* `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
* nullness checker.
*/
if (contains(obj) && obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
removeColumn(entry.getKey());
return true;
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
/*
* We can't inherit the normal implementation (which calls
* Sets.removeAllImpl(Set, *Collection*)) because, under some
* circumstances, it attempts to call columnKeySet().iterator().remove,
* which is unsupported.
*/
checkNotNull(c);
return Sets.removeAllImpl(this, c.iterator());
}
@Override
public boolean retainAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
if (!c.contains(Maps.immutableEntry(columnKey, column(columnKey)))) {
removeColumn(columnKey);
changed = true;
}
}
return changed;
}
}
@WeakOuter
private class ColumnMapValues extends Maps.Values<C, Map<R, V>> {
ColumnMapValues() {
super(ColumnMap.this);
}
@Override
public boolean remove(@CheckForNull Object obj) {
for (Entry<C, Map<R, V>> entry : ColumnMap.this.entrySet()) {
if (entry.getValue().equals(obj)) {
removeColumn(entry.getKey());
return true;
}
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
if (c.contains(column(columnKey))) {
removeColumn(columnKey);
changed = true;
}
}
return changed;
}
@Override
public boolean retainAll(Collection<?> c) {
checkNotNull(c);
boolean changed = false;
for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
if (!c.contains(column(columnKey))) {
removeColumn(columnKey);
changed = true;
}
}
return changed;
}
}
}
private static final long serialVersionUID = 0;
}
| google/guava | android/guava/src/com/google/common/collect/StandardTable.java |
679 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/** A writer that performs serialization of protobuf message fields. */
@ExperimentalApi
@CheckReturnValue
interface Writer {
/** The order in which the fields are written by a {@link Writer}. */
enum FieldOrder {
/** Fields are written in ascending order by field number. */
ASCENDING,
/** Fields are written in descending order by field number. */
DESCENDING
}
/** Indicates the order in which the fields are written by this {@link Writer}. */
FieldOrder fieldOrder();
/** Writes a field of type {@link FieldType#SFIXED32}. */
void writeSFixed32(int fieldNumber, int value) throws IOException;
/** Writes a field of type {@link FieldType#INT64}. */
void writeInt64(int fieldNumber, long value) throws IOException;
/** Writes a field of type {@link FieldType#SFIXED64}. */
void writeSFixed64(int fieldNumber, long value) throws IOException;
/** Writes a field of type {@link FieldType#FLOAT}. */
void writeFloat(int fieldNumber, float value) throws IOException;
/** Writes a field of type {@link FieldType#DOUBLE}. */
void writeDouble(int fieldNumber, double value) throws IOException;
/** Writes a field of type {@link FieldType#ENUM}. */
void writeEnum(int fieldNumber, int value) throws IOException;
/** Writes a field of type {@link FieldType#UINT64}. */
void writeUInt64(int fieldNumber, long value) throws IOException;
/** Writes a field of type {@link FieldType#INT32}. */
void writeInt32(int fieldNumber, int value) throws IOException;
/** Writes a field of type {@link FieldType#FIXED64}. */
void writeFixed64(int fieldNumber, long value) throws IOException;
/** Writes a field of type {@link FieldType#FIXED32}. */
void writeFixed32(int fieldNumber, int value) throws IOException;
/** Writes a field of type {@link FieldType#BOOL}. */
void writeBool(int fieldNumber, boolean value) throws IOException;
/** Writes a field of type {@link FieldType#STRING}. */
void writeString(int fieldNumber, String value) throws IOException;
/** Writes a field of type {@link FieldType#BYTES}. */
void writeBytes(int fieldNumber, ByteString value) throws IOException;
/** Writes a field of type {@link FieldType#UINT32}. */
void writeUInt32(int fieldNumber, int value) throws IOException;
/** Writes a field of type {@link FieldType#SINT32}. */
void writeSInt32(int fieldNumber, int value) throws IOException;
/** Writes a field of type {@link FieldType#SINT64}. */
void writeSInt64(int fieldNumber, long value) throws IOException;
/** Writes a field of type {@link FieldType#MESSAGE}. */
void writeMessage(int fieldNumber, Object value) throws IOException;
/** Writes a field of type {@link FieldType#MESSAGE}. */
void writeMessage(int fieldNumber, Object value, Schema schema) throws IOException;
/**
* Writes a field of type {@link FieldType#GROUP}.
*
* @deprecated groups fields are deprecated.
*/
@Deprecated
void writeGroup(int fieldNumber, Object value) throws IOException;
/**
* Writes a field of type {@link FieldType#GROUP}.
*
* @deprecated groups fields are deprecated.
*/
@Deprecated
void writeGroup(int fieldNumber, Object value, Schema schema) throws IOException;
/**
* Writes a single start group tag.
*
* @deprecated groups fields are deprecated.
*/
@Deprecated
void writeStartGroup(int fieldNumber) throws IOException;
/**
* Writes a single end group tag.
*
* @deprecated groups fields are deprecated.
*/
@Deprecated
void writeEndGroup(int fieldNumber) throws IOException;
/** Writes a list field of type {@link FieldType#INT32}. */
void writeInt32List(int fieldNumber, List<Integer> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#FIXED32}. */
void writeFixed32List(int fieldNumber, List<Integer> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#INT64}. */
void writeInt64List(int fieldNumber, List<Long> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#UINT64}. */
void writeUInt64List(int fieldNumber, List<Long> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#FIXED64}. */
void writeFixed64List(int fieldNumber, List<Long> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#FLOAT}. */
void writeFloatList(int fieldNumber, List<Float> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#DOUBLE}. */
void writeDoubleList(int fieldNumber, List<Double> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#ENUM}. */
void writeEnumList(int fieldNumber, List<Integer> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#BOOL}. */
void writeBoolList(int fieldNumber, List<Boolean> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#STRING}. */
void writeStringList(int fieldNumber, List<String> value) throws IOException;
/** Writes a list field of type {@link FieldType#BYTES}. */
void writeBytesList(int fieldNumber, List<ByteString> value) throws IOException;
/** Writes a list field of type {@link FieldType#UINT32}. */
void writeUInt32List(int fieldNumber, List<Integer> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#SFIXED32}. */
void writeSFixed32List(int fieldNumber, List<Integer> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#SFIXED64}. */
void writeSFixed64List(int fieldNumber, List<Long> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#SINT32}. */
void writeSInt32List(int fieldNumber, List<Integer> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#SINT64}. */
void writeSInt64List(int fieldNumber, List<Long> value, boolean packed) throws IOException;
/** Writes a list field of type {@link FieldType#MESSAGE}. */
void writeMessageList(int fieldNumber, List<?> value) throws IOException;
/** Writes a list field of type {@link FieldType#MESSAGE}. */
void writeMessageList(int fieldNumber, List<?> value, Schema schema) throws IOException;
/**
* Writes a list field of type {@link FieldType#GROUP}.
*
* @deprecated groups fields are deprecated.
*/
@Deprecated
void writeGroupList(int fieldNumber, List<?> value) throws IOException;
/**
* Writes a list field of type {@link FieldType#GROUP}.
*
* @deprecated groups fields are deprecated.
*/
@Deprecated
void writeGroupList(int fieldNumber, List<?> value, Schema schema) throws IOException;
/**
* Writes a message field in {@code MessageSet} wire-format.
*
* @param value A message instance or an opaque {@link ByteString} for an unknown field.
*/
void writeMessageSetItem(int fieldNumber, Object value) throws IOException;
/** Writes a map field. */
<K, V> void writeMap(int fieldNumber, MapEntryLite.Metadata<K, V> metadata, Map<K, V> map)
throws IOException;
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/Writer.java |
680 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.shard;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.DelegatingAnalyzerWrapper;
import org.apache.lucene.index.CheckIndex;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FilterDirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.QueryCachingPolicy;
import org.apache.lucene.search.ReferenceManager;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.UsageTrackingQueryCachingPolicy;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.util.SetOnce;
import org.apache.lucene.util.ThreadInterruptedException;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRunnable;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.SubscribableListener;
import org.elasticsearch.action.support.replication.PendingReplicationActions;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.cluster.metadata.DataStream;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RecoverySource;
import org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.metrics.MeanMetric;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.Assertions;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.core.CheckedFunction;
import org.elasticsearch.core.CheckedRunnable;
import org.elasticsearch.core.IOUtils;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Releasable;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.gateway.WriteStateException;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexModule;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.IndexVersion;
import org.elasticsearch.index.IndexVersions;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.bulk.stats.BulkOperationListener;
import org.elasticsearch.index.bulk.stats.BulkStats;
import org.elasticsearch.index.bulk.stats.ShardBulkStats;
import org.elasticsearch.index.cache.IndexCache;
import org.elasticsearch.index.cache.bitset.ShardBitsetFilterCache;
import org.elasticsearch.index.cache.query.TrivialQueryCachingPolicy;
import org.elasticsearch.index.cache.request.ShardRequestCache;
import org.elasticsearch.index.codec.CodecService;
import org.elasticsearch.index.engine.CommitStats;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.Engine.GetResult;
import org.elasticsearch.index.engine.EngineConfig;
import org.elasticsearch.index.engine.EngineException;
import org.elasticsearch.index.engine.EngineFactory;
import org.elasticsearch.index.engine.ReadOnlyEngine;
import org.elasticsearch.index.engine.RefreshFailedEngineException;
import org.elasticsearch.index.engine.SafeCommitInfo;
import org.elasticsearch.index.engine.Segment;
import org.elasticsearch.index.engine.SegmentsStats;
import org.elasticsearch.index.fielddata.FieldDataStats;
import org.elasticsearch.index.fielddata.ShardFieldData;
import org.elasticsearch.index.flush.FlushStats;
import org.elasticsearch.index.get.GetStats;
import org.elasticsearch.index.get.ShardGetService;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperMetrics;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.MappingLookup;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.merge.MergeStats;
import org.elasticsearch.index.recovery.RecoveryStats;
import org.elasticsearch.index.refresh.RefreshStats;
import org.elasticsearch.index.search.stats.FieldUsageStats;
import org.elasticsearch.index.search.stats.SearchStats;
import org.elasticsearch.index.search.stats.ShardFieldUsageTracker;
import org.elasticsearch.index.search.stats.ShardSearchStats;
import org.elasticsearch.index.seqno.ReplicationTracker;
import org.elasticsearch.index.seqno.RetentionLease;
import org.elasticsearch.index.seqno.RetentionLeaseStats;
import org.elasticsearch.index.seqno.RetentionLeaseSyncer;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.seqno.SeqNoStats;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.PrimaryReplicaSyncer.ResyncTask;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.Store.MetadataSnapshot;
import org.elasticsearch.index.store.StoreFileMetadata;
import org.elasticsearch.index.store.StoreStats;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogConfig;
import org.elasticsearch.index.translog.TranslogStats;
import org.elasticsearch.index.warmer.ShardIndexWarmerService;
import org.elasticsearch.index.warmer.WarmerStats;
import org.elasticsearch.indices.IndexingMemoryController;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.cluster.IndicesClusterStateService;
import org.elasticsearch.indices.recovery.PeerRecoveryTargetService;
import org.elasticsearch.indices.recovery.RecoveryFailedException;
import org.elasticsearch.indices.recovery.RecoverySettings;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.elasticsearch.indices.recovery.RecoveryTarget;
import org.elasticsearch.plugins.IndexStorePlugin;
import org.elasticsearch.repositories.RepositoriesService;
import org.elasticsearch.repositories.Repository;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.internal.FieldUsageTrackingDirectoryReader;
import org.elasticsearch.search.suggest.completion.CompletionStats;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.channels.ClosedByInterruptException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongSupplier;
import java.util.function.LongUnaryOperator;
import java.util.function.Supplier;
import static org.elasticsearch.cluster.metadata.DataStream.TIMESERIES_LEAF_READERS_SORTER;
import static org.elasticsearch.core.Strings.format;
import static org.elasticsearch.index.seqno.RetentionLeaseActions.RETAIN_ALL;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
public class IndexShard extends AbstractIndexShardComponent implements IndicesClusterStateService.Shard {
private final ThreadPool threadPool;
private final MapperService mapperService;
private final IndexCache indexCache;
private final Store store;
private final InternalIndexingStats internalIndexingStats;
private final ShardSearchStats searchStats = new ShardSearchStats();
private final ShardFieldUsageTracker fieldUsageTracker;
private final String shardUuid = UUIDs.randomBase64UUID();
private final long shardCreationTime;
private final ShardGetService getService;
private final ShardIndexWarmerService shardWarmerService;
private final ShardRequestCache requestCacheStats;
private final ShardFieldData shardFieldData;
private final ShardBitsetFilterCache shardBitsetFilterCache;
private final Object mutex = new Object();
private final String checkIndexOnStartup;
private final CodecService codecService;
private final Engine.Warmer warmer;
private final SimilarityService similarityService;
private final TranslogConfig translogConfig;
private final IndexEventListener indexEventListener;
private final QueryCachingPolicy cachingPolicy;
private final Supplier<Sort> indexSortSupplier;
// Package visible for testing
final CircuitBreakerService circuitBreakerService;
private final SearchOperationListener searchOperationListener;
private final ShardBulkStats bulkOperationListener;
private final GlobalCheckpointListeners globalCheckpointListeners;
private final PendingReplicationActions pendingReplicationActions;
private final ReplicationTracker replicationTracker;
private final IndexStorePlugin.SnapshotCommitSupplier snapshotCommitSupplier;
private final Engine.IndexCommitListener indexCommitListener;
private FieldInfos fieldInfos;
// sys prop to disable the field has value feature, defaults to true (enabled) if set to false (disabled) the
// field caps always returns empty fields ignoring the value of the query param `field_caps_empty_fields_filter`.
private final boolean enableFieldHasValue = Booleans.parseBoolean(
System.getProperty("es.field_caps_empty_fields_filter", Boolean.TRUE.toString())
);
protected volatile ShardRouting shardRouting;
protected volatile IndexShardState state;
// ensure happens-before relation between addRefreshListener() and postRecovery()
private volatile SubscribableListener<Void> postRecoveryComplete;
private volatile long pendingPrimaryTerm; // see JavaDocs for getPendingPrimaryTerm
private final Object engineMutex = new Object(); // lock ordering: engineMutex -> mutex
private final AtomicReference<Engine> currentEngineReference = new AtomicReference<>();
final EngineFactory engineFactory;
private final IndexingOperationListener indexingOperationListeners;
private final GlobalCheckpointSyncer globalCheckpointSyncer;
private final RetentionLeaseSyncer retentionLeaseSyncer;
@Nullable
private volatile RecoveryState recoveryState;
private final RecoveryStats recoveryStats = new RecoveryStats();
private final MeanMetric refreshMetric = new MeanMetric();
private final MeanMetric externalRefreshMetric = new MeanMetric();
private final MeanMetric flushMetric = new MeanMetric();
private final CounterMetric periodicFlushMetric = new CounterMetric();
private final ShardEventListener shardEventListener = new ShardEventListener();
private final ShardPath path;
private final IndexShardOperationPermits indexShardOperationPermits;
private static final EnumSet<IndexShardState> readAllowedStates = EnumSet.of(IndexShardState.STARTED, IndexShardState.POST_RECOVERY);
// for primaries, we only allow to write when actually started (so the cluster has decided we started)
// in case we have a relocation of a primary, we also allow to write after phase 2 completed, where the shard may be
// in state RECOVERING or POST_RECOVERY.
// for replicas, replication is also allowed while recovering, since we index also during recovery to replicas and rely on
// version checks to make sure its consistent a relocated shard can also be target of a replication if the relocation target has not
// been marked as active yet and is syncing it's changes back to the relocation source
private static final EnumSet<IndexShardState> writeAllowedStates = EnumSet.of(
IndexShardState.RECOVERING,
IndexShardState.POST_RECOVERY,
IndexShardState.STARTED
);
private final CheckedFunction<DirectoryReader, DirectoryReader, IOException> readerWrapper;
/**
* True if this shard is still indexing (recently) and false if we've been idle for long enough (as periodically checked by {@link
* IndexingMemoryController}).
*/
private final AtomicBoolean active = new AtomicBoolean();
/**
* Allows for the registration of listeners that are called when a change becomes visible for search.
*/
private final RefreshListeners refreshListeners;
private final AtomicLong lastSearcherAccess = new AtomicLong();
private final AtomicReference<Translog.Location> pendingRefreshLocation = new AtomicReference<>();
private final RefreshPendingLocationListener refreshPendingLocationListener;
private final RefreshFieldHasValueListener refreshFieldHasValueListener;
private volatile boolean useRetentionLeasesInPeerRecovery;
private final LongSupplier relativeTimeInNanosSupplier;
private volatile long startedRelativeTimeInNanos;
private volatile long indexingTimeBeforeShardStartedInNanos;
private final SubscribableListener<Void> waitForEngineOrClosedShardListeners = new SubscribableListener<>();
// the translog keeps track of the GCP, but unpromotable shards have no translog so we need to track the GCP here instead
private volatile long globalCheckPointIfUnpromotable;
@SuppressWarnings("this-escape")
public IndexShard(
final ShardRouting shardRouting,
final IndexSettings indexSettings,
final ShardPath path,
final Store store,
final Supplier<Sort> indexSortSupplier,
final IndexCache indexCache,
final MapperService mapperService,
final SimilarityService similarityService,
final EngineFactory engineFactory,
final IndexEventListener indexEventListener,
final CheckedFunction<DirectoryReader, DirectoryReader, IOException> indexReaderWrapper,
final ThreadPool threadPool,
final BigArrays bigArrays,
final Engine.Warmer warmer,
final List<SearchOperationListener> searchOperationListener,
final List<IndexingOperationListener> listeners,
final GlobalCheckpointSyncer globalCheckpointSyncer,
final RetentionLeaseSyncer retentionLeaseSyncer,
final CircuitBreakerService circuitBreakerService,
final IndexStorePlugin.SnapshotCommitSupplier snapshotCommitSupplier,
final LongSupplier relativeTimeInNanosSupplier,
final Engine.IndexCommitListener indexCommitListener,
final MapperMetrics mapperMetrics
) throws IOException {
super(shardRouting.shardId(), indexSettings);
assert shardRouting.initializing();
this.shardRouting = shardRouting;
final Settings settings = indexSettings.getSettings();
this.codecService = new CodecService(mapperService, bigArrays);
this.warmer = warmer;
this.similarityService = similarityService;
Objects.requireNonNull(store, "Store must be provided to the index shard");
this.engineFactory = Objects.requireNonNull(engineFactory);
this.snapshotCommitSupplier = Objects.requireNonNull(snapshotCommitSupplier);
this.store = store;
this.indexSortSupplier = indexSortSupplier;
this.indexEventListener = indexEventListener;
this.threadPool = threadPool;
this.mapperService = mapperService;
this.indexCache = indexCache;
this.internalIndexingStats = new InternalIndexingStats();
this.indexingOperationListeners = new IndexingOperationListener.CompositeListener(
CollectionUtils.appendToCopyNoNullElements(listeners, internalIndexingStats),
logger
);
this.bulkOperationListener = new ShardBulkStats();
this.globalCheckpointSyncer = globalCheckpointSyncer;
this.retentionLeaseSyncer = Objects.requireNonNull(retentionLeaseSyncer);
this.searchOperationListener = new SearchOperationListener.CompositeListener(
CollectionUtils.appendToCopyNoNullElements(searchOperationListener, searchStats),
logger
);
this.getService = new ShardGetService(indexSettings, this, mapperService, mapperMetrics);
this.shardWarmerService = new ShardIndexWarmerService(shardId, indexSettings);
this.requestCacheStats = new ShardRequestCache();
this.shardFieldData = new ShardFieldData();
this.shardBitsetFilterCache = new ShardBitsetFilterCache(shardId, indexSettings);
state = IndexShardState.CREATED;
this.path = path;
this.circuitBreakerService = circuitBreakerService;
/* create engine config */
logger.debug("state: [CREATED]");
this.checkIndexOnStartup = indexSettings.getValue(IndexSettings.INDEX_CHECK_ON_STARTUP);
this.translogConfig = new TranslogConfig(shardId, shardPath().resolveTranslog(), indexSettings, bigArrays);
final String aId = shardRouting.allocationId().getId();
final long primaryTerm = indexSettings.getIndexMetadata().primaryTerm(shardId.id());
this.pendingPrimaryTerm = primaryTerm;
this.globalCheckpointListeners = new GlobalCheckpointListeners(shardId, threadPool.scheduler(), logger);
this.pendingReplicationActions = new PendingReplicationActions(shardId, threadPool);
this.replicationTracker = new ReplicationTracker(
shardId,
aId,
indexSettings,
primaryTerm,
UNASSIGNED_SEQ_NO,
globalCheckpointListeners::globalCheckpointUpdated,
threadPool::absoluteTimeInMillis,
(retentionLeases, listener) -> retentionLeaseSyncer.sync(shardId, aId, getPendingPrimaryTerm(), retentionLeases, listener),
this::getSafeCommitInfo,
pendingReplicationActions
);
fieldUsageTracker = new ShardFieldUsageTracker();
shardCreationTime = threadPool.absoluteTimeInMillis();
// the query cache is a node-level thing, however we want the most popular filters
// to be computed on a per-shard basis
if (IndexModule.INDEX_QUERY_CACHE_EVERYTHING_SETTING.get(settings)) {
cachingPolicy = TrivialQueryCachingPolicy.ALWAYS;
} else {
cachingPolicy = new UsageTrackingQueryCachingPolicy();
}
indexShardOperationPermits = new IndexShardOperationPermits(shardId, threadPool);
readerWrapper = indexReaderWrapper;
refreshListeners = new RefreshListeners(
indexSettings::getMaxRefreshListeners,
() -> refresh("too_many_listeners"),
logger,
threadPool.getThreadContext(),
externalRefreshMetric
);
lastSearcherAccess.set(threadPool.relativeTimeInMillis());
persistMetadata(path, indexSettings, shardRouting, null, logger);
this.useRetentionLeasesInPeerRecovery = replicationTracker.hasAllPeerRecoveryRetentionLeases();
this.refreshPendingLocationListener = new RefreshPendingLocationListener();
this.refreshFieldHasValueListener = new RefreshFieldHasValueListener();
this.relativeTimeInNanosSupplier = relativeTimeInNanosSupplier;
this.indexCommitListener = indexCommitListener;
this.fieldInfos = FieldInfos.EMPTY;
}
public ThreadPool getThreadPool() {
return this.threadPool;
}
public Store store() {
return this.store;
}
/**
* Return the sort order of this index, or null if the index has no sort.
*/
public Sort getIndexSort() {
return indexSortSupplier.get();
}
public ShardGetService getService() {
return this.getService;
}
public ShardBitsetFilterCache shardBitsetFilterCache() {
return shardBitsetFilterCache;
}
public MapperService mapperService() {
return mapperService;
}
public SearchOperationListener getSearchOperationListener() {
return this.searchOperationListener;
}
public BulkOperationListener getBulkOperationListener() {
return this.bulkOperationListener;
}
public ShardIndexWarmerService warmerService() {
return this.shardWarmerService;
}
public ShardRequestCache requestCache() {
return this.requestCacheStats;
}
public ShardFieldData fieldData() {
return this.shardFieldData;
}
public boolean isSystem() {
return indexSettings.getIndexMetadata().isSystem();
}
/**
* USE THIS METHOD WITH CARE!
* Returns the primary term the index shard is supposed to be on. In case of primary promotion or when a replica learns about
* a new term due to a new primary, the term that's exposed here will not be the term that the shard internally uses to assign
* to operations. The shard will auto-correct its internal operation term, but this might take time.
* See {@link org.elasticsearch.cluster.metadata.IndexMetadata#primaryTerm(int)}
*/
public long getPendingPrimaryTerm() {
return this.pendingPrimaryTerm;
}
/** Returns the primary term that is currently being used to assign to operations */
public long getOperationPrimaryTerm() {
return replicationTracker.getOperationPrimaryTerm();
}
/**
* Returns a unique UUID that identifies this IndexShard instance
*/
public String getShardUuid() {
return shardUuid;
}
/**
* Returns the timestamp at which this IndexShard instance was created
*/
public long getShardCreationTime() {
return shardCreationTime;
}
/**
* Returns the latest cluster routing entry received with this shard.
*/
@Override
public ShardRouting routingEntry() {
return this.shardRouting;
}
@Override
public void updateShardState(
final ShardRouting newRouting,
final long newPrimaryTerm,
final BiConsumer<IndexShard, ActionListener<ResyncTask>> primaryReplicaSyncer,
final long applyingClusterStateVersion,
final Set<String> inSyncAllocationIds,
final IndexShardRoutingTable routingTable
) throws IOException {
final ShardRouting currentRouting;
synchronized (mutex) {
currentRouting = this.shardRouting;
assert currentRouting != null;
if (newRouting.shardId().equals(shardId()) == false) {
throw new IllegalArgumentException(
"Trying to set a routing entry with shardId " + newRouting.shardId() + " on a shard with shardId " + shardId()
);
}
if (newRouting.isSameAllocation(currentRouting) == false) {
throw new IllegalArgumentException(
"Trying to set a routing entry with a different allocation. Current " + currentRouting + ", new " + newRouting
);
}
if (currentRouting.primary() && newRouting.primary() == false) {
throw new IllegalArgumentException(
"illegal state: trying to move shard from primary mode to replica mode. Current "
+ currentRouting
+ ", new "
+ newRouting
);
}
if (newRouting.primary()) {
replicationTracker.updateFromMaster(applyingClusterStateVersion, inSyncAllocationIds, routingTable);
}
if (state == IndexShardState.POST_RECOVERY && newRouting.active()) {
assert currentRouting.active() == false : "we are in POST_RECOVERY, but our shard routing is active " + currentRouting;
assert currentRouting.isRelocationTarget() == false
|| currentRouting.primary() == false
|| replicationTracker.isPrimaryMode()
: "a primary relocation is completed by the master, but primary mode is not active " + currentRouting;
changeState(IndexShardState.STARTED, "global state is [" + newRouting.state() + "]");
startedRelativeTimeInNanos = getRelativeTimeInNanos();
indexingTimeBeforeShardStartedInNanos = internalIndexingStats.totalIndexingTimeInNanos();
} else if (currentRouting.primary()
&& currentRouting.relocating()
&& replicationTracker.isRelocated()
&& (newRouting.relocating() == false || newRouting.equalsIgnoringMetadata(currentRouting) == false)) {
// if the shard is not in primary mode anymore (after primary relocation) we have to fail when any changes in shard
// routing occur (e.g. due to recovery failure / cancellation). The reason is that at the moment we cannot safely
// reactivate primary mode without risking two active primaries.
throw new IndexShardRelocatedException(
shardId(),
"Shard is marked as relocated, cannot safely move to state " + newRouting.state()
);
}
if (newRouting.active() && state != IndexShardState.STARTED && state != IndexShardState.CLOSED) {
// If cluster.no_master_block: all then we remove all shards locally whenever there's no master, but there might still be
// a shard-started message in flight. When the new master is elected we start to recover our shards again and the stale
// shard-started message could arrive and move this shard to STARTED in the cluster state too soon. This is pretty rare so
// we fix it by just failing the shard and starting the recovery again.
//
// NB this can only happen on replicas - if it happened to a primary then we'd move to a new primary term and ignore the
// stale shard-started message.
assert newRouting.primary() == false
: "primary routing is active, but local shard state isn't. routing: " + newRouting + ", local state: " + state;
throw new IllegalIndexShardStateException(shardId, state, "master processed stale shard-started event, failing shard");
}
persistMetadata(path, indexSettings, newRouting, currentRouting, logger);
final CountDownLatch shardStateUpdated = new CountDownLatch(1);
if (newRouting.primary()) {
if (newPrimaryTerm == pendingPrimaryTerm) {
if (currentRouting.initializing() && currentRouting.isRelocationTarget() == false && newRouting.active()) {
// the master started a recovering primary, activate primary mode.
replicationTracker.activatePrimaryMode(getLocalCheckpoint());
ensurePeerRecoveryRetentionLeasesExist();
}
} else {
assert currentRouting.primary() == false : "term is only increased as part of primary promotion";
/* Note that due to cluster state batching an initializing primary shard term can failed and re-assigned
* in one state causing it's term to be incremented. Note that if both current shard state and new
* shard state are initializing, we could replace the current shard and reinitialize it. It is however
* possible that this shard is being started. This can happen if:
* 1) Shard is post recovery and sends shard started to the master
* 2) Node gets disconnected and rejoins
* 3) Master assigns the shard back to the node
* 4) Master processes the shard started and starts the shard
* 5) The node process the cluster state where the shard is both started and primary term is incremented.
*
* We could fail the shard in that case, but this will cause it to be removed from the insync allocations list
* potentially preventing re-allocation.
*/
assert newRouting.initializing() == false
: "a started primary shard should never update its term; "
+ "shard "
+ newRouting
+ ", "
+ "current term ["
+ pendingPrimaryTerm
+ "], "
+ "new term ["
+ newPrimaryTerm
+ "]";
assert newPrimaryTerm > pendingPrimaryTerm
: "primary terms can only go up; current term [" + pendingPrimaryTerm + "], new term [" + newPrimaryTerm + "]";
/*
* Before this call returns, we are guaranteed that all future operations are delayed and so this happens before we
* increment the primary term. The latch is needed to ensure that we do not unblock operations before the primary
* term is incremented.
*/
// to prevent primary relocation handoff while resync is not completed
boolean resyncStarted = primaryReplicaResyncInProgress.compareAndSet(false, true);
if (resyncStarted == false) {
throw new IllegalStateException("cannot start resync while it's already in progress");
}
bumpPrimaryTerm(newPrimaryTerm, () -> {
shardStateUpdated.await();
assert pendingPrimaryTerm == newPrimaryTerm
: "shard term changed on primary. expected ["
+ newPrimaryTerm
+ "] but was ["
+ pendingPrimaryTerm
+ "]"
+ ", current routing: "
+ currentRouting
+ ", new routing: "
+ newRouting;
assert getOperationPrimaryTerm() == newPrimaryTerm;
try {
replicationTracker.activatePrimaryMode(getLocalCheckpoint());
ensurePeerRecoveryRetentionLeasesExist();
/*
* If this shard was serving as a replica shard when another shard was promoted to primary then
* its Lucene index was reset during the primary term transition. In particular, the Lucene index
* on this shard was reset to the global checkpoint and the operations above the local checkpoint
* were reverted. If the other shard that was promoted to primary subsequently fails before the
* primary/replica re-sync completes successfully and we are now being promoted, we have to restore
* the reverted operations on this shard by replaying the translog to avoid losing acknowledged writes.
*/
final Engine engine = getEngine();
engine.restoreLocalHistoryFromTranslog(
(resettingEngine, snapshot) -> runTranslogRecovery(
resettingEngine,
snapshot,
Engine.Operation.Origin.LOCAL_RESET,
() -> {}
)
);
/* Rolling the translog generation is not strictly needed here (as we will never have collisions between
* sequence numbers in a translog generation in a new primary as it takes the last known sequence number
* as a starting point), but it simplifies reasoning about the relationship between primary terms and
* translog generations.
*/
engine.rollTranslogGeneration();
engine.fillSeqNoGaps(newPrimaryTerm);
replicationTracker.updateLocalCheckpoint(currentRouting.allocationId().getId(), getLocalCheckpoint());
primaryReplicaSyncer.accept(this, new ActionListener<ResyncTask>() {
@Override
public void onResponse(ResyncTask resyncTask) {
logger.info("primary-replica resync completed with {} operations", resyncTask.getResyncedOperations());
boolean resyncCompleted = primaryReplicaResyncInProgress.compareAndSet(true, false);
assert resyncCompleted : "primary-replica resync finished but was not started";
}
@Override
public void onFailure(Exception e) {
boolean resyncCompleted = primaryReplicaResyncInProgress.compareAndSet(true, false);
assert resyncCompleted : "primary-replica resync finished but was not started";
if (state == IndexShardState.CLOSED) {
// ignore, shutting down
} else {
try {
failShard("exception during primary-replica resync", e);
} catch (AlreadyClosedException ace) {
// okay, the index was deleted
}
}
}
});
} catch (final AlreadyClosedException e) {
// okay, the index was deleted
}
}, null);
}
}
// set this last, once we finished updating all internal state.
this.shardRouting = newRouting;
assert this.shardRouting.primary() == false || this.shardRouting.started() == false || // note that we use started and not
// active to avoid relocating shards
this.indexShardOperationPermits.isBlocked() || // if permits are blocked, we are still transitioning
this.replicationTracker.isPrimaryMode()
: "a started primary with non-pending operation term must be in primary mode " + this.shardRouting;
shardStateUpdated.countDown();
}
if (currentRouting.active() == false && newRouting.active()) {
indexEventListener.afterIndexShardStarted(this);
}
if (newRouting.equals(currentRouting) == false) {
indexEventListener.shardRoutingChanged(this, currentRouting, newRouting);
}
if (indexSettings.isSoftDeleteEnabled() && useRetentionLeasesInPeerRecovery == false) {
final RetentionLeases retentionLeases = replicationTracker.getRetentionLeases();
boolean allShardsUseRetentionLeases = true;
for (int copy = 0; copy < routingTable.size(); copy++) {
ShardRouting shardRouting = routingTable.shard(copy);
if (shardRouting.isPromotableToPrimary()) {
if (shardRouting.assignedToNode() == false
|| retentionLeases.contains(ReplicationTracker.getPeerRecoveryRetentionLeaseId(shardRouting)) == false) {
allShardsUseRetentionLeases = false;
break;
}
if (this.shardRouting.relocating()) {
ShardRouting shardRoutingReloc = this.shardRouting.getTargetRelocatingShard();
if (shardRoutingReloc.assignedToNode() == false
|| retentionLeases.contains(ReplicationTracker.getPeerRecoveryRetentionLeaseId(shardRoutingReloc)) == false) {
allShardsUseRetentionLeases = false;
break;
}
}
}
}
useRetentionLeasesInPeerRecovery = allShardsUseRetentionLeases;
}
}
/**
* Marks the shard as recovering based on a recovery state, fails with exception is recovering is not allowed to be set.
*/
public IndexShardState markAsRecovering(String reason, RecoveryState recoveryState) throws IndexShardStartedException,
IndexShardRelocatedException, IndexShardRecoveringException, IndexShardClosedException {
synchronized (mutex) {
if (state == IndexShardState.CLOSED) {
throw new IndexShardClosedException(shardId);
}
if (state == IndexShardState.STARTED) {
throw new IndexShardStartedException(shardId);
}
if (state == IndexShardState.RECOVERING) {
throw new IndexShardRecoveringException(shardId);
}
if (state == IndexShardState.POST_RECOVERY) {
throw new IndexShardRecoveringException(shardId);
}
this.recoveryState = recoveryState;
return changeState(IndexShardState.RECOVERING, reason);
}
}
private final AtomicBoolean primaryReplicaResyncInProgress = new AtomicBoolean();
/**
* Completes the relocation. Operations are blocked and current operations are drained before changing state to relocated. The provided
* {@link BiConsumer} is executed after all operations are successfully blocked.
*
* @param consumer a {@link BiConsumer} that is executed after operations are blocked and that consumes the primary context as well as
* a listener to resolve once it finished
* @param listener listener to resolve once this method actions including executing {@code consumer} in the non-failure case complete
* @throws IllegalIndexShardStateException if the shard is not relocating due to concurrent cancellation
* @throws IllegalStateException if the relocation target is no longer part of the replication group
*/
public void relocated(
final String targetNodeId,
final String targetAllocationId,
final BiConsumer<ReplicationTracker.PrimaryContext, ActionListener<Void>> consumer,
final ActionListener<Void> listener
) throws IllegalIndexShardStateException, IllegalStateException {
assert shardRouting.primary() : "only primaries can be marked as relocated: " + shardRouting;
try (Releasable forceRefreshes = refreshListeners.forceRefreshes()) {
indexShardOperationPermits.blockOperations(new ActionListener<>() {
@Override
public void onResponse(Releasable releasable) {
boolean success = false;
try {
forceRefreshes.close();
// no shard operation permits are being held here, move state from started to relocated
assert indexShardOperationPermits.getActiveOperationsCount() == OPERATIONS_BLOCKED
: "in-flight operations in progress while moving shard state to relocated";
/*
* We should not invoke the runnable under the mutex as the expected implementation is to handoff the primary
* context via a network operation. Doing this under the mutex can implicitly block the cluster state update thread
* on network operations.
*/
verifyRelocatingState(targetNodeId);
final ReplicationTracker.PrimaryContext primaryContext = replicationTracker.startRelocationHandoff(
targetAllocationId
);
// make sure we release all permits before we resolve the final listener
final ActionListener<Void> wrappedInnerListener = ActionListener.runBefore(
listener,
Releasables.releaseOnce(releasable)::close
);
final ActionListener<Void> wrappedListener = new ActionListener<>() {
@Override
public void onResponse(Void unused) {
try {
// make changes to primaryMode and relocated flag only under mutex
synchronized (mutex) {
verifyRelocatingState(targetNodeId);
replicationTracker.completeRelocationHandoff();
}
wrappedInnerListener.onResponse(null);
} catch (Exception e) {
onFailure(e);
}
}
@Override
public void onFailure(Exception e) {
try {
replicationTracker.abortRelocationHandoff();
} catch (final Exception inner) {
e.addSuppressed(inner);
}
wrappedInnerListener.onFailure(e);
}
};
try {
consumer.accept(primaryContext, wrappedListener);
} catch (final Exception e) {
wrappedListener.onFailure(e);
}
success = true;
} catch (Exception e) {
listener.onFailure(e);
} finally {
if (success == false) {
releasable.close();
}
}
}
@Override
public void onFailure(Exception e) {
if (e instanceof TimeoutException) {
logger.warn("timed out waiting for relocation hand-off to complete");
// This is really bad as ongoing replication operations are preventing this shard from completing relocation
// hand-off.
// Fail primary relocation source and target shards.
failShard("timed out waiting for relocation hand-off to complete", null);
listener.onFailure(
new IndexShardClosedException(shardId(), "timed out waiting for relocation hand-off to complete")
);
} else {
listener.onFailure(e);
}
}
}, 30L, TimeUnit.MINUTES, EsExecutors.DIRECT_EXECUTOR_SERVICE); // Wait on current thread because this execution is wrapped by
// CancellableThreads and we want to be able to interrupt it
}
}
private void verifyRelocatingState(String targetNodeId) {
if (state != IndexShardState.STARTED) {
throw new IndexShardNotStartedException(shardId, state);
}
/*
* If the master cancelled recovery, the target will be removed and the recovery will be cancelled. However, it is still possible
* that we concurrently end up here and therefore have to protect that we do not mark the shard as relocated when its shard routing
* says otherwise.
*/
if (shardRouting.relocating() == false) {
throw new IllegalIndexShardStateException(shardId, IndexShardState.STARTED, ": shard is no longer relocating " + shardRouting);
}
if (Objects.equals(targetNodeId, shardRouting.relocatingNodeId()) == false) {
throw new IllegalIndexShardStateException(
shardId,
IndexShardState.STARTED,
": shard is no longer relocating to node [" + targetNodeId + "]: " + shardRouting
);
}
if (primaryReplicaResyncInProgress.get()) {
throw new IllegalIndexShardStateException(
shardId,
IndexShardState.STARTED,
": primary relocation is forbidden while primary-replica resync is in progress " + shardRouting
);
}
}
@Override
public IndexShardState state() {
return state;
}
/**
* Changes the state of the current shard
*
* @param newState the new shard state
* @param reason the reason for the state change
* @return the previous shard state
*/
private IndexShardState changeState(IndexShardState newState, String reason) {
assert Thread.holdsLock(mutex);
logger.debug("state: [{}]->[{}], reason [{}]", state, newState, reason);
IndexShardState previousState = state;
state = newState;
this.indexEventListener.indexShardStateChanged(this, previousState, newState, reason);
return previousState;
}
public Engine.IndexResult applyIndexOperationOnPrimary(
long version,
VersionType versionType,
SourceToParse sourceToParse,
long ifSeqNo,
long ifPrimaryTerm,
long autoGeneratedTimestamp,
boolean isRetry
) throws IOException {
assert versionType.validateVersionForWrites(version);
return applyIndexOperation(
getEngine(),
UNASSIGNED_SEQ_NO,
getOperationPrimaryTerm(),
version,
versionType,
ifSeqNo,
ifPrimaryTerm,
autoGeneratedTimestamp,
isRetry,
Engine.Operation.Origin.PRIMARY,
sourceToParse
);
}
public Engine.IndexResult applyIndexOperationOnReplica(
long seqNo,
long opPrimaryTerm,
long version,
long autoGeneratedTimeStamp,
boolean isRetry,
SourceToParse sourceToParse
) throws IOException {
return applyIndexOperation(
getEngine(),
seqNo,
opPrimaryTerm,
version,
null,
UNASSIGNED_SEQ_NO,
0,
autoGeneratedTimeStamp,
isRetry,
Engine.Operation.Origin.REPLICA,
sourceToParse
);
}
private Engine.IndexResult applyIndexOperation(
Engine engine,
long seqNo,
long opPrimaryTerm,
long version,
@Nullable VersionType versionType,
long ifSeqNo,
long ifPrimaryTerm,
long autoGeneratedTimeStamp,
boolean isRetry,
Engine.Operation.Origin origin,
SourceToParse sourceToParse
) throws IOException {
assert opPrimaryTerm <= getOperationPrimaryTerm()
: "op term [ " + opPrimaryTerm + " ] > shard term [" + getOperationPrimaryTerm() + "]";
ensureWriteAllowed(origin);
Engine.Index operation;
try {
operation = prepareIndex(
mapperService,
sourceToParse,
seqNo,
opPrimaryTerm,
version,
versionType,
origin,
autoGeneratedTimeStamp,
isRetry,
ifSeqNo,
ifPrimaryTerm,
getRelativeTimeInNanos()
);
Mapping update = operation.parsedDoc().dynamicMappingsUpdate();
if (update != null) {
return new Engine.IndexResult(update, operation.parsedDoc().id());
}
} catch (Exception e) {
// We treat any exception during parsing and or mapping update as a document level failure
// with the exception side effects of closing the shard. Since we don't have the shard, we
// can not raise an exception that may block any replication of previous operations to the
// replicas
verifyNotClosed(e);
return new Engine.IndexResult(e, version, opPrimaryTerm, seqNo, sourceToParse.id());
}
return index(engine, operation);
}
public void setFieldInfos(FieldInfos fieldInfos) {
this.fieldInfos = fieldInfos;
}
public FieldInfos getFieldInfos() {
return fieldInfos;
}
public static Engine.Index prepareIndex(
MapperService mapperService,
SourceToParse source,
long seqNo,
long primaryTerm,
long version,
VersionType versionType,
Engine.Operation.Origin origin,
long autoGeneratedIdTimestamp,
boolean isRetry,
long ifSeqNo,
long ifPrimaryTerm,
long startTimeInNanos
) {
assert source.dynamicTemplates().isEmpty() || origin == Engine.Operation.Origin.PRIMARY
: "dynamic_templates parameter can only be associated with primary operations";
DocumentMapper documentMapper = mapperService.documentMapper();
Mapping mapping = null;
if (documentMapper == null) {
documentMapper = DocumentMapper.createEmpty(mapperService);
mapping = documentMapper.mapping();
}
ParsedDocument doc = documentMapper.parse(source);
if (mapping != null) {
// If we are indexing but there is no mapping we create one. This is to ensure that whenever at least a document is indexed
// some mappings do exist. It covers for the case of indexing an empty doc (`{}`).
// TODO this can be removed if we eagerly create mappings as soon as a new index is created, regardless of
// whether mappings were provided or not.
doc.addDynamicMappingsUpdate(mapping);
}
Term uid = new Term(IdFieldMapper.NAME, Uid.encodeId(doc.id()));
return new Engine.Index(
uid,
doc,
seqNo,
primaryTerm,
version,
versionType,
origin,
startTimeInNanos,
autoGeneratedIdTimestamp,
isRetry,
ifSeqNo,
ifPrimaryTerm
);
}
private Engine.IndexResult index(Engine engine, Engine.Index index) throws IOException {
try {
final Engine.IndexResult result;
final Engine.Index preIndex = indexingOperationListeners.preIndex(shardId, index);
try {
if (logger.isTraceEnabled()) {
// don't use index.source().utf8ToString() here source might not be valid UTF-8
logger.trace(
"index [{}] seq# [{}] allocation-id [{}] primaryTerm [{}] operationPrimaryTerm [{}] origin [{}]",
preIndex.id(),
preIndex.seqNo(),
routingEntry().allocationId(),
preIndex.primaryTerm(),
getOperationPrimaryTerm(),
preIndex.origin()
);
}
result = engine.index(preIndex);
if (logger.isTraceEnabled()) {
logger.trace(
"index-done [{}] seq# [{}] allocation-id [{}] primaryTerm [{}] operationPrimaryTerm [{}] origin [{}] "
+ "result-seq# [{}] result-term [{}] failure [{}]",
preIndex.id(),
preIndex.seqNo(),
routingEntry().allocationId(),
preIndex.primaryTerm(),
getOperationPrimaryTerm(),
preIndex.origin(),
result.getSeqNo(),
result.getTerm(),
result.getFailure()
);
}
} catch (Exception e) {
if (logger.isTraceEnabled()) {
logger.trace(
() -> format(
"index-fail [%s] seq# [%s] allocation-id [%s] primaryTerm [%s] operationPrimaryTerm [%s] origin [%s]",
preIndex.id(),
preIndex.seqNo(),
routingEntry().allocationId(),
preIndex.primaryTerm(),
getOperationPrimaryTerm(),
preIndex.origin()
),
e
);
}
indexingOperationListeners.postIndex(shardId, preIndex, e);
throw e;
}
indexingOperationListeners.postIndex(shardId, preIndex, result);
return result;
} finally {
active.set(true);
}
}
public Engine.NoOpResult markSeqNoAsNoop(long seqNo, long opPrimaryTerm, String reason) throws IOException {
return markSeqNoAsNoop(getEngine(), seqNo, opPrimaryTerm, reason, Engine.Operation.Origin.REPLICA);
}
private Engine.NoOpResult markSeqNoAsNoop(Engine engine, long seqNo, long opPrimaryTerm, String reason, Engine.Operation.Origin origin)
throws IOException {
assert opPrimaryTerm <= getOperationPrimaryTerm()
: "op term [ " + opPrimaryTerm + " ] > shard term [" + getOperationPrimaryTerm() + "]";
long startTime = System.nanoTime();
ensureWriteAllowed(origin);
final Engine.NoOp noOp = new Engine.NoOp(seqNo, opPrimaryTerm, origin, startTime, reason);
return noOp(engine, noOp);
}
private Engine.NoOpResult noOp(Engine engine, Engine.NoOp noOp) throws IOException {
try {
if (logger.isTraceEnabled()) {
logger.trace("noop (seq# [{}])", noOp.seqNo());
}
return engine.noOp(noOp);
} finally {
active.set(true);
}
}
public Engine.IndexResult getFailedIndexResult(Exception e, long version, String id) {
return new Engine.IndexResult(e, version, id);
}
public Engine.DeleteResult getFailedDeleteResult(Exception e, long version, String id) {
return new Engine.DeleteResult(e, version, getOperationPrimaryTerm(), id);
}
public Engine.DeleteResult applyDeleteOperationOnPrimary(
long version,
String id,
VersionType versionType,
long ifSeqNo,
long ifPrimaryTerm
) throws IOException {
assert versionType.validateVersionForWrites(version);
return applyDeleteOperation(
getEngine(),
UNASSIGNED_SEQ_NO,
getOperationPrimaryTerm(),
version,
id,
versionType,
ifSeqNo,
ifPrimaryTerm,
Engine.Operation.Origin.PRIMARY
);
}
public Engine.DeleteResult applyDeleteOperationOnReplica(long seqNo, long opPrimaryTerm, long version, String id) throws IOException {
return applyDeleteOperation(
getEngine(),
seqNo,
opPrimaryTerm,
version,
id,
null,
UNASSIGNED_SEQ_NO,
0,
Engine.Operation.Origin.REPLICA
);
}
private Engine.DeleteResult applyDeleteOperation(
Engine engine,
long seqNo,
long opPrimaryTerm,
long version,
String id,
@Nullable VersionType versionType,
long ifSeqNo,
long ifPrimaryTerm,
Engine.Operation.Origin origin
) throws IOException {
assert opPrimaryTerm <= getOperationPrimaryTerm()
: "op term [ " + opPrimaryTerm + " ] > shard term [" + getOperationPrimaryTerm() + "]";
ensureWriteAllowed(origin);
try {
Engine.Delete delete = indexingOperationListeners.preDelete(
shardId,
prepareDelete(id, seqNo, opPrimaryTerm, version, versionType, origin, ifSeqNo, ifPrimaryTerm)
);
final Engine.DeleteResult result;
try {
if (logger.isTraceEnabled()) {
logger.trace("delete [{}] (seq no [{}])", delete.uid().text(), delete.seqNo());
}
result = engine.delete(delete);
} catch (Exception e) {
indexingOperationListeners.postDelete(shardId, delete, e);
throw e;
}
indexingOperationListeners.postDelete(shardId, delete, result);
return result;
} finally {
active.set(true);
}
}
public static Engine.Delete prepareDelete(
String id,
long seqNo,
long primaryTerm,
long version,
VersionType versionType,
Engine.Operation.Origin origin,
long ifSeqNo,
long ifPrimaryTerm
) {
long startTime = System.nanoTime();
final Term uid = new Term(IdFieldMapper.NAME, Uid.encodeId(id));
return new Engine.Delete(id, uid, seqNo, primaryTerm, version, versionType, origin, startTime, ifSeqNo, ifPrimaryTerm);
}
public Engine.GetResult get(Engine.Get get) {
return innerGet(get, false, this::wrapSearcher);
}
/**
* Invokes the consumer with a {@link MultiEngineGet} that can perform multiple engine gets without wrapping searchers multiple times.
* Callers must not pass the provided {@link MultiEngineGet} to other threads.
*/
public void mget(Consumer<MultiEngineGet> mgetter) {
final MultiEngineGet mget = new MultiEngineGet(this::wrapSearcher) {
@Override
public GetResult get(Engine.Get get) {
return innerGet(get, false, this::wrapSearchSearchWithCache);
}
};
try {
mgetter.accept(mget);
} finally {
mget.releaseCachedSearcher();
}
}
public Engine.GetResult getFromTranslog(Engine.Get get) {
assert get.realtime();
return innerGet(get, true, this::wrapSearcher);
}
private Engine.GetResult innerGet(Engine.Get get, boolean translogOnly, Function<Engine.Searcher, Engine.Searcher> searcherWrapper) {
readAllowed();
MappingLookup mappingLookup = mapperService.mappingLookup();
if (mappingLookup.hasMappings() == false) {
return GetResult.NOT_EXISTS;
}
if (indexSettings.getIndexVersionCreated().isLegacyIndexVersion()) {
throw new IllegalStateException("get operations not allowed on a legacy index");
}
if (translogOnly) {
return getEngine().getFromTranslog(get, mappingLookup, mapperService.documentParser(), searcherWrapper);
}
return getEngine().get(get, mappingLookup, mapperService.documentParser(), searcherWrapper);
}
/**
* Writes all indexing changes to disk and opens a new searcher reflecting all changes. This can throw {@link AlreadyClosedException}.
*/
public Engine.RefreshResult refresh(String source) {
verifyNotClosed();
logger.trace("refresh with source [{}]", source);
return getEngine().refresh(source);
}
public void externalRefresh(String source, ActionListener<Engine.RefreshResult> listener) {
verifyNotClosed();
getEngine().externalRefresh(source, listener);
}
/**
* Returns how many bytes we are currently moving from heap to disk
*/
public long getWritingBytes() {
Engine engine = getEngineOrNull();
if (engine == null) {
return 0;
}
return engine.getWritingBytes();
}
public RefreshStats refreshStats() {
int listeners = refreshListeners.pendingCount();
return new RefreshStats(
refreshMetric.count(),
TimeUnit.NANOSECONDS.toMillis(refreshMetric.sum()),
externalRefreshMetric.count(),
TimeUnit.NANOSECONDS.toMillis(externalRefreshMetric.sum()),
listeners
);
}
public FlushStats flushStats() {
return new FlushStats(
flushMetric.count(),
periodicFlushMetric.count(),
TimeUnit.NANOSECONDS.toMillis(flushMetric.sum()),
getEngineOrNull() != null ? getEngineOrNull().getTotalFlushTimeExcludingWaitingOnLockInMillis() : 0L
);
}
public DocsStats docStats() {
readAllowed();
return getEngine().docStats();
}
/**
* @return {@link CommitStats}
* @throws AlreadyClosedException if shard is closed
*/
public CommitStats commitStats() {
return getEngine().commitStats();
}
/**
* @return {@link SeqNoStats}
* @throws AlreadyClosedException if shard is closed
*/
public SeqNoStats seqNoStats() {
return getEngine().getSeqNoStats(replicationTracker.getGlobalCheckpoint());
}
public IndexingStats indexingStats() {
Engine engine = getEngineOrNull();
final boolean throttled;
final long throttleTimeInMillis;
if (engine == null) {
throttled = false;
throttleTimeInMillis = 0;
} else {
throttled = engine.isThrottled();
throttleTimeInMillis = engine.getIndexThrottleTimeInMillis();
}
return internalIndexingStats.stats(
throttled,
throttleTimeInMillis,
indexingTimeBeforeShardStartedInNanos,
getRelativeTimeInNanos() - startedRelativeTimeInNanos
);
}
public SearchStats searchStats(String... groups) {
return searchStats.stats(groups);
}
public FieldUsageStats fieldUsageStats(String... fields) {
return fieldUsageTracker.stats(fields);
}
public GetStats getStats() {
return getService.stats();
}
public StoreStats storeStats() {
try {
final RecoveryState recoveryState = this.recoveryState;
if (DiskThresholdDecider.SETTING_IGNORE_DISK_WATERMARKS.get(indexSettings.getSettings())) {
// if this shard has no disk footprint then its local size is reported as 0
return store.stats(0, size -> 0);
} else {
final long bytesStillToRecover = recoveryState == null ? -1L : recoveryState.getIndex().bytesStillToRecover();
final long reservedBytes = bytesStillToRecover == -1 ? StoreStats.UNKNOWN_RESERVED_BYTES : bytesStillToRecover;
return store.stats(reservedBytes, LongUnaryOperator.identity());
}
} catch (IOException e) {
failShard("Failing shard because of exception during storeStats", e);
throw new ElasticsearchException("io exception while building 'store stats'", e);
}
}
public MergeStats mergeStats() {
final Engine engine = getEngineOrNull();
if (engine == null) {
return new MergeStats();
}
return engine.getMergeStats();
}
public SegmentsStats segmentStats(boolean includeSegmentFileSizes, boolean includeUnloadedSegments) {
SegmentsStats segmentsStats = getEngine().segmentsStats(includeSegmentFileSizes, includeUnloadedSegments);
segmentsStats.addBitsetMemoryInBytes(shardBitsetFilterCache.getMemorySizeInBytes());
return segmentsStats;
}
public WarmerStats warmerStats() {
return shardWarmerService.stats();
}
public FieldDataStats fieldDataStats(String... fields) {
return shardFieldData.stats(fields);
}
public TranslogStats translogStats() {
return getEngine().getTranslogStats();
}
public CompletionStats completionStats(String... fields) {
readAllowed();
return getEngine().completionStats(fields);
}
public DenseVectorStats denseVectorStats() {
readAllowed();
return getEngine().denseVectorStats();
}
public BulkStats bulkStats() {
return bulkOperationListener.stats();
}
/**
* Executes the given flush request against the engine.
*
* @param request the flush request
* @return <code>false</code> if <code>waitIfOngoing==false</code> and an ongoing request is detected, else <code>true</code>.
* If <code>false</code> is returned, no flush happened.
*/
public boolean flush(FlushRequest request) {
PlainActionFuture<Boolean> future = new PlainActionFuture<>();
flush(request, future);
return future.actionGet();
}
/**
* Executes the given flush request against the engine.
*
* @param request the flush request
* @param listener to notify after full durability has been achieved.
* <code>false</code> if <code>waitIfOngoing==false</code>
* and an ongoing request is detected, else <code>true</code>.
* If <code>false</code> is returned, no flush happened.
*/
public void flush(FlushRequest request, ActionListener<Boolean> listener) {
final boolean waitIfOngoing = request.waitIfOngoing();
final boolean force = request.force();
logger.trace("flush with {}", request);
ActionListener.run(listener, l -> {
/*
* We allow flushes while recovery since we allow operations to happen while recovering and we want to keep the translog under
* control (up to deletes, which we do not GC). Yet, we do not use flush internally to clear deletes and flush the index writer
* since we use Engine#writeIndexingBuffer for this now.
*/
verifyNotClosed();
final long startTime = System.nanoTime();
getEngine().flush(
force,
waitIfOngoing,
ActionListener.runBefore(l.map(Engine.FlushResult::flushPerformed), () -> flushMetric.inc(System.nanoTime() - startTime))
);
});
}
/**
* checks and removes translog files that no longer need to be retained. See
* {@link org.elasticsearch.index.translog.TranslogDeletionPolicy} for details
*/
public void trimTranslog() {
verifyNotClosed();
final Engine engine = getEngine();
engine.trimUnreferencedTranslogFiles();
}
/**
* Rolls the tranlog generation and cleans unneeded.
*/
public void rollTranslogGeneration() {
final Engine engine = getEngine();
engine.rollTranslogGeneration();
}
public void forceMerge(ForceMergeRequest forceMerge) throws IOException {
IndexShardState state = this.state; // one time volatile read
if (state != IndexShardState.STARTED) {
throw new IllegalIndexShardStateException(shardId, state, "operation only allowed when shard is active");
}
logger.trace("force merge with {}", forceMerge);
Engine engine = getEngine();
engine.forceMerge(forceMerge.flush(), forceMerge.maxNumSegments(), forceMerge.onlyExpungeDeletes(), forceMerge.forceMergeUUID());
}
/**
* Creates a new {@link IndexCommit} snapshot from the currently running engine. All resources referenced by this
* commit won't be freed until the commit / snapshot is closed.
*
* @param flushFirst <code>true</code> if the index should first be flushed to disk / a low level lucene commit should be executed
*/
public Engine.IndexCommitRef acquireLastIndexCommit(boolean flushFirst) throws EngineException {
final IndexShardState state = this.state; // one time volatile read
// we allow snapshot on closed index shard, since we want to do one after we close the shard and before we close the engine
if (state == IndexShardState.STARTED || state == IndexShardState.CLOSED) {
return getEngine().acquireLastIndexCommit(flushFirst);
} else {
throw new IllegalIndexShardStateException(shardId, state, "snapshot is not allowed");
}
}
/**
* Acquires the {@link IndexCommit} which should be included in a snapshot.
*/
public Engine.IndexCommitRef acquireIndexCommitForSnapshot() throws EngineException {
final IndexShardState state = this.state; // one time volatile read
if (state == IndexShardState.STARTED) {
// unlike acquireLastIndexCommit(), there's no need to acquire a snapshot on a shard that is shutting down
return getEngine().acquireIndexCommitForSnapshot();
} else {
throw new IllegalIndexShardStateException(shardId, state, "snapshot is not allowed");
}
}
/**
* Snapshots the most recent safe index commit from the currently running engine.
* All index files referenced by this index commit won't be freed until the commit/snapshot is closed.
*/
public Engine.IndexCommitRef acquireSafeIndexCommit() throws EngineException {
final IndexShardState state = this.state; // one time volatile read
// we allow snapshot on closed index shard, since we want to do one after we close the shard and before we close the engine
if (state == IndexShardState.STARTED || state == IndexShardState.CLOSED) {
return getEngine().acquireSafeIndexCommit();
} else {
throw new IllegalIndexShardStateException(shardId, state, "snapshot is not allowed");
}
}
/**
* gets a {@link Store.MetadataSnapshot} for the current directory. This method is safe to call in all lifecycle of the index shard,
* without having to worry about the current state of the engine and concurrent flushes.
*
* @throws org.apache.lucene.index.IndexNotFoundException if no index is found in the current directory
* @throws org.apache.lucene.index.CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum
* mismatch or an unexpected exception when opening the index reading the
* segments file.
* @throws org.apache.lucene.index.IndexFormatTooOldException if the lucene index is too old to be opened.
* @throws org.apache.lucene.index.IndexFormatTooNewException if the lucene index is too new to be opened.
* @throws java.io.FileNotFoundException if one or more files referenced by a commit are not present.
* @throws java.nio.file.NoSuchFileException if one or more files referenced by a commit are not present.
*/
public Store.MetadataSnapshot snapshotStoreMetadata() throws IOException {
assert Thread.holdsLock(mutex) == false : "snapshotting store metadata under mutex";
Engine.IndexCommitRef indexCommit = null;
store.incRef();
try {
synchronized (engineMutex) {
// if the engine is not running, we can access the store directly, but we need to make sure no one starts
// the engine on us. If the engine is running, we can get a snapshot via the deletion policy of the engine.
final Engine engine = getEngineOrNull();
if (engine != null) {
indexCommit = engine.acquireLastIndexCommit(false);
}
if (indexCommit == null) {
return store.getMetadata(null, true);
}
}
return store.getMetadata(indexCommit.getIndexCommit());
} finally {
store.decRef();
IOUtils.close(indexCommit);
}
}
/**
* Fails the shard and marks the shard store as corrupted if
* <code>e</code> is caused by index corruption
*/
public void failShard(String reason, @Nullable Exception e) {
// fail the engine. This will cause this shard to also be removed from the node's index service.
getEngine().failEngine(reason, e);
}
/**
* Acquires a point-in-time reader that can be used to create {@link Engine.Searcher}s on demand.
*/
public Engine.SearcherSupplier acquireSearcherSupplier() {
return acquireSearcherSupplier(Engine.SearcherScope.EXTERNAL);
}
/**
* Acquires a point-in-time reader that can be used to create {@link Engine.Searcher}s on demand.
*/
public Engine.SearcherSupplier acquireSearcherSupplier(Engine.SearcherScope scope) {
readAllowed();
markSearcherAccessed();
final Engine engine = getEngine();
return engine.acquireSearcherSupplier(this::wrapSearcher, scope);
}
public Engine.Searcher acquireSearcher(String source) {
readAllowed();
markSearcherAccessed();
final Engine engine = getEngine();
return engine.acquireSearcher(source, Engine.SearcherScope.EXTERNAL, this::wrapSearcher);
}
private void markSearcherAccessed() {
lastSearcherAccess.lazySet(threadPool.relativeTimeInMillis());
}
private Engine.Searcher wrapSearcher(Engine.Searcher searcher) {
assert ElasticsearchDirectoryReader.unwrap(searcher.getDirectoryReader()) != null
: "DirectoryReader must be an instance or ElasticsearchDirectoryReader";
boolean success = false;
try {
final Engine.Searcher newSearcher = wrapSearcher(searcher, fieldUsageTracker.createSession(), readerWrapper);
assert newSearcher != null;
success = true;
return newSearcher;
} catch (IOException ex) {
throw new ElasticsearchException("failed to wrap searcher", ex);
} finally {
if (success == false) {
Releasables.closeWhileHandlingException(searcher);
}
}
}
static Engine.Searcher wrapSearcher(
Engine.Searcher engineSearcher,
ShardFieldUsageTracker.FieldUsageStatsTrackingSession fieldUsageStatsTrackingSession,
@Nullable CheckedFunction<DirectoryReader, DirectoryReader, IOException> readerWrapper
) throws IOException {
final ElasticsearchDirectoryReader elasticsearchDirectoryReader = ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(
engineSearcher.getDirectoryReader()
);
if (elasticsearchDirectoryReader == null) {
throw new IllegalStateException("Can't wrap non elasticsearch directory reader");
}
if (readerWrapper == null) {
readerWrapper = r -> r;
}
NonClosingReaderWrapper nonClosingReaderWrapper = new NonClosingReaderWrapper(engineSearcher.getDirectoryReader());
// first apply field usage stats wrapping before applying other wrappers so that it can track the effects of these wrappers
DirectoryReader reader = readerWrapper.apply(
new FieldUsageTrackingDirectoryReader(nonClosingReaderWrapper, fieldUsageStatsTrackingSession)
);
if (reader.getReaderCacheHelper() != elasticsearchDirectoryReader.getReaderCacheHelper()) {
throw new IllegalStateException(
"wrapped directory reader doesn't delegate IndexReader#getCoreCacheKey,"
+ " wrappers must override this method and delegate to the original readers core cache key. Wrapped readers can't be "
+ "used as cache keys since their are used only per request which would lead to subtle bugs"
);
}
if (ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(reader) != elasticsearchDirectoryReader) {
// prevent that somebody wraps with a non-filter reader
throw new IllegalStateException("wrapped directory reader hides actual ElasticsearchDirectoryReader but shouldn't");
}
// we close the reader to make sure wrappers can release resources if needed....
// our NonClosingReaderWrapper makes sure that our reader is not closed
return new Engine.Searcher(
engineSearcher.source(),
reader,
engineSearcher.getSimilarity(),
engineSearcher.getQueryCache(),
engineSearcher.getQueryCachingPolicy(),
() -> IOUtils.close(
reader, // this will close the wrappers excluding the NonClosingReaderWrapper
engineSearcher, // this will run the closeable on the wrapped engine reader
fieldUsageStatsTrackingSession
)
); // completes stats recording
}
public void setGlobalCheckpointIfUnpromotable(long globalCheckpoint) {
assert shardRouting.isPromotableToPrimary() == false : "must only call this on unpromotable shards";
globalCheckPointIfUnpromotable = globalCheckpoint;
}
private static final class NonClosingReaderWrapper extends FilterDirectoryReader {
private NonClosingReaderWrapper(DirectoryReader in) throws IOException {
super(in, new SubReaderWrapper() {
@Override
public LeafReader wrap(LeafReader reader) {
return reader;
}
});
}
@Override
protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException {
return new NonClosingReaderWrapper(in);
}
@Override
protected void doClose() {
// don't close here - mimic the MultiReader#doClose = false behavior that FilterDirectoryReader doesn't have
}
@Override
public CacheHelper getReaderCacheHelper() {
return in.getReaderCacheHelper();
}
}
public void close(String reason, boolean flushEngine, Executor closeExecutor, ActionListener<Void> closeListener) throws IOException {
synchronized (engineMutex) {
try {
synchronized (mutex) {
changeState(IndexShardState.CLOSED, reason);
}
checkAndCallWaitForEngineOrClosedShardListeners();
} finally {
final Engine engine = this.currentEngineReference.getAndSet(null);
closeExecutor.execute(ActionRunnable.run(closeListener, new CheckedRunnable<>() {
@Override
public void run() throws Exception {
try {
if (engine != null && flushEngine) {
engine.flushAndClose();
}
} finally {
// playing safe here and close the engine even if the above succeeds - close can be called multiple times
// Also closing refreshListeners to prevent us from accumulating any more listeners
IOUtils.close(
engine,
globalCheckpointListeners,
refreshListeners,
pendingReplicationActions,
indexShardOperationPermits
);
}
}
@Override
public String toString() {
return "IndexShard#close[" + shardId + "]";
}
}));
}
}
}
public void preRecovery(ActionListener<Void> listener) {
final IndexShardState currentState = this.state; // single volatile read
if (currentState == IndexShardState.CLOSED) {
throw new IndexShardNotRecoveringException(shardId, currentState);
}
assert currentState == IndexShardState.RECOVERING : "expected a recovering shard " + shardId + " but got " + currentState;
indexEventListener.beforeIndexShardRecovery(this, indexSettings, listener);
}
public void postRecovery(String reason, ActionListener<Void> listener) throws IndexShardStartedException, IndexShardRelocatedException,
IndexShardClosedException {
assert postRecoveryComplete == null;
SubscribableListener<Void> subscribableListener = new SubscribableListener<>();
postRecoveryComplete = subscribableListener;
final ActionListener<Void> finalListener = ActionListener.runBefore(listener, () -> subscribableListener.onResponse(null));
try {
getEngine().refresh("post_recovery");
// we need to refresh again to expose all operations that were index until now. Otherwise
// we may not expose operations that were indexed with a refresh listener that was immediately
// responded to in addRefreshListener. The refresh must happen under the same mutex used in addRefreshListener
synchronized (mutex) {
if (state == IndexShardState.CLOSED) {
throw new IndexShardClosedException(shardId);
}
if (state == IndexShardState.STARTED) {
throw new IndexShardStartedException(shardId);
}
recoveryState.setStage(RecoveryState.Stage.DONE);
changeState(IndexShardState.POST_RECOVERY, reason);
}
indexEventListener.afterIndexShardRecovery(this, finalListener);
} catch (Exception e) {
finalListener.onFailure(e);
}
}
/**
* called before starting to copy index files over
*/
public void prepareForIndexRecovery() {
if (state != IndexShardState.RECOVERING) {
throw new IndexShardNotRecoveringException(shardId, state);
}
recoveryState.setStage(RecoveryState.Stage.INDEX);
assert currentEngineReference.get() == null;
}
/**
* A best-effort attempt to bring up this shard to the global checkpoint using the local translog before performing a peer recovery.
*
* @param recoveryStartingSeqNoListener a listener to be completed with the sequence number from which an operation-based peer recovery
* can start. This is the first operation after the local checkpoint of the safe commit if exists.
*/
public void recoverLocallyUpToGlobalCheckpoint(ActionListener<Long> recoveryStartingSeqNoListener) {
assert Thread.holdsLock(mutex) == false : "must not hold the mutex here";
if (state != IndexShardState.RECOVERING) {
recoveryStartingSeqNoListener.onFailure(new IndexShardNotRecoveringException(shardId, state));
return;
}
try {
recoveryState.validateCurrentStage(RecoveryState.Stage.INDEX);
} catch (Exception e) {
recoveryStartingSeqNoListener.onFailure(e);
return;
}
assert routingEntry().recoverySource().getType() == RecoverySource.Type.PEER : "not a peer recovery [" + routingEntry() + "]";
try {
final var translogUUID = store.readLastCommittedSegmentsInfo().getUserData().get(Translog.TRANSLOG_UUID_KEY);
final var globalCheckpoint = Translog.readGlobalCheckpoint(translogConfig.getTranslogPath(), translogUUID);
final var safeCommit = store.findSafeIndexCommit(globalCheckpoint);
ActionListener.run(recoveryStartingSeqNoListener.delegateResponse((l, e) -> {
logger.debug(() -> format("failed to recover shard locally up to global checkpoint %s", globalCheckpoint), e);
l.onResponse(UNASSIGNED_SEQ_NO);
}), l -> doLocalRecovery(globalCheckpoint, safeCommit, l));
} catch (org.apache.lucene.index.IndexNotFoundException e) {
logger.trace("skip local recovery as no index commit found");
recoveryStartingSeqNoListener.onResponse(UNASSIGNED_SEQ_NO);
} catch (Exception e) {
logger.debug("skip local recovery as failed to find the safe commit", e);
recoveryStartingSeqNoListener.onResponse(UNASSIGNED_SEQ_NO);
}
}
private void doLocalRecovery(
long globalCheckpoint,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") Optional<SequenceNumbers.CommitInfo> safeCommit,
ActionListener<Long> recoveryStartingSeqNoListener
) {
maybeCheckIndex(); // check index here and won't do it again if ops-based recovery occurs
recoveryState.setLocalTranslogStage();
if (safeCommit.isPresent() == false) {
logger.trace("skip local recovery as no safe commit found");
recoveryStartingSeqNoListener.onResponse(UNASSIGNED_SEQ_NO);
return;
}
assert safeCommit.get().localCheckpoint <= globalCheckpoint : safeCommit.get().localCheckpoint + " > " + globalCheckpoint;
if (safeCommit.get().localCheckpoint == globalCheckpoint) {
logger.trace(
"skip local recovery as the safe commit is up to date; safe commit {} global checkpoint {}",
safeCommit.get(),
globalCheckpoint
);
recoveryState.getTranslog().totalLocal(0);
recoveryStartingSeqNoListener.onResponse(globalCheckpoint + 1);
return;
}
if (indexSettings.getIndexMetadata().getState() == IndexMetadata.State.CLOSE
|| IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.get(indexSettings.getSettings())) {
logger.trace(
"skip local recovery as the index was closed or not allowed to write; safe commit {} global checkpoint {}",
safeCommit.get(),
globalCheckpoint
);
recoveryState.getTranslog().totalLocal(0);
recoveryStartingSeqNoListener.onResponse(safeCommit.get().localCheckpoint + 1);
return;
}
SubscribableListener
// First, start a temporary engine, recover the local translog up to the given checkpoint, and then close the engine again.
.<Void>newForked(l -> ActionListener.runWithResource(ActionListener.assertOnce(l), () -> () -> {
assert Thread.holdsLock(mutex) == false : "must not hold the mutex here";
synchronized (engineMutex) {
IOUtils.close(currentEngineReference.getAndSet(null));
}
}, (recoveryCompleteListener, ignoredRef) -> {
assert Thread.holdsLock(mutex) == false : "must not hold the mutex here";
final Engine.TranslogRecoveryRunner translogRecoveryRunner = (engine, snapshot) -> {
recoveryState.getTranslog().totalLocal(snapshot.totalOperations());
final int recoveredOps = runTranslogRecovery(
engine,
snapshot,
Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY,
recoveryState.getTranslog()::incrementRecoveredOperations
);
recoveryState.getTranslog().totalLocal(recoveredOps); // adjust the total local to reflect the actual count
return recoveredOps;
};
innerOpenEngineAndTranslog(() -> globalCheckpoint);
getEngine().recoverFromTranslog(translogRecoveryRunner, globalCheckpoint, recoveryCompleteListener.map(v -> {
logger.trace("shard locally recovered up to {}", getEngine().getSeqNoStats(globalCheckpoint));
return v;
}));
}))
// If the recovery replayed any operations then it will have created a new safe commit for the specified global checkpoint,
// which we can use for the rest of the recovery, so now we load the safe commit and use its local checkpoint as the recovery
// starting point.
.andThenApply(ignored -> {
assert Thread.holdsLock(mutex) == false : "must not hold the mutex here";
try {
// we need to find the safe commit again as we should have created a new one during the local recovery
final Optional<SequenceNumbers.CommitInfo> newSafeCommit = store.findSafeIndexCommit(globalCheckpoint);
assert newSafeCommit.isPresent() : "no safe commit found after local recovery";
return newSafeCommit.get().localCheckpoint + 1;
} catch (Exception e) {
logger.debug(
() -> format(
"failed to find the safe commit after recovering shard locally up to global checkpoint %s",
globalCheckpoint
),
e
);
return UNASSIGNED_SEQ_NO;
}
})
.addListener(recoveryStartingSeqNoListener);
}
public void trimOperationOfPreviousPrimaryTerms(long aboveSeqNo) {
getEngine().trimOperationsFromTranslog(getOperationPrimaryTerm(), aboveSeqNo);
}
/**
* Returns the maximum auto_id_timestamp of all append-only requests have been processed by this shard or the auto_id_timestamp received
* from the primary via {@link #updateMaxUnsafeAutoIdTimestamp(long)} at the beginning of a peer-recovery or a primary-replica resync.
*
* @see #updateMaxUnsafeAutoIdTimestamp(long)
*/
public long getMaxSeenAutoIdTimestamp() {
return getEngine().getMaxSeenAutoIdTimestamp();
}
/**
* Since operations stored in soft-deletes do not have max_auto_id_timestamp, the primary has to propagate its max_auto_id_timestamp
* (via {@link #getMaxSeenAutoIdTimestamp()} of all processed append-only requests to replicas at the beginning of a peer-recovery
* or a primary-replica resync to force a replica to disable optimization for all append-only requests which are replicated via
* replication while its retry variants are replicated via recovery without auto_id_timestamp.
* <p>
* Without this force-update, a replica can generate duplicate documents (for the same id) if it first receives
* a retry append-only (without timestamp) via recovery, then an original append-only (with timestamp) via replication.
*/
public void updateMaxUnsafeAutoIdTimestamp(long maxSeenAutoIdTimestampFromPrimary) {
getEngine().updateMaxUnsafeAutoIdTimestamp(maxSeenAutoIdTimestampFromPrimary);
}
public Engine.Result applyTranslogOperation(Translog.Operation operation, Engine.Operation.Origin origin) throws IOException {
return applyTranslogOperation(getEngine(), operation, origin);
}
private Engine.Result applyTranslogOperation(Engine engine, Translog.Operation operation, Engine.Operation.Origin origin)
throws IOException {
// If a translog op is replayed on the primary (eg. ccr), we need to use external instead of null for its version type.
final VersionType versionType = (origin == Engine.Operation.Origin.PRIMARY) ? VersionType.EXTERNAL : null;
final Engine.Result result;
switch (operation.opType()) {
case INDEX -> {
final Translog.Index index = (Translog.Index) operation;
// we set canHaveDuplicates to true all the time such that we de-optimze the translog case and ensure that all
// autoGeneratedID docs that are coming from the primary are updated correctly.
result = applyIndexOperation(
engine,
index.seqNo(),
index.primaryTerm(),
index.version(),
versionType,
UNASSIGNED_SEQ_NO,
0,
index.getAutoGeneratedIdTimestamp(),
true,
origin,
new SourceToParse(index.id(), index.source(), XContentHelper.xContentType(index.source()), index.routing())
);
}
case DELETE -> {
final Translog.Delete delete = (Translog.Delete) operation;
result = applyDeleteOperation(
engine,
delete.seqNo(),
delete.primaryTerm(),
delete.version(),
delete.id(),
versionType,
UNASSIGNED_SEQ_NO,
0,
origin
);
}
case NO_OP -> {
final Translog.NoOp noOp = (Translog.NoOp) operation;
result = markSeqNoAsNoop(engine, noOp.seqNo(), noOp.primaryTerm(), noOp.reason(), origin);
}
default -> throw new IllegalStateException("No operation defined for [" + operation + "]");
}
return result;
}
/**
* Replays translog operations from the provided translog {@code snapshot} to the current engine using the given {@code origin}.
* The callback {@code onOperationRecovered} is notified after each translog operation is replayed successfully.
*/
int runTranslogRecovery(Engine engine, Translog.Snapshot snapshot, Engine.Operation.Origin origin, Runnable onOperationRecovered)
throws IOException {
int opsRecovered = 0;
Translog.Operation operation;
while ((operation = snapshot.next()) != null) {
try {
logger.trace("[translog] recover op {}", operation);
Engine.Result result = applyTranslogOperation(engine, operation, origin);
switch (result.getResultType()) {
case FAILURE:
throw result.getFailure();
case MAPPING_UPDATE_REQUIRED:
throw new IllegalArgumentException("unexpected mapping update: " + result.getRequiredMappingUpdate());
case SUCCESS:
break;
default:
throw new AssertionError("Unknown result type [" + result.getResultType() + "]");
}
opsRecovered++;
onOperationRecovered.run();
} catch (Exception e) {
// TODO: Don't enable this leniency unless users explicitly opt-in
if (origin == Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY && ExceptionsHelper.status(e) == RestStatus.BAD_REQUEST) {
// mainly for MapperParsingException and Failure to detect xcontent
logger.info("ignoring recovery of a corrupt translog entry", e);
} else {
throw ExceptionsHelper.convertToRuntime(e);
}
}
}
return opsRecovered;
}
private void loadGlobalCheckpointToReplicationTracker() throws IOException {
if (shardRouting.isPromotableToPrimary()) {
// we have to set it before we open an engine and recover from the translog because
// acquiring a snapshot from the translog causes a sync which causes the global checkpoint to be pulled in,
// and an engine can be forced to close in ctor which also causes the global checkpoint to be pulled in.
final String translogUUID = store.readLastCommittedSegmentsInfo().getUserData().get(Translog.TRANSLOG_UUID_KEY);
final long globalCheckpoint = Translog.readGlobalCheckpoint(translogConfig.getTranslogPath(), translogUUID);
replicationTracker.updateGlobalCheckpointOnReplica(globalCheckpoint, "read from translog checkpoint");
} else {
replicationTracker.updateGlobalCheckpointOnReplica(globalCheckPointIfUnpromotable, "from CleanFilesRequest");
}
}
/**
* opens the engine on top of the existing lucene engine and translog.
* Operations from the translog will be replayed to bring lucene up to date.
**/
public void openEngineAndRecoverFromTranslog(ActionListener<Void> listener) {
try {
recoveryState.validateCurrentStage(RecoveryState.Stage.INDEX);
maybeCheckIndex();
recoveryState.setLocalTranslogStage();
final RecoveryState.Translog translogRecoveryStats = recoveryState.getTranslog();
final Engine.TranslogRecoveryRunner translogRecoveryRunner = (engine, snapshot) -> {
translogRecoveryStats.totalOperations(snapshot.totalOperations());
translogRecoveryStats.totalOperationsOnStart(snapshot.totalOperations());
return runTranslogRecovery(
engine,
snapshot,
Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY,
translogRecoveryStats::incrementRecoveredOperations
);
};
loadGlobalCheckpointToReplicationTracker();
innerOpenEngineAndTranslog(replicationTracker);
getEngine().recoverFromTranslog(translogRecoveryRunner, Long.MAX_VALUE, listener);
} catch (Exception e) {
listener.onFailure(e);
}
}
/**
* Opens the engine on top of the existing lucene engine and translog.
* The translog is kept but its operations won't be replayed.
*/
public void openEngineAndSkipTranslogRecovery() throws IOException {
assert routingEntry().recoverySource().getType() == RecoverySource.Type.PEER : "not a peer recovery [" + routingEntry() + "]";
recoveryState.validateCurrentStage(RecoveryState.Stage.TRANSLOG);
loadGlobalCheckpointToReplicationTracker();
innerOpenEngineAndTranslog(replicationTracker);
getEngine().skipTranslogRecovery();
}
private void innerOpenEngineAndTranslog(LongSupplier globalCheckpointSupplier) throws IOException {
assert Thread.holdsLock(mutex) == false : "opening engine under mutex";
if (state != IndexShardState.RECOVERING) {
throw new IndexShardNotRecoveringException(shardId, state);
}
final EngineConfig config = newEngineConfig(globalCheckpointSupplier);
// we disable deletes since we allow for operations to be executed against the shard while recovering
// but we need to make sure we don't loose deletes until we are done recovering
config.setEnableGcDeletes(false);
updateRetentionLeasesOnReplica(loadRetentionLeases());
assert recoveryState.getRecoverySource().expectEmptyRetentionLeases() == false || getRetentionLeases().leases().isEmpty()
: "expected empty set of retention leases with recovery source ["
+ recoveryState.getRecoverySource()
+ "] but got "
+ getRetentionLeases();
synchronized (engineMutex) {
assert currentEngineReference.get() == null : "engine is running";
verifyNotClosed();
// we must create a new engine under mutex (see IndexShard#snapshotStoreMetadata).
final Engine newEngine = createEngine(config);
onNewEngine(newEngine);
currentEngineReference.set(newEngine);
// We set active because we are now writing operations to the engine; this way,
// we can flush if we go idle after some time and become inactive.
active.set(true);
}
// time elapses after the engine is created above (pulling the config settings) until we set the engine reference, during
// which settings changes could possibly have happened, so here we forcefully push any config changes to the new engine.
onSettingsChanged();
assert assertSequenceNumbersInCommit();
recoveryState.validateCurrentStage(RecoveryState.Stage.TRANSLOG);
checkAndCallWaitForEngineOrClosedShardListeners();
}
// awful hack to work around problem in CloseFollowerIndexIT
static boolean suppressCreateEngineErrors;
private Engine createEngine(EngineConfig config) {
if (suppressCreateEngineErrors) {
try {
return engineFactory.newReadWriteEngine(config);
} catch (Error e) {
ExceptionsHelper.maybeDieOnAnotherThread(e);
throw new RuntimeException("rethrowing suppressed error", e);
}
} else {
return engineFactory.newReadWriteEngine(config);
}
}
private boolean assertSequenceNumbersInCommit() throws IOException {
final SegmentInfos segmentCommitInfos = SegmentInfos.readLatestCommit(store.directory());
final Map<String, String> userData = segmentCommitInfos.getUserData();
assert userData.containsKey(SequenceNumbers.LOCAL_CHECKPOINT_KEY) : "commit point doesn't contains a local checkpoint";
assert userData.containsKey(SequenceNumbers.MAX_SEQ_NO) : "commit point doesn't contains a maximum sequence number";
assert userData.containsKey(Engine.HISTORY_UUID_KEY) : "commit point doesn't contains a history uuid";
assert userData.get(Engine.HISTORY_UUID_KEY).equals(getHistoryUUID())
: "commit point history uuid ["
+ userData.get(Engine.HISTORY_UUID_KEY)
+ "] is different than engine ["
+ getHistoryUUID()
+ "]";
assert userData.containsKey(Engine.MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID)
: "opening index which was created post 5.5.0 but " + Engine.MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID + " is not found in commit";
final org.apache.lucene.util.Version commitLuceneVersion = segmentCommitInfos.getCommitLuceneVersion();
// This relies in the previous minor having another lucene version
assert commitLuceneVersion.onOrAfter(RecoverySettings.SEQ_NO_SNAPSHOT_RECOVERIES_SUPPORTED_VERSION.luceneVersion()) == false
|| userData.containsKey(Engine.ES_VERSION)
&& Engine.readIndexVersion(userData.get(Engine.ES_VERSION)).onOrBefore(IndexVersion.current())
: "commit point has an invalid ES_VERSION value. commit point lucene version ["
+ commitLuceneVersion
+ "],"
+ " ES_VERSION ["
+ userData.get(Engine.ES_VERSION)
+ "]";
return true;
}
private void onNewEngine(Engine newEngine) {
assert Thread.holdsLock(engineMutex);
refreshListeners.setCurrentRefreshLocationSupplier(newEngine::getTranslogLastWriteLocation);
refreshListeners.setCurrentProcessedCheckpointSupplier(newEngine::getProcessedLocalCheckpoint);
refreshListeners.setMaxIssuedSeqNoSupplier(newEngine::getMaxSeqNo);
}
/**
* called if recovery has to be restarted after network error / delay **
*/
public void performRecoveryRestart() throws IOException {
assert Thread.holdsLock(mutex) == false : "restart recovery under mutex";
synchronized (engineMutex) {
assert refreshListeners.pendingCount() == 0 : "we can't restart with pending listeners";
IOUtils.close(currentEngineReference.getAndSet(null));
resetRecoveryStage();
}
}
/**
* If a file-based recovery occurs, a recovery target calls this method to reset the recovery stage.
*/
public void resetRecoveryStage() {
assert routingEntry().recoverySource().getType() == RecoverySource.Type.PEER : "not a peer recovery [" + routingEntry() + "]";
assert currentEngineReference.get() == null;
if (state != IndexShardState.RECOVERING) {
throw new IndexShardNotRecoveringException(shardId, state);
}
synchronized (mutex) {
this.recoveryState = recoveryState().reset();
}
}
/**
* returns stats about ongoing recoveries, both source and target
*/
public RecoveryStats recoveryStats() {
return recoveryStats;
}
/**
* Returns the current {@link RecoveryState} if this shard is recovering or has been recovering.
* Returns null if the recovery has not yet started or shard was not recovered (created via an API).
*/
@Override
public RecoveryState recoveryState() {
return this.recoveryState;
}
@Override
public ShardLongFieldRange getTimestampRange() {
if (mapperService() == null) {
return ShardLongFieldRange.UNKNOWN; // no mapper service, no idea if the field even exists
}
final MappedFieldType mappedFieldType = mapperService().fieldType(DataStream.TIMESTAMP_FIELD_NAME);
if (mappedFieldType instanceof DateFieldMapper.DateFieldType == false) {
return ShardLongFieldRange.UNKNOWN; // field missing or not a date
}
if (mappedFieldType.isIndexed() == false) {
return ShardLongFieldRange.UNKNOWN; // range information missing
}
final ShardLongFieldRange rawTimestampFieldRange;
try {
rawTimestampFieldRange = getEngine().getRawFieldRange(DataStream.TIMESTAMP_FIELD_NAME);
assert rawTimestampFieldRange != null;
} catch (IOException | AlreadyClosedException e) {
logger.debug("exception obtaining range for timestamp field", e);
return ShardLongFieldRange.UNKNOWN;
}
if (rawTimestampFieldRange == ShardLongFieldRange.UNKNOWN) {
return ShardLongFieldRange.UNKNOWN;
}
if (rawTimestampFieldRange == ShardLongFieldRange.EMPTY) {
return ShardLongFieldRange.EMPTY;
}
return ShardLongFieldRange.of(rawTimestampFieldRange.getMin(), rawTimestampFieldRange.getMax());
}
/**
* perform the last stages of recovery once all translog operations are done.
* note that you should still call {@link #postRecovery(String, ActionListener)}.
*/
public void finalizeRecovery() {
recoveryState().setStage(RecoveryState.Stage.FINALIZE);
Engine engine = getEngine();
engine.refresh("recovery_finalization");
engine.config().setEnableGcDeletes(true);
}
/**
* Returns {@code true} if this shard can ignore a recovery attempt made to it (since the already doing/done it)
*/
public boolean ignoreRecoveryAttempt() {
IndexShardState state = state(); // one time volatile read
return state == IndexShardState.POST_RECOVERY
|| state == IndexShardState.RECOVERING
|| state == IndexShardState.STARTED
|| state == IndexShardState.CLOSED;
}
public void readAllowed() throws IllegalIndexShardStateException {
IndexShardState state = this.state; // one time volatile read
if (readAllowedStates.contains(state) == false) {
throw new IllegalIndexShardStateException(
shardId,
state,
"operations only allowed when shard state is one of " + readAllowedStates.toString()
);
}
}
/** returns true if the {@link IndexShardState} allows reading */
public boolean isReadAllowed() {
return readAllowedStates.contains(state);
}
private void ensureWriteAllowed(Engine.Operation.Origin origin) throws IllegalIndexShardStateException {
IndexShardState state = this.state; // one time volatile read
if (origin.isRecovery()) {
if (state != IndexShardState.RECOVERING) {
throw new IllegalIndexShardStateException(
shardId,
state,
"operation only allowed when recovering, origin [" + origin + "]"
);
}
} else {
assert assertWriteOriginInvariants(origin);
if (writeAllowedStates.contains(state) == false) {
throw new IllegalIndexShardStateException(
shardId,
state,
"operation only allowed when shard state is one of " + writeAllowedStates + ", origin [" + origin + "]"
);
}
}
}
private boolean assertWriteOriginInvariants(Engine.Operation.Origin origin) {
switch (origin) {
case PRIMARY -> {
assertPrimaryMode();
assertExpectedStateForPrimaryIndexing(state);
}
case REPLICA -> {
assert assertReplicationTarget();
}
case LOCAL_RESET -> {
final var activeOperationsCount = getActiveOperationsCount();
assert activeOperationsCount == OPERATIONS_BLOCKED
: "locally resetting without blocking operations, active operations [" + activeOperationsCount + "]";
}
default -> {
assert false : "unexpected origin: " + origin;
}
}
return true;
}
private void assertExpectedStateForPrimaryIndexing(IndexShardState state) {
// We do not do indexing into primaries that have not reached state STARTED since:
// * TransportReplicationAction.ReroutePhase only allows to index into active primaries.
// * A relocation will retry the reroute phase.
// * Allocation ids protect against spurious requests towards old allocations.
// * We apply the cluster state on IndexShard instances before making it available for routing
assert state == IndexShardState.STARTED || state == IndexShardState.CLOSED : "primary indexing unexpected in state [" + state + "]";
}
private boolean assertPrimaryMode() {
assert shardRouting.primary() && replicationTracker.isPrimaryMode()
: "shard " + shardRouting + " is not a primary shard in primary mode";
return true;
}
private boolean assertReplicationTarget() {
assert replicationTracker.isPrimaryMode() == false : "shard " + shardRouting + " in primary mode cannot be a replication target";
return true;
}
private void verifyNotClosed() throws IllegalIndexShardStateException {
verifyNotClosed(null);
}
private void verifyNotClosed(Exception suppressed) throws IllegalIndexShardStateException {
IndexShardState state = this.state; // one time volatile read
if (state == IndexShardState.CLOSED) {
final IllegalIndexShardStateException exc = new IndexShardClosedException(shardId, "operation only allowed when not closed");
if (suppressed != null) {
exc.addSuppressed(suppressed);
}
throw exc;
}
}
/**
* Returns number of heap bytes used by the indexing buffer for this shard, or 0 if the shard is closed
*/
public long getIndexBufferRAMBytesUsed() {
Engine engine = getEngineOrNull();
if (engine == null) {
return 0;
}
try {
return engine.getIndexBufferRAMBytesUsed();
} catch (AlreadyClosedException ex) {
return 0;
}
}
public void addShardFailureCallback(Consumer<ShardFailure> onShardFailure) {
this.shardEventListener.delegates.add(onShardFailure);
}
/**
* Called by {@link IndexingMemoryController} to check whether more than {@code inactiveTimeNS} has passed since the last
* indexing operation, so we can flush the index.
*/
public void flushOnIdle(long inactiveTimeNS) {
Engine engineOrNull = getEngineOrNull();
if (engineOrNull != null && System.nanoTime() - engineOrNull.getLastWriteNanos() >= inactiveTimeNS) {
boolean wasActive = active.getAndSet(false);
if (wasActive) {
logger.debug("flushing shard on inactive");
threadPool.executor(ThreadPool.Names.FLUSH)
.execute(() -> flush(new FlushRequest().waitIfOngoing(false).force(false), new ActionListener<>() {
@Override
public void onResponse(Boolean flushed) {
if (flushed == false) {
// In case an ongoing flush was detected, revert active flag so that a next flushOnIdle request
// will retry (#87888)
active.set(true);
}
periodicFlushMetric.inc();
}
@Override
public void onFailure(Exception e) {
if (state != IndexShardState.CLOSED) {
active.set(true);
logger.warn("failed to flush shard on inactive", e);
}
}
}));
}
}
}
public boolean isActive() {
return active.get();
}
public ShardPath shardPath() {
return path;
}
void recoverFromLocalShards(
BiConsumer<MappingMetadata, ActionListener<Void>> mappingUpdateConsumer,
List<IndexShard> localShards,
ActionListener<Boolean> listener
) throws IOException {
assert shardRouting.primary() : "recover from local shards only makes sense if the shard is a primary shard";
assert recoveryState.getRecoverySource().getType() == RecoverySource.Type.LOCAL_SHARDS
: "invalid recovery type: " + recoveryState.getRecoverySource();
final List<LocalShardSnapshot> snapshots = new ArrayList<>();
final ActionListener<Boolean> recoveryListener = ActionListener.runBefore(listener, () -> IOUtils.close(snapshots));
boolean success = false;
try {
for (IndexShard shard : localShards) {
snapshots.add(new LocalShardSnapshot(shard));
}
// we are the first primary, recover from the gateway
// if its post api allocation, the index should exists
assert shardRouting.primary() : "recover from local shards only makes sense if the shard is a primary shard";
StoreRecovery storeRecovery = new StoreRecovery(shardId, logger);
storeRecovery.recoverFromLocalShards(mappingUpdateConsumer, this, snapshots, recoveryListener);
success = true;
} finally {
if (success == false) {
IOUtils.close(snapshots);
}
}
}
public void recoverFromStore(ActionListener<Boolean> listener) {
// we are the first primary, recover from the gateway
// if its post api allocation, the index should exists
assert shardRouting.primary() : "recover from store only makes sense if the shard is a primary shard";
assert shardRouting.initializing() : "can only start recovery on initializing shard";
StoreRecovery storeRecovery = new StoreRecovery(shardId, logger);
storeRecovery.recoverFromStore(this, listener);
}
public void restoreFromRepository(Repository repository, ActionListener<Boolean> listener) {
try {
assert shardRouting.primary() : "recover from store only makes sense if the shard is a primary shard";
assert recoveryState.getRecoverySource().getType() == RecoverySource.Type.SNAPSHOT
: "invalid recovery type: " + recoveryState.getRecoverySource();
StoreRecovery storeRecovery = new StoreRecovery(shardId, logger);
storeRecovery.recoverFromRepository(this, repository, listener);
} catch (Exception e) {
listener.onFailure(e);
}
}
/**
* Tests whether or not the engine should be flushed periodically.
* This test is based on the current size of the translog compared to the configured flush threshold size.
*
* @return {@code true} if the engine should be flushed
*/
boolean shouldPeriodicallyFlush() {
final Engine engine = getEngineOrNull();
if (engine != null) {
try {
return engine.shouldPeriodicallyFlush();
} catch (final AlreadyClosedException e) {
// we are already closed, no need to flush or roll
}
}
return false;
}
/**
* Tests whether or not the translog generation should be rolled to a new generation. This test is based on the size of the current
* generation compared to the configured generation threshold size.
*
* @return {@code true} if the current generation should be rolled to a new generation
*/
boolean shouldRollTranslogGeneration() {
final Engine engine = getEngineOrNull();
if (engine != null) {
try {
return engine.shouldRollTranslogGeneration();
} catch (final AlreadyClosedException e) {
// we are already closed, no need to flush or roll
}
}
return false;
}
public void onSettingsChanged() {
Engine engineOrNull = getEngineOrNull();
if (engineOrNull != null) {
engineOrNull.onSettingsChanged();
}
}
/**
* Acquires a lock on the translog files and Lucene soft-deleted documents to prevent them from being trimmed
*/
public Closeable acquireHistoryRetentionLock() {
return getEngine().acquireHistoryRetentionLock();
}
/**
* Checks if we have a completed history of operations since the given starting seqno (inclusive).
* This method should be called after acquiring the retention lock; See {@link #acquireHistoryRetentionLock()}
*/
public boolean hasCompleteHistoryOperations(String reason, long startingSeqNo) {
return getEngine().hasCompleteOperationHistory(reason, startingSeqNo);
}
/**
* Gets the minimum retained sequence number for this engine.
*
* @return the minimum retained sequence number
*/
public long getMinRetainedSeqNo() {
return getEngine().getMinRetainedSeqNo();
}
/**
* Counts the number of operations in the range of the given sequence numbers.
*
* @param source the source of the request
* @param fromSeqNo the start sequence number (inclusive)
* @param toSeqNo the end sequence number (inclusive)
* @see #newChangesSnapshot(String, long, long, boolean, boolean, boolean)
*/
public int countChanges(String source, long fromSeqNo, long toSeqNo) throws IOException {
return getEngine().countChanges(source, fromSeqNo, toSeqNo);
}
/**
* Creates a new changes snapshot for reading operations whose seq_no are between {@code fromSeqNo}(inclusive)
* and {@code toSeqNo}(inclusive). The caller has to close the returned snapshot after finishing the reading.
*
* @param source the source of the request
* @param fromSeqNo the from seq_no (inclusive) to read
* @param toSeqNo the to seq_no (inclusive) to read
* @param requiredFullRange if {@code true} then {@link Translog.Snapshot#next()} will throw {@link IllegalStateException}
* if any operation between {@code fromSeqNo} and {@code toSeqNo} is missing.
* This parameter should be only enabled when the entire requesting range is below the global checkpoint.
* @param singleConsumer true if the snapshot is accessed by only the thread that creates the snapshot. In this case, the
* snapshot can enable some optimizations to improve the performance.
* @param accessStats true if the stats of the snapshot is accessed via {@link Translog.Snapshot#totalOperations()}
*/
public Translog.Snapshot newChangesSnapshot(
String source,
long fromSeqNo,
long toSeqNo,
boolean requiredFullRange,
boolean singleConsumer,
boolean accessStats
) throws IOException {
return getEngine().newChangesSnapshot(source, fromSeqNo, toSeqNo, requiredFullRange, singleConsumer, accessStats);
}
public List<Segment> segments() {
return getEngine().segments();
}
public List<Segment> segments(boolean includeVectorFormatsInfo) {
return getEngine().segments(includeVectorFormatsInfo);
}
public String getHistoryUUID() {
return getEngine().getHistoryUUID();
}
public IndexEventListener getIndexEventListener() {
return indexEventListener;
}
public void activateThrottling() {
try {
getEngine().activateThrottling();
} catch (AlreadyClosedException ex) {
// ignore
}
}
public void deactivateThrottling() {
try {
getEngine().deactivateThrottling();
} catch (AlreadyClosedException ex) {
// ignore
}
}
private void handleRefreshException(Exception e) {
if (e instanceof AlreadyClosedException) {
// ignore
} else if (e instanceof RefreshFailedEngineException rfee) {
if (rfee.getCause() instanceof InterruptedException) {
// ignore, we are being shutdown
} else if (rfee.getCause() instanceof ClosedByInterruptException) {
// ignore, we are being shutdown
} else if (rfee.getCause() instanceof ThreadInterruptedException) {
// ignore, we are being shutdown
} else {
if (state != IndexShardState.CLOSED) {
logger.warn("Failed to perform engine refresh", e);
}
}
} else {
if (state != IndexShardState.CLOSED) {
logger.warn("Failed to perform engine refresh", e);
}
}
}
/**
* Called when our shard is using too much heap and should move buffered indexed/deleted documents to disk.
*/
public void writeIndexingBuffer() {
try {
Engine engine = getEngine();
engine.writeIndexingBuffer();
} catch (Exception e) {
handleRefreshException(e);
}
}
/**
* Notifies the service to update the local checkpoint for the shard with the provided allocation ID. See
* {@link ReplicationTracker#updateLocalCheckpoint(String, long)} for
* details.
*
* @param allocationId the allocation ID of the shard to update the local checkpoint for
* @param checkpoint the local checkpoint for the shard
*/
public void updateLocalCheckpointForShard(final String allocationId, final long checkpoint) {
assert assertPrimaryMode();
verifyNotClosed();
replicationTracker.updateLocalCheckpoint(allocationId, checkpoint);
}
/**
* Update the local knowledge of the persisted global checkpoint for the specified allocation ID.
*
* @param allocationId the allocation ID to update the global checkpoint for
* @param globalCheckpoint the global checkpoint
*/
public void updateGlobalCheckpointForShard(final String allocationId, final long globalCheckpoint) {
assert assertPrimaryMode();
verifyNotClosed();
replicationTracker.updateGlobalCheckpointForShard(allocationId, globalCheckpoint);
}
/**
* Add a global checkpoint listener. If the global checkpoint is equal to or above the global checkpoint the listener is waiting for,
* then the listener will be notified immediately via an executor (so possibly not on the current thread). If the specified timeout
* elapses before the listener is notified, the listener will be notified with an {@link TimeoutException}. A caller may pass null to
* specify no timeout.
*
* @param waitingForGlobalCheckpoint the global checkpoint the listener is waiting for
* @param listener the listener
* @param timeout the timeout
*/
public void addGlobalCheckpointListener(
final long waitingForGlobalCheckpoint,
final GlobalCheckpointListeners.GlobalCheckpointListener listener,
final TimeValue timeout
) {
this.globalCheckpointListeners.add(waitingForGlobalCheckpoint, listener, timeout);
}
private void ensureSoftDeletesEnabled() {
if (indexSettings.isSoftDeleteEnabled() == false) {
String message = "retention leases requires soft deletes but "
+ indexSettings.getIndex()
+ " does not have soft deletes enabled";
assert false : message;
throw new IllegalStateException(message);
}
}
/**
* Get all retention leases tracked on this shard.
*
* @return the retention leases
*/
public RetentionLeases getRetentionLeases() {
return getRetentionLeases(false);
}
/**
* If the expire leases parameter is false, gets all retention leases tracked on this shard and otherwise first calculates
* expiration of existing retention leases, and then gets all non-expired retention leases tracked on this shard. Note that only the
* primary shard calculates which leases are expired, and if any have expired, syncs the retention leases to any replicas. If the
* expire leases parameter is true, this replication tracker must be in primary mode.
*
* @return the non-expired retention leases
*/
public RetentionLeases getRetentionLeases(final boolean expireLeases) {
assert expireLeases == false || assertPrimaryMode();
verifyNotClosed();
return replicationTracker.getRetentionLeases(expireLeases);
}
public RetentionLeaseStats getRetentionLeaseStats() {
verifyNotClosed();
return new RetentionLeaseStats(getRetentionLeases());
}
/**
* Adds a new retention lease.
*
* @param id the identifier of the retention lease
* @param retainingSequenceNumber the retaining sequence number
* @param source the source of the retention lease
* @param listener the callback when the retention lease is successfully added and synced to replicas
* @return the new retention lease
* @throws IllegalArgumentException if the specified retention lease already exists
*/
public RetentionLease addRetentionLease(
final String id,
final long retainingSequenceNumber,
final String source,
final ActionListener<ReplicationResponse> listener
) {
Objects.requireNonNull(listener);
assert assertPrimaryMode();
verifyNotClosed();
ensureSoftDeletesEnabled();
try (Closeable ignore = acquireHistoryRetentionLock()) {
final long actualRetainingSequenceNumber = retainingSequenceNumber == RETAIN_ALL
? getMinRetainedSeqNo()
: retainingSequenceNumber;
return replicationTracker.addRetentionLease(id, actualRetainingSequenceNumber, source, listener);
} catch (final IOException e) {
throw new AssertionError(e);
}
}
/**
* Renews an existing retention lease.
*
* @param id the identifier of the retention lease
* @param retainingSequenceNumber the retaining sequence number
* @param source the source of the retention lease
* @return the renewed retention lease
* @throws IllegalArgumentException if the specified retention lease does not exist
*/
public RetentionLease renewRetentionLease(final String id, final long retainingSequenceNumber, final String source) {
assert assertPrimaryMode();
verifyNotClosed();
ensureSoftDeletesEnabled();
try (Closeable ignore = acquireHistoryRetentionLock()) {
final long actualRetainingSequenceNumber = retainingSequenceNumber == RETAIN_ALL
? getMinRetainedSeqNo()
: retainingSequenceNumber;
return replicationTracker.renewRetentionLease(id, actualRetainingSequenceNumber, source);
} catch (final IOException e) {
throw new AssertionError(e);
}
}
/**
* Removes an existing retention lease.
*
* @param id the identifier of the retention lease
* @param listener the callback when the retention lease is successfully removed and synced to replicas
*/
public void removeRetentionLease(final String id, final ActionListener<ReplicationResponse> listener) {
Objects.requireNonNull(listener);
assert assertPrimaryMode();
verifyNotClosed();
ensureSoftDeletesEnabled();
replicationTracker.removeRetentionLease(id, listener);
}
/**
* Updates retention leases on a replica.
*
* @param retentionLeases the retention leases
*/
public void updateRetentionLeasesOnReplica(final RetentionLeases retentionLeases) {
assert assertReplicationTarget();
verifyNotClosed();
replicationTracker.updateRetentionLeasesOnReplica(retentionLeases);
}
/**
* Loads the latest retention leases from their dedicated state file.
*
* @return the retention leases
* @throws IOException if an I/O exception occurs reading the retention leases
*/
public RetentionLeases loadRetentionLeases() throws IOException {
verifyNotClosed();
return replicationTracker.loadRetentionLeases(path.getShardStatePath());
}
/**
* Persists the current retention leases to their dedicated state file.
*
* @throws WriteStateException if an exception occurs writing the state file
*/
public void persistRetentionLeases() throws WriteStateException {
verifyNotClosed();
replicationTracker.persistRetentionLeases(path.getShardStatePath());
}
public boolean assertRetentionLeasesPersisted() throws IOException {
return replicationTracker.assertRetentionLeasesPersisted(path.getShardStatePath());
}
/**
* Syncs the current retention leases to all replicas.
*/
public void syncRetentionLeases() {
assert assertPrimaryMode();
verifyNotClosed();
replicationTracker.renewPeerRecoveryRetentionLeases();
final RetentionLeases retentionLeases = getRetentionLeases(true);
logger.trace("background syncing retention leases [{}] after expiration check", retentionLeases);
retentionLeaseSyncer.backgroundSync(shardId, shardRouting.allocationId().getId(), getPendingPrimaryTerm(), retentionLeases);
}
/**
* Called when the recovery process for a shard has opened the engine on the target shard. Ensures that the right data structures
* have been set up locally to track local checkpoint information for the shard and that the shard is added to the replication group.
*
* @param allocationId the allocation ID of the shard for which recovery was initiated
*/
public void initiateTracking(final String allocationId) {
assert assertPrimaryMode();
replicationTracker.initiateTracking(allocationId);
}
/**
* Marks the shard with the provided allocation ID as in-sync with the primary shard. See
* {@link ReplicationTracker#markAllocationIdAsInSync(String, long)}
* for additional details.
*
* @param allocationId the allocation ID of the shard to mark as in-sync
* @param localCheckpoint the current local checkpoint on the shard
*/
public void markAllocationIdAsInSync(final String allocationId, final long localCheckpoint) throws InterruptedException {
assert assertPrimaryMode();
replicationTracker.markAllocationIdAsInSync(allocationId, localCheckpoint);
}
/**
* Returns the persisted local checkpoint for the shard.
*
* @return the local checkpoint
*/
public long getLocalCheckpoint() {
return getEngine().getPersistedLocalCheckpoint();
}
/**
* Returns the global checkpoint for the shard.
*
* @return the global checkpoint
*/
public long getLastKnownGlobalCheckpoint() {
return replicationTracker.getGlobalCheckpoint();
}
/**
* Returns the latest global checkpoint value that has been persisted in the underlying storage (i.e. translog's checkpoint)
*/
public long getLastSyncedGlobalCheckpoint() {
return getEngine().getLastSyncedGlobalCheckpoint();
}
/**
* Get the local knowledge of the global checkpoints for all in-sync allocation IDs.
*
* @return a map from allocation ID to the local knowledge of the global checkpoint for that allocation ID
*/
public Map<String, Long> getInSyncGlobalCheckpoints() {
assert assertPrimaryMode();
verifyNotClosed();
return replicationTracker.getInSyncGlobalCheckpoints();
}
/**
* Syncs the global checkpoint to the replicas if the global checkpoint on at least one replica is behind the global checkpoint on the
* primary.
*/
public void maybeSyncGlobalCheckpoint(final String reason) {
verifyNotClosed();
assert shardRouting.primary() : "only call maybeSyncGlobalCheckpoint on primary shard";
if (replicationTracker.isPrimaryMode() == false) {
return;
}
assert assertPrimaryMode();
// only sync if there are no operations in flight, or when using async durability
final SeqNoStats stats = getEngine().getSeqNoStats(replicationTracker.getGlobalCheckpoint());
final boolean asyncDurability = indexSettings().getTranslogDurability() == Translog.Durability.ASYNC;
if (stats.getMaxSeqNo() == stats.getGlobalCheckpoint() || asyncDurability) {
final var trackedGlobalCheckpointsNeedSync = replicationTracker.trackedGlobalCheckpointsNeedSync();
// async durability means that the local checkpoint might lag (as it is only advanced on fsync)
// periodically ask for the newest local checkpoint by syncing the global checkpoint, so that ultimately the global
// checkpoint can be synced. Also take into account that a shard might be pending sync, which means that it isn't
// in the in-sync set just yet but might be blocked on waiting for its persisted local checkpoint to catch up to
// the global checkpoint.
final boolean syncNeeded = (asyncDurability
&& (stats.getGlobalCheckpoint() < stats.getMaxSeqNo() || replicationTracker.pendingInSync()))
|| trackedGlobalCheckpointsNeedSync;
// only sync if index is not closed and there is a shard lagging the primary
if (syncNeeded && indexSettings.getIndexMetadata().getState() == IndexMetadata.State.OPEN) {
syncGlobalCheckpoints(reason);
}
}
}
private void syncGlobalCheckpoints(String reason) {
logger.trace("syncing global checkpoint for [{}]", reason);
globalCheckpointSyncer.syncGlobalCheckpoints(shardId);
}
// exposed for tests
GlobalCheckpointSyncer getGlobalCheckpointSyncer() {
return globalCheckpointSyncer;
}
/**
* Returns the current replication group for the shard.
*
* @return the replication group
*/
public ReplicationGroup getReplicationGroup() {
assert assertPrimaryMode();
verifyNotClosed();
ReplicationGroup replicationGroup = replicationTracker.getReplicationGroup();
// PendingReplicationActions is dependent on ReplicationGroup. Every time we expose ReplicationGroup,
// ensure PendingReplicationActions is updated with the newest version to prevent races.
pendingReplicationActions.accept(replicationGroup);
return replicationGroup;
}
/**
* Returns the pending replication actions for the shard.
*
* @return the pending replication actions
*/
public PendingReplicationActions getPendingReplicationActions() {
assert assertPrimaryMode();
verifyNotClosed();
return pendingReplicationActions;
}
/**
* Updates the global checkpoint on a replica shard after it has been updated by the primary.
*
* @param globalCheckpoint the global checkpoint
* @param reason the reason the global checkpoint was updated
*/
public void updateGlobalCheckpointOnReplica(final long globalCheckpoint, final String reason) {
assert assertReplicationTarget();
final long localCheckpoint = getLocalCheckpoint();
if (globalCheckpoint > localCheckpoint) {
/*
* This can happen during recovery when the shard has started its engine but recovery is not finalized and is receiving global
* checkpoint updates. However, since this shard is not yet contributing to calculating the global checkpoint, it can be the
* case that the global checkpoint update from the primary is ahead of the local checkpoint on this shard. In this case, we
* ignore the global checkpoint update. This can happen if we are in the translog stage of recovery. Prior to this, the engine
* is not opened and this shard will not receive global checkpoint updates, and after this the shard will be contributing to
* calculations of the global checkpoint. However, we can not assert that we are in the translog stage of recovery here as
* while the global checkpoint update may have emanated from the primary when we were in that state, we could subsequently move
* to recovery finalization, or even finished recovery before the update arrives here.
*/
assert state() != IndexShardState.POST_RECOVERY && state() != IndexShardState.STARTED
: "supposedly in-sync shard copy received a global checkpoint ["
+ globalCheckpoint
+ "] "
+ "that is higher than its local checkpoint ["
+ localCheckpoint
+ "]";
return;
}
replicationTracker.updateGlobalCheckpointOnReplica(globalCheckpoint, reason);
}
private final AtomicInteger outstandingCleanFilesConditions = new AtomicInteger(0);
private final Deque<Runnable> afterCleanFilesActions = new LinkedList<>();
/**
* Creates a {@link Runnable} that must be executed before the clean files step in peer recovery can complete.
*
* @return runnable that must be executed during the clean files step in peer recovery
*/
public Runnable addCleanFilesDependency() {
logger.trace("adding clean files dependency for [{}]", shardRouting);
outstandingCleanFilesConditions.incrementAndGet();
return () -> {
if (outstandingCleanFilesConditions.decrementAndGet() == 0) {
runAfterCleanFilesActions();
}
};
}
/**
* Execute a {@link Runnable} on the generic pool once all dependencies added via {@link #addCleanFilesDependency()} have finished.
* If there are no dependencies to wait for then the {@code Runnable} will be executed on the calling thread.
*/
public void afterCleanFiles(Runnable runnable) {
if (outstandingCleanFilesConditions.get() == 0) {
runnable.run();
} else {
synchronized (afterCleanFilesActions) {
afterCleanFilesActions.add(runnable);
}
if (outstandingCleanFilesConditions.get() == 0) {
runAfterCleanFilesActions();
}
}
}
// for tests
public int outstandingCleanFilesConditions() {
return outstandingCleanFilesConditions.get();
}
private void runAfterCleanFilesActions() {
synchronized (afterCleanFilesActions) {
final Executor executor = threadPool.generic();
Runnable afterCleanFilesAction;
while ((afterCleanFilesAction = afterCleanFilesActions.poll()) != null) {
executor.execute(afterCleanFilesAction);
}
}
}
/**
* Updates the known allocation IDs and the local checkpoints for the corresponding allocations from a primary relocation source.
*
* @param primaryContext the sequence number context
*/
public void activateWithPrimaryContext(final ReplicationTracker.PrimaryContext primaryContext) {
assert shardRouting.primary() && shardRouting.isRelocationTarget()
: "only primary relocation target can update allocation IDs from primary context: " + shardRouting;
assert primaryContext.getCheckpointStates().containsKey(routingEntry().allocationId().getId())
: "primary context [" + primaryContext + "] does not contain relocation target [" + routingEntry() + "]";
assert getLocalCheckpoint() == primaryContext.getCheckpointStates().get(routingEntry().allocationId().getId()).getLocalCheckpoint()
|| indexSettings().getTranslogDurability() == Translog.Durability.ASYNC
: "local checkpoint [" + getLocalCheckpoint() + "] does not match checkpoint from primary context [" + primaryContext + "]";
synchronized (mutex) {
replicationTracker.activateWithPrimaryContext(primaryContext); // make changes to primaryMode flag only under mutex
}
ensurePeerRecoveryRetentionLeasesExist();
}
private void ensurePeerRecoveryRetentionLeasesExist() {
threadPool.generic()
.execute(
() -> replicationTracker.createMissingPeerRecoveryRetentionLeases(
ActionListener.wrap(
r -> logger.trace("created missing peer recovery retention leases"),
e -> logger.debug("failed creating missing peer recovery retention leases", e)
)
)
);
}
/**
* Check if there are any recoveries pending in-sync.
*
* @return {@code true} if there is at least one shard pending in-sync, otherwise false
*/
public boolean pendingInSync() {
assert assertPrimaryMode();
return replicationTracker.pendingInSync();
}
/**
* Should be called for each no-op update operation to increment relevant statistics.
*/
public void noopUpdate() {
internalIndexingStats.noopUpdate();
}
public void maybeCheckIndex() {
recoveryState.setStage(RecoveryState.Stage.VERIFY_INDEX);
if (Booleans.isTrue(checkIndexOnStartup) || "checksum".equals(checkIndexOnStartup)) {
logger.warn(
"performing expensive diagnostic checks during shard startup [{}={}]; "
+ "these checks should only be enabled temporarily, you must remove this index setting as soon as possible",
IndexSettings.INDEX_CHECK_ON_STARTUP.getKey(),
checkIndexOnStartup
);
try {
checkIndex();
} catch (IOException ex) {
throw new RecoveryFailedException(recoveryState, "check index failed", ex);
}
}
}
void checkIndex() throws IOException {
if (store.tryIncRef()) {
try {
doCheckIndex();
} catch (IOException e) {
store.markStoreCorrupted(e);
throw e;
} finally {
store.decRef();
}
}
}
private void doCheckIndex() throws IOException {
long timeNS = System.nanoTime();
if (Lucene.indexExists(store.directory()) == false) {
return;
}
if ("checksum".equals(checkIndexOnStartup)) {
// physical verification only: verify all checksums for the latest commit
IOException corrupt = null;
final MetadataSnapshot metadata;
try {
metadata = snapshotStoreMetadata();
} catch (IOException e) {
logger.warn("check index [failure]", e);
throw e;
}
final List<String> checkedFiles = new ArrayList<>(metadata.size());
for (Map.Entry<String, StoreFileMetadata> entry : metadata.fileMetadataMap().entrySet()) {
try {
Store.checkIntegrity(entry.getValue(), store.directory());
if (corrupt == null) {
checkedFiles.add(entry.getKey());
} else {
logger.info("check index [ok]: checksum check passed on [{}]", entry.getKey());
}
} catch (IOException ioException) {
for (final String checkedFile : checkedFiles) {
logger.info("check index [ok]: checksum check passed on [{}]", checkedFile);
}
checkedFiles.clear();
logger.warn(() -> "check index [failure]: checksum failed on [" + entry.getKey() + "]", ioException);
corrupt = ioException;
}
}
if (corrupt != null) {
throw corrupt;
}
if (logger.isDebugEnabled()) {
for (final String checkedFile : checkedFiles) {
logger.debug("check index [ok]: checksum check passed on [{}]", checkedFile);
}
}
} else {
// full checkindex
final BytesStreamOutput os = new BytesStreamOutput();
final PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
final CheckIndex.Status status = store.checkIndex(out);
out.flush();
if (status.clean == false) {
if (state == IndexShardState.CLOSED) {
// ignore if closed....
return;
}
logger.warn("check index [failure]");
// report details in a separate message, it might contain control characters which mess up detection of the failure message
logger.warn("{}", os.bytes().utf8ToString());
throw new IOException("index check failure");
}
if (logger.isDebugEnabled()) {
logger.debug("check index [success]\n{}", os.bytes().utf8ToString());
}
}
recoveryState.getVerifyIndex().checkIndexTime(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - timeNS)));
}
Engine getEngine() {
Engine engine = getEngineOrNull();
if (engine == null) {
throw new AlreadyClosedException("engine is closed");
}
return engine;
}
/**
* NOTE: returns null if engine is not yet started (e.g. recovery phase 1, copying over index files, is still running), or if engine is
* closed.
*/
public Engine getEngineOrNull() {
return this.currentEngineReference.get();
}
public void startRecovery(
RecoveryState recoveryState,
PeerRecoveryTargetService recoveryTargetService,
PeerRecoveryTargetService.RecoveryListener recoveryListener,
RepositoriesService repositoriesService,
BiConsumer<MappingMetadata, ActionListener<Void>> mappingUpdateConsumer,
IndicesService indicesService,
long clusterStateVersion
) {
// TODO: Create a proper object to encapsulate the recovery context
// all of the current methods here follow a pattern of:
// resolve context which isn't really dependent on the local shards and then async
// call some external method with this pointer.
// with a proper recovery context object we can simply change this to:
// startRecovery(RecoveryState recoveryState, ShardRecoverySource source ) {
// markAsRecovery("from " + source.getShortDescription(), recoveryState);
// threadPool.generic().execute() {
// onFailure () { listener.failure() };
// doRun() {
// if (source.recover(this)) {
// recoveryListener.onRecoveryDone(recoveryState);
// }
// }
// }}
// }
assert recoveryState.getRecoverySource().equals(shardRouting.recoverySource());
switch (recoveryState.getRecoverySource().getType()) {
case EMPTY_STORE, EXISTING_STORE -> executeRecovery("from store", recoveryState, recoveryListener, this::recoverFromStore);
case PEER -> {
try {
markAsRecovering("from " + recoveryState.getSourceNode(), recoveryState);
recoveryTargetService.startRecovery(this, recoveryState.getSourceNode(), clusterStateVersion, recoveryListener);
} catch (Exception e) {
failShard("corrupted preexisting index", e);
recoveryListener.onRecoveryFailure(new RecoveryFailedException(recoveryState, null, e), true);
}
}
case SNAPSHOT -> {
final String repo = ((SnapshotRecoverySource) recoveryState.getRecoverySource()).snapshot().getRepository();
executeRecovery(
"from snapshot",
recoveryState,
recoveryListener,
l -> restoreFromRepository(repositoriesService.repository(repo), l)
);
}
case LOCAL_SHARDS -> {
final IndexMetadata indexMetadata = indexSettings().getIndexMetadata();
final Index resizeSourceIndex = indexMetadata.getResizeSourceIndex();
final List<IndexShard> startedShards = new ArrayList<>();
final IndexService sourceIndexService = indicesService.indexService(resizeSourceIndex);
final Set<ShardId> requiredShards;
final int numShards;
if (sourceIndexService != null) {
requiredShards = IndexMetadata.selectRecoverFromShards(
shardId().id(),
sourceIndexService.getMetadata(),
indexMetadata.getNumberOfShards()
);
for (IndexShard shard : sourceIndexService) {
if (shard.state() == IndexShardState.STARTED && requiredShards.contains(shard.shardId())) {
startedShards.add(shard);
}
}
numShards = requiredShards.size();
} else {
numShards = -1;
requiredShards = Collections.emptySet();
}
if (numShards == startedShards.size()) {
assert requiredShards.isEmpty() == false;
executeRecovery(
"from local shards",
recoveryState,
recoveryListener,
l -> recoverFromLocalShards(
mappingUpdateConsumer,
startedShards.stream().filter((s) -> requiredShards.contains(s.shardId())).toList(),
l
)
);
} else {
final RuntimeException e;
if (numShards == -1) {
e = new IndexNotFoundException(resizeSourceIndex);
} else {
e = new IllegalStateException(
"not all required shards of index "
+ resizeSourceIndex
+ " are started yet, expected "
+ numShards
+ " found "
+ startedShards.size()
+ " can't recover shard "
+ shardId()
);
}
throw e;
}
}
default -> throw new IllegalArgumentException("Unknown recovery source " + recoveryState.getRecoverySource());
}
}
private void executeRecovery(
String reason,
RecoveryState recoveryState,
PeerRecoveryTargetService.RecoveryListener recoveryListener,
CheckedConsumer<ActionListener<Boolean>, Exception> action
) {
markAsRecovering(reason, recoveryState); // mark the shard as recovering on the cluster state thread
threadPool.generic().execute(ActionRunnable.wrap(ActionListener.wrap(r -> {
if (r) {
recoveryListener.onRecoveryDone(recoveryState, getTimestampRange());
}
}, e -> recoveryListener.onRecoveryFailure(new RecoveryFailedException(recoveryState, null, e), true)), action));
}
/**
* Returns whether the shard is a relocated primary, i.e. not in charge anymore of replicating changes (see {@link ReplicationTracker}).
*/
public boolean isRelocatedPrimary() {
assert shardRouting.primary() : "only call isRelocatedPrimary on primary shard";
return replicationTracker.isRelocated();
}
public RetentionLease addPeerRecoveryRetentionLease(
String nodeId,
long globalCheckpoint,
ActionListener<ReplicationResponse> listener
) {
assert assertPrimaryMode();
// only needed for BWC reasons involving rolling upgrades from versions that do not support PRRLs:
assert indexSettings.getIndexVersionCreated().before(IndexVersions.V_7_4_0) || indexSettings.isSoftDeleteEnabled() == false;
return replicationTracker.addPeerRecoveryRetentionLease(nodeId, globalCheckpoint, listener);
}
public RetentionLease cloneLocalPeerRecoveryRetentionLease(String nodeId, ActionListener<ReplicationResponse> listener) {
assert assertPrimaryMode();
return replicationTracker.cloneLocalPeerRecoveryRetentionLease(nodeId, listener);
}
public void removePeerRecoveryRetentionLease(String nodeId, ActionListener<ReplicationResponse> listener) {
assert assertPrimaryMode();
replicationTracker.removePeerRecoveryRetentionLease(nodeId, listener);
}
/**
* Returns a list of retention leases for peer recovery installed in this shard copy.
*/
public List<RetentionLease> getPeerRecoveryRetentionLeases() {
return replicationTracker.getPeerRecoveryRetentionLeases();
}
public boolean useRetentionLeasesInPeerRecovery() {
return useRetentionLeasesInPeerRecovery;
}
private SafeCommitInfo getSafeCommitInfo() {
final Engine engine = getEngineOrNull();
return engine == null ? SafeCommitInfo.EMPTY : engine.getSafeCommitInfo();
}
class ShardEventListener implements Engine.EventListener {
private final CopyOnWriteArrayList<Consumer<ShardFailure>> delegates = new CopyOnWriteArrayList<>();
// called by the current engine
@Override
public void onFailedEngine(String reason, @Nullable Exception failure) {
final ShardFailure shardFailure = new ShardFailure(shardRouting, reason, failure);
for (Consumer<ShardFailure> listener : delegates) {
try {
listener.accept(shardFailure);
} catch (Exception inner) {
inner.addSuppressed(failure);
logger.warn("exception while notifying engine failure", inner);
}
}
}
}
private static void persistMetadata(
final ShardPath shardPath,
final IndexSettings indexSettings,
final ShardRouting newRouting,
final @Nullable ShardRouting currentRouting,
final Logger logger
) throws IOException {
assert newRouting != null : "newRouting must not be null";
// only persist metadata if routing information that is persisted in shard state metadata actually changed
final ShardId shardId = newRouting.shardId();
if (currentRouting == null
|| currentRouting.primary() != newRouting.primary()
|| currentRouting.allocationId().equals(newRouting.allocationId()) == false) {
assert currentRouting == null || currentRouting.isSameAllocation(newRouting);
if (logger.isTraceEnabled()) {
final String writeReason;
if (currentRouting == null) {
writeReason = "initial state with allocation id [" + newRouting.allocationId() + "]";
} else {
writeReason = "routing changed from " + currentRouting + " to " + newRouting;
}
logger.trace("{} writing shard state, reason [{}]", shardId, writeReason);
}
final ShardStateMetadata newShardStateMetadata = new ShardStateMetadata(
newRouting.primary(),
indexSettings.getUUID(),
newRouting.allocationId()
);
ShardStateMetadata.FORMAT.writeAndCleanup(newShardStateMetadata, shardPath.getShardStatePath());
} else {
logger.trace("{} skip writing shard state, has been written before", shardId);
}
}
public static Analyzer buildIndexAnalyzer(MapperService mapperService) {
if (mapperService == null) {
return null;
}
return new DelegatingAnalyzerWrapper(Analyzer.PER_FIELD_REUSE_STRATEGY) {
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
return mapperService.indexAnalyzer(
fieldName,
f -> { throw new IllegalArgumentException("Field [" + f + "] has no associated analyzer"); }
);
}
};
}
private EngineConfig newEngineConfig(LongSupplier globalCheckpointSupplier) {
final Sort indexSort = indexSortSupplier.get();
final Engine.Warmer warmer = reader -> {
assert Thread.holdsLock(mutex) == false : "warming engine under mutex";
assert reader != null;
if (this.warmer != null) {
this.warmer.warm(reader);
}
};
final boolean isTimeBasedIndex = mapperService == null ? false : mapperService.mappingLookup().hasTimestampField();
return new EngineConfig(
shardId,
threadPool,
indexSettings,
warmer,
store,
indexSettings.getMergePolicy(isTimeBasedIndex),
buildIndexAnalyzer(mapperService),
similarityService.similarity(mapperService == null ? null : mapperService::fieldType),
codecService,
shardEventListener,
indexCache != null ? indexCache.query() : null,
cachingPolicy,
translogConfig,
IndexingMemoryController.SHARD_INACTIVE_TIME_SETTING.get(indexSettings.getSettings()),
List.of(refreshListeners, refreshPendingLocationListener, refreshFieldHasValueListener),
Collections.singletonList(new RefreshMetricUpdater(refreshMetric)),
indexSort,
circuitBreakerService,
globalCheckpointSupplier,
replicationTracker::getRetentionLeases,
this::getOperationPrimaryTerm,
snapshotCommitSupplier,
isTimeBasedIndex ? TIMESERIES_LEAF_READERS_SORTER : null,
relativeTimeInNanosSupplier,
indexCommitListener,
routingEntry().isPromotableToPrimary()
);
}
/**
* Acquire a primary operation permit whenever the shard is ready for indexing. If a permit is directly available, the provided
* ActionListener will be called on the calling thread. During relocation hand-off, permit acquisition can be delayed. The provided
* ActionListener will then be called using the provided executor.
*
*/
public void acquirePrimaryOperationPermit(ActionListener<Releasable> onPermitAcquired, Executor executorOnDelay) {
acquirePrimaryOperationPermit(onPermitAcquired, executorOnDelay, false);
}
public void acquirePrimaryOperationPermit(
ActionListener<Releasable> onPermitAcquired,
Executor executorOnDelay,
boolean forceExecution
) {
verifyNotClosed();
assert shardRouting.primary() : "acquirePrimaryOperationPermit should only be called on primary shard: " + shardRouting;
indexShardOperationPermits.acquire(wrapPrimaryOperationPermitListener(onPermitAcquired), executorOnDelay, forceExecution);
}
public boolean isPrimaryMode() {
assert indexShardOperationPermits.getActiveOperationsCount() != 0 : "must hold permit to check primary mode";
return replicationTracker.isPrimaryMode();
}
/**
* Acquire all primary operation permits. Once all permits are acquired, the provided ActionListener is called.
* It is the responsibility of the caller to close the {@link Releasable}.
*/
public void acquireAllPrimaryOperationsPermits(final ActionListener<Releasable> onPermitAcquired, final TimeValue timeout) {
verifyNotClosed();
assert shardRouting.primary() : "acquireAllPrimaryOperationsPermits should only be called on primary shard: " + shardRouting;
asyncBlockOperations(wrapPrimaryOperationPermitListener(onPermitAcquired), timeout.duration(), timeout.timeUnit());
}
/**
* Wraps the action to run on a primary after acquiring permit. This wrapping is used to check if the shard is in primary mode before
* executing the action.
*
* @param listener the listener to wrap
* @return the wrapped listener
*/
private ActionListener<Releasable> wrapPrimaryOperationPermitListener(final ActionListener<Releasable> listener) {
return listener.delegateFailure((l, r) -> {
if (isPrimaryMode()) {
l.onResponse(r);
} else {
r.close();
l.onFailure(new ShardNotInPrimaryModeException(shardId, state));
}
});
}
private void asyncBlockOperations(ActionListener<Releasable> onPermitAcquired, long timeout, TimeUnit timeUnit) {
final Releasable forceRefreshes = refreshListeners.forceRefreshes();
final ActionListener<Releasable> wrappedListener = ActionListener.wrap(r -> {
forceRefreshes.close();
onPermitAcquired.onResponse(r);
}, e -> {
forceRefreshes.close();
onPermitAcquired.onFailure(e);
});
try {
indexShardOperationPermits.blockOperations(wrappedListener, timeout, timeUnit, threadPool.generic());
} catch (Exception e) {
forceRefreshes.close();
throw e;
}
}
/**
* Runs the specified runnable under a permit and otherwise calling back the specified failure callback. This method is really a
* convenience for {@link #acquirePrimaryOperationPermit(ActionListener, Executor)} where the listener equates to
* try-with-resources closing the releasable after executing the runnable on successfully acquiring the permit, an otherwise calling
* back the failure callback.
*
* @param runnable the runnable to execute under permit
* @param onFailure the callback on failure
* @param executorOnDelay the executor to execute the runnable on if permit acquisition is blocked
*/
public void runUnderPrimaryPermit(final Runnable runnable, final Consumer<Exception> onFailure, final Executor executorOnDelay) {
verifyNotClosed();
assert shardRouting.primary() : "runUnderPrimaryPermit should only be called on primary shard but was " + shardRouting;
final ActionListener<Releasable> onPermitAcquired = ActionListener.wrap(releasable -> {
try (Releasable ignore = releasable) {
runnable.run();
}
}, onFailure);
acquirePrimaryOperationPermit(onPermitAcquired, executorOnDelay);
}
private <E extends Exception> void bumpPrimaryTerm(
final long newPrimaryTerm,
final CheckedRunnable<E> onBlocked,
@Nullable ActionListener<Releasable> combineWithAction
) {
assert Thread.holdsLock(mutex);
assert newPrimaryTerm > pendingPrimaryTerm || (newPrimaryTerm >= pendingPrimaryTerm && combineWithAction != null);
assert getOperationPrimaryTerm() <= pendingPrimaryTerm;
final CountDownLatch termUpdated = new CountDownLatch(1);
asyncBlockOperations(new ActionListener<Releasable>() {
@Override
public void onFailure(final Exception e) {
try {
innerFail(e);
} finally {
if (combineWithAction != null) {
combineWithAction.onFailure(e);
}
}
}
private void innerFail(final Exception e) {
try {
failShard("exception during primary term transition", e);
} catch (AlreadyClosedException ace) {
// ignore, shard is already closed
}
}
@Override
public void onResponse(final Releasable releasable) {
final Releasable releaseOnce = Releasables.releaseOnce(releasable);
try {
assert getOperationPrimaryTerm() <= pendingPrimaryTerm;
termUpdated.await();
// indexShardOperationPermits doesn't guarantee that async submissions are executed
// in the order submitted. We need to guard against another term bump
if (getOperationPrimaryTerm() < newPrimaryTerm) {
replicationTracker.setOperationPrimaryTerm(newPrimaryTerm);
onBlocked.run();
}
} catch (final Exception e) {
if (combineWithAction == null) {
// otherwise leave it to combineWithAction to release the permit
releaseOnce.close();
}
innerFail(e);
} finally {
if (combineWithAction != null) {
combineWithAction.onResponse(releasable);
} else {
releaseOnce.close();
}
}
}
}, 30, TimeUnit.MINUTES);
pendingPrimaryTerm = newPrimaryTerm;
termUpdated.countDown();
}
/**
* Acquire a replica operation permit whenever the shard is ready for indexing (see
* {@link #acquirePrimaryOperationPermit(ActionListener, Executor)}). If the given primary term is lower than then one in
* {@link #shardRouting}, the {@link ActionListener#onFailure(Exception)} method of the provided listener is invoked with an
* {@link IllegalStateException}. If permit acquisition is delayed, the listener will be invoked on the executor with the specified
* name.
*
* @param opPrimaryTerm the operation primary term
* @param globalCheckpoint the global checkpoint associated with the request
* @param maxSeqNoOfUpdatesOrDeletes the max seq_no of updates (index operations overwrite Lucene) or deletes captured on the primary
* after this replication request was executed on it (see {@link #getMaxSeqNoOfUpdatesOrDeletes()}
* @param onPermitAcquired the listener for permit acquisition
* @param executorOnDelay the name of the executor to invoke the listener on if permit acquisition is delayed
*/
public void acquireReplicaOperationPermit(
final long opPrimaryTerm,
final long globalCheckpoint,
final long maxSeqNoOfUpdatesOrDeletes,
final ActionListener<Releasable> onPermitAcquired,
final Executor executorOnDelay
) {
innerAcquireReplicaOperationPermit(
opPrimaryTerm,
globalCheckpoint,
maxSeqNoOfUpdatesOrDeletes,
onPermitAcquired,
false,
(listener) -> indexShardOperationPermits.acquire(listener, executorOnDelay, true)
);
}
/**
* Acquire all replica operation permits whenever the shard is ready for indexing (see
* {@link #acquireAllPrimaryOperationsPermits(ActionListener, TimeValue)}. If the given primary term is lower than then one in
* {@link #shardRouting}, the {@link ActionListener#onFailure(Exception)} method of the provided listener is invoked with an
* {@link IllegalStateException}.
*
* @param opPrimaryTerm the operation primary term
* @param globalCheckpoint the global checkpoint associated with the request
* @param maxSeqNoOfUpdatesOrDeletes the max seq_no of updates (index operations overwrite Lucene) or deletes captured on the primary
* after this replication request was executed on it (see {@link #getMaxSeqNoOfUpdatesOrDeletes()}
* @param onPermitAcquired the listener for permit acquisition
* @param timeout the maximum time to wait for the in-flight operations block
*/
public void acquireAllReplicaOperationsPermits(
final long opPrimaryTerm,
final long globalCheckpoint,
final long maxSeqNoOfUpdatesOrDeletes,
final ActionListener<Releasable> onPermitAcquired,
final TimeValue timeout
) {
innerAcquireReplicaOperationPermit(
opPrimaryTerm,
globalCheckpoint,
maxSeqNoOfUpdatesOrDeletes,
onPermitAcquired,
true,
listener -> asyncBlockOperations(listener, timeout.duration(), timeout.timeUnit())
);
}
private void innerAcquireReplicaOperationPermit(
final long opPrimaryTerm,
final long globalCheckpoint,
final long maxSeqNoOfUpdatesOrDeletes,
final ActionListener<Releasable> onPermitAcquired,
final boolean allowCombineOperationWithPrimaryTermUpdate,
final Consumer<ActionListener<Releasable>> operationExecutor
) {
verifyNotClosed();
// This listener is used for the execution of the operation. If the operation requires all the permits for its
// execution and the primary term must be updated first, we can combine the operation execution with the
// primary term update. Since indexShardOperationPermits doesn't guarantee that async submissions are executed
// in the order submitted, combining both operations ensure that the term is updated before the operation is
// executed. It also has the side effect of acquiring all the permits one time instead of two.
final ActionListener<Releasable> operationListener = onPermitAcquired.delegateFailure((delegatedListener, releasable) -> {
if (opPrimaryTerm < getOperationPrimaryTerm()) {
releasable.close();
final String message = String.format(
Locale.ROOT,
"%s operation primary term [%d] is too old (current [%d])",
shardId,
opPrimaryTerm,
getOperationPrimaryTerm()
);
delegatedListener.onFailure(new IllegalStateException(message));
} else {
assert assertReplicationTarget();
try {
updateGlobalCheckpointOnReplica(globalCheckpoint, "operation");
advanceMaxSeqNoOfUpdatesOrDeletes(maxSeqNoOfUpdatesOrDeletes);
} catch (Exception e) {
releasable.close();
delegatedListener.onFailure(e);
return;
}
delegatedListener.onResponse(releasable);
}
});
if (requirePrimaryTermUpdate(opPrimaryTerm, allowCombineOperationWithPrimaryTermUpdate)) {
synchronized (mutex) {
if (requirePrimaryTermUpdate(opPrimaryTerm, allowCombineOperationWithPrimaryTermUpdate)) {
final IndexShardState shardState = state();
// only roll translog and update primary term if shard has made it past recovery
// Having a new primary term here means that the old primary failed and that there is a new primary, which again
// means that the master will fail this shard as all initializing shards are failed when a primary is selected
// We abort early here to prevent an ongoing recovery from the failed primary to mess with the global / local checkpoint
if (shardState != IndexShardState.POST_RECOVERY && shardState != IndexShardState.STARTED) {
throw new IndexShardNotStartedException(shardId, shardState);
}
bumpPrimaryTerm(opPrimaryTerm, () -> {
updateGlobalCheckpointOnReplica(globalCheckpoint, "primary term transition");
final long currentGlobalCheckpoint = getLastKnownGlobalCheckpoint();
final long maxSeqNo = seqNoStats().getMaxSeqNo();
logger.info(
"detected new primary with primary term [{}], global checkpoint [{}], max_seq_no [{}]",
opPrimaryTerm,
currentGlobalCheckpoint,
maxSeqNo
);
if (currentGlobalCheckpoint < maxSeqNo) {
resetEngineToGlobalCheckpoint();
} else {
getEngine().rollTranslogGeneration();
}
}, allowCombineOperationWithPrimaryTermUpdate ? operationListener : null);
if (allowCombineOperationWithPrimaryTermUpdate) {
logger.debug("operation execution has been combined with primary term update");
return;
}
}
}
}
assert opPrimaryTerm <= pendingPrimaryTerm
: "operation primary term [" + opPrimaryTerm + "] should be at most [" + pendingPrimaryTerm + "]";
operationExecutor.accept(operationListener);
}
private boolean requirePrimaryTermUpdate(final long opPrimaryTerm, final boolean allPermits) {
return (opPrimaryTerm > pendingPrimaryTerm) || (allPermits && opPrimaryTerm > getOperationPrimaryTerm());
}
public static final int OPERATIONS_BLOCKED = -1;
/**
* Obtain the active operation count, or {@link IndexShard#OPERATIONS_BLOCKED} if all permits are held (even if there are
* outstanding operations in flight).
*
* @return the active operation count, or {@link IndexShard#OPERATIONS_BLOCKED} when all permits are held.
*/
public int getActiveOperationsCount() {
return indexShardOperationPermits.getActiveOperationsCount();
}
/**
* Syncs the given location with the underlying storage, unless already synced, as part of a write operation.
* <p>
* This method might return immediately without actually fsyncing the location until the sync listener is called. Yet, unless there is
* already another thread fsyncing the transaction log the caller thread will be hijacked to run the fsync for all pending fsync
* operations.
* <p>
* This method allows indexing threads to continue indexing without blocking on fsync calls. We ensure that there is only one thread
* blocking on the sync an all others can continue indexing.
* <p>
* NOTE: if the syncListener throws an exception when it's processed the exception will only be logged. Users should make sure that the
* listener handles all exception cases internally.
*/
public final void syncAfterWrite(Translog.Location location, Consumer<Exception> syncListener) {
// TODO AwaitsFix https://github.com/elastic/elasticsearch/issues/97183
// assert indexShardOperationPermits.getActiveOperationsCount() != 0;
verifyNotClosed();
getEngine().asyncEnsureTranslogSynced(location, syncListener);
}
/**
* This method provides the same behavior as #sync but for persisting the global checkpoint. It will initiate a sync
* if the request global checkpoint is greater than the currently persisted global checkpoint. However, same as #sync it
* will not ensure that the request global checkpoint is available to be synced. It is the caller's duty to only call this
* method with a valid processed global checkpoint that is available to sync.
*/
public void syncGlobalCheckpoint(long globalCheckpoint, Consumer<Exception> syncListener) {
verifyNotClosed();
getEngine().asyncEnsureGlobalCheckpointSynced(globalCheckpoint, syncListener);
}
public void sync() throws IOException {
verifyNotClosed();
getEngine().syncTranslog();
}
/**
* Checks if the underlying storage sync is required.
*/
public boolean isSyncNeeded() {
return getEngine().isTranslogSyncNeeded();
}
/**
* Returns the current translog durability mode
*/
public Translog.Durability getTranslogDurability() {
return indexSettings.getTranslogDurability();
}
// we can not protect with a lock since we "release" on a different thread
private final AtomicBoolean flushOrRollRunning = new AtomicBoolean();
/**
* Schedules a flush or translog generation roll if needed but will not schedule more than one concurrently. The operation will be
* executed asynchronously on the flush thread pool.
*/
public void afterWriteOperation() {
if (shouldPeriodicallyFlush() || shouldRollTranslogGeneration()) {
if (flushOrRollRunning.compareAndSet(false, true)) {
/*
* We have to check again since otherwise there is a race when a thread passes the first check next to another thread which
* performs the operation quickly enough to finish before the current thread could flip the flag. In that situation, we
* have an extra operation.
*
* Additionally, a flush implicitly executes a translog generation roll so if we execute a flush then we do not need to
* check if we should roll the translog generation.
*/
if (shouldPeriodicallyFlush()) {
logger.debug("submitting async flush request");
threadPool.executor(ThreadPool.Names.FLUSH).execute(() -> {
flush(new FlushRequest(), new ActionListener<>() {
@Override
public void onResponse(Boolean flushed) {
periodicFlushMetric.inc();
}
@Override
public void onFailure(Exception e) {
if (state != IndexShardState.CLOSED) {
logger.warn("failed to flush index", e);
}
}
});
flushOrRollRunning.compareAndSet(true, false);
afterWriteOperation();
});
} else if (shouldRollTranslogGeneration()) {
logger.debug("submitting async roll translog generation request");
final AbstractRunnable roll = new AbstractRunnable() {
@Override
public void onFailure(final Exception e) {
if (state != IndexShardState.CLOSED) {
logger.warn("failed to roll translog generation", e);
}
}
@Override
protected void doRun() {
rollTranslogGeneration();
}
@Override
public void onAfter() {
flushOrRollRunning.compareAndSet(true, false);
afterWriteOperation();
}
};
threadPool.executor(ThreadPool.Names.FLUSH).execute(roll);
} else {
flushOrRollRunning.compareAndSet(true, false);
}
}
}
}
/**
* Simple struct encapsulating a shard failure
*
* @see IndexShard#addShardFailureCallback(Consumer)
*/
public record ShardFailure(ShardRouting routing, String reason, @Nullable Exception cause) {}
EngineFactory getEngineFactory() {
return engineFactory;
}
// for tests
ReplicationTracker getReplicationTracker() {
return replicationTracker;
}
/**
* Executes a scheduled refresh if necessary. Completes the listener with true if a refresh was performed otherwise false.
*/
public void scheduledRefresh(ActionListener<Boolean> listener) {
ActionListener.run(listener, l -> {
verifyNotClosed();
boolean listenerNeedsRefresh = refreshListeners.refreshNeeded();
final Engine engine = getEngine();
if (isReadAllowed() && (listenerNeedsRefresh || engine.refreshNeeded())) {
if (listenerNeedsRefresh == false // if we have a listener that is waiting for a refresh we need to force it
&& engine.allowSearchIdleOptimization()
&& isSearchIdle()
&& indexSettings.isExplicitRefresh() == false
&& active.get()) { // it must be active otherwise we might not free up segment memory once the shard became inactive
// lets skip this refresh since we are search idle and
// don't necessarily need to refresh. the next searcher access will register a refreshListener and that will
// cause the next schedule to refresh.
logger.trace("scheduledRefresh: search-idle, skipping refresh");
engine.maybePruneDeletes(); // try to prune the deletes in the engine if we accumulated some
setRefreshPending(engine);
l.onResponse(false);
return;
} else {
logger.trace("scheduledRefresh: refresh with source [schedule]");
engine.maybeRefresh("schedule", l.map(Engine.RefreshResult::refreshed));
return;
}
}
logger.trace("scheduledRefresh: no refresh needed");
engine.maybePruneDeletes(); // try to prune the deletes in the engine if we accumulated some
l.onResponse(false);
});
}
/**
* Returns true if this shards is search idle
*/
public final boolean isSearchIdle() {
return (threadPool.relativeTimeInMillis() - lastSearcherAccess.get()) >= indexSettings.getSearchIdleAfter().getMillis();
}
public long searchIdleTime() {
return threadPool.relativeTimeInMillis() - lastSearcherAccess.get();
}
/**
* Returns the last timestamp the searcher was accessed. This is a relative timestamp in milliseconds.
*/
final long getLastSearcherAccess() {
return lastSearcherAccess.get();
}
/**
* Returns true if this shard has some scheduled refresh that is pending because of search-idle.
*/
public final boolean hasRefreshPending() {
return pendingRefreshLocation.get() != null;
}
private void setRefreshPending(Engine engine) {
final Translog.Location lastWriteLocation = engine.getTranslogLastWriteLocation();
pendingRefreshLocation.updateAndGet(curr -> {
if (curr == null || curr.compareTo(lastWriteLocation) <= 0) {
return lastWriteLocation;
} else {
return curr;
}
});
}
private class RefreshPendingLocationListener implements ReferenceManager.RefreshListener {
Translog.Location lastWriteLocation;
@Override
public void beforeRefresh() {
try {
lastWriteLocation = getEngine().getTranslogLastWriteLocation();
} catch (AlreadyClosedException exc) {
// shard is closed - no location is fine
lastWriteLocation = null;
}
}
@Override
public void afterRefresh(boolean didRefresh) {
if (didRefresh && lastWriteLocation != null) {
pendingRefreshLocation.updateAndGet(pendingLocation -> {
if (pendingLocation == null || pendingLocation.compareTo(lastWriteLocation) <= 0) {
return null;
} else {
return pendingLocation;
}
});
}
}
}
private class RefreshFieldHasValueListener implements ReferenceManager.RefreshListener {
@Override
public void beforeRefresh() {}
@Override
public void afterRefresh(boolean didRefresh) {
if (enableFieldHasValue) {
try (Engine.Searcher hasValueSearcher = getEngine().acquireSearcher("field_has_value")) {
setFieldInfos(FieldInfos.getMergedFieldInfos(hasValueSearcher.getIndexReader()));
} catch (AlreadyClosedException ignore) {
// engine is closed - no updated FieldInfos is fine
}
}
}
}
/**
* Ensures this shard is search active before invoking the provided listener.
* <p>
* This is achieved by registering a refresh listener and invoking the provided listener from the refresh listener once the shard is
* active again and all pending refresh translog location has been refreshed. A refresh may be executed to avoid waiting for
* {@link #scheduledRefresh(ActionListener)} to be invoked. If there is no pending refresh location registered the provided listener
* will be invoked immediately.
*
* @param listener the listener to invoke once the pending refresh location is visible. The listener will be called with
* <code>true</code> if the listener was registered to wait for a refresh.
*/
public final void ensureShardSearchActive(Consumer<Boolean> listener) {
markSearcherAccessed(); // move the shard into non-search idle
final Translog.Location location = pendingRefreshLocation.get();
if (location != null) {
addRefreshListener(location, (result) -> {
pendingRefreshLocation.compareAndSet(location, null);
listener.accept(true);
});
// trigger a refresh to avoid waiting for scheduledRefresh(...) to be invoked from index level refresh scheduler.
// (The if statement should avoid doing an additional refresh if scheduled refresh was invoked between getting
// the current refresh location and adding a refresh listener.)
if (location == pendingRefreshLocation.get()) {
// This method may be called from many different threads including transport_worker threads and
// a refresh can be a costly operation, so we should fork to a refresh thread to be safe:
threadPool.executor(ThreadPool.Names.REFRESH).execute(() -> {
if (location == pendingRefreshLocation.get()) {
getEngine().maybeRefresh("ensure-shard-search-active", new PlainActionFuture<>());
}
});
}
} else {
listener.accept(false);
}
}
/**
* Add a listener for refreshes.
*
* @param location the location to listen for
* @param listener for the refresh. Called with true if registering the listener ran it out of slots and forced a refresh. Called with
* false otherwise.
*/
public void addRefreshListener(Translog.Location location, Consumer<Boolean> listener) {
SubscribableListener<Void> subscribableListener = postRecoveryComplete;
if (postRecoveryComplete != null) {
subscribableListener.addListener(new ActionListener<>() {
@Override
public void onResponse(Void unused) {
if (isReadAllowed()) {
refreshListeners.addOrNotify(location, listener);
} else {
listener.accept(false);
}
}
@Override
public void onFailure(Exception e) {
listener.accept(false);
}
}, EsExecutors.DIRECT_EXECUTOR_SERVICE, threadPool.getThreadContext());
} else {
// we're not yet ready for reads, just ignore refresh cycles
listener.accept(false);
}
}
/**
* Add a listener for refreshes.
*
* @param checkpoint the seqNo checkpoint to listen for
* @param allowUnIssuedSequenceNumber whether to allow waiting for checkpoints larger than the processed local checkpoint
* @param listener for the refresh.
*/
public void addRefreshListener(long checkpoint, boolean allowUnIssuedSequenceNumber, ActionListener<Void> listener) {
SubscribableListener<Void> subscribableListener = postRecoveryComplete;
if (subscribableListener != null) {
subscribableListener.addListener(new ActionListener<>() {
@Override
public void onResponse(Void unused) {
if (isReadAllowed()) {
refreshListeners.addOrNotify(checkpoint, allowUnIssuedSequenceNumber, listener);
} else {
listener.onFailure(new IllegalIndexShardStateException(shardId, state, "Read not allowed on IndexShard"));
}
}
@Override
public void onFailure(Exception e) {
listener.onFailure(e);
}
}, EsExecutors.DIRECT_EXECUTOR_SERVICE, threadPool.getThreadContext());
} else {
listener.onFailure(new IllegalIndexShardStateException(shardId, state, "Read not allowed on IndexShard"));
}
}
private static class RefreshMetricUpdater implements ReferenceManager.RefreshListener {
private final MeanMetric refreshMetric;
private long currentRefreshStartTime;
private Thread callingThread = null;
private RefreshMetricUpdater(MeanMetric refreshMetric) {
this.refreshMetric = refreshMetric;
}
@Override
public void beforeRefresh() {
if (Assertions.ENABLED) {
assert callingThread == null
: "beforeRefresh was called by " + callingThread.getName() + " without a corresponding call to afterRefresh";
callingThread = Thread.currentThread();
}
currentRefreshStartTime = System.nanoTime();
}
@Override
public void afterRefresh(boolean didRefresh) {
if (Assertions.ENABLED) {
assert callingThread != null : "afterRefresh called but not beforeRefresh";
assert callingThread == Thread.currentThread()
: "beforeRefreshed called by a different thread. current ["
+ Thread.currentThread().getName()
+ "], thread that called beforeRefresh ["
+ callingThread.getName()
+ "]";
callingThread = null;
}
refreshMetric.inc(System.nanoTime() - currentRefreshStartTime);
}
}
/**
* Rollback the current engine to the safe commit, then replay local translog up to the global checkpoint.
*/
void resetEngineToGlobalCheckpoint() throws IOException {
assert Thread.holdsLock(mutex) == false : "resetting engine under mutex";
assert getActiveOperationsCount() == OPERATIONS_BLOCKED
: "resetting engine without blocking operations; active operations are [" + getActiveOperationsCount() + ']';
sync(); // persist the global checkpoint to disk
final SeqNoStats seqNoStats = seqNoStats();
final TranslogStats translogStats = translogStats();
// flush to make sure the latest commit, which will be opened by the read-only engine, includes all operations.
flush(new FlushRequest().waitIfOngoing(true));
SetOnce<Engine> newEngineReference = new SetOnce<>();
final long globalCheckpoint = getLastKnownGlobalCheckpoint();
assert globalCheckpoint == getLastSyncedGlobalCheckpoint();
synchronized (engineMutex) {
verifyNotClosed();
// we must create both new read-only engine and new read-write engine under engineMutex to ensure snapshotStoreMetadata,
// acquireXXXCommit and close works.
final Engine readOnlyEngine = new ReadOnlyEngine(
newEngineConfig(replicationTracker),
seqNoStats,
translogStats,
false,
Function.identity(),
true,
false
) {
@Override
public IndexCommitRef acquireLastIndexCommit(boolean flushFirst) {
synchronized (engineMutex) {
if (newEngineReference.get() == null) {
throw new AlreadyClosedException("engine was closed");
}
// ignore flushFirst since we flushed above and we do not want to interfere with ongoing translog replay
return newEngineReference.get().acquireLastIndexCommit(false);
}
}
@Override
public IndexCommitRef acquireSafeIndexCommit() {
synchronized (engineMutex) {
if (newEngineReference.get() == null) {
throw new AlreadyClosedException("engine was closed");
}
return newEngineReference.get().acquireSafeIndexCommit();
}
}
@Override
public void close() throws IOException {
Engine newEngine;
synchronized (engineMutex) {
newEngine = newEngineReference.get();
if (newEngine == currentEngineReference.get()) {
// we successfully installed the new engine so do not close it.
newEngine = null;
}
}
IOUtils.close(super::close, newEngine);
}
};
IOUtils.close(currentEngineReference.getAndSet(readOnlyEngine));
newEngineReference.set(engineFactory.newReadWriteEngine(newEngineConfig(replicationTracker)));
onNewEngine(newEngineReference.get());
}
final Engine.TranslogRecoveryRunner translogRunner = (engine, snapshot) -> runTranslogRecovery(
engine,
snapshot,
Engine.Operation.Origin.LOCAL_RESET,
() -> {
// TODO: add a dedicate recovery stats for the reset translog
}
);
newEngineReference.get().recoverFromTranslog(translogRunner, globalCheckpoint);
newEngineReference.get().refresh("reset_engine");
synchronized (engineMutex) {
verifyNotClosed();
IOUtils.close(currentEngineReference.getAndSet(newEngineReference.get()));
// We set active because we are now writing operations to the engine; this way,
// if we go idle after some time and become inactive, we still give sync'd flush a chance to run.
active.set(true);
}
// time elapses after the engine is created above (pulling the config settings) until we set the engine reference, during
// which settings changes could possibly have happened, so here we forcefully push any config changes to the new engine.
onSettingsChanged();
}
/**
* Returns the maximum sequence number of either update or delete operations have been processed in this shard
* or the sequence number from {@link #advanceMaxSeqNoOfUpdatesOrDeletes(long)}. An index request is considered
* as an update operation if it overwrites the existing documents in Lucene index with the same document id.
* <p>
* The primary captures this value after executes a replication request, then transfers it to a replica before
* executing that replication request on a replica.
*/
public long getMaxSeqNoOfUpdatesOrDeletes() {
return getEngine().getMaxSeqNoOfUpdatesOrDeletes();
}
/**
* A replica calls this method to advance the max_seq_no_of_updates marker of its engine to at least the max_seq_no_of_updates
* value (piggybacked in a replication request) that it receives from its primary before executing that replication request.
* The receiving value is at least as high as the max_seq_no_of_updates on the primary was when any of the operations of that
* replication request were processed on it.
* <p>
* A replica shard also calls this method to bootstrap the max_seq_no_of_updates marker with the value that it received from
* the primary in peer-recovery, before it replays remote translog operations from the primary. The receiving value is at least
* as high as the max_seq_no_of_updates on the primary was when any of these operations were processed on it.
* <p>
* These transfers guarantee that every index/delete operation when executing on a replica engine will observe this marker a value
* which is at least the value of the max_seq_no_of_updates marker on the primary after that operation was executed on the primary.
*
* @see #acquireReplicaOperationPermit(long, long, long, ActionListener, Executor)
* @see RecoveryTarget#indexTranslogOperations(List, int, long, long, RetentionLeases, long, ActionListener)
*/
public void advanceMaxSeqNoOfUpdatesOrDeletes(long seqNo) {
getEngine().advanceMaxSeqNoOfUpdatesOrDeletes(seqNo);
}
/**
* Performs the pre-closing checks on the {@link IndexShard}.
*
* @throws IllegalStateException if the sanity checks failed
*/
public void verifyShardBeforeIndexClosing() throws IllegalStateException {
getEngine().verifyEngineBeforeIndexClosing();
}
RetentionLeaseSyncer getRetentionLeaseSyncer() {
return retentionLeaseSyncer;
}
public long getRelativeTimeInNanos() {
return relativeTimeInNanosSupplier.getAsLong();
}
@Override
public String toString() {
return "IndexShard(shardRouting=" + shardRouting + ")";
}
/**
* @deprecated use {@link #waitForPrimaryTermAndGeneration(long, long, ActionListener)} instead.
*/
@Deprecated
public void waitForSegmentGeneration(long segmentGeneration, ActionListener<Long> listener) {
waitForPrimaryTermAndGeneration(getOperationPrimaryTerm(), segmentGeneration, listener);
}
private void checkAndCallWaitForEngineOrClosedShardListeners() {
if (getEngineOrNull() != null || state == IndexShardState.CLOSED) {
waitForEngineOrClosedShardListeners.onResponse(null);
}
}
/**
* Registers a listener for an event when the shard opens the engine or is the shard is closed
*/
public void waitForEngineOrClosedShard(ActionListener<Void> listener) {
waitForEngineOrClosedShardListeners.addListener(listener);
}
/**
* Registers a listener for an event when the shard advances to the provided primary term and segment generation
*/
public void waitForPrimaryTermAndGeneration(long primaryTerm, long segmentGeneration, ActionListener<Long> listener) {
waitForEngineOrClosedShard(
listener.delegateFailureAndWrap(
(l, ignored) -> getEngine().addPrimaryTermAndGenerationListener(primaryTerm, segmentGeneration, l)
)
);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/shard/IndexShard.java |
681 | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourceRegion;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Represents an HTTP (byte) range for use with the HTTP {@code "Range"} header.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 4.2
* @see <a href="https://tools.ietf.org/html/rfc7233">HTTP/1.1: Range Requests</a>
* @see HttpHeaders#setRange(List)
* @see HttpHeaders#getRange()
*/
public abstract class HttpRange {
/** Maximum ranges per request. */
private static final int MAX_RANGES = 100;
private static final String BYTE_RANGE_PREFIX = "bytes=";
/**
* Turn a {@code Resource} into a {@link ResourceRegion} using the range
* information contained in the current {@code HttpRange}.
* @param resource the {@code Resource} to select the region from
* @return the selected region of the given {@code Resource}
* @since 4.3
*/
public ResourceRegion toResourceRegion(Resource resource) {
// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
Assert.isTrue(resource.getClass() != InputStreamResource.class,
"Cannot convert an InputStreamResource to a ResourceRegion");
long contentLength = getLengthFor(resource);
long start = getRangeStart(contentLength);
long end = getRangeEnd(contentLength);
Assert.isTrue(start < contentLength, () -> "'position' exceeds the resource length " + contentLength);
return new ResourceRegion(resource, start, end - start + 1);
}
/**
* Return the start of the range given the total length of a representation.
* @param length the length of the representation
* @return the start of this range for the representation
*/
public abstract long getRangeStart(long length);
/**
* Return the end of the range (inclusive) given the total length of a representation.
* @param length the length of the representation
* @return the end of the range for the representation
*/
public abstract long getRangeEnd(long length);
/**
* Create an {@code HttpRange} from the given position to the end.
* @param firstBytePos the first byte position
* @return a byte range that ranges from {@code firstPos} till the end
* @see <a href="https://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
*/
public static HttpRange createByteRange(long firstBytePos) {
return new ByteRange(firstBytePos, null);
}
/**
* Create a {@code HttpRange} from the given fist to last position.
* @param firstBytePos the first byte position
* @param lastBytePos the last byte position
* @return a byte range that ranges from {@code firstPos} till {@code lastPos}
* @see <a href="https://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
*/
public static HttpRange createByteRange(long firstBytePos, long lastBytePos) {
return new ByteRange(firstBytePos, lastBytePos);
}
/**
* Create an {@code HttpRange} that ranges over the last given number of bytes.
* @param suffixLength the number of bytes for the range
* @return a byte range that ranges over the last {@code suffixLength} number of bytes
* @see <a href="https://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
*/
public static HttpRange createSuffixRange(long suffixLength) {
return new SuffixByteRange(suffixLength);
}
/**
* Parse the given, comma-separated string into a list of {@code HttpRange} objects.
* <p>This method can be used to parse an {@code Range} header.
* @param ranges the string to parse
* @return the list of ranges
* @throws IllegalArgumentException if the string cannot be parsed
* or if the number of ranges is greater than 100
*/
public static List<HttpRange> parseRanges(@Nullable String ranges) {
if (!StringUtils.hasLength(ranges)) {
return Collections.emptyList();
}
if (!ranges.startsWith(BYTE_RANGE_PREFIX)) {
throw new IllegalArgumentException("Range '" + ranges + "' does not start with 'bytes='");
}
ranges = ranges.substring(BYTE_RANGE_PREFIX.length());
String[] tokens = StringUtils.tokenizeToStringArray(ranges, ",");
if (tokens.length > MAX_RANGES) {
throw new IllegalArgumentException("Too many ranges: " + tokens.length);
}
List<HttpRange> result = new ArrayList<>(tokens.length);
for (String token : tokens) {
result.add(parseRange(token));
}
return result;
}
private static HttpRange parseRange(String range) {
Assert.hasLength(range, "Range String must not be empty");
int dashIdx = range.indexOf('-');
if (dashIdx > 0) {
long firstPos = Long.parseLong(range, 0, dashIdx, 10);
if (dashIdx < range.length() - 1) {
Long lastPos = Long.parseLong(range, dashIdx + 1, range.length(), 10);
return new ByteRange(firstPos, lastPos);
}
else {
return new ByteRange(firstPos, null);
}
}
else if (dashIdx == 0) {
long suffixLength = Long.parseLong(range, 1, range.length(), 10);
return new SuffixByteRange(suffixLength);
}
else {
throw new IllegalArgumentException("Range '" + range + "' does not contain \"-\"");
}
}
/**
* Convert each {@code HttpRange} into a {@code ResourceRegion}, selecting the
* appropriate segment of the given {@code Resource} using HTTP Range information.
* @param ranges the list of ranges
* @param resource the resource to select the regions from
* @return the list of regions for the given resource
* @throws IllegalArgumentException if the sum of all ranges exceeds the resource length
* @since 4.3
*/
public static List<ResourceRegion> toResourceRegions(List<HttpRange> ranges, Resource resource) {
if (CollectionUtils.isEmpty(ranges)) {
return Collections.emptyList();
}
List<ResourceRegion> regions = new ArrayList<>(ranges.size());
for (HttpRange range : ranges) {
regions.add(range.toResourceRegion(resource));
}
if (ranges.size() > 1) {
long length = getLengthFor(resource);
long total = 0;
for (ResourceRegion region : regions) {
total += region.getCount();
}
if (total >= length) {
throw new IllegalArgumentException("The sum of all ranges (" + total +
") should be less than the resource length (" + length + ")");
}
}
return regions;
}
private static long getLengthFor(Resource resource) {
try {
long contentLength = resource.contentLength();
Assert.isTrue(contentLength > 0, "Resource content length should be > 0");
return contentLength;
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to obtain Resource content length", ex);
}
}
/**
* Return a string representation of the given list of {@code HttpRange} objects.
* <p>This method can be used to for an {@code Range} header.
* @param ranges the ranges to create a string of
* @return the string representation
*/
public static String toString(Collection<HttpRange> ranges) {
Assert.notEmpty(ranges, "Ranges Collection must not be empty");
StringJoiner builder = new StringJoiner(", ", BYTE_RANGE_PREFIX, "");
for (HttpRange range : ranges) {
builder.add(range.toString());
}
return builder.toString();
}
/**
* Represents an HTTP/1.1 byte range, with a first and optional last position.
* @see <a href="https://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
* @see HttpRange#createByteRange(long)
* @see HttpRange#createByteRange(long, long)
*/
private static class ByteRange extends HttpRange {
private final long firstPos;
@Nullable
private final Long lastPos;
public ByteRange(long firstPos, @Nullable Long lastPos) {
assertPositions(firstPos, lastPos);
this.firstPos = firstPos;
this.lastPos = lastPos;
}
private void assertPositions(long firstBytePos, @Nullable Long lastBytePos) {
if (firstBytePos < 0) {
throw new IllegalArgumentException("Invalid first byte position: " + firstBytePos);
}
if (lastBytePos != null && lastBytePos < firstBytePos) {
throw new IllegalArgumentException("firstBytePosition=" + firstBytePos +
" should be less then or equal to lastBytePosition=" + lastBytePos);
}
}
@Override
public long getRangeStart(long length) {
return this.firstPos;
}
@Override
public long getRangeEnd(long length) {
if (this.lastPos != null && this.lastPos < length) {
return this.lastPos;
}
else {
return length - 1;
}
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof ByteRange that &&
this.firstPos == that.firstPos &&
ObjectUtils.nullSafeEquals(this.lastPos, that.lastPos)));
}
@Override
public int hashCode() {
return Objects.hash(this.firstPos, this.lastPos);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.firstPos);
builder.append('-');
if (this.lastPos != null) {
builder.append(this.lastPos);
}
return builder.toString();
}
}
/**
* Represents an HTTP/1.1 suffix byte range, with a number of suffix bytes.
* @see <a href="https://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
* @see HttpRange#createSuffixRange(long)
*/
private static class SuffixByteRange extends HttpRange {
private final long suffixLength;
public SuffixByteRange(long suffixLength) {
if (suffixLength < 0) {
throw new IllegalArgumentException("Invalid suffix length: " + suffixLength);
}
this.suffixLength = suffixLength;
}
@Override
public long getRangeStart(long length) {
if (this.suffixLength < length) {
return length - this.suffixLength;
}
else {
return 0;
}
}
@Override
public long getRangeEnd(long length) {
return length - 1;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof SuffixByteRange that &&
this.suffixLength == that.suffixLength));
}
@Override
public int hashCode() {
return Long.hashCode(this.suffixLength);
}
@Override
public String toString() {
return "-" + this.suffixLength;
}
}
}
| spring-projects/spring-framework | spring-web/src/main/java/org/springframework/http/HttpRange.java |
682 | /*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.collectingAndThen;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.TreeMap;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Collectors utilities for {@code common.collect} internals. */
@GwtCompatible
@ElementTypesAreNonnullByDefault
final class CollectCollectors {
private static final Collector<Object, ?, ImmutableList<Object>> TO_IMMUTABLE_LIST =
Collector.of(
ImmutableList::builder,
ImmutableList.Builder::add,
ImmutableList.Builder::combine,
ImmutableList.Builder::build);
private static final Collector<Object, ?, ImmutableSet<Object>> TO_IMMUTABLE_SET =
Collector.of(
ImmutableSet::builder,
ImmutableSet.Builder::add,
ImmutableSet.Builder::combine,
ImmutableSet.Builder::build);
@GwtIncompatible
private static final Collector<Range<Comparable<?>>, ?, ImmutableRangeSet<Comparable<?>>>
TO_IMMUTABLE_RANGE_SET =
Collector.of(
ImmutableRangeSet::builder,
ImmutableRangeSet.Builder::add,
ImmutableRangeSet.Builder::combine,
ImmutableRangeSet.Builder::build);
// Lists
@SuppressWarnings({"rawtypes", "unchecked"})
static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
return (Collector) TO_IMMUTABLE_LIST;
}
// Sets
@SuppressWarnings({"rawtypes", "unchecked"})
static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
return (Collector) TO_IMMUTABLE_SET;
}
static <E> Collector<E, ?, ImmutableSortedSet<E>> toImmutableSortedSet(
Comparator<? super E> comparator) {
checkNotNull(comparator);
return Collector.of(
() -> new ImmutableSortedSet.Builder<E>(comparator),
ImmutableSortedSet.Builder::add,
ImmutableSortedSet.Builder::combine,
ImmutableSortedSet.Builder::build);
}
@SuppressWarnings({"rawtypes", "unchecked"})
static <E extends Enum<E>> Collector<E, ?, ImmutableSet<E>> toImmutableEnumSet() {
return (Collector) EnumSetAccumulator.TO_IMMUTABLE_ENUM_SET;
}
private static <E extends Enum<E>>
Collector<E, EnumSetAccumulator<E>, ImmutableSet<E>> toImmutableEnumSetGeneric() {
return Collector.of(
EnumSetAccumulator::new,
EnumSetAccumulator::add,
EnumSetAccumulator::combine,
EnumSetAccumulator::toImmutableSet,
Collector.Characteristics.UNORDERED);
}
private static final class EnumSetAccumulator<E extends Enum<E>> {
@SuppressWarnings({"rawtypes", "unchecked"})
static final Collector<Enum<?>, ?, ImmutableSet<? extends Enum<?>>> TO_IMMUTABLE_ENUM_SET =
(Collector) toImmutableEnumSetGeneric();
@CheckForNull private EnumSet<E> set;
void add(E e) {
if (set == null) {
set = EnumSet.of(e);
} else {
set.add(e);
}
}
EnumSetAccumulator<E> combine(EnumSetAccumulator<E> other) {
if (this.set == null) {
return other;
} else if (other.set == null) {
return this;
} else {
this.set.addAll(other.set);
return this;
}
}
ImmutableSet<E> toImmutableSet() {
if (set == null) {
return ImmutableSet.of();
}
ImmutableSet<E> ret = ImmutableEnumSet.asImmutable(set);
set = null; // subsequent manual manipulation of the accumulator mustn't affect ret
return ret;
}
}
@GwtIncompatible
@SuppressWarnings({"rawtypes", "unchecked"})
static <E extends Comparable<? super E>>
Collector<Range<E>, ?, ImmutableRangeSet<E>> toImmutableRangeSet() {
return (Collector) TO_IMMUTABLE_RANGE_SET;
}
// Multisets
static <T extends @Nullable Object, E> Collector<T, ?, ImmutableMultiset<E>> toImmutableMultiset(
Function<? super T, ? extends E> elementFunction, ToIntFunction<? super T> countFunction) {
checkNotNull(elementFunction);
checkNotNull(countFunction);
return Collector.of(
LinkedHashMultiset::create,
(multiset, t) ->
multiset.add(checkNotNull(elementFunction.apply(t)), countFunction.applyAsInt(t)),
(multiset1, multiset2) -> {
multiset1.addAll(multiset2);
return multiset1;
},
(Multiset<E> multiset) -> ImmutableMultiset.copyFromEntries(multiset.entrySet()));
}
static <T extends @Nullable Object, E extends @Nullable Object, M extends Multiset<E>>
Collector<T, ?, M> toMultiset(
Function<? super T, E> elementFunction,
ToIntFunction<? super T> countFunction,
Supplier<M> multisetSupplier) {
checkNotNull(elementFunction);
checkNotNull(countFunction);
checkNotNull(multisetSupplier);
return Collector.of(
multisetSupplier,
(ms, t) -> ms.add(elementFunction.apply(t), countFunction.applyAsInt(t)),
(ms1, ms2) -> {
ms1.addAll(ms2);
return ms1;
});
}
// Maps
static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
return Collector.of(
ImmutableMap.Builder<K, V>::new,
(builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
ImmutableMap.Builder::combine,
ImmutableMap.Builder::buildOrThrow);
}
static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(mergeFunction);
return collectingAndThen(
Collectors.toMap(keyFunction, valueFunction, mergeFunction, LinkedHashMap::new),
ImmutableMap::copyOf);
}
static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
Comparator<? super K> comparator,
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(comparator);
checkNotNull(keyFunction);
checkNotNull(valueFunction);
/*
* We will always fail if there are duplicate keys, and the keys are always sorted by
* the Comparator, so the entries can come in an arbitrary order -- so we report UNORDERED.
*/
return Collector.of(
() -> new ImmutableSortedMap.Builder<K, V>(comparator),
(builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
ImmutableSortedMap.Builder::combine,
ImmutableSortedMap.Builder::buildOrThrow,
Collector.Characteristics.UNORDERED);
}
static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
Comparator<? super K> comparator,
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
checkNotNull(comparator);
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(mergeFunction);
return collectingAndThen(
Collectors.toMap(
keyFunction, valueFunction, mergeFunction, () -> new TreeMap<K, V>(comparator)),
ImmutableSortedMap::copyOfSorted);
}
static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toImmutableBiMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
return Collector.of(
ImmutableBiMap.Builder<K, V>::new,
(builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
ImmutableBiMap.Builder::combine,
ImmutableBiMap.Builder::buildOrThrow,
new Collector.Characteristics[0]);
}
static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
return Collector.of(
() ->
new EnumMapAccumulator<K, V>(
(v1, v2) -> {
throw new IllegalArgumentException("Multiple values for key: " + v1 + ", " + v2);
}),
(accum, t) -> {
/*
* We assign these to variables before calling checkNotNull to work around a bug in our
* nullness checker.
*/
K key = keyFunction.apply(t);
V newValue = valueFunction.apply(t);
accum.put(
checkNotNull(key, "Null key for input %s", t),
checkNotNull(newValue, "Null value for input %s", t));
},
EnumMapAccumulator::combine,
EnumMapAccumulator::toImmutableMap,
Collector.Characteristics.UNORDERED);
}
static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(mergeFunction);
// not UNORDERED because we don't know if mergeFunction is commutative
return Collector.of(
() -> new EnumMapAccumulator<K, V>(mergeFunction),
(accum, t) -> {
/*
* We assign these to variables before calling checkNotNull to work around a bug in our
* nullness checker.
*/
K key = keyFunction.apply(t);
V newValue = valueFunction.apply(t);
accum.put(
checkNotNull(key, "Null key for input %s", t),
checkNotNull(newValue, "Null value for input %s", t));
},
EnumMapAccumulator::combine,
EnumMapAccumulator::toImmutableMap);
}
private static class EnumMapAccumulator<K extends Enum<K>, V> {
private final BinaryOperator<V> mergeFunction;
@CheckForNull private EnumMap<K, V> map = null;
EnumMapAccumulator(BinaryOperator<V> mergeFunction) {
this.mergeFunction = mergeFunction;
}
void put(K key, V value) {
if (map == null) {
map = new EnumMap<>(singletonMap(key, value));
} else {
map.merge(key, value, mergeFunction);
}
}
EnumMapAccumulator<K, V> combine(EnumMapAccumulator<K, V> other) {
if (this.map == null) {
return other;
} else if (other.map == null) {
return this;
} else {
other.map.forEach(this::put);
return this;
}
}
ImmutableMap<K, V> toImmutableMap() {
return (map == null) ? ImmutableMap.<K, V>of() : ImmutableEnumMap.asImmutable(map);
}
}
@GwtIncompatible
static <T extends @Nullable Object, K extends Comparable<? super K>, V>
Collector<T, ?, ImmutableRangeMap<K, V>> toImmutableRangeMap(
Function<? super T, Range<K>> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
return Collector.of(
ImmutableRangeMap::<K, V>builder,
(builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
ImmutableRangeMap.Builder::combine,
ImmutableRangeMap.Builder::build);
}
// Multimaps
static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction, "keyFunction");
checkNotNull(valueFunction, "valueFunction");
return Collector.of(
ImmutableListMultimap::<K, V>builder,
(builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)),
ImmutableListMultimap.Builder::combine,
ImmutableListMultimap.Builder::build);
}
static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableListMultimap<K, V>> flatteningToImmutableListMultimap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
checkNotNull(keyFunction);
checkNotNull(valuesFunction);
return collectingAndThen(
flatteningToMultimap(
input -> checkNotNull(keyFunction.apply(input)),
input -> valuesFunction.apply(input).peek(Preconditions::checkNotNull),
MultimapBuilder.linkedHashKeys().arrayListValues()::<K, V>build),
ImmutableListMultimap::copyOf);
}
static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction, "keyFunction");
checkNotNull(valueFunction, "valueFunction");
return Collector.of(
ImmutableSetMultimap::<K, V>builder,
(builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)),
ImmutableSetMultimap.Builder::combine,
ImmutableSetMultimap.Builder::build);
}
static <T extends @Nullable Object, K, V>
Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
checkNotNull(keyFunction);
checkNotNull(valuesFunction);
return collectingAndThen(
flatteningToMultimap(
input -> checkNotNull(keyFunction.apply(input)),
input -> valuesFunction.apply(input).peek(Preconditions::checkNotNull),
MultimapBuilder.linkedHashKeys().linkedHashSetValues()::<K, V>build),
ImmutableSetMultimap::copyOf);
}
static <
T extends @Nullable Object,
K extends @Nullable Object,
V extends @Nullable Object,
M extends Multimap<K, V>>
Collector<T, ?, M> toMultimap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
Supplier<M> multimapSupplier) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(multimapSupplier);
return Collector.of(
multimapSupplier,
(multimap, input) -> multimap.put(keyFunction.apply(input), valueFunction.apply(input)),
(multimap1, multimap2) -> {
multimap1.putAll(multimap2);
return multimap1;
});
}
static <
T extends @Nullable Object,
K extends @Nullable Object,
V extends @Nullable Object,
M extends Multimap<K, V>>
Collector<T, ?, M> flatteningToMultimap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends Stream<? extends V>> valueFunction,
Supplier<M> multimapSupplier) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(multimapSupplier);
return Collector.of(
multimapSupplier,
(multimap, input) -> {
K key = keyFunction.apply(input);
Collection<V> valuesForKey = multimap.get(key);
valueFunction.apply(input).forEachOrdered(valuesForKey::add);
},
(multimap1, multimap2) -> {
multimap1.putAll(multimap2);
return multimap1;
});
}
private CollectCollectors() {}
}
| google/guava | guava/src/com/google/common/collect/CollectCollectors.java |
683 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index;
import java.time.Instant;
/**
* Bounds for the {@code @timestamp} field on this index.
*/
public class TimestampBounds {
/**
* @return an updated instance based on current instance with a new end time.
*/
public static TimestampBounds updateEndTime(TimestampBounds current, Instant newEndTime) {
long newEndTimeMillis = newEndTime.toEpochMilli();
if (current.endTime > newEndTimeMillis) {
throw new IllegalArgumentException(
"index.time_series.end_time must be larger than current value [" + current.endTime + "] but was [" + newEndTime + "]"
);
}
return new TimestampBounds(current.startTime(), newEndTimeMillis);
}
private final long startTime;
private final long endTime;
public TimestampBounds(Instant startTime, Instant endTime) {
this(startTime.toEpochMilli(), endTime.toEpochMilli());
}
private TimestampBounds(long startTime, long endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
/**
* The first valid {@code @timestamp} for the index.
*/
public long startTime() {
return startTime;
}
/**
* The first invalid {@code @timestamp} for the index.
*/
public long endTime() {
return endTime;
}
@Override
public String toString() {
return startTime + "-" + endTime;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/TimestampBounds.java |
685 | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.logging;
import java.io.Serializable;
import java.util.function.Function;
import java.util.logging.LogRecord;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.ExtendedLogger;
import org.apache.logging.log4j.spi.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
/**
* Spring's common JCL adapter behind {@link LogFactory} and {@link LogFactoryService}.
* Detects the presence of Log4j 2.x / SLF4J, falling back to {@code java.util.logging}.
*
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 5.1
*/
final class LogAdapter {
private static final boolean log4jSpiPresent = isPresent("org.apache.logging.log4j.spi.ExtendedLogger");
private static final boolean log4jSlf4jProviderPresent = isPresent("org.apache.logging.slf4j.SLF4JProvider");
private static final boolean slf4jSpiPresent = isPresent("org.slf4j.spi.LocationAwareLogger");
private static final boolean slf4jApiPresent = isPresent("org.slf4j.Logger");
private static final Function<String, Log> createLog;
static {
if (log4jSpiPresent) {
if (log4jSlf4jProviderPresent && slf4jSpiPresent) {
// log4j-to-slf4j bridge -> we'll rather go with the SLF4J SPI;
// however, we still prefer Log4j over the plain SLF4J API since
// the latter does not have location awareness support.
createLog = Slf4jAdapter::createLocationAwareLog;
}
else {
// Use Log4j 2.x directly, including location awareness support
createLog = Log4jAdapter::createLog;
}
}
else if (slf4jSpiPresent) {
// Full SLF4J SPI including location awareness support
createLog = Slf4jAdapter::createLocationAwareLog;
}
else if (slf4jApiPresent) {
// Minimal SLF4J API without location awareness support
createLog = Slf4jAdapter::createLog;
}
else {
// java.util.logging as default
// Defensively use lazy-initializing adapter class here as well since the
// java.logging module is not present by default on JDK 9. We are requiring
// its presence if neither Log4j nor SLF4J is available; however, in the
// case of Log4j or SLF4J, we are trying to prevent early initialization
// of the JavaUtilLog adapter - e.g. by a JVM in debug mode - when eagerly
// trying to parse the bytecode for all the cases of this switch clause.
createLog = JavaUtilAdapter::createLog;
}
}
private LogAdapter() {
}
/**
* Create an actual {@link Log} instance for the selected API.
* @param name the logger name
*/
public static Log createLog(String name) {
return createLog.apply(name);
}
private static boolean isPresent(String className) {
try {
Class.forName(className, false, LogAdapter.class.getClassLoader());
return true;
}
catch (Throwable ex) {
// Typically ClassNotFoundException or NoClassDefFoundError...
return false;
}
}
private static class Log4jAdapter {
public static Log createLog(String name) {
return new Log4jLog(name);
}
}
private static class Slf4jAdapter {
public static Log createLocationAwareLog(String name) {
Logger logger = LoggerFactory.getLogger(name);
return (logger instanceof LocationAwareLogger locationAwareLogger ?
new Slf4jLocationAwareLog(locationAwareLogger) : new Slf4jLog<>(logger));
}
public static Log createLog(String name) {
return new Slf4jLog<>(LoggerFactory.getLogger(name));
}
}
private static class JavaUtilAdapter {
public static Log createLog(String name) {
return new JavaUtilLog(name);
}
}
@SuppressWarnings("serial")
private static class Log4jLog implements Log, Serializable {
private static final String FQCN = Log4jLog.class.getName();
private static final LoggerContext loggerContext =
LogManager.getContext(Log4jLog.class.getClassLoader(), false);
private final String name;
private final transient ExtendedLogger logger;
public Log4jLog(String name) {
this.name = name;
LoggerContext context = loggerContext;
if (context == null) {
// Circular call in early-init scenario -> static field not initialized yet
context = LogManager.getContext(Log4jLog.class.getClassLoader(), false);
}
this.logger = context.getLogger(name);
}
@Override
public boolean isFatalEnabled() {
return this.logger.isEnabled(Level.FATAL);
}
@Override
public boolean isErrorEnabled() {
return this.logger.isEnabled(Level.ERROR);
}
@Override
public boolean isWarnEnabled() {
return this.logger.isEnabled(Level.WARN);
}
@Override
public boolean isInfoEnabled() {
return this.logger.isEnabled(Level.INFO);
}
@Override
public boolean isDebugEnabled() {
return this.logger.isEnabled(Level.DEBUG);
}
@Override
public boolean isTraceEnabled() {
return this.logger.isEnabled(Level.TRACE);
}
@Override
public void fatal(Object message) {
log(Level.FATAL, message, null);
}
@Override
public void fatal(Object message, Throwable exception) {
log(Level.FATAL, message, exception);
}
@Override
public void error(Object message) {
log(Level.ERROR, message, null);
}
@Override
public void error(Object message, Throwable exception) {
log(Level.ERROR, message, exception);
}
@Override
public void warn(Object message) {
log(Level.WARN, message, null);
}
@Override
public void warn(Object message, Throwable exception) {
log(Level.WARN, message, exception);
}
@Override
public void info(Object message) {
log(Level.INFO, message, null);
}
@Override
public void info(Object message, Throwable exception) {
log(Level.INFO, message, exception);
}
@Override
public void debug(Object message) {
log(Level.DEBUG, message, null);
}
@Override
public void debug(Object message, Throwable exception) {
log(Level.DEBUG, message, exception);
}
@Override
public void trace(Object message) {
log(Level.TRACE, message, null);
}
@Override
public void trace(Object message, Throwable exception) {
log(Level.TRACE, message, exception);
}
private void log(Level level, Object message, Throwable exception) {
if (message instanceof String text) {
// Explicitly pass a String argument, avoiding Log4j's argument expansion
// for message objects in case of "{}" sequences (SPR-16226)
if (exception != null) {
this.logger.logIfEnabled(FQCN, level, null, text, exception);
}
else {
this.logger.logIfEnabled(FQCN, level, null, text);
}
}
else {
this.logger.logIfEnabled(FQCN, level, null, message, exception);
}
}
protected Object readResolve() {
return new Log4jLog(this.name);
}
}
@SuppressWarnings("serial")
private static class Slf4jLog<T extends Logger> implements Log, Serializable {
protected final String name;
protected final transient T logger;
public Slf4jLog(T logger) {
this.name = logger.getName();
this.logger = logger;
}
@Override
public boolean isFatalEnabled() {
return isErrorEnabled();
}
@Override
public boolean isErrorEnabled() {
return this.logger.isErrorEnabled();
}
@Override
public boolean isWarnEnabled() {
return this.logger.isWarnEnabled();
}
@Override
public boolean isInfoEnabled() {
return this.logger.isInfoEnabled();
}
@Override
public boolean isDebugEnabled() {
return this.logger.isDebugEnabled();
}
@Override
public boolean isTraceEnabled() {
return this.logger.isTraceEnabled();
}
@Override
public void fatal(Object message) {
error(message);
}
@Override
public void fatal(Object message, Throwable exception) {
error(message, exception);
}
@Override
public void error(Object message) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.error(String.valueOf(message));
}
}
@Override
public void error(Object message, Throwable exception) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.error(String.valueOf(message), exception);
}
}
@Override
public void warn(Object message) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.warn(String.valueOf(message));
}
}
@Override
public void warn(Object message, Throwable exception) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.warn(String.valueOf(message), exception);
}
}
@Override
public void info(Object message) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.info(String.valueOf(message));
}
}
@Override
public void info(Object message, Throwable exception) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.info(String.valueOf(message), exception);
}
}
@Override
public void debug(Object message) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.debug(String.valueOf(message));
}
}
@Override
public void debug(Object message, Throwable exception) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.debug(String.valueOf(message), exception);
}
}
@Override
public void trace(Object message) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.trace(String.valueOf(message));
}
}
@Override
public void trace(Object message, Throwable exception) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.trace(String.valueOf(message), exception);
}
}
protected Object readResolve() {
return Slf4jAdapter.createLog(this.name);
}
}
@SuppressWarnings("serial")
private static class Slf4jLocationAwareLog extends Slf4jLog<LocationAwareLogger> implements Serializable {
private static final String FQCN = Slf4jLocationAwareLog.class.getName();
public Slf4jLocationAwareLog(LocationAwareLogger logger) {
super(logger);
}
@Override
public void fatal(Object message) {
error(message);
}
@Override
public void fatal(Object message, Throwable exception) {
error(message, exception);
}
@Override
public void error(Object message) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
}
}
@Override
public void error(Object message, Throwable exception) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, exception);
}
}
@Override
public void warn(Object message) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null);
}
}
@Override
public void warn(Object message, Throwable exception) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, exception);
}
}
@Override
public void info(Object message) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null);
}
}
@Override
public void info(Object message, Throwable exception) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, exception);
}
}
@Override
public void debug(Object message) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null);
}
}
@Override
public void debug(Object message, Throwable exception) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, exception);
}
}
@Override
public void trace(Object message) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null);
}
}
@Override
public void trace(Object message, Throwable exception) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, exception);
}
}
@Override
protected Object readResolve() {
return Slf4jAdapter.createLocationAwareLog(this.name);
}
}
@SuppressWarnings("serial")
private static class JavaUtilLog implements Log, Serializable {
private final String name;
private final transient java.util.logging.Logger logger;
public JavaUtilLog(String name) {
this.name = name;
this.logger = java.util.logging.Logger.getLogger(name);
}
@Override
public boolean isFatalEnabled() {
return isErrorEnabled();
}
@Override
public boolean isErrorEnabled() {
return this.logger.isLoggable(java.util.logging.Level.SEVERE);
}
@Override
public boolean isWarnEnabled() {
return this.logger.isLoggable(java.util.logging.Level.WARNING);
}
@Override
public boolean isInfoEnabled() {
return this.logger.isLoggable(java.util.logging.Level.INFO);
}
@Override
public boolean isDebugEnabled() {
return this.logger.isLoggable(java.util.logging.Level.FINE);
}
@Override
public boolean isTraceEnabled() {
return this.logger.isLoggable(java.util.logging.Level.FINEST);
}
@Override
public void fatal(Object message) {
error(message);
}
@Override
public void fatal(Object message, Throwable exception) {
error(message, exception);
}
@Override
public void error(Object message) {
log(java.util.logging.Level.SEVERE, message, null);
}
@Override
public void error(Object message, Throwable exception) {
log(java.util.logging.Level.SEVERE, message, exception);
}
@Override
public void warn(Object message) {
log(java.util.logging.Level.WARNING, message, null);
}
@Override
public void warn(Object message, Throwable exception) {
log(java.util.logging.Level.WARNING, message, exception);
}
@Override
public void info(Object message) {
log(java.util.logging.Level.INFO, message, null);
}
@Override
public void info(Object message, Throwable exception) {
log(java.util.logging.Level.INFO, message, exception);
}
@Override
public void debug(Object message) {
log(java.util.logging.Level.FINE, message, null);
}
@Override
public void debug(Object message, Throwable exception) {
log(java.util.logging.Level.FINE, message, exception);
}
@Override
public void trace(Object message) {
log(java.util.logging.Level.FINEST, message, null);
}
@Override
public void trace(Object message, Throwable exception) {
log(java.util.logging.Level.FINEST, message, exception);
}
private void log(java.util.logging.Level level, Object message, Throwable exception) {
if (this.logger.isLoggable(level)) {
LogRecord rec;
if (message instanceof LogRecord logRecord) {
rec = logRecord;
}
else {
rec = new LocationResolvingLogRecord(level, String.valueOf(message));
rec.setLoggerName(this.name);
rec.setResourceBundleName(this.logger.getResourceBundleName());
rec.setResourceBundle(this.logger.getResourceBundle());
rec.setThrown(exception);
}
logger.log(rec);
}
}
protected Object readResolve() {
return new JavaUtilLog(this.name);
}
}
@SuppressWarnings("serial")
private static class LocationResolvingLogRecord extends LogRecord {
private static final String FQCN = JavaUtilLog.class.getName();
private volatile boolean resolved;
public LocationResolvingLogRecord(java.util.logging.Level level, String msg) {
super(level, msg);
}
@Override
public String getSourceClassName() {
if (!this.resolved) {
resolve();
}
return super.getSourceClassName();
}
@Override
public void setSourceClassName(String sourceClassName) {
super.setSourceClassName(sourceClassName);
this.resolved = true;
}
@Override
public String getSourceMethodName() {
if (!this.resolved) {
resolve();
}
return super.getSourceMethodName();
}
@Override
public void setSourceMethodName(String sourceMethodName) {
super.setSourceMethodName(sourceMethodName);
this.resolved = true;
}
private void resolve() {
StackTraceElement[] stack = new Throwable().getStackTrace();
String sourceClassName = null;
String sourceMethodName = null;
boolean found = false;
for (StackTraceElement element : stack) {
String className = element.getClassName();
if (FQCN.equals(className)) {
found = true;
}
else if (found) {
sourceClassName = className;
sourceMethodName = element.getMethodName();
break;
}
}
setSourceClassName(sourceClassName);
setSourceMethodName(sourceMethodName);
}
protected Object writeReplace() {
LogRecord serialized = new LogRecord(getLevel(), getMessage());
serialized.setLoggerName(getLoggerName());
serialized.setResourceBundle(getResourceBundle());
serialized.setResourceBundleName(getResourceBundleName());
serialized.setSourceClassName(getSourceClassName());
serialized.setSourceMethodName(getSourceMethodName());
serialized.setSequenceNumber(getSequenceNumber());
serialized.setParameters(getParameters());
serialized.setLongThreadID(getLongThreadID());
serialized.setInstant(getInstant());
serialized.setThrown(getThrown());
return serialized;
}
}
}
| spring-projects/spring-framework | spring-jcl/src/main/java/org/apache/commons/logging/LogAdapter.java |
686 | /*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.ImmutableMapEntry.createEntryArray;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableMapEntry;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.IdentityHashMap;
import java.util.function.BiConsumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of {@link ImmutableMap} used for 0 entries and for 2+ entries. Additional
* implementations exist for particular cases, like {@link ImmutableTable} views and hash flooding.
* (This doc discusses {@link ImmutableMap} subclasses only for the JRE flavor; the Android flavor
* differs.)
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Gregory Kick
*/
@GwtCompatible(serializable = true, emulated = true)
@ElementTypesAreNonnullByDefault
final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
@SuppressWarnings("unchecked")
static final ImmutableMap<Object, Object> EMPTY =
new RegularImmutableMap<>((Entry<Object, Object>[]) ImmutableMap.EMPTY_ENTRY_ARRAY, null, 0);
/**
* Closed addressing tends to perform well even with high load factors. Being conservative here
* ensures that the table is still likely to be relatively sparse (hence it misses fast) while
* saving space.
*/
@VisibleForTesting static final double MAX_LOAD_FACTOR = 1.2;
/**
* Maximum allowed false positive probability of detecting a hash flooding attack given random
* input.
*/
@VisibleForTesting static final double HASH_FLOODING_FPP = 0.001;
/**
* Maximum allowed length of a hash table bucket before falling back to a j.u.HashMap based
* implementation. Experimentally determined.
*/
@VisibleForTesting static final int MAX_HASH_BUCKET_LENGTH = 8;
// entries in insertion order
@VisibleForTesting final transient Entry<K, V>[] entries;
// array of linked lists of entries
@CheckForNull private final transient @Nullable ImmutableMapEntry<K, V>[] table;
// 'and' with an int to get a table index
private final transient int mask;
static <K, V> ImmutableMap<K, V> fromEntries(Entry<K, V>... entries) {
return fromEntryArray(entries.length, entries, /* throwIfDuplicateKeys= */ true);
}
/**
* Creates an ImmutableMap from the first n entries in entryArray. This implementation may replace
* the entries in entryArray with its own entry objects (though they will have the same key/value
* contents), and may take ownership of entryArray.
*/
static <K, V> ImmutableMap<K, V> fromEntryArray(
int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) {
checkPositionIndex(n, entryArray.length);
if (n == 0) {
@SuppressWarnings("unchecked") // it has no entries so the type variables don't matter
ImmutableMap<K, V> empty = (ImmutableMap<K, V>) EMPTY;
return empty;
}
try {
return fromEntryArrayCheckingBucketOverflow(n, entryArray, throwIfDuplicateKeys);
} catch (BucketOverflowException e) {
// probable hash flooding attack, fall back to j.u.HM based implementation and use its
// implementation of hash flooding protection
return JdkBackedImmutableMap.create(n, entryArray, throwIfDuplicateKeys);
}
}
private static <K, V> ImmutableMap<K, V> fromEntryArrayCheckingBucketOverflow(
int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys)
throws BucketOverflowException {
/*
* The cast is safe: n==entryArray.length means that we have filled the whole array with Entry
* instances, in which case it is safe to cast it from an array of nullable entries to an array
* of non-null entries.
*/
@SuppressWarnings("nullness")
Entry<K, V>[] entries =
(n == entryArray.length) ? (Entry<K, V>[]) entryArray : createEntryArray(n);
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
@Nullable ImmutableMapEntry<K, V>[] table = createEntryArray(tableSize);
int mask = tableSize - 1;
// If duplicates are allowed, this IdentityHashMap will record the final Entry for each
// duplicated key. We will use this final Entry to overwrite earlier slots in the entries array
// that have the same key. Then a second pass will remove all but the first of the slots that
// have this Entry. The value in the map becomes false when this first entry has been copied, so
// we know not to copy the remaining ones.
IdentityHashMap<Entry<K, V>, Boolean> duplicates = null;
int dupCount = 0;
for (int entryIndex = n - 1; entryIndex >= 0; entryIndex--) {
// requireNonNull is safe because the first `n` elements have been filled in.
Entry<K, V> entry = requireNonNull(entryArray[entryIndex]);
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int tableIndex = Hashing.smear(key.hashCode()) & mask;
ImmutableMapEntry<K, V> keyBucketHead = table[tableIndex];
ImmutableMapEntry<K, V> effectiveEntry =
checkNoConflictInKeyBucket(key, value, keyBucketHead, throwIfDuplicateKeys);
if (effectiveEntry == null) {
// prepend, not append, so the entries can be immutable
effectiveEntry =
(keyBucketHead == null)
? makeImmutable(entry, key, value)
: new NonTerminalImmutableMapEntry<K, V>(key, value, keyBucketHead);
table[tableIndex] = effectiveEntry;
} else {
// We already saw this key, and the first value we saw (going backwards) is the one we are
// keeping. So we won't touch table[], but we do still want to add the existing entry that
// we found to entries[] so that we will see this key in the right place when iterating.
if (duplicates == null) {
duplicates = new IdentityHashMap<>();
}
duplicates.put(effectiveEntry, true);
dupCount++;
// Make sure we are not overwriting the original entries array, in case we later do
// buildOrThrow(). We would want an exception to include two values for the duplicate key.
if (entries == entryArray) {
// Temporary variable is necessary to defeat bad smartcast (entries adopting the type of
// entryArray) in the Kotlin translation.
Entry<K, V>[] originalEntries = entries;
entries = originalEntries.clone();
}
}
entries[entryIndex] = effectiveEntry;
}
if (duplicates != null) {
// Explicit type parameters needed here to avoid a problem with nullness inference.
entries = RegularImmutableMap.<K, V>removeDuplicates(entries, n, n - dupCount, duplicates);
int newTableSize = Hashing.closedTableSize(entries.length, MAX_LOAD_FACTOR);
if (newTableSize != tableSize) {
return fromEntryArrayCheckingBucketOverflow(
entries.length, entries, /* throwIfDuplicateKeys= */ true);
}
}
return new RegularImmutableMap<>(entries, table, mask);
}
/**
* Constructs a new entry array where each duplicated key from the original appears only once, at
* its first position but with its final value. The {@code duplicates} map is modified.
*
* @param entries the original array of entries including duplicates
* @param n the number of valid entries in {@code entries}
* @param newN the expected number of entries once duplicates are removed
* @param duplicates a map of canonical {@link Entry} objects for each duplicate key. This map
* will be updated by the method, setting each value to false as soon as the {@link Entry} has
* been included in the new entry array.
* @return an array of {@code newN} entries where no key appears more than once.
*/
static <K, V> Entry<K, V>[] removeDuplicates(
Entry<K, V>[] entries, int n, int newN, IdentityHashMap<Entry<K, V>, Boolean> duplicates) {
Entry<K, V>[] newEntries = createEntryArray(newN);
for (int in = 0, out = 0; in < n; in++) {
Entry<K, V> entry = entries[in];
Boolean status = duplicates.get(entry);
// null=>not dup'd; true=>dup'd, first; false=>dup'd, not first
if (status != null) {
if (status) {
duplicates.put(entry, false);
} else {
continue; // delete this entry; we already copied an earlier one for the same key
}
}
newEntries[out++] = entry;
}
return newEntries;
}
/** Makes an entry usable internally by a new ImmutableMap without rereading its contents. */
static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry, K key, V value) {
boolean reusable =
entry instanceof ImmutableMapEntry && ((ImmutableMapEntry<K, V>) entry).isReusable();
return reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value);
}
/** Makes an entry usable internally by a new ImmutableMap. */
static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry) {
return makeImmutable(entry, entry.getKey(), entry.getValue());
}
private RegularImmutableMap(
Entry<K, V>[] entries, @CheckForNull @Nullable ImmutableMapEntry<K, V>[] table, int mask) {
this.entries = entries;
this.table = table;
this.mask = mask;
}
/**
* Checks if the given key already appears in the hash chain starting at {@code keyBucketHead}. If
* it does not, then null is returned. If it does, then if {@code throwIfDuplicateKeys} is true an
* {@code IllegalArgumentException} is thrown, and otherwise the existing {@link Entry} is
* returned.
*
* @throws IllegalArgumentException if another entry in the bucket has the same key and {@code
* throwIfDuplicateKeys} is true
* @throws BucketOverflowException if this bucket has too many entries, which may indicate a hash
* flooding attack
*/
@CanIgnoreReturnValue
@CheckForNull
static <K, V> ImmutableMapEntry<K, V> checkNoConflictInKeyBucket(
Object key,
Object newValue,
@CheckForNull ImmutableMapEntry<K, V> keyBucketHead,
boolean throwIfDuplicateKeys)
throws BucketOverflowException {
int bucketSize = 0;
for (; keyBucketHead != null; keyBucketHead = keyBucketHead.getNextInKeyBucket()) {
if (keyBucketHead.getKey().equals(key)) {
if (throwIfDuplicateKeys) {
checkNoConflict(/* safe= */ false, "key", keyBucketHead, key + "=" + newValue);
} else {
return keyBucketHead;
}
}
if (++bucketSize > MAX_HASH_BUCKET_LENGTH) {
throw new BucketOverflowException();
}
}
return null;
}
static class BucketOverflowException extends Exception {}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return get(key, table, mask);
}
@CheckForNull
static <V> V get(
@CheckForNull Object key,
@CheckForNull @Nullable ImmutableMapEntry<?, V>[] keyTable,
int mask) {
if (key == null || keyTable == null) {
return null;
}
int index = Hashing.smear(key.hashCode()) & mask;
for (ImmutableMapEntry<?, V> entry = keyTable[index];
entry != null;
entry = entry.getNextInKeyBucket()) {
Object candidateKey = entry.getKey();
/*
* Assume that equals uses the == optimization when appropriate, and that
* it would check hash codes as an optimization when appropriate. If we
* did these things, it would just make things worse for the most
* performance-conscious users.
*/
if (key.equals(candidateKey)) {
return entry.getValue();
}
}
return null;
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
for (Entry<K, V> entry : entries) {
action.accept(entry.getKey(), entry.getValue());
}
}
@Override
public int size() {
return entries.length;
}
@Override
boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet.RegularEntrySet<>(this, entries);
}
@Override
ImmutableSet<K> createKeySet() {
return new KeySet<>(this);
}
@GwtCompatible(emulated = true)
private static final class KeySet<K> extends IndexedImmutableSet<K> {
private final RegularImmutableMap<K, ?> map;
KeySet(RegularImmutableMap<K, ?> map) {
this.map = map;
}
@Override
K get(int index) {
return map.entries[index].getKey();
}
@Override
public boolean contains(@CheckForNull Object object) {
return map.containsKey(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
public int size() {
return map.size();
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
@J2ktIncompatible
@SuppressWarnings("unused")
private static class SerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
SerializedForm(ImmutableMap<K, ?> map) {
this.map = map;
}
Object readResolve() {
return map.keySet();
}
@J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
}
@Override
ImmutableCollection<V> createValues() {
return new Values<>(this);
}
@GwtCompatible(emulated = true)
private static final class Values<K, V> extends ImmutableList<V> {
final RegularImmutableMap<K, V> map;
Values(RegularImmutableMap<K, V> map) {
this.map = map;
}
@Override
public V get(int index) {
return map.entries[index].getValue();
}
@Override
public int size() {
return map.size();
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
@J2ktIncompatible
@SuppressWarnings("unused")
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
SerializedForm(ImmutableMap<?, V> map) {
this.map = map;
}
Object readResolve() {
return map.values();
}
@J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
@J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
| google/guava | guava/src/com/google/common/collect/RegularImmutableMap.java |
687 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.bootstrap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.VectorUtil;
import org.elasticsearch.Build;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ReleaseVersions;
import org.elasticsearch.action.support.SubscribableListener;
import org.elasticsearch.common.ReferenceDocs;
import org.elasticsearch.common.filesystem.FileSystemNatives;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.logging.LogConfigurator;
import org.elasticsearch.common.network.IfConfig;
import org.elasticsearch.common.settings.SecureSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.util.concurrent.RunOnce;
import org.elasticsearch.core.AbstractRefCounted;
import org.elasticsearch.core.IOUtils;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexVersion;
import org.elasticsearch.jdk.JarHell;
import org.elasticsearch.monitor.jvm.HotThreads;
import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.monitor.os.OsProbe;
import org.elasticsearch.monitor.process.ProcessProbe;
import org.elasticsearch.nativeaccess.NativeAccess;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeValidationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.Permission;
import java.security.Security;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.bootstrap.BootstrapSettings.SECURITY_FILTER_BAD_DEFAULTS_SETTING;
/**
* This class starts elasticsearch.
*/
class Elasticsearch {
/**
* Main entry point for starting elasticsearch.
*/
public static void main(final String[] args) {
Bootstrap bootstrap = initPhase1();
assert bootstrap != null;
try {
initPhase2(bootstrap);
initPhase3(bootstrap);
} catch (NodeValidationException e) {
bootstrap.exitWithNodeValidationException(e);
} catch (Throwable t) {
bootstrap.exitWithUnknownException(t);
}
}
@SuppressForbidden(reason = "grab stderr for communication with server-cli")
private static PrintStream getStderr() {
return System.err;
}
// TODO: remove this, just for debugging
@SuppressForbidden(reason = "grab stdout for communication with server-cli")
private static PrintStream getStdout() {
return System.out;
}
/**
* First phase of process initialization.
*
* <p> Phase 1 consists of some static initialization, reading args from the CLI process, and
* finally initializing logging. As little as possible should be done in this phase because
* initializing logging is the last step.
*/
private static Bootstrap initPhase1() {
final PrintStream out = getStdout();
final PrintStream err = getStderr();
final ServerArgs args;
try {
initSecurityProperties();
/*
* We want the JVM to think there is a security manager installed so that if internal policy decisions that would be based on
* the presence of a security manager or lack thereof act as if there is a security manager present (e.g., DNS cache policy).
* This forces such policies to take effect immediately.
*/
org.elasticsearch.bootstrap.Security.setSecurityManager(new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
// grant all permissions so that we can later set the security manager to the one that we want
}
});
LogConfigurator.registerErrorListener();
BootstrapInfo.init();
// note that reading server args does *not* close System.in, as it will be read from later for shutdown notification
var in = new InputStreamStreamInput(System.in);
args = new ServerArgs(in);
// mostly just paths are used in phase 1, so secure settings are not needed
Environment nodeEnv = new Environment(args.nodeSettings(), args.configDir());
BootstrapInfo.setConsole(ConsoleLoader.loadConsole(nodeEnv));
// DO NOT MOVE THIS
// Logging must remain the last step of phase 1. Anything init steps needing logging should be in phase 2.
LogConfigurator.setNodeName(Node.NODE_NAME_SETTING.get(args.nodeSettings()));
LogConfigurator.configure(nodeEnv, args.quiet() == false);
} catch (Throwable t) {
// any exception this early needs to be fully printed and fail startup
t.printStackTrace(err);
err.flush();
Bootstrap.exit(1); // mimic JDK exit code on exception
return null; // unreachable, to satisfy compiler
}
return new Bootstrap(out, err, args);
}
/**
* Second phase of process initialization.
*
* <p> Phase 2 consists of everything that must occur up to and including security manager initialization.
*/
private static void initPhase2(Bootstrap bootstrap) throws IOException {
final ServerArgs args = bootstrap.args();
final SecureSettings secrets = args.secrets();
bootstrap.setSecureSettings(secrets);
Environment nodeEnv = createEnvironment(args.configDir(), args.nodeSettings(), secrets);
bootstrap.setEnvironment(nodeEnv);
initPidFile(args.pidFile());
// install the default uncaught exception handler; must be done before security is
// initialized as we do not want to grant the runtime permission
// setDefaultUncaughtExceptionHandler
Thread.setDefaultUncaughtExceptionHandler(new ElasticsearchUncaughtExceptionHandler());
bootstrap.spawner().spawnNativeControllers(nodeEnv);
nodeEnv.validateNativesConfig(); // temporary directories are important for JNA
initializeNatives(
nodeEnv.tmpFile(),
BootstrapSettings.MEMORY_LOCK_SETTING.get(args.nodeSettings()),
true, // always install system call filters, not user-configurable since 8.0.0
BootstrapSettings.CTRLHANDLER_SETTING.get(args.nodeSettings())
);
// initialize probes before the security manager is installed
initializeProbes();
Runtime.getRuntime().addShutdownHook(new Thread(Elasticsearch::shutdown, "elasticsearch-shutdown"));
// look for jar hell
final Logger logger = LogManager.getLogger(JarHell.class);
JarHell.checkJarHell(logger::debug);
// Log ifconfig output before SecurityManager is installed
IfConfig.logIfNecessary();
ensureInitialized(
// ReleaseVersions does nontrivial static initialization which should always succeed but load it now (before SM) to be sure
ReleaseVersions.class,
// ReferenceDocs class does nontrivial static initialization which should always succeed but load it now (before SM) to be sure
ReferenceDocs.class,
// The following classes use MethodHandles.lookup during initialization, load them now (before SM) to be sure they succeed
AbstractRefCounted.class,
SubscribableListener.class,
RunOnce.class,
// We eagerly initialize to work around log4j permissions & JDK-8309727
VectorUtil.class
);
// install SM after natives, shutdown hooks, etc.
org.elasticsearch.bootstrap.Security.configure(
nodeEnv,
SECURITY_FILTER_BAD_DEFAULTS_SETTING.get(args.nodeSettings()),
args.pidFile()
);
}
private static void ensureInitialized(Class<?>... classes) {
for (final var clazz : classes) {
try {
MethodHandles.publicLookup().ensureInitialized(clazz);
} catch (IllegalAccessException unexpected) {
throw new AssertionError(unexpected);
}
}
}
/**
* Third phase of initialization.
*
* <p> Phase 3 consists of everything after security manager is initialized. Up until now, the system has been single
* threaded. This phase can spawn threads, write to the log, and is subject ot the security manager policy.
*
* <p> At the end of phase 3 the system is ready to accept requests and the main thread is ready to terminate. This means:
* <ul>
* <li>The node components have been constructed and started</li>
* <li>Cleanup has been done (eg secure settings are closed)</li>
* <li>At least one thread other than the main thread is alive and will stay alive after the main thread terminates</li>
* <li>The parent CLI process has been notified the system is ready</li>
* </ul>
*
* @param bootstrap the bootstrap state
* @throws IOException if a problem with filesystem or network occurs
* @throws NodeValidationException if the node cannot start due to a node configuration issue
*/
private static void initPhase3(Bootstrap bootstrap) throws IOException, NodeValidationException {
checkLucene();
Node node = new Node(bootstrap.environment()) {
@Override
protected void validateNodeBeforeAcceptingRequests(
final BootstrapContext context,
final BoundTransportAddress boundTransportAddress,
List<BootstrapCheck> checks
) throws NodeValidationException {
BootstrapChecks.check(context, boundTransportAddress, checks);
}
};
INSTANCE = new Elasticsearch(bootstrap.spawner(), node);
// any secure settings must be read during node construction
IOUtils.close(bootstrap.secureSettings());
INSTANCE.start();
if (bootstrap.args().daemonize()) {
LogConfigurator.removeConsoleAppender();
}
// DO NOT MOVE THIS
// Signaling readiness to accept requests must remain the last step of initialization. Note that it is extremely
// important closing the err stream to the CLI when daemonizing is the last statement since that is the only
// way to pass errors to the CLI
bootstrap.sendCliMarker(BootstrapInfo.SERVER_READY_MARKER);
if (bootstrap.args().daemonize()) {
bootstrap.closeStreams();
} else {
startCliMonitorThread(System.in);
}
}
/**
* Initialize native resources.
*
* @param tmpFile the temp directory
* @param mlockAll whether or not to lock memory
* @param systemCallFilter whether or not to install system call filters
* @param ctrlHandler whether or not to install the ctrl-c handler (applies to Windows only)
*/
static void initializeNatives(final Path tmpFile, final boolean mlockAll, final boolean systemCallFilter, final boolean ctrlHandler) {
final Logger logger = LogManager.getLogger(Elasticsearch.class);
// check if the user is running as root, and bail
if (NativeAccess.instance().definitelyRunningAsRoot()) {
throw new RuntimeException("can not run elasticsearch as root");
}
if (systemCallFilter) {
/*
* Try to install system call filters; if they fail to install; a bootstrap check will fail startup in production mode.
*
* TODO: should we fail hard here if system call filters fail to install, or remain lenient in non-production environments?
*/
Natives.tryInstallSystemCallFilter(tmpFile);
}
// mlockall if requested
if (mlockAll) {
if (Constants.WINDOWS) {
Natives.tryVirtualLock();
} else {
Natives.tryMlockall();
}
}
// listener for windows close event
if (ctrlHandler) {
Natives.addConsoleCtrlHandler(new ConsoleCtrlHandler() {
@Override
public boolean handle(int code) {
if (CTRL_CLOSE_EVENT == code) {
logger.info("running graceful exit on windows");
shutdown();
return true;
}
return false;
}
});
}
// force remainder of JNA to be loaded (if available).
try {
JNAKernel32Library.getInstance();
} catch (Exception ignored) {
// we've already logged this.
}
Natives.trySetMaxNumberOfThreads();
Natives.trySetMaxSizeVirtualMemory();
Natives.trySetMaxFileSize();
// init lucene random seed. it will use /dev/urandom where available:
StringHelper.randomId();
// init filesystem natives
FileSystemNatives.init();
}
static void initializeProbes() {
// Force probes to be loaded
ProcessProbe.getInstance();
OsProbe.getInstance();
JvmInfo.jvmInfo();
HotThreads.initializeRuntimeMonitoring();
}
static void checkLucene() {
if (IndexVersion.current().luceneVersion().equals(org.apache.lucene.util.Version.LATEST) == false) {
throw new AssertionError(
"Lucene version mismatch this version of Elasticsearch requires lucene version ["
+ IndexVersion.current().luceneVersion()
+ "] but the current lucene version is ["
+ org.apache.lucene.util.Version.LATEST
+ "]"
);
}
}
/**
* Starts a thread that monitors stdin for a shutdown signal.
*
* If the shutdown signal is received, Elasticsearch exits with status code 0.
* If the pipe is broken, Elasticsearch exits with status code 1.
*
* @param stdin Standard input for this process
*/
private static void startCliMonitorThread(InputStream stdin) {
new Thread(() -> {
int msg = -1;
try {
msg = stdin.read();
} catch (IOException e) {
// ignore, whether we cleanly got end of stream (-1) or an error, we will shut down below
} finally {
if (msg == BootstrapInfo.SERVER_SHUTDOWN_MARKER) {
Bootstrap.exit(0);
} else {
// parent process died or there was an error reading from it
Bootstrap.exit(1);
}
}
}, "elasticsearch-cli-monitor-thread").start();
}
/**
* Writes the current process id into the given pidfile, if not null. The pidfile is cleaned up on system exit.
*
* @param pidFile A path to a file, or null of no pidfile should be written
*/
private static void initPidFile(Path pidFile) throws IOException {
if (pidFile == null) {
return;
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
Files.deleteIfExists(pidFile);
} catch (IOException e) {
throw new ElasticsearchException("Failed to delete pid file " + pidFile, e);
}
}, "elasticsearch[pidfile-cleanup]"));
// It has to be an absolute path, otherwise pidFile.getParent() will return null
assert pidFile.isAbsolute();
if (Files.exists(pidFile.getParent()) == false) {
Files.createDirectories(pidFile.getParent());
}
Files.writeString(pidFile, Long.toString(ProcessHandle.current().pid()));
}
private static void initSecurityProperties() {
for (final String property : new String[] { "networkaddress.cache.ttl", "networkaddress.cache.negative.ttl" }) {
final String overrideProperty = "es." + property;
final String overrideValue = System.getProperty(overrideProperty);
if (overrideValue != null) {
try {
// round-trip the property to an integer and back to a string to ensure that it parses properly
Security.setProperty(property, Integer.toString(Integer.valueOf(overrideValue)));
} catch (final NumberFormatException e) {
throw new IllegalArgumentException("failed to parse [" + overrideProperty + "] with value [" + overrideValue + "]", e);
}
}
}
// policy file codebase declarations in security.policy rely on property expansion, see PolicyUtil.readPolicy
Security.setProperty("policy.expandProperties", "true");
}
private static Environment createEnvironment(Path configDir, Settings initialSettings, SecureSettings secureSettings) {
Settings.Builder builder = Settings.builder();
builder.put(initialSettings);
if (secureSettings != null) {
builder.setSecureSettings(secureSettings);
}
return new Environment(builder.build(), configDir);
}
// -- instance
private static volatile Elasticsearch INSTANCE;
private final Spawner spawner;
private final Node node;
private final CountDownLatch keepAliveLatch = new CountDownLatch(1);
private final Thread keepAliveThread;
private Elasticsearch(Spawner spawner, Node node) {
this.spawner = Objects.requireNonNull(spawner);
this.node = Objects.requireNonNull(node);
this.keepAliveThread = new Thread(() -> {
try {
keepAliveLatch.await();
} catch (InterruptedException e) {
// bail out
}
}, "elasticsearch[keepAlive/" + Build.current().version() + "]");
}
private void start() throws NodeValidationException {
node.start();
keepAliveThread.start();
}
private static void shutdown() {
ElasticsearchProcess.markStopping();
if (INSTANCE == null) {
return; // never got far enough
}
var es = INSTANCE;
try {
es.node.prepareForClose();
IOUtils.close(es.node, es.spawner);
if (es.node.awaitClose(10, TimeUnit.SECONDS) == false) {
throw new IllegalStateException(
"Node didn't stop within 10 seconds. " + "Any outstanding requests or tasks might get killed."
);
}
} catch (IOException ex) {
throw new ElasticsearchException("Failure occurred while shutting down node", ex);
} catch (InterruptedException e) {
LogManager.getLogger(Elasticsearch.class).warn("Thread got interrupted while waiting for the node to shutdown.");
Thread.currentThread().interrupt();
} finally {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configurator.shutdown(context);
es.keepAliveLatch.countDown();
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/Elasticsearch.java |
689 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gateway;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexGraveyard;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.Manifest;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.core.UpdateForV9;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
/**
* Handles writing and loading {@link Manifest}, {@link Metadata} and {@link IndexMetadata} as used for cluster state persistence in
* versions prior to {@link Version#V_7_6_0}, used to read this older format during an upgrade from these versions.
*/
public class MetaStateService {
private static final Logger logger = LogManager.getLogger(MetaStateService.class);
public final NodeEnvironment nodeEnv;
public final NamedXContentRegistry namedXContentRegistry;
public MetaStateService(NodeEnvironment nodeEnv, NamedXContentRegistry namedXContentRegistry) {
this.nodeEnv = nodeEnv;
this.namedXContentRegistry = namedXContentRegistry;
}
/**
* Loads the full state, which includes both the global state and all the indices meta data. <br>
* When loading, manifest file is consulted (represented by {@link Manifest} class), to load proper generations. <br>
* If there is no manifest file on disk, this method fallbacks to BWC mode, where latest generation of global and indices
* metadata is loaded. Please note that currently there is no way to distinguish between manifest file being removed and manifest
* file was not yet created. It means that this method always fallbacks to BWC mode, if there is no manifest file.
*
* @return tuple of {@link Manifest} and {@link Metadata} with global metadata and indices metadata. If there is no state on disk,
* meta state with globalGeneration -1 and empty meta data is returned.
* @throws IOException if some IOException when loading files occurs or there is no metadata referenced by manifest file.
*/
@UpdateForV9
public Tuple<Manifest, Metadata> loadFullState() throws IOException {
final Manifest manifest = Manifest.FORMAT.loadLatestState(logger, namedXContentRegistry, nodeEnv.nodeDataPaths());
if (manifest == null) {
return loadFullStateBWC();
}
final Metadata.Builder metadataBuilder;
if (manifest.isGlobalGenerationMissing()) {
metadataBuilder = Metadata.builder();
} else {
final Metadata globalMetadata = Metadata.FORMAT.loadGeneration(
logger,
namedXContentRegistry,
manifest.globalGeneration(),
nodeEnv.nodeDataPaths()
);
if (globalMetadata != null) {
metadataBuilder = Metadata.builder(globalMetadata);
} else {
throw new IOException("failed to find global metadata [generation: " + manifest.globalGeneration() + "]");
}
}
for (Map.Entry<Index, Long> entry : manifest.indexGenerations().entrySet()) {
final Index index = entry.getKey();
final long generation = entry.getValue();
final String indexFolderName = index.getUUID();
final IndexMetadata indexMetadata = IndexMetadata.FORMAT.loadGeneration(
logger,
namedXContentRegistry,
generation,
nodeEnv.resolveIndexFolder(indexFolderName)
);
if (indexMetadata != null) {
metadataBuilder.put(indexMetadata, false);
} else {
throw new IOException(
"failed to find metadata for existing index "
+ index.getName()
+ " [location: "
+ indexFolderName
+ ", generation: "
+ generation
+ "]"
);
}
}
return new Tuple<>(manifest, metadataBuilder.build());
}
/**
* "Manifest-less" BWC version of loading metadata from disk. See also {@link #loadFullState()}
*/
private Tuple<Manifest, Metadata> loadFullStateBWC() throws IOException {
Map<Index, Long> indices = new HashMap<>();
Metadata.Builder metadataBuilder;
Tuple<Metadata, Long> metadataAndGeneration = Metadata.FORMAT.loadLatestStateWithGeneration(
logger,
namedXContentRegistry,
nodeEnv.nodeDataPaths()
);
Metadata globalMetadata = metadataAndGeneration.v1();
long globalStateGeneration = metadataAndGeneration.v2();
final IndexGraveyard indexGraveyard;
if (globalMetadata != null) {
metadataBuilder = Metadata.builder(globalMetadata);
indexGraveyard = globalMetadata.custom(IndexGraveyard.TYPE);
} else {
metadataBuilder = Metadata.builder();
indexGraveyard = IndexGraveyard.builder().build();
}
for (String indexFolderName : nodeEnv.availableIndexFolders()) {
Tuple<IndexMetadata, Long> indexMetadataAndGeneration = IndexMetadata.FORMAT.loadLatestStateWithGeneration(
logger,
namedXContentRegistry,
nodeEnv.resolveIndexFolder(indexFolderName)
);
IndexMetadata indexMetadata = indexMetadataAndGeneration.v1();
long generation = indexMetadataAndGeneration.v2();
if (indexMetadata != null) {
if (indexGraveyard.containsIndex(indexMetadata.getIndex())) {
logger.debug("[{}] found metadata for deleted index [{}]", indexFolderName, indexMetadata.getIndex());
// this index folder is cleared up when state is recovered
} else {
indices.put(indexMetadata.getIndex(), generation);
metadataBuilder.put(indexMetadata, false);
}
} else {
logger.debug("[{}] failed to find metadata for existing index location", indexFolderName);
}
}
Manifest manifest = Manifest.unknownCurrentTermAndVersion(globalStateGeneration, indices);
return new Tuple<>(manifest, metadataBuilder.build());
}
/**
* Loads the index state for the provided index name, returning null if doesn't exists.
*/
@Nullable
public IndexMetadata loadIndexState(Index index) throws IOException {
return IndexMetadata.FORMAT.loadLatestState(logger, namedXContentRegistry, nodeEnv.indexPaths(index));
}
/**
* Loads all indices states available on disk
*/
List<IndexMetadata> loadIndicesStates(Predicate<String> excludeIndexPathIdsPredicate) throws IOException {
List<IndexMetadata> indexMetadataList = new ArrayList<>();
for (String indexFolderName : nodeEnv.availableIndexFolders(excludeIndexPathIdsPredicate)) {
assert excludeIndexPathIdsPredicate.test(indexFolderName) == false
: "unexpected folder " + indexFolderName + " which should have been excluded";
IndexMetadata indexMetadata = IndexMetadata.FORMAT.loadLatestState(
logger,
namedXContentRegistry,
nodeEnv.resolveIndexFolder(indexFolderName)
);
if (indexMetadata != null) {
final String indexPathId = indexMetadata.getIndex().getUUID();
if (indexFolderName.equals(indexPathId)) {
indexMetadataList.add(indexMetadata);
} else {
throw new IllegalStateException("[" + indexFolderName + "] invalid index folder name, rename to [" + indexPathId + "]");
}
} else {
logger.debug("[{}] failed to find metadata for existing index location", indexFolderName);
}
}
return indexMetadataList;
}
/**
* Loads the global state, *without* index state, see {@link #loadFullState()} for that.
*/
Metadata loadGlobalState() throws IOException {
return Metadata.FORMAT.loadLatestState(logger, namedXContentRegistry, nodeEnv.nodeDataPaths());
}
/**
* Creates empty cluster state file on disk, deleting global metadata and unreferencing all index metadata
* (only used for dangling indices at that point).
*/
public void unreferenceAll() throws IOException {
Manifest.FORMAT.writeAndCleanup(Manifest.empty(), nodeEnv.nodeDataPaths()); // write empty file so that indices become unreferenced
Metadata.FORMAT.cleanupOldFiles(Long.MAX_VALUE, nodeEnv.nodeDataPaths());
}
/**
* Removes manifest file, global metadata and all index metadata
*/
public void deleteAll() throws IOException {
// To ensure that the metadata is never reimported by loadFullStateBWC in case where the deletions here fail mid-way through,
// we first write an empty manifest file so that the indices become unreferenced, then clean up the indices, and only then delete
// the manifest file.
unreferenceAll();
for (String indexFolderName : nodeEnv.availableIndexFolders()) {
// delete meta state directories of indices
MetadataStateFormat.deleteMetaState(nodeEnv.resolveIndexFolder(indexFolderName));
}
Manifest.FORMAT.cleanupOldFiles(Long.MAX_VALUE, nodeEnv.nodeDataPaths()); // finally delete manifest
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/gateway/MetaStateService.java |
691 | /*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import org.springframework.core.SerializableTypeWrapper.FieldTypeProvider;
import org.springframework.core.SerializableTypeWrapper.MethodParameterTypeProvider;
import org.springframework.core.SerializableTypeWrapper.TypeProvider;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Encapsulates a Java {@link java.lang.reflect.Type}, providing access to
* {@link #getSuperType() supertypes}, {@link #getInterfaces() interfaces}, and
* {@link #getGeneric(int...) generic parameters} along with the ability to ultimately
* {@link #resolve() resolve} to a {@link java.lang.Class}.
*
* <p>A {@code ResolvableType} may be obtained from a {@linkplain #forField(Field) field},
* a {@linkplain #forMethodParameter(Method, int) method parameter},
* a {@linkplain #forMethodReturnType(Method) method return type}, or a
* {@linkplain #forClass(Class) class}. Most methods on this class will themselves return
* a {@code ResolvableType}, allowing for easy navigation. For example:
* <pre class="code">
* private HashMap<Integer, List<String>> myMap;
*
* public void example() {
* ResolvableType t = ResolvableType.forField(getClass().getDeclaredField("myMap"));
* t.getSuperType(); // AbstractMap<Integer, List<String>>
* t.asMap(); // Map<Integer, List<String>>
* t.getGeneric(0).resolve(); // Integer
* t.getGeneric(1).resolve(); // List
* t.getGeneric(1); // List<String>
* t.resolveGeneric(1, 0); // String
* }
* </pre>
*
* @author Phillip Webb
* @author Juergen Hoeller
* @author Stephane Nicoll
* @author Yanming Zhou
* @since 4.0
* @see #forField(Field)
* @see #forMethodParameter(Method, int)
* @see #forMethodReturnType(Method)
* @see #forConstructorParameter(Constructor, int)
* @see #forClass(Class)
* @see #forType(Type)
* @see #forInstance(Object)
* @see ResolvableTypeProvider
*/
@SuppressWarnings("serial")
public class ResolvableType implements Serializable {
/**
* {@code ResolvableType} returned when no value is available. {@code NONE} is used
* in preference to {@code null} so that multiple method calls can be safely chained.
*/
public static final ResolvableType NONE = new ResolvableType(EmptyType.INSTANCE, null, null, 0);
private static final ResolvableType[] EMPTY_TYPES_ARRAY = new ResolvableType[0];
private static final ConcurrentReferenceHashMap<ResolvableType, ResolvableType> cache =
new ConcurrentReferenceHashMap<>(256);
/**
* The underlying Java type being managed.
*/
private final Type type;
/**
* The component type for an array or {@code null} if the type should be deduced.
*/
@Nullable
private final ResolvableType componentType;
/**
* Optional provider for the type.
*/
@Nullable
private final TypeProvider typeProvider;
/**
* The {@code VariableResolver} to use or {@code null} if no resolver is available.
*/
@Nullable
private final VariableResolver variableResolver;
@Nullable
private final Integer hash;
@Nullable
private Class<?> resolved;
@Nullable
private volatile ResolvableType superType;
@Nullable
private volatile ResolvableType[] interfaces;
@Nullable
private volatile ResolvableType[] generics;
@Nullable
private volatile Boolean unresolvableGenerics;
/**
* Private constructor used to create a new {@code ResolvableType} for cache key purposes,
* with no upfront resolution.
*/
private ResolvableType(
Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) {
this.type = type;
this.componentType = null;
this.typeProvider = typeProvider;
this.variableResolver = variableResolver;
this.hash = calculateHashCode();
this.resolved = null;
}
/**
* Private constructor used to create a new {@code ResolvableType} for cache value purposes,
* with upfront resolution and a pre-calculated hash.
* @since 4.2
*/
private ResolvableType(Type type, @Nullable TypeProvider typeProvider,
@Nullable VariableResolver variableResolver, @Nullable Integer hash) {
this.type = type;
this.componentType = null;
this.typeProvider = typeProvider;
this.variableResolver = variableResolver;
this.hash = hash;
this.resolved = resolveClass();
}
/**
* Private constructor used to create a new {@code ResolvableType} for uncached purposes,
* with upfront resolution but lazily calculated hash.
*/
private ResolvableType(Type type, @Nullable ResolvableType componentType,
@Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) {
this.type = type;
this.componentType = componentType;
this.typeProvider = typeProvider;
this.variableResolver = variableResolver;
this.hash = null;
this.resolved = resolveClass();
}
/**
* Private constructor used to create a new {@code ResolvableType} on a {@link Class} basis.
* <p>Avoids all {@code instanceof} checks in order to create a straight {@link Class} wrapper.
* @since 4.2
*/
private ResolvableType(@Nullable Class<?> clazz) {
this.resolved = (clazz != null ? clazz : Object.class);
this.type = this.resolved;
this.componentType = null;
this.typeProvider = null;
this.variableResolver = null;
this.hash = null;
}
/**
* Return the underling Java {@link Type} being managed.
*/
public Type getType() {
return SerializableTypeWrapper.unwrap(this.type);
}
/**
* Return the underlying Java {@link Class} being managed, if available;
* otherwise {@code null}.
*/
@Nullable
public Class<?> getRawClass() {
if (this.type == this.resolved) {
return this.resolved;
}
Type rawType = this.type;
if (rawType instanceof ParameterizedType parameterizedType) {
rawType = parameterizedType.getRawType();
}
return (rawType instanceof Class<?> rawClass ? rawClass : null);
}
/**
* Return the underlying source of the resolvable type. Will return a {@link Field},
* {@link MethodParameter} or {@link Type} depending on how the {@code ResolvableType}
* was constructed. This method is primarily to provide access to additional type
* information or meta-data that alternative JVM languages may provide.
*/
public Object getSource() {
Object source = (this.typeProvider != null ? this.typeProvider.getSource() : null);
return (source != null ? source : this.type);
}
/**
* Return this type as a resolved {@code Class}, falling back to
* {@link java.lang.Object} if no specific class can be resolved.
* @return the resolved {@link Class} or the {@code Object} fallback
* @since 5.1
* @see #getRawClass()
* @see #resolve(Class)
*/
public Class<?> toClass() {
return resolve(Object.class);
}
/**
* Determine whether the given object is an instance of this {@code ResolvableType}.
* @param obj the object to check
* @since 4.2
* @see #isAssignableFrom(Class)
*/
public boolean isInstance(@Nullable Object obj) {
return (obj != null && isAssignableFrom(obj.getClass()));
}
/**
* Determine whether this {@code ResolvableType} is assignable from the
* specified other type.
* @param other the type to be checked against (as a {@code Class})
* @since 4.2
* @see #isAssignableFrom(ResolvableType)
*/
public boolean isAssignableFrom(Class<?> other) {
// As of 6.1: shortcut assignability check for top-level Class references
return (this.type instanceof Class<?> clazz ? ClassUtils.isAssignable(clazz, other) :
isAssignableFrom(forClass(other), false, null, false));
}
/**
* Determine whether this {@code ResolvableType} is assignable from the
* specified other type.
* <p>Attempts to follow the same rules as the Java compiler, considering
* whether both the {@link #resolve() resolved} {@code Class} is
* {@link Class#isAssignableFrom(Class) assignable from} the given type
* as well as whether all {@link #getGenerics() generics} are assignable.
* @param other the type to be checked against (as a {@code ResolvableType})
* @return {@code true} if the specified other type can be assigned to this
* {@code ResolvableType}; {@code false} otherwise
*/
public boolean isAssignableFrom(ResolvableType other) {
return isAssignableFrom(other, false, null, false);
}
/**
* Determine whether this {@code ResolvableType} is assignable from the
* specified other type, as far as the other type is actually resolvable.
* @param other the type to be checked against (as a {@code ResolvableType})
* @return {@code true} if the specified other type can be assigned to this
* {@code ResolvableType} as far as it is resolvable; {@code false} otherwise
* @since 6.2
*/
public boolean isAssignableFromResolvedPart(ResolvableType other) {
return isAssignableFrom(other, false, null, true);
}
private boolean isAssignableFrom(ResolvableType other, boolean strict,
@Nullable Map<Type, Type> matchedBefore, boolean upUntilUnresolvable) {
Assert.notNull(other, "ResolvableType must not be null");
// If we cannot resolve types, we are not assignable
if (this == NONE || other == NONE) {
return false;
}
if (matchedBefore != null) {
if (matchedBefore.get(this.type) == other.type) {
return true;
}
}
else {
// As of 6.1: shortcut assignability check for top-level Class references
if (this.type instanceof Class<?> clazz && other.type instanceof Class<?> otherClazz) {
return (strict ? clazz.isAssignableFrom(otherClazz) : ClassUtils.isAssignable(clazz, otherClazz));
}
}
// Deal with array by delegating to the component type
if (isArray()) {
return (other.isArray() && getComponentType().isAssignableFrom(
other.getComponentType(), true, matchedBefore, upUntilUnresolvable));
}
if (upUntilUnresolvable && (other.isUnresolvableTypeVariable() || other.isWildcardWithoutBounds())) {
return true;
}
boolean exactMatch = (strict && matchedBefore != null); // We're checking nested generic variables now...
// Deal with wildcard bounds
WildcardBounds ourBounds = WildcardBounds.get(this);
WildcardBounds typeBounds = WildcardBounds.get(other);
// In the form X is assignable to <? extends Number>
if (typeBounds != null) {
if (ourBounds != null) {
return (ourBounds.isSameKind(typeBounds) &&
ourBounds.isAssignableFrom(typeBounds.getBounds(), matchedBefore));
}
else if (upUntilUnresolvable) {
return typeBounds.isAssignableFrom(this, matchedBefore);
}
else if (!exactMatch) {
return typeBounds.isAssignableTo(this, matchedBefore);
}
else {
return false;
}
}
// In the form <? extends Number> is assignable to X...
if (ourBounds != null) {
return ourBounds.isAssignableFrom(other, matchedBefore);
}
// Main assignability check about to follow
boolean checkGenerics = true;
Class<?> ourResolved = null;
if (this.type instanceof TypeVariable<?> variable) {
// Try default variable resolution
if (this.variableResolver != null) {
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
if (resolved != null) {
ourResolved = resolved.resolve();
}
}
if (ourResolved == null) {
// Try variable resolution against target type
if (other.variableResolver != null) {
ResolvableType resolved = other.variableResolver.resolveVariable(variable);
if (resolved != null) {
ourResolved = resolved.resolve();
checkGenerics = false;
}
}
}
if (ourResolved == null) {
// Unresolved type variable, potentially nested -> never insist on exact match
exactMatch = false;
}
}
if (ourResolved == null) {
ourResolved = toClass();
}
Class<?> otherResolved = other.toClass();
// We need an exact type match for generics
// List<CharSequence> is not assignable from List<String>
if (exactMatch ? !ourResolved.equals(otherResolved) :
(strict ? !ourResolved.isAssignableFrom(otherResolved) :
!ClassUtils.isAssignable(ourResolved, otherResolved))) {
return false;
}
if (checkGenerics) {
// Recursively check each generic
ResolvableType[] ourGenerics = getGenerics();
ResolvableType[] typeGenerics = other.as(ourResolved).getGenerics();
if (ourGenerics.length != typeGenerics.length) {
return false;
}
if (ourGenerics.length > 0) {
if (matchedBefore == null) {
matchedBefore = new IdentityHashMap<>(1);
}
matchedBefore.put(this.type, other.type);
for (int i = 0; i < ourGenerics.length; i++) {
if (!ourGenerics[i].isAssignableFrom(typeGenerics[i], true, matchedBefore, upUntilUnresolvable)) {
return false;
}
}
}
}
return true;
}
/**
* Return {@code true} if this type resolves to a Class that represents an array.
* @see #getComponentType()
*/
public boolean isArray() {
if (this == NONE) {
return false;
}
return ((this.type instanceof Class<?> clazz && clazz.isArray()) ||
this.type instanceof GenericArrayType || resolveType().isArray());
}
/**
* Return the ResolvableType representing the component type of the array or
* {@link #NONE} if this type does not represent an array.
* @see #isArray()
*/
public ResolvableType getComponentType() {
if (this == NONE) {
return NONE;
}
if (this.componentType != null) {
return this.componentType;
}
if (this.type instanceof Class<?> clazz) {
Class<?> componentType = clazz.componentType();
return forType(componentType, this.variableResolver);
}
if (this.type instanceof GenericArrayType genericArrayType) {
return forType(genericArrayType.getGenericComponentType(), this.variableResolver);
}
return resolveType().getComponentType();
}
/**
* Convenience method to return this type as a resolvable {@link Collection} type.
* <p>Returns {@link #NONE} if this type does not implement or extend
* {@link Collection}.
* @see #as(Class)
* @see #asMap()
*/
public ResolvableType asCollection() {
return as(Collection.class);
}
/**
* Convenience method to return this type as a resolvable {@link Map} type.
* <p>Returns {@link #NONE} if this type does not implement or extend
* {@link Map}.
* @see #as(Class)
* @see #asCollection()
*/
public ResolvableType asMap() {
return as(Map.class);
}
/**
* Return this type as a {@code ResolvableType} of the specified class. Searches
* {@link #getSuperType() supertype} and {@link #getInterfaces() interface}
* hierarchies to find a match, returning {@link #NONE} if this type does not
* implement or extend the specified class.
* @param type the required type (typically narrowed)
* @return a {@code ResolvableType} representing this object as the specified
* type, or {@link #NONE} if not resolvable as that type
* @see #asCollection()
* @see #asMap()
* @see #getSuperType()
* @see #getInterfaces()
*/
public ResolvableType as(Class<?> type) {
if (this == NONE) {
return NONE;
}
Class<?> resolved = resolve();
if (resolved == null || resolved == type) {
return this;
}
for (ResolvableType interfaceType : getInterfaces()) {
ResolvableType interfaceAsType = interfaceType.as(type);
if (interfaceAsType != NONE) {
return interfaceAsType;
}
}
return getSuperType().as(type);
}
/**
* Return a {@code ResolvableType} representing the direct supertype of this type.
* <p>If no supertype is available this method returns {@link #NONE}.
* <p>Note: The resulting {@code ResolvableType} instance may not be {@link Serializable}.
* @see #getInterfaces()
*/
public ResolvableType getSuperType() {
Class<?> resolved = resolve();
if (resolved == null) {
return NONE;
}
try {
Type superclass = resolved.getGenericSuperclass();
if (superclass == null) {
return NONE;
}
ResolvableType superType = this.superType;
if (superType == null) {
superType = forType(superclass, this);
this.superType = superType;
}
return superType;
}
catch (TypeNotPresentException ex) {
// Ignore non-present types in generic signature
return NONE;
}
}
/**
* Return a {@code ResolvableType} array representing the direct interfaces
* implemented by this type. If this type does not implement any interfaces an
* empty array is returned.
* <p>Note: The resulting {@code ResolvableType} instances may not be {@link Serializable}.
* @see #getSuperType()
*/
public ResolvableType[] getInterfaces() {
Class<?> resolved = resolve();
if (resolved == null) {
return EMPTY_TYPES_ARRAY;
}
ResolvableType[] interfaces = this.interfaces;
if (interfaces == null) {
Type[] genericIfcs = resolved.getGenericInterfaces();
interfaces = new ResolvableType[genericIfcs.length];
for (int i = 0; i < genericIfcs.length; i++) {
interfaces[i] = forType(genericIfcs[i], this);
}
this.interfaces = interfaces;
}
return interfaces;
}
/**
* Return {@code true} if this type contains generic parameters.
* @see #getGeneric(int...)
* @see #getGenerics()
*/
public boolean hasGenerics() {
return (getGenerics().length > 0);
}
/**
* Return {@code true} if this type contains unresolvable generics only,
* that is, no substitute for any of its declared type variables.
*/
boolean isEntirelyUnresolvable() {
if (this == NONE) {
return false;
}
ResolvableType[] generics = getGenerics();
for (ResolvableType generic : generics) {
if (!generic.isUnresolvableTypeVariable() && !generic.isWildcardWithoutBounds()) {
return false;
}
}
return true;
}
/**
* Determine whether the underlying type has any unresolvable generics:
* either through an unresolvable type variable on the type itself
* or through implementing a generic interface in a raw fashion,
* i.e. without substituting that interface's type variables.
* The result will be {@code true} only in those two scenarios.
*/
public boolean hasUnresolvableGenerics() {
if (this == NONE) {
return false;
}
return hasUnresolvableGenerics(null);
}
private boolean hasUnresolvableGenerics(@Nullable Set<Type> alreadySeen) {
Boolean unresolvableGenerics = this.unresolvableGenerics;
if (unresolvableGenerics == null) {
unresolvableGenerics = determineUnresolvableGenerics(alreadySeen);
this.unresolvableGenerics = unresolvableGenerics;
}
return unresolvableGenerics;
}
private boolean determineUnresolvableGenerics(@Nullable Set<Type> alreadySeen) {
if (alreadySeen != null && alreadySeen.contains(this.type)) {
// Self-referencing generic -> not unresolvable
return false;
}
ResolvableType[] generics = getGenerics();
for (ResolvableType generic : generics) {
if (generic.isUnresolvableTypeVariable() || generic.isWildcardWithoutBounds() ||
generic.hasUnresolvableGenerics(currentTypeSeen(alreadySeen))) {
return true;
}
}
Class<?> resolved = resolve();
if (resolved != null) {
try {
for (Type genericInterface : resolved.getGenericInterfaces()) {
if (genericInterface instanceof Class<?> clazz) {
if (clazz.getTypeParameters().length > 0) {
return true;
}
}
}
}
catch (TypeNotPresentException ex) {
// Ignore non-present types in generic signature
}
Class<?> superclass = resolved.getSuperclass();
if (superclass != null && superclass != Object.class) {
return getSuperType().hasUnresolvableGenerics(currentTypeSeen(alreadySeen));
}
}
return false;
}
private Set<Type> currentTypeSeen(@Nullable Set<Type> alreadySeen) {
if (alreadySeen == null) {
alreadySeen = new HashSet<>(4);
}
alreadySeen.add(this.type);
return alreadySeen;
}
/**
* Determine whether the underlying type is a type variable that
* cannot be resolved through the associated variable resolver.
*/
private boolean isUnresolvableTypeVariable() {
if (this.type instanceof TypeVariable<?> variable) {
if (this.variableResolver == null) {
return true;
}
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
if (resolved == null || resolved.isUnresolvableTypeVariable() || resolved.isWildcardWithoutBounds()) {
return true;
}
}
return false;
}
/**
* Determine whether the underlying type represents a wildcard
* without specific bounds (i.e., equal to {@code ? extends Object}).
*/
private boolean isWildcardWithoutBounds() {
if (this.type instanceof WildcardType wildcardType) {
if (wildcardType.getLowerBounds().length == 0) {
Type[] upperBounds = wildcardType.getUpperBounds();
if (upperBounds.length == 0 || (upperBounds.length == 1 && Object.class == upperBounds[0])) {
return true;
}
}
}
return false;
}
/**
* Return a {@code ResolvableType} for the specified nesting level.
* <p>See {@link #getNested(int, Map)} for details.
* @param nestingLevel the nesting level
* @return the {@code ResolvableType} type, or {@code #NONE}
*/
public ResolvableType getNested(int nestingLevel) {
return getNested(nestingLevel, null);
}
/**
* Return a {@code ResolvableType} for the specified nesting level.
* <p>The nesting level refers to the specific generic parameter that should be returned.
* A nesting level of 1 indicates this type; 2 indicates the first nested generic;
* 3 the second; and so on. For example, given {@code List<Set<Integer>>} level 1 refers
* to the {@code List}, level 2 the {@code Set}, and level 3 the {@code Integer}.
* <p>The {@code typeIndexesPerLevel} map can be used to reference a specific generic
* for the given level. For example, an index of 0 would refer to a {@code Map} key;
* whereas, 1 would refer to the value. If the map does not contain a value for a
* specific level the last generic will be used (e.g. a {@code Map} value).
* <p>Nesting levels may also apply to array types; for example given
* {@code String[]}, a nesting level of 2 refers to {@code String}.
* <p>If a type does not {@link #hasGenerics() contain} generics the
* {@link #getSuperType() supertype} hierarchy will be considered.
* @param nestingLevel the required nesting level, indexed from 1 for the
* current type, 2 for the first nested generic, 3 for the second and so on
* @param typeIndexesPerLevel a map containing the generic index for a given
* nesting level (can be {@code null})
* @return a {@code ResolvableType} for the nested level, or {@link #NONE}
*/
public ResolvableType getNested(int nestingLevel, @Nullable Map<Integer, Integer> typeIndexesPerLevel) {
ResolvableType result = this;
for (int i = 2; i <= nestingLevel; i++) {
if (result.isArray()) {
result = result.getComponentType();
}
else {
// Handle derived types
while (result != ResolvableType.NONE && !result.hasGenerics()) {
result = result.getSuperType();
}
Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null);
index = (index == null ? result.getGenerics().length - 1 : index);
result = result.getGeneric(index);
}
}
return result;
}
/**
* Return a {@code ResolvableType} representing the generic parameter for the
* given indexes. Indexes are zero based; for example given the type
* {@code Map<Integer, List<String>>}, {@code getGeneric(0)} will access the
* {@code Integer}. Nested generics can be accessed by specifying multiple indexes;
* for example {@code getGeneric(1, 0)} will access the {@code String} from the
* nested {@code List}. For convenience, if no indexes are specified the first
* generic is returned.
* <p>If no generic is available at the specified indexes {@link #NONE} is returned.
* @param indexes the indexes that refer to the generic parameter
* (can be omitted to return the first generic)
* @return a {@code ResolvableType} for the specified generic, or {@link #NONE}
* @see #hasGenerics()
* @see #getGenerics()
* @see #resolveGeneric(int...)
* @see #resolveGenerics()
*/
public ResolvableType getGeneric(@Nullable int... indexes) {
ResolvableType[] generics = getGenerics();
if (indexes == null || indexes.length == 0) {
return (generics.length == 0 ? NONE : generics[0]);
}
ResolvableType generic = this;
for (int index : indexes) {
generics = generic.getGenerics();
if (index < 0 || index >= generics.length) {
return NONE;
}
generic = generics[index];
}
return generic;
}
/**
* Return an array of {@code ResolvableType ResolvableTypes} representing the generic parameters of
* this type. If no generics are available an empty array is returned. If you need to
* access a specific generic consider using the {@link #getGeneric(int...)} method as
* it allows access to nested generics and protects against
* {@code IndexOutOfBoundsExceptions}.
* @return an array of {@code ResolvableType ResolvableTypes} representing the generic parameters
* (never {@code null})
* @see #hasGenerics()
* @see #getGeneric(int...)
* @see #resolveGeneric(int...)
* @see #resolveGenerics()
*/
public ResolvableType[] getGenerics() {
if (this == NONE) {
return EMPTY_TYPES_ARRAY;
}
ResolvableType[] generics = this.generics;
if (generics == null) {
if (this.type instanceof Class<?> clazz) {
Type[] typeParams = clazz.getTypeParameters();
generics = new ResolvableType[typeParams.length];
for (int i = 0; i < generics.length; i++) {
generics[i] = ResolvableType.forType(typeParams[i], this);
}
}
else if (this.type instanceof ParameterizedType parameterizedType) {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
generics = new ResolvableType[actualTypeArguments.length];
for (int i = 0; i < actualTypeArguments.length; i++) {
generics[i] = forType(actualTypeArguments[i], this.variableResolver);
}
}
else {
generics = resolveType().getGenerics();
}
this.generics = generics;
}
return generics;
}
/**
* Convenience method that will {@link #getGenerics() get} and
* {@link #resolve() resolve} generic parameters.
* @return an array of resolved generic parameters (the resulting array
* will never be {@code null}, but it may contain {@code null} elements)
* @see #getGenerics()
* @see #resolve()
*/
public Class<?>[] resolveGenerics() {
ResolvableType[] generics = getGenerics();
Class<?>[] resolvedGenerics = new Class<?>[generics.length];
for (int i = 0; i < generics.length; i++) {
resolvedGenerics[i] = generics[i].resolve();
}
return resolvedGenerics;
}
/**
* Convenience method that will {@link #getGenerics() get} and {@link #resolve()
* resolve} generic parameters, using the specified {@code fallback} if any type
* cannot be resolved.
* @param fallback the fallback class to use if resolution fails
* @return an array of resolved generic parameters
* @see #getGenerics()
* @see #resolve()
*/
public Class<?>[] resolveGenerics(Class<?> fallback) {
ResolvableType[] generics = getGenerics();
Class<?>[] resolvedGenerics = new Class<?>[generics.length];
for (int i = 0; i < generics.length; i++) {
resolvedGenerics[i] = generics[i].resolve(fallback);
}
return resolvedGenerics;
}
/**
* Convenience method that will {@link #getGeneric(int...) get} and
* {@link #resolve() resolve} a specific generic parameter.
* @param indexes the indexes that refer to the generic parameter
* (can be omitted to return the first generic)
* @return a resolved {@link Class} or {@code null}
* @see #getGeneric(int...)
* @see #resolve()
*/
@Nullable
public Class<?> resolveGeneric(int... indexes) {
return getGeneric(indexes).resolve();
}
/**
* Resolve this type to a {@link java.lang.Class}, returning {@code null}
* if the type cannot be resolved. This method will consider bounds of
* {@link TypeVariable TypeVariables} and {@link WildcardType WildcardTypes} if
* direct resolution fails; however, bounds of {@code Object.class} will be ignored.
* <p>If this method returns a non-null {@code Class} and {@link #hasGenerics()}
* returns {@code false}, the given type effectively wraps a plain {@code Class},
* allowing for plain {@code Class} processing if desirable.
* @return the resolved {@link Class}, or {@code null} if not resolvable
* @see #resolve(Class)
* @see #resolveGeneric(int...)
* @see #resolveGenerics()
*/
@Nullable
public Class<?> resolve() {
return this.resolved;
}
/**
* Resolve this type to a {@link java.lang.Class}, returning the specified
* {@code fallback} if the type cannot be resolved. This method will consider bounds
* of {@link TypeVariable TypeVariables} and {@link WildcardType WildcardTypes} if
* direct resolution fails; however, bounds of {@code Object.class} will be ignored.
* @param fallback the fallback class to use if resolution fails
* @return the resolved {@link Class} or the {@code fallback}
* @see #resolve()
* @see #resolveGeneric(int...)
* @see #resolveGenerics()
*/
public Class<?> resolve(Class<?> fallback) {
return (this.resolved != null ? this.resolved : fallback);
}
@Nullable
private Class<?> resolveClass() {
if (this.type == EmptyType.INSTANCE) {
return null;
}
if (this.type instanceof Class<?> clazz) {
return clazz;
}
if (this.type instanceof GenericArrayType) {
Class<?> resolvedComponent = getComponentType().resolve();
return (resolvedComponent != null ? Array.newInstance(resolvedComponent, 0).getClass() : null);
}
return resolveType().resolve();
}
/**
* Resolve this type by a single level, returning the resolved value or {@link #NONE}.
* <p>Note: The returned {@code ResolvableType} should only be used as an intermediary
* as it cannot be serialized.
*/
ResolvableType resolveType() {
if (this.type instanceof ParameterizedType parameterizedType) {
return forType(parameterizedType.getRawType(), this.variableResolver);
}
if (this.type instanceof WildcardType wildcardType) {
Type resolved = resolveBounds(wildcardType.getUpperBounds());
if (resolved == null) {
resolved = resolveBounds(wildcardType.getLowerBounds());
}
return forType(resolved, this.variableResolver);
}
if (this.type instanceof TypeVariable<?> variable) {
// Try default variable resolution
if (this.variableResolver != null) {
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
if (resolved != null) {
return resolved;
}
}
// Fallback to bounds
return forType(resolveBounds(variable.getBounds()), this.variableResolver);
}
return NONE;
}
@Nullable
private Type resolveBounds(Type[] bounds) {
if (bounds.length == 0 || bounds[0] == Object.class) {
return null;
}
return bounds[0];
}
@Nullable
private ResolvableType resolveVariable(TypeVariable<?> variable) {
if (this.type instanceof TypeVariable) {
return resolveType().resolveVariable(variable);
}
if (this.type instanceof ParameterizedType parameterizedType) {
Class<?> resolved = resolve();
if (resolved == null) {
return null;
}
TypeVariable<?>[] variables = resolved.getTypeParameters();
for (int i = 0; i < variables.length; i++) {
if (ObjectUtils.nullSafeEquals(variables[i].getName(), variable.getName())) {
Type actualType = parameterizedType.getActualTypeArguments()[i];
return forType(actualType, this.variableResolver);
}
}
Type ownerType = parameterizedType.getOwnerType();
if (ownerType != null) {
return forType(ownerType, this.variableResolver).resolveVariable(variable);
}
}
if (this.type instanceof WildcardType) {
ResolvableType resolved = resolveType().resolveVariable(variable);
if (resolved != null) {
return resolved;
}
}
if (this.variableResolver != null) {
return this.variableResolver.resolveVariable(variable);
}
return null;
}
/**
* Check for full equality of all type resolution artifacts:
* type as well as {@code TypeProvider} and {@code VariableResolver}.
* @see #equalsType(ResolvableType)
*/
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other == null || other.getClass() != getClass()) {
return false;
}
ResolvableType otherType = (ResolvableType) other;
if (!equalsType(otherType)) {
return false;
}
if (this.typeProvider != otherType.typeProvider &&
(this.typeProvider == null || otherType.typeProvider == null ||
!ObjectUtils.nullSafeEquals(this.typeProvider.getType(), otherType.typeProvider.getType()))) {
return false;
}
if (this.variableResolver != otherType.variableResolver &&
(this.variableResolver == null || otherType.variableResolver == null ||
!ObjectUtils.nullSafeEquals(this.variableResolver.getSource(), otherType.variableResolver.getSource()))) {
return false;
}
return true;
}
/**
* Check for type-level equality with another {@code ResolvableType}.
* <p>In contrast to {@link #equals(Object)} or {@link #isAssignableFrom(ResolvableType)},
* this works between different sources as well, e.g. method parameters and return types.
* @param otherType the {@code ResolvableType} to match against
* @return whether the declared type and type variables match
* @since 6.1
*/
public boolean equalsType(ResolvableType otherType) {
return (ObjectUtils.nullSafeEquals(this.type, otherType.type) &&
ObjectUtils.nullSafeEquals(this.componentType, otherType.componentType));
}
@Override
public int hashCode() {
return (this.hash != null ? this.hash : calculateHashCode());
}
private int calculateHashCode() {
int hashCode = ObjectUtils.nullSafeHashCode(this.type);
if (this.componentType != null) {
hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.componentType);
}
if (this.typeProvider != null) {
hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.typeProvider.getType());
}
if (this.variableResolver != null) {
hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.variableResolver.getSource());
}
return hashCode;
}
/**
* Adapts this {@code ResolvableType} to a {@link VariableResolver}.
*/
@Nullable
VariableResolver asVariableResolver() {
if (this == NONE) {
return null;
}
return new DefaultVariableResolver(this);
}
/**
* Custom serialization support for {@link #NONE}.
*/
private Object readResolve() {
return (this.type == EmptyType.INSTANCE ? NONE : this);
}
/**
* Return a String representation of this type in its fully resolved form
* (including any generic parameters).
*/
@Override
public String toString() {
if (isArray()) {
return getComponentType() + "[]";
}
if (this.resolved == null) {
return "?";
}
if (this.type instanceof TypeVariable<?> variable) {
if (this.variableResolver == null || this.variableResolver.resolveVariable(variable) == null) {
// Don't bother with variable boundaries for toString()...
// Can cause infinite recursions in case of self-references
return "?";
}
}
if (hasGenerics()) {
return this.resolved.getName() + '<' + StringUtils.arrayToDelimitedString(getGenerics(), ", ") + '>';
}
return this.resolved.getName();
}
// Factory methods
/**
* Return a {@code ResolvableType} for the specified {@link Class},
* using the full generic type information for assignability checks.
* <p>For example: {@code ResolvableType.forClass(MyArrayList.class)}.
* @param clazz the class to introspect ({@code null} is semantically
* equivalent to {@code Object.class} for typical use cases here)
* @return a {@code ResolvableType} for the specified class
* @see #forClass(Class, Class)
* @see #forClassWithGenerics(Class, Class...)
*/
public static ResolvableType forClass(@Nullable Class<?> clazz) {
return new ResolvableType(clazz);
}
/**
* Return a {@code ResolvableType} for the specified {@link Class},
* doing assignability checks against the raw class only (analogous to
* {@link Class#isAssignableFrom}, which this serves as a wrapper for).
* <p>For example: {@code ResolvableType.forRawClass(List.class)}.
* @param clazz the class to introspect ({@code null} is semantically
* equivalent to {@code Object.class} for typical use cases here)
* @return a {@code ResolvableType} for the specified class
* @since 4.2
* @see #forClass(Class)
* @see #getRawClass()
*/
public static ResolvableType forRawClass(@Nullable Class<?> clazz) {
return new ResolvableType(clazz) {
@Override
public ResolvableType[] getGenerics() {
return EMPTY_TYPES_ARRAY;
}
@Override
public boolean isAssignableFrom(Class<?> other) {
return (clazz == null || ClassUtils.isAssignable(clazz, other));
}
@Override
public boolean isAssignableFrom(ResolvableType other) {
Class<?> otherClass = other.resolve();
return (otherClass != null && (clazz == null || ClassUtils.isAssignable(clazz, otherClass)));
}
};
}
/**
* Return a {@code ResolvableType} for the specified base type
* (interface or base class) with a given implementation class.
* <p>For example: {@code ResolvableType.forClass(List.class, MyArrayList.class)}.
* @param baseType the base type (must not be {@code null})
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified base type backed by the
* given implementation class
* @see #forClass(Class)
* @see #forClassWithGenerics(Class, Class...)
*/
public static ResolvableType forClass(Class<?> baseType, Class<?> implementationClass) {
Assert.notNull(baseType, "Base type must not be null");
ResolvableType asType = forType(implementationClass).as(baseType);
return (asType == NONE ? forType(baseType) : asType);
}
/**
* Return a {@code ResolvableType} for the specified {@link Class} with pre-declared generics.
* @param clazz the class (or interface) to introspect
* @param generics the generics of the class
* @return a {@code ResolvableType} for the specific class and generics
* @see #forClassWithGenerics(Class, ResolvableType...)
*/
public static ResolvableType forClassWithGenerics(Class<?> clazz, Class<?>... generics) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(generics, "Generics array must not be null");
ResolvableType[] resolvableGenerics = new ResolvableType[generics.length];
for (int i = 0; i < generics.length; i++) {
resolvableGenerics[i] = forClass(generics[i]);
}
return forClassWithGenerics(clazz, resolvableGenerics);
}
/**
* Return a {@code ResolvableType} for the specified {@link Class} with pre-declared generics.
* @param clazz the class (or interface) to introspect
* @param generics the generics of the class
* @return a {@code ResolvableType} for the specific class and generics
* @see #forClassWithGenerics(Class, Class...)
*/
public static ResolvableType forClassWithGenerics(Class<?> clazz, @Nullable ResolvableType... generics) {
Assert.notNull(clazz, "Class must not be null");
TypeVariable<?>[] variables = clazz.getTypeParameters();
if (generics != null) {
Assert.isTrue(variables.length == generics.length,
() -> "Mismatched number of generics specified for " + clazz.toGenericString());
}
Type[] arguments = new Type[variables.length];
for (int i = 0; i < variables.length; i++) {
ResolvableType generic = (generics != null ? generics[i] : null);
Type argument = (generic != null ? generic.getType() : null);
arguments[i] = (argument != null && !(argument instanceof TypeVariable) ? argument : variables[i]);
}
return forType(new SyntheticParameterizedType(clazz, arguments),
(generics != null ? new TypeVariablesVariableResolver(variables, generics) : null));
}
/**
* Return a {@code ResolvableType} for the specified instance. The instance does not
* convey generic information but if it implements {@link ResolvableTypeProvider} a
* more precise {@code ResolvableType} can be used than the simple one based on
* the {@link #forClass(Class) Class instance}.
* @param instance the instance (possibly {@code null})
* @return a {@code ResolvableType} for the specified instance,
* or {@code NONE} for {@code null}
* @since 4.2
* @see ResolvableTypeProvider
*/
public static ResolvableType forInstance(@Nullable Object instance) {
if (instance instanceof ResolvableTypeProvider resolvableTypeProvider) {
ResolvableType type = resolvableTypeProvider.getResolvableType();
if (type != null) {
return type;
}
}
return (instance != null ? forClass(instance.getClass()) : NONE);
}
/**
* Return a {@code ResolvableType} for the specified {@link Field}.
* @param field the source field
* @return a {@code ResolvableType} for the specified field
* @see #forField(Field, Class)
*/
public static ResolvableType forField(Field field) {
Assert.notNull(field, "Field must not be null");
return forType(null, new FieldTypeProvider(field), null);
}
/**
* Return a {@code ResolvableType} for the specified {@link Field} with a given
* implementation.
* <p>Use this variant when the class that declares the field includes generic
* parameter variables that are satisfied by the implementation class.
* @param field the source field
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified field
* @see #forField(Field)
*/
public static ResolvableType forField(Field field, Class<?> implementationClass) {
Assert.notNull(field, "Field must not be null");
ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass());
return forType(null, new FieldTypeProvider(field), owner.asVariableResolver());
}
/**
* Return a {@code ResolvableType} for the specified {@link Field} with a given
* implementation.
* <p>Use this variant when the class that declares the field includes generic
* parameter variables that are satisfied by the implementation type.
* @param field the source field
* @param implementationType the implementation type
* @return a {@code ResolvableType} for the specified field
* @see #forField(Field)
*/
public static ResolvableType forField(Field field, @Nullable ResolvableType implementationType) {
Assert.notNull(field, "Field must not be null");
ResolvableType owner = (implementationType != null ? implementationType : NONE);
owner = owner.as(field.getDeclaringClass());
return forType(null, new FieldTypeProvider(field), owner.asVariableResolver());
}
/**
* Return a {@code ResolvableType} for the specified {@link Field} with the
* given nesting level.
* @param field the source field
* @param nestingLevel the nesting level (1 for the outer level; 2 for a nested
* generic type; etc)
* @see #forField(Field)
*/
public static ResolvableType forField(Field field, int nestingLevel) {
Assert.notNull(field, "Field must not be null");
return forType(null, new FieldTypeProvider(field), null).getNested(nestingLevel);
}
/**
* Return a {@code ResolvableType} for the specified {@link Field} with a given
* implementation and the given nesting level.
* <p>Use this variant when the class that declares the field includes generic
* parameter variables that are satisfied by the implementation class.
* @param field the source field
* @param nestingLevel the nesting level (1 for the outer level; 2 for a nested
* generic type; etc)
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified field
* @see #forField(Field)
*/
public static ResolvableType forField(Field field, int nestingLevel, @Nullable Class<?> implementationClass) {
Assert.notNull(field, "Field must not be null");
ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass());
return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()).getNested(nestingLevel);
}
/**
* Return a {@code ResolvableType} for the specified {@link Constructor} parameter.
* @param constructor the source constructor (must not be {@code null})
* @param parameterIndex the parameter index
* @return a {@code ResolvableType} for the specified constructor parameter
* @see #forConstructorParameter(Constructor, int, Class)
*/
public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex) {
Assert.notNull(constructor, "Constructor must not be null");
return forMethodParameter(new MethodParameter(constructor, parameterIndex));
}
/**
* Return a {@code ResolvableType} for the specified {@link Constructor} parameter
* with a given implementation. Use this variant when the class that declares the
* constructor includes generic parameter variables that are satisfied by the
* implementation class.
* @param constructor the source constructor (must not be {@code null})
* @param parameterIndex the parameter index
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified constructor parameter
* @see #forConstructorParameter(Constructor, int)
*/
public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex,
Class<?> implementationClass) {
Assert.notNull(constructor, "Constructor must not be null");
MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex, implementationClass);
return forMethodParameter(methodParameter);
}
/**
* Return a {@code ResolvableType} for the specified {@link Method} return type.
* @param method the source for the method return type
* @return a {@code ResolvableType} for the specified method return
* @see #forMethodReturnType(Method, Class)
*/
public static ResolvableType forMethodReturnType(Method method) {
Assert.notNull(method, "Method must not be null");
return forMethodParameter(new MethodParameter(method, -1));
}
/**
* Return a {@code ResolvableType} for the specified {@link Method} return type.
* <p>Use this variant when the class that declares the method includes generic
* parameter variables that are satisfied by the implementation class.
* @param method the source for the method return type
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified method return
* @see #forMethodReturnType(Method)
*/
public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) {
Assert.notNull(method, "Method must not be null");
MethodParameter methodParameter = new MethodParameter(method, -1, implementationClass);
return forMethodParameter(methodParameter);
}
/**
* Return a {@code ResolvableType} for the specified {@link Method} parameter.
* @param method the source method (must not be {@code null})
* @param parameterIndex the parameter index
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int, Class)
* @see #forMethodParameter(MethodParameter)
*/
public static ResolvableType forMethodParameter(Method method, int parameterIndex) {
Assert.notNull(method, "Method must not be null");
return forMethodParameter(new MethodParameter(method, parameterIndex));
}
/**
* Return a {@code ResolvableType} for the specified {@link Method} parameter with a
* given implementation. Use this variant when the class that declares the method
* includes generic parameter variables that are satisfied by the implementation class.
* @param method the source method (must not be {@code null})
* @param parameterIndex the parameter index
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int, Class)
* @see #forMethodParameter(MethodParameter)
*/
public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class<?> implementationClass) {
Assert.notNull(method, "Method must not be null");
MethodParameter methodParameter = new MethodParameter(method, parameterIndex, implementationClass);
return forMethodParameter(methodParameter);
}
/**
* Return a {@code ResolvableType} for the specified {@link MethodParameter}.
* @param methodParameter the source method parameter (must not be {@code null})
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int)
*/
public static ResolvableType forMethodParameter(MethodParameter methodParameter) {
return forMethodParameter(methodParameter, (Type) null);
}
/**
* Return a {@code ResolvableType} for the specified {@link MethodParameter} with a
* given implementation type. Use this variant when the class that declares the method
* includes generic parameter variables that are satisfied by the implementation type.
* @param methodParameter the source method parameter (must not be {@code null})
* @param implementationType the implementation type
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(MethodParameter)
*/
public static ResolvableType forMethodParameter(MethodParameter methodParameter,
@Nullable ResolvableType implementationType) {
Assert.notNull(methodParameter, "MethodParameter must not be null");
implementationType = (implementationType != null ? implementationType :
forType(methodParameter.getContainingClass()));
ResolvableType owner = implementationType.as(methodParameter.getDeclaringClass());
return forType(null, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).
getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel);
}
/**
* Return a {@code ResolvableType} for the specified {@link MethodParameter},
* overriding the target type to resolve with a specific given type.
* @param methodParameter the source method parameter (must not be {@code null})
* @param targetType the type to resolve (a part of the method parameter's type)
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int)
*/
public static ResolvableType forMethodParameter(MethodParameter methodParameter, @Nullable Type targetType) {
Assert.notNull(methodParameter, "MethodParameter must not be null");
return forMethodParameter(methodParameter, targetType, methodParameter.getNestingLevel());
}
/**
* Return a {@code ResolvableType} for the specified {@link MethodParameter} at
* a specific nesting level, overriding the target type to resolve with a specific
* given type.
* @param methodParameter the source method parameter (must not be {@code null})
* @param targetType the type to resolve (a part of the method parameter's type)
* @param nestingLevel the nesting level to use
* @return a {@code ResolvableType} for the specified method parameter
* @since 5.2
* @see #forMethodParameter(Method, int)
*/
static ResolvableType forMethodParameter(
MethodParameter methodParameter, @Nullable Type targetType, int nestingLevel) {
ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass());
return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).
getNested(nestingLevel, methodParameter.typeIndexesPerLevel);
}
/**
* Return a {@code ResolvableType} as an array of the specified {@code componentType}.
* @param componentType the component type
* @return a {@code ResolvableType} as an array of the specified component type
*/
public static ResolvableType forArrayComponent(ResolvableType componentType) {
Assert.notNull(componentType, "Component type must not be null");
Class<?> arrayType = componentType.toClass().arrayType();
return new ResolvableType(arrayType, componentType, null, null);
}
/**
* Return a {@code ResolvableType} for the specified {@link Type}.
* <p>Note: The resulting {@code ResolvableType} instance may not be {@link Serializable}.
* @param type the source type (potentially {@code null})
* @return a {@code ResolvableType} for the specified {@link Type}
* @see #forType(Type, ResolvableType)
*/
public static ResolvableType forType(@Nullable Type type) {
return forType(type, null, null);
}
/**
* Return a {@code ResolvableType} for the specified {@link Type} backed by the given
* owner type.
* <p>Note: The resulting {@code ResolvableType} instance may not be {@link Serializable}.
* @param type the source type or {@code null}
* @param owner the owner type used to resolve variables
* @return a {@code ResolvableType} for the specified {@link Type} and owner
* @see #forType(Type)
*/
public static ResolvableType forType(@Nullable Type type, @Nullable ResolvableType owner) {
VariableResolver variableResolver = null;
if (owner != null) {
variableResolver = owner.asVariableResolver();
}
return forType(type, variableResolver);
}
/**
* Return a {@code ResolvableType} for the specified {@link ParameterizedTypeReference}.
* <p>Note: The resulting {@code ResolvableType} instance may not be {@link Serializable}.
* @param typeReference the reference to obtain the source type from
* @return a {@code ResolvableType} for the specified {@link ParameterizedTypeReference}
* @since 4.3.12
* @see #forType(Type)
*/
public static ResolvableType forType(ParameterizedTypeReference<?> typeReference) {
return forType(typeReference.getType(), null, null);
}
/**
* Return a {@code ResolvableType} for the specified {@link Type} backed by a given
* {@link VariableResolver}.
* @param type the source type or {@code null}
* @param variableResolver the variable resolver or {@code null}
* @return a {@code ResolvableType} for the specified {@link Type} and {@link VariableResolver}
*/
static ResolvableType forType(@Nullable Type type, @Nullable VariableResolver variableResolver) {
return forType(type, null, variableResolver);
}
/**
* Return a {@code ResolvableType} for the specified {@link Type} backed by a given
* {@link VariableResolver}.
* @param type the source type or {@code null}
* @param typeProvider the type provider or {@code null}
* @param variableResolver the variable resolver or {@code null}
* @return a {@code ResolvableType} for the specified {@link Type} and {@link VariableResolver}
*/
static ResolvableType forType(
@Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) {
if (type == null && typeProvider != null) {
type = SerializableTypeWrapper.forTypeProvider(typeProvider);
}
if (type == null) {
return NONE;
}
// For simple Class references, build the wrapper right away -
// no expensive resolution necessary, so not worth caching...
if (type instanceof Class) {
return new ResolvableType(type, null, typeProvider, variableResolver);
}
// Purge empty entries on access since we don't have a clean-up thread or the like.
cache.purgeUnreferencedEntries();
// Check the cache - we may have a ResolvableType which has been resolved before...
ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver);
ResolvableType cachedType = cache.get(resultType);
if (cachedType == null) {
cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash);
cache.put(cachedType, cachedType);
}
resultType.resolved = cachedType.resolved;
return resultType;
}
/**
* Clear the internal {@code ResolvableType}/{@code SerializableTypeWrapper} cache.
* @since 4.2
*/
public static void clearCache() {
cache.clear();
SerializableTypeWrapper.cache.clear();
}
/**
* Strategy interface used to resolve {@link TypeVariable TypeVariables}.
*/
interface VariableResolver extends Serializable {
/**
* Return the source of the resolver (used for hashCode and equals).
*/
Object getSource();
/**
* Resolve the specified variable.
* @param variable the variable to resolve
* @return the resolved variable, or {@code null} if not found
*/
@Nullable
ResolvableType resolveVariable(TypeVariable<?> variable);
}
@SuppressWarnings("serial")
private static class DefaultVariableResolver implements VariableResolver {
private final ResolvableType source;
DefaultVariableResolver(ResolvableType resolvableType) {
this.source = resolvableType;
}
@Override
@Nullable
public ResolvableType resolveVariable(TypeVariable<?> variable) {
return this.source.resolveVariable(variable);
}
@Override
public Object getSource() {
return this.source;
}
}
@SuppressWarnings("serial")
private static class TypeVariablesVariableResolver implements VariableResolver {
private final TypeVariable<?>[] variables;
private final ResolvableType[] generics;
public TypeVariablesVariableResolver(TypeVariable<?>[] variables, ResolvableType[] generics) {
this.variables = variables;
this.generics = generics;
}
@Override
@Nullable
public ResolvableType resolveVariable(TypeVariable<?> variable) {
TypeVariable<?> variableToCompare = SerializableTypeWrapper.unwrap(variable);
for (int i = 0; i < this.variables.length; i++) {
TypeVariable<?> resolvedVariable = SerializableTypeWrapper.unwrap(this.variables[i]);
if (ObjectUtils.nullSafeEquals(resolvedVariable, variableToCompare)) {
return this.generics[i];
}
}
return null;
}
@Override
public Object getSource() {
return this.generics;
}
}
private static final class SyntheticParameterizedType implements ParameterizedType, Serializable {
private final Type rawType;
private final Type[] typeArguments;
public SyntheticParameterizedType(Type rawType, Type[] typeArguments) {
this.rawType = rawType;
this.typeArguments = typeArguments;
}
@Override
public String getTypeName() {
String typeName = this.rawType.getTypeName();
if (this.typeArguments.length > 0) {
StringJoiner stringJoiner = new StringJoiner(", ", "<", ">");
for (Type argument : this.typeArguments) {
stringJoiner.add(argument.getTypeName());
}
return typeName + stringJoiner;
}
return typeName;
}
@Override
@Nullable
public Type getOwnerType() {
return null;
}
@Override
public Type getRawType() {
return this.rawType;
}
@Override
public Type[] getActualTypeArguments() {
return this.typeArguments;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof ParameterizedType that &&
that.getOwnerType() == null && this.rawType.equals(that.getRawType()) &&
Arrays.equals(this.typeArguments, that.getActualTypeArguments())));
}
@Override
public int hashCode() {
return (this.rawType.hashCode() * 31 + Arrays.hashCode(this.typeArguments));
}
@Override
public String toString() {
return getTypeName();
}
}
/**
* Internal helper to handle bounds from {@link WildcardType WildcardTypes}.
*/
private static class WildcardBounds {
private final Kind kind;
private final ResolvableType[] bounds;
/**
* Internal constructor to create a new {@link WildcardBounds} instance.
* @param kind the kind of bounds
* @param bounds the bounds
* @see #get(ResolvableType)
*/
public WildcardBounds(Kind kind, ResolvableType[] bounds) {
this.kind = kind;
this.bounds = bounds;
}
/**
* Return {@code true} if these bounds are the same kind as the specified bounds.
*/
public boolean isSameKind(WildcardBounds bounds) {
return this.kind == bounds.kind;
}
/**
* Return {@code true} if these bounds are assignable from all the specified types.
* @param types the types to test against
* @return {@code true} if these bounds are assignable from all types
*/
public boolean isAssignableFrom(ResolvableType[] types, @Nullable Map<Type, Type> matchedBefore) {
for (ResolvableType type : types) {
if (!isAssignableFrom(type, matchedBefore)) {
return false;
}
}
return true;
}
/**
* Return {@code true} if these bounds are assignable from the specified type.
* @param type the type to test against
* @return {@code true} if these bounds are assignable from the type
* @since 6.2
*/
public boolean isAssignableFrom(ResolvableType type, @Nullable Map<Type, Type> matchedBefore) {
for (ResolvableType bound : this.bounds) {
if (this.kind == Kind.UPPER ? !bound.isAssignableFrom(type, false, matchedBefore, false) :
!type.isAssignableFrom(bound, false, matchedBefore, false)) {
return false;
}
}
return true;
}
/**
* Return {@code true} if these bounds are assignable to the specified type.
* @param type the type to test against
* @return {@code true} if these bounds are assignable to the type
* @since 6.2
*/
public boolean isAssignableTo(ResolvableType type, @Nullable Map<Type, Type> matchedBefore) {
if (this.kind == Kind.UPPER) {
for (ResolvableType bound : this.bounds) {
if (type.isAssignableFrom(bound, false, matchedBefore, false)) {
return true;
}
}
return false;
}
else {
return (type.resolve() == Object.class);
}
}
/**
* Return the underlying bounds.
*/
public ResolvableType[] getBounds() {
return this.bounds;
}
/**
* Get a {@link WildcardBounds} instance for the specified type, returning
* {@code null} if the specified type cannot be resolved to a {@link WildcardType}
* or an equivalent unresolvable type variable.
* @param type the source type
* @return a {@link WildcardBounds} instance or {@code null}
*/
@Nullable
public static WildcardBounds get(ResolvableType type) {
ResolvableType candidate = type;
while (!(candidate.getType() instanceof WildcardType || candidate.isUnresolvableTypeVariable())) {
if (candidate == NONE) {
return null;
}
candidate = candidate.resolveType();
}
Kind boundsType;
Type[] bounds;
if (candidate.getType() instanceof WildcardType wildcardType) {
boundsType = (wildcardType.getLowerBounds().length > 0 ? Kind.LOWER : Kind.UPPER);
bounds = (boundsType == Kind.UPPER ? wildcardType.getUpperBounds() : wildcardType.getLowerBounds());
}
else {
boundsType = Kind.UPPER;
bounds = ((TypeVariable<?>) candidate.getType()).getBounds();
}
ResolvableType[] resolvableBounds = new ResolvableType[bounds.length];
for (int i = 0; i < bounds.length; i++) {
resolvableBounds[i] = ResolvableType.forType(bounds[i], type.variableResolver);
}
return new WildcardBounds(boundsType, resolvableBounds);
}
/**
* The various kinds of bounds.
*/
enum Kind {UPPER, LOWER}
}
/**
* Internal {@link Type} used to represent an empty value.
*/
@SuppressWarnings("serial")
static class EmptyType implements Type, Serializable {
static final Type INSTANCE = new EmptyType();
Object readResolve() {
return INSTANCE;
}
}
}
| spring-projects/spring-framework | spring-core/src/main/java/org/springframework/core/ResolvableType.java |
692 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.ViewCachingAbstractMap;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of {@link Multimaps#filterEntries(Multimap, Predicate)}.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
class FilteredEntryMultimap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> {
final Multimap<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
FilteredEntryMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = checkNotNull(unfiltered);
this.predicate = checkNotNull(predicate);
}
@Override
public Multimap<K, V> unfiltered() {
return unfiltered;
}
@Override
public Predicate<? super Entry<K, V>> entryPredicate() {
return predicate;
}
@Override
public int size() {
return entries().size();
}
private boolean satisfies(@ParametricNullness K key, @ParametricNullness V value) {
return predicate.apply(Maps.immutableEntry(key, value));
}
final class ValuePredicate implements Predicate<V> {
@ParametricNullness private final K key;
ValuePredicate(@ParametricNullness K key) {
this.key = key;
}
@Override
public boolean apply(@ParametricNullness V value) {
return satisfies(key, value);
}
}
static <E extends @Nullable Object> Collection<E> filterCollection(
Collection<E> collection, Predicate<? super E> predicate) {
if (collection instanceof Set) {
return Sets.filter((Set<E>) collection, predicate);
} else {
return Collections2.filter(collection, predicate);
}
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return asMap().get(key) != null;
}
@Override
public Collection<V> removeAll(@CheckForNull Object key) {
return MoreObjects.firstNonNull(asMap().remove(key), unmodifiableEmptyCollection());
}
Collection<V> unmodifiableEmptyCollection() {
// These return false, rather than throwing a UOE, on remove calls.
return (unfiltered instanceof SetMultimap)
? Collections.<V>emptySet()
: Collections.<V>emptyList();
}
@Override
public void clear() {
entries().clear();
}
@Override
public Collection<V> get(@ParametricNullness K key) {
return filterCollection(unfiltered.get(key), new ValuePredicate(key));
}
@Override
Collection<Entry<K, V>> createEntries() {
return filterCollection(unfiltered.entries(), predicate);
}
@Override
Collection<V> createValues() {
return new FilteredMultimapValues<>(this);
}
@Override
Iterator<Entry<K, V>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
Map<K, Collection<V>> createAsMap() {
return new AsMap();
}
@Override
Set<K> createKeySet() {
return asMap().keySet();
}
boolean removeEntriesIf(Predicate<? super Entry<K, Collection<V>>> predicate) {
Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator();
boolean changed = false;
while (entryIterator.hasNext()) {
Entry<K, Collection<V>> entry = entryIterator.next();
K key = entry.getKey();
Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key));
if (!collection.isEmpty()
&& predicate.apply(Maps.<K, Collection<V>>immutableEntry(key, collection))) {
if (collection.size() == entry.getValue().size()) {
entryIterator.remove();
} else {
collection.clear();
}
changed = true;
}
}
return changed;
}
@WeakOuter
class AsMap extends ViewCachingAbstractMap<K, Collection<V>> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
public void clear() {
FilteredEntryMultimap.this.clear();
}
@Override
@CheckForNull
public Collection<V> get(@CheckForNull Object key) {
Collection<V> result = unfiltered.asMap().get(key);
if (result == null) {
return null;
}
@SuppressWarnings("unchecked") // key is equal to a K, if not a K itself
K k = (K) key;
result = filterCollection(result, new ValuePredicate(k));
return result.isEmpty() ? null : result;
}
@Override
@CheckForNull
public Collection<V> remove(@CheckForNull Object key) {
Collection<V> collection = unfiltered.asMap().get(key);
if (collection == null) {
return null;
}
@SuppressWarnings("unchecked") // it's definitely equal to a K
K k = (K) key;
List<V> result = Lists.newArrayList();
Iterator<V> itr = collection.iterator();
while (itr.hasNext()) {
V v = itr.next();
if (satisfies(k, v)) {
itr.remove();
result.add(v);
}
}
if (result.isEmpty()) {
return null;
} else if (unfiltered instanceof SetMultimap) {
return Collections.unmodifiableSet(Sets.newLinkedHashSet(result));
} else {
return Collections.unmodifiableList(result);
}
}
@Override
Set<K> createKeySet() {
@WeakOuter
class KeySetImpl extends Maps.KeySet<K, Collection<V>> {
KeySetImpl() {
super(AsMap.this);
}
@Override
public boolean removeAll(Collection<?> c) {
return removeEntriesIf(Maps.<K>keyPredicateOnEntries(in(c)));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntriesIf(Maps.<K>keyPredicateOnEntries(not(in(c))));
}
@Override
public boolean remove(@CheckForNull Object o) {
return AsMap.this.remove(o) != null;
}
}
return new KeySetImpl();
}
@Override
Set<Entry<K, Collection<V>>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends Maps.EntrySet<K, Collection<V>> {
@Override
Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override
public Iterator<Entry<K, Collection<V>>> iterator() {
return new AbstractIterator<Entry<K, Collection<V>>>() {
final Iterator<Entry<K, Collection<V>>> backingIterator =
unfiltered.asMap().entrySet().iterator();
@Override
@CheckForNull
protected Entry<K, Collection<V>> computeNext() {
while (backingIterator.hasNext()) {
Entry<K, Collection<V>> entry = backingIterator.next();
K key = entry.getKey();
Collection<V> collection =
filterCollection(entry.getValue(), new ValuePredicate(key));
if (!collection.isEmpty()) {
return Maps.immutableEntry(key, collection);
}
}
return endOfData();
}
};
}
@Override
public boolean removeAll(Collection<?> c) {
return removeEntriesIf(in(c));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntriesIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
}
return new EntrySetImpl();
}
@Override
Collection<Collection<V>> createValues() {
@WeakOuter
class ValuesImpl extends Maps.Values<K, Collection<V>> {
ValuesImpl() {
super(AsMap.this);
}
@Override
public boolean remove(@CheckForNull Object o) {
if (o instanceof Collection) {
Collection<?> c = (Collection<?>) o;
Iterator<Entry<K, Collection<V>>> entryIterator =
unfiltered.asMap().entrySet().iterator();
while (entryIterator.hasNext()) {
Entry<K, Collection<V>> entry = entryIterator.next();
K key = entry.getKey();
Collection<V> collection =
filterCollection(entry.getValue(), new ValuePredicate(key));
if (!collection.isEmpty() && c.equals(collection)) {
if (collection.size() == entry.getValue().size()) {
entryIterator.remove();
} else {
collection.clear();
}
return true;
}
}
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return removeEntriesIf(Maps.<Collection<V>>valuePredicateOnEntries(in(c)));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntriesIf(Maps.<Collection<V>>valuePredicateOnEntries(not(in(c))));
}
}
return new ValuesImpl();
}
}
@Override
Multiset<K> createKeys() {
return new Keys();
}
@WeakOuter
class Keys extends Multimaps.Keys<K, V> {
Keys() {
super(FilteredEntryMultimap.this);
}
@Override
public int remove(@CheckForNull Object key, int occurrences) {
checkNonnegative(occurrences, "occurrences");
if (occurrences == 0) {
return count(key);
}
Collection<V> collection = unfiltered.asMap().get(key);
if (collection == null) {
return 0;
}
@SuppressWarnings("unchecked") // key is equal to a K, if not a K itself
K k = (K) key;
int oldCount = 0;
Iterator<V> itr = collection.iterator();
while (itr.hasNext()) {
V v = itr.next();
if (satisfies(k, v)) {
oldCount++;
if (oldCount <= occurrences) {
itr.remove();
}
}
}
return oldCount;
}
@Override
public Set<Multiset.Entry<K>> entrySet() {
return new Multisets.EntrySet<K>() {
@Override
Multiset<K> multiset() {
return Keys.this;
}
@Override
public Iterator<Multiset.Entry<K>> iterator() {
return Keys.this.entryIterator();
}
@Override
public int size() {
return FilteredEntryMultimap.this.keySet().size();
}
private boolean removeEntriesIf(Predicate<? super Multiset.Entry<K>> predicate) {
return FilteredEntryMultimap.this.removeEntriesIf(
(Map.Entry<K, Collection<V>> entry) ->
predicate.apply(
Multisets.<K>immutableEntry(entry.getKey(), entry.getValue().size())));
}
@Override
public boolean removeAll(Collection<?> c) {
return removeEntriesIf(in(c));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntriesIf(not(in(c)));
}
};
}
}
}
| google/guava | guava/src/com/google/common/collect/FilteredEntryMultimap.java |
693 | /*
* Copyright (C) 2018 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.RegularImmutableMap.makeImmutable;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of ImmutableMap backed by a JDK HashMap, which has smartness protecting against
* hash flooding.
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
final class JdkBackedImmutableMap<K, V> extends ImmutableMap<K, V> {
/**
* Creates an {@code ImmutableMap} backed by a JDK HashMap. Used when probable hash flooding is
* detected. This implementation may replace the entries in entryArray with its own entry objects
* (though they will have the same key/value contents), and will take ownership of entryArray.
*/
static <K, V> ImmutableMap<K, V> create(
int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) {
Map<K, V> delegateMap = Maps.newHashMapWithExpectedSize(n);
// If duplicates are allowed, this map will track the last value for each duplicated key.
// A second pass will retain only the first entry for that key, but with this last value. The
// value will then be replaced by null, signaling that later entries with the same key should
// be deleted.
Map<K, @Nullable V> duplicates = null;
int dupCount = 0;
for (int i = 0; i < n; i++) {
// requireNonNull is safe because the first `n` elements have been filled in.
entryArray[i] = makeImmutable(requireNonNull(entryArray[i]));
K key = entryArray[i].getKey();
V value = entryArray[i].getValue();
V oldValue = delegateMap.put(key, value);
if (oldValue != null) {
if (throwIfDuplicateKeys) {
throw conflictException("key", entryArray[i], entryArray[i].getKey() + "=" + oldValue);
}
if (duplicates == null) {
duplicates = new HashMap<>();
}
duplicates.put(key, value);
dupCount++;
}
}
if (duplicates != null) {
@SuppressWarnings({"rawtypes", "unchecked"})
Entry<K, V>[] newEntryArray = new Entry[n - dupCount];
for (int inI = 0, outI = 0; inI < n; inI++) {
Entry<K, V> entry = requireNonNull(entryArray[inI]);
K key = entry.getKey();
if (duplicates.containsKey(key)) {
V value = duplicates.get(key);
if (value == null) {
continue; // delete this duplicate
}
entry = new ImmutableMapEntry<>(key, value);
duplicates.put(key, null);
}
newEntryArray[outI++] = entry;
}
entryArray = newEntryArray;
}
return new JdkBackedImmutableMap<>(delegateMap, ImmutableList.asImmutableList(entryArray, n));
}
private final transient Map<K, V> delegateMap;
private final transient ImmutableList<Entry<K, V>> entries;
JdkBackedImmutableMap(Map<K, V> delegateMap, ImmutableList<Entry<K, V>> entries) {
this.delegateMap = delegateMap;
this.entries = entries;
}
@Override
public int size() {
return entries.size();
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return delegateMap.get(key);
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet.RegularEntrySet<>(this, entries);
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
entries.forEach(e -> action.accept(e.getKey(), e.getValue()));
}
@Override
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<>(this);
}
@Override
ImmutableCollection<V> createValues() {
return new ImmutableMapValues<>(this);
}
@Override
boolean isPartialView() {
return false;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
| google/guava | guava/src/com/google/common/collect/JdkBackedImmutableMap.java |
694 | /*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import java.util.function.BiConsumer;
import javax.annotation.CheckForNull;
/**
* Implementation of {@link ImmutableMap} with exactly one entry.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
@ElementTypesAreNonnullByDefault
final class SingletonImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
final transient K singleKey;
final transient V singleValue;
SingletonImmutableBiMap(K singleKey, V singleValue) {
checkEntryNotNull(singleKey, singleValue);
this.singleKey = singleKey;
this.singleValue = singleValue;
this.inverse = null;
}
private SingletonImmutableBiMap(K singleKey, V singleValue, ImmutableBiMap<V, K> inverse) {
this.singleKey = singleKey;
this.singleValue = singleValue;
this.inverse = inverse;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return singleKey.equals(key) ? singleValue : null;
}
@Override
public int size() {
return 1;
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action).accept(singleKey, singleValue);
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return singleKey.equals(key);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return singleValue.equals(value);
}
@Override
boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return ImmutableSet.of(Maps.immutableEntry(singleKey, singleValue));
}
@Override
ImmutableSet<K> createKeySet() {
return ImmutableSet.of(singleKey);
}
@CheckForNull private final transient ImmutableBiMap<V, K> inverse;
@LazyInit @RetainedWith @CheckForNull private transient ImmutableBiMap<V, K> lazyInverse;
@Override
public ImmutableBiMap<V, K> inverse() {
if (inverse != null) {
return inverse;
} else {
// racy single-check idiom
ImmutableBiMap<V, K> result = lazyInverse;
if (result == null) {
return lazyInverse = new SingletonImmutableBiMap<>(singleValue, singleKey, this);
} else {
return result;
}
}
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
| google/guava | guava/src/com/google/common/collect/SingletonImmutableBiMap.java |
695 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| google/guava | guava/src/com/google/common/collect/TreeRangeMap.java |
696 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.script;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.Arrays;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.LongSupplier;
/**
* Provides a counter with a history of 5m/15m/24h.
*
* Callers increment the counter and query the current state of the TimeSeries.
*
* {@link TimeSeriesCounter#inc()} increments the counter to indicate an event happens "now", with metadata about "now"
* from the given {@link TimeSeriesCounter#timeProvider}.
*
* {@link TimeSeriesCounter#timeSeries()} provides a snapshot of the counters at the current time, given by
* {@link TimeSeriesCounter#timeProvider}. The snapshot includes the number of events in the last five minutes, the last fifteen
* minutes, the last twenty-four hours and an all-time count.
*
* Caveats:
* * If the timeProvider produces a time stamp value, {@code t[j]} that occurs _before_ an earlier invocation {@code t[j]} (where j is an
* invocation that *happens-before*, in the java memory model sense), the time stamp is treated as occurring at the latest time seen,
* {@code t[latest]}, EXCEPT if {@code t[latest] - t[j]} is earlier than any time covered by the twenty-four counter. If that occurs,
* time goes backwards more than 24 hours (between 24:00 and 23:45 depending on the circumstance) the history is reset but total is
* retained.
* * All counters have a resolution:
* - 5m resolution is 15s
* - 15m resolution is 90s
* - 24h resolution is 15m
* The counter will drop events between one second and the resolution minus one second during a bucket rollover.
*/
public class TimeSeriesCounter {
public static final int SECOND = 1;
public static final int MINUTE = 60;
public static final int HOUR = 60 * MINUTE;
protected LongAdder adder = new LongAdder();
protected ReadWriteLock lock = new ReentrantReadWriteLock();
protected Counter fiveMinutes = new Counter(15 * SECOND, 5 * MINUTE);
protected Counter fifteenMinutes = new Counter(90 * SECOND, 15 * MINUTE);
protected Counter twentyFourHours = new Counter(15 * MINUTE, 24 * HOUR);
protected final LongSupplier timeProvider;
/**
* Create a TimeSeriesCounter with the given {@code timeProvider}.
*
* The {@code timeProvider} must return positive values, in milliseconds. In live code, this is expected
* to be {@link System#currentTimeMillis()} or a proxy such as {@link ThreadPool#absoluteTimeInMillis()}.
*/
public TimeSeriesCounter(LongSupplier timeProvider) {
this.timeProvider = timeProvider;
}
/**
* Increment counters at timestamp t, any increment more than 24hours before the current time
* series resets all historical counters, but the total counter is still increments.
*/
public void inc() {
long now = now();
adder.increment();
lock.writeLock().lock();
try {
// If time has skewed more than a day in the past, reset the histories, but not the adder.
// Counters clamp all times before the end of the current bucket as happening in the current
// bucket, so this reset avoids pegging counters to their current buckets for too long.
if (now < twentyFourHours.earliestTimeInCounter()) {
fiveMinutes.reset(now);
fifteenMinutes.reset(now);
twentyFourHours.reset(now);
} else {
fiveMinutes.inc(now);
fifteenMinutes.inc(now);
twentyFourHours.inc(now);
}
} finally {
lock.writeLock().unlock();
}
}
/**
* Get the value of the counters for the last 5 minutes, last 15 minutes and the last 24 hours from
* t. May include events up to resolution before those durations due to counter granularity.
*/
public TimeSeries timeSeries() {
long now = now();
lock.readLock().lock();
try {
return new TimeSeries(fiveMinutes.sum(now), fifteenMinutes.sum(now), twentyFourHours.sum(now), count());
} finally {
lock.readLock().unlock();
}
}
// The current time, in seconds, from the timeProvider, which emits milliseconds. Clamped to zero or positive numbers.
protected long now() {
long t = timeProvider.getAsLong();
if (t < 0) {
t = 0;
} else {
t /= 1000;
}
return t;
}
/**
* The total number of events for all time covered by the counters.
*/
public long count() {
long total = adder.sum();
return total < 0 ? 0 : total;
}
/*
* Keeps track event counts over a duration. Events are clamped to buckets, either the current bucket or a future
* bucket. A bucket represents all events over a period of resolution number of seconds.
*/
public static class Counter {
/*
* In the following diagrams, we take a duration of 100 and resolution of 20.
*
* |___________________________________________________________|
* duration = 100
*
* |___________|___________|___________|___________|___________|
* buckets = 5
*
* |___________|
* resolution = 20
*
* Action: inc(235) - Increment the counter at time 235 seconds.
*
* While there is only one `buckets` array, it's useful to view the array as overlapping three
* epoch (time at bucket[0]), the last epoch, the present epoch and the future epoch.
*
* Past
* [_] [_] [2] [3] [4]
* |___________|___________|___________|___________|___________|
* 140[e]-> 160-> 180-> 199
*
* Present
* [0] [1][b] [2][g] [3] [4]
* |___________|_____1_____|___________|___________|___________|
* 200[a]-> 220-> 240[d]-> 260-> 280-> 299
*
* Future
* [0] [_] [_] [_] [_]
* |___________|___________|___________|___________|___________|
* 300[c]-> 320[f]
*
* [a] Beginning of the current epoch
* startOfCurrentEpoch = 200 = (t / duration) * duration = (235 / 100) * 100
* Start time of bucket zero, this is used to anchor the bucket ring in time. Without `startOfCurrentEpoch`,
* it would be impossible to distinguish between two times that are `duration` away from each other.
* In this example, the first inc used time 235, since startOfCurrentEpoch is rounded down to the nearest
* duration (100), it is 200.
*
* [b] The current bucket
* curBucket = 1 = (t / resolution) % buckets.length = (235 / 20) % 5
* The latest active bucket in the bucket ring. The bucket of a timestamp is determined by the `resolution`.
* In this case the `resolution` is 20, so each bucket covers 20 seconds, the first covers 200-219, the
* second covers 220->239, the third 240->259 and so on. 235 is in the second bucket, at index 1.
*
* [c] Beginning of the next epoch
* nextEpoch() = 300 = startOfCurrentEpoch + duration = 200 + 100
* The first time of the next epoch, this indicates when `startOfCurrentEpoch` should be updated. When `curBucket`
* advances to or past zero, `startOfCurrentEpoch` must be updated to `nextEpoch()`
*
* [d] Beginning of the next bucket
* nextBucketStartTime() = 240 = startOfCurrentEpoch + ((curBucket + 1) * resolution) = 200 + ((1 + 1) * 20
* The first time of the next bucket, when a timestamp is greater than or equal to this time, we must update
* the `curBucket` and potentially the `startOfCurrentEpoch`.
*
* [e] The earliest time to sum
* earliestTimeInCounter() = 140 = nextBucketStartTime() - duration = 240 - 100
* `curBucket` covers the latest timestamp seen by the `Counter`. Since the counter keeps a history, when a
* caller calls `sum(t)`, the `Counter` must clamp the range to the earliest time covered by its current state.
* The times proceed backwards for `buckets.length - 1`.
* **Important** this is likely _before_ the `startOfCurrentEpoch`. `startOfCurrentEpoch` is the timestamp of bucket[0].
*
* [f] The counter is no longer valid at this time
* counterExpired() = 320 = startOfCurrentEpoch + (curBucket * resolution) + duration = 200 + (1 * 20) + 100
* Where `earliestTimeInCounter()` is looking backwards, to the history covered by the counter, `counterExpired()`
* looks forward to when current counter has expired. Since `curBucket` represents the latest time in this counter,
* `counterExpired()` is `duration` from the start of the time covered from `curBucket`
*
* [g] The next bucket in the bucket ring
* nextBucket(curBucket) = 2 = (i + 1) % buckets.length = (1 + 1) % 5
* Since `buckets` is a ring, the next bucket may wrap around.
*
* ------------------------------------------------------------------------------------------------------------------
*
* Action: inc(238) - since this inc is within the current bucket, it is incremented and nothing else changes
*
* Present
* [0] [1][b] [2][g] [3] [4]
* |___________|_____2_____|___________|___________|___________|
* 200[a]-> 220-> 240[d]-> 260-> 280-> 299
*
* ------------------------------------------------------------------------------------------------------------------
*
* Action: inc(165) - only the current bucket is incremented, so increments from a timestamp in the past are
* clamped to the current bucket. This makes `inc(long)` dependent on the ordering of timestamps,
* but it avoids revising a history that may have already been exposed via `sum(long)`.
*
* Present
* [0] [1][b] [2][g] [3] [4]
* |___________|_____3_____|___________|___________|___________|
* 200[a]-> 220-> 240[d]-> 260-> 280-> 299
*
* ------------------------------------------------------------------------------------------------------------------
*
* Action: inc(267) - 267 is in bucket 3, so bucket 2 is zeroed and skipped. Bucket 2 is zeroed because it may have
* had contents that were relevant for timestamps 140 - 159.
*
* The `startOfCurrentEpoch`[a], does not change while `curBucket`[b] is now bucket 3.
*
* `nextEpoch()`[c] does not change as there hasn't been a rollover.
*
* `nextBucketStartTime()`[d] is now 280, the start time of bucket 4.
*
* `earliestTimeInCounter()`[e] is now 180, bucket 2 was zeroed, erasing the history from 140-159 and
* bucket 3 was set to 1, now representing 260-279 rather than 160-179.
*
* `counterExpired()`[f] is now 360. Bucket 3 in the current epoch represents 260->279, an
* `inc(long)` any of time (260 + `duration`) or beyond would require clearing all `buckets` in the
* `Counter` and any `sum(long)` that starts at 360 or later does not cover the valid time range for
* this state of the counter.
*
* `nextBucket(curBucket)`[g] is now 4, the bucket after 3.
*
*
* Past
* [_] [_] [_] [_] [4]
* |___________|___________|___________|___________|___________|
* 180[e]-> 199
*
* Present
* [0] [1] [2] [3][b] [4][g]
* |___________|_____3_____|___________|______1____|___________|
* 200[a]-> 220-> 240-> 260-> 280[d]-> 299
*
* Future
* [0] [1] [2] [_] [_]
* |___________|___________|___________|___________|___________|
* 300[c]-> 320-> 340-> 360[f]->
*
* ------------------------------------------------------------------------------------------------------------------
*
* Action: inc(310) - 310 is in bucket 0, so bucket 4 is zeroed and skipped, as it may have had contents
* for timestamps 180-199.
*
* The `startOfCurrentEpoch`[a], is now 300 as the `Counter` has rolled through bucket 0.
*
* `curBucket`[b] is now bucket 0.
*
* `nextEpoch()`[c] is now 400 because `startOfCurrentEpoch`[a] has changed.
*
* `nextBucketStartTime()`[d] is now 320, the start time of bucket 1 in this new epoch.
*
* `earliestTimeInCounter()`[e] is now 220, bucket 4 was zeroed, erasing the history from 180-199 and
* bucket 0 was set to 1, now representing 300-319 due to the epoch change, rather than 200-219, so
* 220 is the earliest time available in the `Counter`.
*
* `counterExpired()`[f] is now 400. Bucket 0 in the current epoch represents 300-319, an
* `inc(long)` any of time (300 + `duration`) or beyond would require clearing all `buckets` in the
* `Counter` and any `sum(long)` that starts at 400 or later does not cover the valid time range for
* this state of the counter.
*
* `nextBucket(curBucket)`[g] is now 1, the bucket after 0.
*
*
* Past
* [_] [1] [2] [3] [4]
* |___________|_____3_____|___________|______1____|___________|
* 220[e]-> 240-> 260-> 280-> 299
*
* Present
* [0][b] [1][g] [2] [3] [4]
* |_____1_____|___________|___________|___________|___________|
* 300[a]-> 320[d]-> 340-> 360-> 380-> 399
*
* Future
* [_] [_] [_] [_] [_]
* |___________|___________|___________|___________|___________|
* 400[c][f]->
*
* ------------------------------------------------------------------------------------------------------------------
*
* Action: inc(321) - 321 is in bucket 1, so the previous contents of bucket 1 is replaced with the value 1.
*
* The `startOfCurrentEpoch`[a] remains 300.
*
* `curBucket`[b] is now bucket 1.
*
* `nextEpoch()`[c] remains 400.
*
* `nextBucketStartTime()`[d] is now 340, the start time of bucket 2.
*
* `earliestTimeInCounter()`[e] is now 240 as bucket 1 now represents 320-339 rather than 220-239.
*
* `counterExpired()`[f] is now 420. Bucket 1 in the current epoch represents 320-339, an
* `inc(long)` any of time (320 + `duration`) or beyond would require clearing all `buckets` in the
* `Counter` and any `sum(long)` that starts at 420 or later does not cover the valid time range for
* this state of the counter.
*
* `nextBucket(curBucket)`[g] is now 2, the bucket after 1.
*
* Past
* [_] [_] [2] [3] [4]
* |___________|___________|___________|______1____|___________|
* 240[e]-> 260-> 280-> 299
*
* Present
* [0] [1][b] [2][g] [3] [4]
* |_____1_____|_____1_____|___________|___________|___________|
* 300[a]-> 320-> 340[d]-> 360-> 380-> 399
*
* Future
* [0] [_] [_] [_] [_]
* |_____0_____|___________|___________|___________|___________|
* 400[c]-> 420[f]->
*
*
* ------------------------------------------------------------------------------------------------------------------
*
* Action: sum(321) - This is a sum at the exact time of the last update, because of the `earliestTimeInCounter` check,
* it starts at bucket 2, which is after the current bucket index, 1, but the earliest time covered by
* the counter, 240 to 259.
* 1) calculate start = 321 - duration = 321 - 100 = 221
* 2) start is before the nextBucketStartTime (340), so sum does not terminate early
* 3) start is before the earliestTimeInCounter (240) -> start = 240
* 3) Iterate from bucket(start) = bucket(240) = 2 until curBucket 1, summing the following
* bucket 2 = 0, bucket 3 = 1, bucket 4 = 0, bucket 0 = 1 -> 1 + 1 = 2
* 4) return that with the context of bucket 1 = 1 -> 2 + 1 = 3
*
* Action: sum(465) - This sum is so far in the future, it does not overlap with any bucket in range
* 1) calculate start = 465 - duration = 465 - 100 = 365
* 2) start is greater than or equal to the nextBucketStartTime (340), so we know the counter has no contexts
* -> return 0
*
* Action: sum(439) - This sum starts _after_ the last update, which is at 321, but because of the bucket resolution
* sum still catches the value bucket 1, times 320 to 339.
* 1) calculate start = 439 - duration = 439 - 100 = 339
* 2) start is before nextBucketStartTime(340), so sum does not terminate early
* 3) start is after earliestTimeInCounter (240), so it is now updated
* 4) bucket(start) = 1 which is curBucket, so the for loop falls through
* 5) return total = 0 + buckets[curBucket] = 0 + 1 = 1
*/
protected final long resolution;
protected final long duration;
protected final long[] buckets;
// The start time of buckets[0]. bucket(t + (i * duration)) is the same for all i. startOfCurrentEpoch allows the counter
// to differentiate between those times.
protected long startOfCurrentEpoch;
protected int curBucket = 0;
/**
* Create a Counter that covers duration seconds at the given resolution. Duration must be divisible by resolution.
*/
public Counter(long resolution, long duration) {
if (resolution <= 0) {
throw new IllegalArgumentException("resolution [" + resolution + "] must be greater than zero");
} else if (duration <= 0) {
throw new IllegalArgumentException("duration [" + duration + "] must be greater than zero");
} else if (duration % resolution != 0) {
throw new IllegalArgumentException("duration [" + duration + "] must divisible by resolution [" + resolution + "]");
}
this.resolution = resolution;
this.duration = duration;
this.buckets = new long[(int) (duration / resolution)];
this.startOfCurrentEpoch = 0;
assert buckets.length > 0;
}
/**
* Increment the counter at time {@code now}, expressed in seconds.
*/
public void inc(long now) {
if (now < nextBucketStartTime()) {
buckets[curBucket]++;
} else if (now >= counterExpired()) {
reset(now);
} else {
int dstBucket = bucket(now);
for (int i = nextBucket(curBucket); i != dstBucket; i = nextBucket(i)) {
buckets[i] = 0;
}
curBucket = dstBucket;
buckets[curBucket] = 1;
if (now >= nextEpoch()) {
startOfCurrentEpoch = epoch(now);
}
}
}
/**
* sum for the duration of the counter until {@code now}.
*/
public long sum(long now) {
long start = now - duration;
if (start >= nextBucketStartTime()) {
return 0;
}
if (start < earliestTimeInCounter()) {
start = earliestTimeInCounter();
}
long total = 0;
for (int i = bucket(start); i != curBucket; i = nextBucket(i)) {
total += buckets[i];
}
return total + buckets[curBucket];
}
/**
* Reset the counter. Next counter begins at now.
*/
void reset(long now) {
Arrays.fill(buckets, 0);
startOfCurrentEpoch = epoch(now);
curBucket = bucket(now);
buckets[curBucket] = 1;
}
// The time at bucket[0] for the given timestamp.
long epoch(long t) {
return (t / duration) * duration;
}
// What is the start time of the next epoch?
long nextEpoch() {
return startOfCurrentEpoch + duration;
}
// What is the earliest time covered by this counter? Counters do not extend before zero.
long earliestTimeInCounter() {
long time = nextBucketStartTime() - duration;
return time <= 0 ? 0 : time;
}
// When does this entire counter expire?
long counterExpired() {
return startOfCurrentEpoch + (curBucket * resolution) + duration;
}
// bucket for the given time
int bucket(long t) {
return (int) (t / resolution) % buckets.length;
}
// the next bucket in the circular bucket array
int nextBucket(int i) {
return (i + 1) % buckets.length;
}
// When does the next bucket start?
long nextBucketStartTime() {
return startOfCurrentEpoch + ((curBucket + 1) * resolution);
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/script/TimeSeriesCounter.java |
698 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A custom map implementation from FieldDescriptor to Object optimized to minimize the number of
* memory allocations for instances with a small number of mappings. The implementation stores the
* first {@code k} mappings in an array for a configurable value of {@code k}, allowing direct
* access to the corresponding {@code Entry}s without the need to create an Iterator. The remaining
* entries are stored in an overflow map. Iteration over the entries in the map should be done as
* follows:
*
* <pre>{@code
* for (int i = 0; i < fieldMap.getNumArrayEntries(); i++) {
* process(fieldMap.getArrayEntryAt(i));
* }
* for (Map.Entry<K, V> entry : fieldMap.getOverflowEntries()) {
* process(entry);
* }
* }</pre>
*
* The resulting iteration is in order of ascending field tag number. The object returned by {@link
* #entrySet()} adheres to the same contract but is less efficient as it necessarily involves
* creating an object for iteration.
*
* <p>The tradeoff for this memory efficiency is that the worst case running time of the {@code
* put()} operation is {@code O(k + lg n)}, which happens when entries are added in descending
* order. {@code k} should be chosen such that it covers enough common cases without adversely
* affecting larger maps. In practice, the worst case scenario does not happen for extensions
* because extension fields are serialized and deserialized in order of ascending tag number, but
* the worst case scenario can happen for DynamicMessages.
*
* <p>The running time for all other operations is similar to that of {@code TreeMap}.
*
* <p>Instances are not thread-safe until {@link #makeImmutable()} is called, after which any
* modifying operation will result in an {@link UnsupportedOperationException}.
*
* @author [email protected] Darick Tong
*/
// This class is final for all intents and purposes because the constructor is
// private. However, the FieldDescriptor-specific logic is encapsulated in
// a subclass to aid testability of the core logic.
class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
* Creates a new instance for mapping FieldDescriptors to their values. The {@link
* #makeImmutable()} implementation will convert the List values of any repeated fields to
* unmodifiable lists.
*
* @param arraySize The size of the entry array containing the lexicographically smallest
* mappings.
*/
static <FieldDescriptorType extends FieldSet.FieldDescriptorLite<FieldDescriptorType>>
SmallSortedMap<FieldDescriptorType, Object> newFieldMap(int arraySize) {
return new SmallSortedMap<FieldDescriptorType, Object>(arraySize) {
@Override
@SuppressWarnings("unchecked")
public void makeImmutable() {
if (!isImmutable()) {
for (int i = 0; i < getNumArrayEntries(); i++) {
final Map.Entry<FieldDescriptorType, Object> entry = getArrayEntryAt(i);
if (entry.getKey().isRepeated()) {
final List value = (List) entry.getValue();
entry.setValue(Collections.unmodifiableList(value));
}
}
for (Map.Entry<FieldDescriptorType, Object> entry : getOverflowEntries()) {
if (entry.getKey().isRepeated()) {
final List value = (List) entry.getValue();
entry.setValue(Collections.unmodifiableList(value));
}
}
}
super.makeImmutable();
}
};
}
/**
* Creates a new instance for testing.
*
* @param arraySize The size of the entry array containing the lexicographically smallest
* mappings.
*/
static <K extends Comparable<K>, V> SmallSortedMap<K, V> newInstanceForTest(int arraySize) {
return new SmallSortedMap<K, V>(arraySize);
}
private final int maxArraySize;
// The "entry array" is actually a List because generic arrays are not
// allowed. ArrayList also nicely handles the entry shifting on inserts and
// removes.
private List<Entry> entryList;
private Map<K, V> overflowEntries;
private boolean isImmutable;
// The EntrySet is a stateless view of the Map. It's initialized the first
// time it is requested and reused henceforth.
private volatile EntrySet lazyEntrySet;
private Map<K, V> overflowEntriesDescending;
private volatile DescendingEntrySet lazyDescendingEntrySet;
/**
* @code arraySize Size of the array in which the lexicographically smallest mappings are stored.
* (i.e. the {@code k} referred to in the class documentation).
*/
private SmallSortedMap(int arraySize) {
this.maxArraySize = arraySize;
this.entryList = Collections.emptyList();
this.overflowEntries = Collections.emptyMap();
this.overflowEntriesDescending = Collections.emptyMap();
}
/** Make this map immutable from this point forward. */
public void makeImmutable() {
if (!isImmutable) {
// Note: There's no need to wrap the entryList in an unmodifiableList
// because none of the list's accessors are exposed. The iterator() of
// overflowEntries, on the other hand, is exposed so it must be made
// unmodifiable.
overflowEntries =
overflowEntries.isEmpty()
? Collections.<K, V>emptyMap()
: Collections.unmodifiableMap(overflowEntries);
overflowEntriesDescending =
overflowEntriesDescending.isEmpty()
? Collections.<K, V>emptyMap()
: Collections.unmodifiableMap(overflowEntriesDescending);
isImmutable = true;
}
}
/** @return Whether {@link #makeImmutable()} has been called. */
public boolean isImmutable() {
return isImmutable;
}
/** @return The number of entries in the entry array. */
public int getNumArrayEntries() {
return entryList.size();
}
/** @return The array entry at the given {@code index}. */
public Map.Entry<K, V> getArrayEntryAt(int index) {
return entryList.get(index);
}
/** @return There number of overflow entries. */
public int getNumOverflowEntries() {
return overflowEntries.size();
}
/** @return An iterable over the overflow entries. */
public Iterable<Map.Entry<K, V>> getOverflowEntries() {
return overflowEntries.isEmpty()
? Collections.emptySet()
: overflowEntries.entrySet();
}
Iterable<Map.Entry<K, V>> getOverflowEntriesDescending() {
return overflowEntriesDescending.isEmpty()
? Collections.emptySet()
: overflowEntriesDescending.entrySet();
}
@Override
public int size() {
return entryList.size() + overflowEntries.size();
}
/**
* The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}.
*
* <p>{@inheritDoc}
*/
@Override
public boolean containsKey(Object o) {
@SuppressWarnings("unchecked")
final K key = (K) o;
return binarySearchInArray(key) >= 0 || overflowEntries.containsKey(key);
}
/**
* The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}.
*
* <p>{@inheritDoc}
*/
@Override
public V get(Object o) {
@SuppressWarnings("unchecked")
final K key = (K) o;
final int index = binarySearchInArray(key);
if (index >= 0) {
return entryList.get(index).getValue();
}
return overflowEntries.get(key);
}
@Override
public V put(K key, V value) {
checkMutable();
final int index = binarySearchInArray(key);
if (index >= 0) {
// Replace existing array entry.
return entryList.get(index).setValue(value);
}
ensureEntryArrayMutable();
final int insertionPoint = -(index + 1);
if (insertionPoint >= maxArraySize) {
// Put directly in overflow.
return getOverflowEntriesMutable().put(key, value);
}
// Insert new Entry in array.
if (entryList.size() == maxArraySize) {
// Shift the last array entry into overflow.
final Entry lastEntryInArray = entryList.remove(maxArraySize - 1);
getOverflowEntriesMutable().put(lastEntryInArray.getKey(), lastEntryInArray.getValue());
}
entryList.add(insertionPoint, new Entry(key, value));
return null;
}
@Override
public void clear() {
checkMutable();
if (!entryList.isEmpty()) {
entryList.clear();
}
if (!overflowEntries.isEmpty()) {
overflowEntries.clear();
}
}
/**
* The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}.
*
* <p>{@inheritDoc}
*/
@Override
public V remove(Object o) {
checkMutable();
@SuppressWarnings("unchecked")
final K key = (K) o;
final int index = binarySearchInArray(key);
if (index >= 0) {
return removeArrayEntryAt(index);
}
// overflowEntries might be Collections.unmodifiableMap(), so only
// call remove() if it is non-empty.
if (overflowEntries.isEmpty()) {
return null;
} else {
return overflowEntries.remove(key);
}
}
private V removeArrayEntryAt(int index) {
checkMutable();
final V removed = entryList.remove(index).getValue();
if (!overflowEntries.isEmpty()) {
// Shift the first entry in the overflow to be the last entry in the
// array.
final Iterator<Map.Entry<K, V>> iterator = getOverflowEntriesMutable().entrySet().iterator();
entryList.add(new Entry(iterator.next()));
iterator.remove();
}
return removed;
}
/**
* @param key The key to find in the entry array.
* @return The returned integer position follows the same semantics as the value returned by
* {@link java.util.Arrays#binarySearch()}.
*/
private int binarySearchInArray(K key) {
int left = 0;
int right = entryList.size() - 1;
// Optimization: For the common case in which entries are added in
// ascending tag order, check the largest element in the array before
// doing a full binary search.
if (right >= 0) {
int cmp = key.compareTo(entryList.get(right).getKey());
if (cmp > 0) {
return -(right + 2); // Insert point is after "right".
} else if (cmp == 0) {
return right;
}
}
while (left <= right) {
int mid = (left + right) / 2;
int cmp = key.compareTo(entryList.get(mid).getKey());
if (cmp < 0) {
right = mid - 1;
} else if (cmp > 0) {
left = mid + 1;
} else {
return mid;
}
}
return -(left + 1);
}
/**
* Similar to the AbstractMap implementation of {@code keySet()} and {@code values()}, the entry
* set is created the first time this method is called, and returned in response to all subsequent
* calls.
*
* <p>{@inheritDoc}
*/
@Override
public Set<Map.Entry<K, V>> entrySet() {
if (lazyEntrySet == null) {
lazyEntrySet = new EntrySet();
}
return lazyEntrySet;
}
Set<Map.Entry<K, V>> descendingEntrySet() {
if (lazyDescendingEntrySet == null) {
lazyDescendingEntrySet = new DescendingEntrySet();
}
return lazyDescendingEntrySet;
}
/** @throws UnsupportedOperationException if {@link #makeImmutable()} has has been called. */
private void checkMutable() {
if (isImmutable) {
throw new UnsupportedOperationException();
}
}
/**
* @return a {@link SortedMap} to which overflow entries mappings can be added or removed.
* @throws UnsupportedOperationException if {@link #makeImmutable()} has been called.
*/
private SortedMap<K, V> getOverflowEntriesMutable() {
checkMutable();
if (overflowEntries.isEmpty() && !(overflowEntries instanceof TreeMap)) {
overflowEntries = new TreeMap<K, V>();
overflowEntriesDescending = ((TreeMap<K, V>) overflowEntries).descendingMap();
}
return (SortedMap<K, V>) overflowEntries;
}
/** Lazily creates the entry list. Any code that adds to the list must first call this method. */
private void ensureEntryArrayMutable() {
checkMutable();
if (entryList.isEmpty() && !(entryList instanceof ArrayList)) {
entryList = new ArrayList<Entry>(maxArraySize);
}
}
/**
* Entry implementation that implements Comparable in order to support binary search within the
* entry array. Also checks mutability in {@link #setValue()}.
*/
private class Entry implements Map.Entry<K, V>, Comparable<Entry> {
private final K key;
private V value;
Entry(Map.Entry<K, V> copy) {
this(copy.getKey(), copy.getValue());
}
Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public int compareTo(Entry other) {
return getKey().compareTo(other.getKey());
}
@Override
public V setValue(V newValue) {
checkMutable();
final V oldValue = this.value;
this.value = newValue;
return oldValue;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> other = (Map.Entry<?, ?>) o;
return equals(key, other.getKey()) && equals(value, other.getValue());
}
@Override
public int hashCode() {
return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
@Override
public String toString() {
return key + "=" + value;
}
/** equals() that handles null values. */
private boolean equals(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
}
/** Stateless view of the entries in the field map. */
private class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public int size() {
return SmallSortedMap.this.size();
}
/**
* Throws a {@link ClassCastException} if o is not of the expected type.
*
* <p>{@inheritDoc}
*/
@Override
public boolean contains(Object o) {
@SuppressWarnings("unchecked")
final Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
final V existing = get(entry.getKey());
final V value = entry.getValue();
return existing == value || (existing != null && existing.equals(value));
}
@Override
public boolean add(Map.Entry<K, V> entry) {
if (!contains(entry)) {
put(entry.getKey(), entry.getValue());
return true;
}
return false;
}
/**
* Throws a {@link ClassCastException} if o is not of the expected type.
*
* <p>{@inheritDoc}
*/
@Override
public boolean remove(Object o) {
@SuppressWarnings("unchecked")
final Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
if (contains(entry)) {
SmallSortedMap.this.remove(entry.getKey());
return true;
}
return false;
}
@Override
public void clear() {
SmallSortedMap.this.clear();
}
}
private class DescendingEntrySet extends EntrySet {
@Override
public Iterator<java.util.Map.Entry<K, V>> iterator() {
return new DescendingEntryIterator();
}
}
/**
* Iterator implementation that switches from the entry array to the overflow entries
* appropriately.
*/
private class EntryIterator implements Iterator<Map.Entry<K, V>> {
private int pos = -1;
private boolean nextCalledBeforeRemove;
private Iterator<Map.Entry<K, V>> lazyOverflowIterator;
@Override
public boolean hasNext() {
return (pos + 1) < entryList.size()
|| (!overflowEntries.isEmpty() && getOverflowIterator().hasNext());
}
@Override
public Map.Entry<K, V> next() {
nextCalledBeforeRemove = true;
// Always increment pos so that we know whether the last returned value
// was from the array or from overflow.
if (++pos < entryList.size()) {
return entryList.get(pos);
}
return getOverflowIterator().next();
}
@Override
public void remove() {
if (!nextCalledBeforeRemove) {
throw new IllegalStateException("remove() was called before next()");
}
nextCalledBeforeRemove = false;
checkMutable();
if (pos < entryList.size()) {
removeArrayEntryAt(pos--);
} else {
getOverflowIterator().remove();
}
}
/**
* It is important to create the overflow iterator only after the array entries have been
* iterated over because the overflow entry set changes when the client calls remove() on the
* array entries, which invalidates any existing iterators.
*/
private Iterator<Map.Entry<K, V>> getOverflowIterator() {
if (lazyOverflowIterator == null) {
lazyOverflowIterator = overflowEntries.entrySet().iterator();
}
return lazyOverflowIterator;
}
}
/**
* Reverse Iterator implementation that switches from the entry array to the overflow entries
* appropriately.
*/
private class DescendingEntryIterator implements Iterator<Map.Entry<K, V>> {
private int pos = entryList.size();
private Iterator<Map.Entry<K, V>> lazyOverflowIterator;
@Override
public boolean hasNext() {
return (pos > 0 && pos <= entryList.size()) || getOverflowIterator().hasNext();
}
@Override
public Map.Entry<K, V> next() {
if (getOverflowIterator().hasNext()) {
return getOverflowIterator().next();
}
return entryList.get(--pos);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/**
* It is important to create the overflow iterator only after the array entries have been
* iterated over because the overflow entry set changes when the client calls remove() on the
* array entries, which invalidates any existing iterators.
*/
private Iterator<Map.Entry<K, V>> getOverflowIterator() {
if (lazyOverflowIterator == null) {
lazyOverflowIterator = overflowEntriesDescending.entrySet().iterator();
}
return lazyOverflowIterator;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SmallSortedMap)) {
return super.equals(o);
}
SmallSortedMap<?, ?> other = (SmallSortedMap<?, ?>) o;
final int size = size();
if (size != other.size()) {
return false;
}
// Best effort try to avoid allocating an entry set.
final int numArrayEntries = getNumArrayEntries();
if (numArrayEntries != other.getNumArrayEntries()) {
return entrySet().equals(other.entrySet());
}
for (int i = 0; i < numArrayEntries; i++) {
if (!getArrayEntryAt(i).equals(other.getArrayEntryAt(i))) {
return false;
}
}
if (numArrayEntries != size) {
return overflowEntries.equals(other.overflowEntries);
}
return true;
}
@Override
public int hashCode() {
int h = 0;
final int listSize = getNumArrayEntries();
for (int i = 0; i < listSize; i++) {
h += entryList.get(i).hashCode();
}
// Avoid the iterator allocation if possible.
if (getNumOverflowEntries() > 0) {
h += overflowEntries.hashCode();
}
return h;
}
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/SmallSortedMap.java |
701 | package NIET;
import java.util.ArrayList;
import java.util.Stack;
public class GTIntro{
public static class Node{
int data;
ArrayList<Node> children = new ArrayList<>();
Node(int data){
this.data = data;
}
}
public static void display(Node node){
System.out.print(node.data+" -> ");
for(Node child : node.children){
System.out.print(child.data+" ");
}
System.out.println(".");
for(Node child : node.children){
display(child);
}
}
public static Node construct(int input[]){
Stack<Node> st = new Stack<>();
Node root = new Node(input[0]);
st.push(root);
for(int idx = 1 ; idx < input.length ; idx++){
int val = input[idx];
if(val == -1){
st.pop();
}else{
Node node = new Node(val);
st.peek().children.add(node);
st.push(node);
}
}
return root;
}
public static void main(String args[]){
int input[] = {10 , 20, -1,30,40,50,60,-1,-1,-1,70,-1,-1,90,100,110,140,-1,-1,120,130,-1,-1,-1,-1,-1};
Node root = construct(input);
}
} | MohitBehl/pepBatches | NIET/GTIntro.java |
702 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.doris.load;
import com.google.common.collect.Maps;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
public class MiniEtlJobInfo extends EtlJobInfo {
// be reports etl task status to fe, and fe also actively get etl task status from be every 5 times
private static final int GET_STATUS_INTERVAL_TIMES = 5;
// load checker check etl job status times
private int checkTimes;
// etlTaskId -> etlTaskInfo
private Map<Long, MiniEtlTaskInfo> idToEtlTask;
public MiniEtlJobInfo() {
super();
checkTimes = 0;
idToEtlTask = Maps.newHashMap();
}
public boolean needGetTaskStatus() {
if (++checkTimes % GET_STATUS_INTERVAL_TIMES == 0) {
return true;
}
return false;
}
public Map<Long, MiniEtlTaskInfo> getEtlTasks() {
return idToEtlTask;
}
public MiniEtlTaskInfo getEtlTask(long taskId) {
return idToEtlTask.get(taskId);
}
public void setEtlTasks(Map<Long, MiniEtlTaskInfo> idToEtlTask) {
this.idToEtlTask = idToEtlTask;
}
@Override
public void write(DataOutput out) throws IOException {
super.write(out);
out.writeInt(idToEtlTask.size());
for (MiniEtlTaskInfo taskInfo : idToEtlTask.values()) {
taskInfo.write(out);
}
}
public void readFields(DataInput in) throws IOException {
super.readFields(in);
int taskNum = in.readInt();
for (int i = 0; i < taskNum; ++i) {
MiniEtlTaskInfo taskInfo = new MiniEtlTaskInfo();
taskInfo.readFields(in);
idToEtlTask.put(taskInfo.getId(), taskInfo);
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
return true;
}
}
| apache/doris | fe/fe-core/src/main/java/org/apache/doris/load/MiniEtlJobInfo.java |
703 | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package routing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import core.Connection;
import core.DTNHost;
import core.Message;
import core.Settings;
import core.SimClock;
import core.Tuple;
/**
* Implementation of PRoPHET router as described in
* <I>Probabilistic routing in intermittently connected networks</I> by
* Anders Lindgren et al.
*
*
* This version tries to estimate a good value of protocol parameters from
* a timescale parameter given by the user, and from the encounters the node
* sees during simulation.
* Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing
* Protocols</I> Chants, 2008
*
*/
public class ProphetRouterWithEstimation extends ActiveRouter {
/** delivery predictability initialization constant*/
public static final double P_INIT = 0.75;
/** delivery predictability transitivity scaling constant default value */
public static final double DEFAULT_BETA = 0.25;
/** delivery predictability aging constant */
public static final double GAMMA = 0.98;
/** default P target */
public static final double DEFAULT_PTARGET = .2;
/** Prophet router's setting namespace ({@value})*/
public static final String PROPHET_NS = "ProphetRouterWithEstimation";
/**
* Number of seconds in time scale.*/
public static final String TIME_SCALE_S ="timeScale";
/**
* Target P_avg
*
*/
public static final String P_AVG_TARGET_S = "targetPavg";
/**
* Transitivity scaling constant (beta) -setting id ({@value}).
* Default value for setting is {@link #DEFAULT_BETA}.
*/
public static final String BETA_S = "beta";
/** values of parameter settings */
private double beta;
private double gamma;
private double pinit;
/** value of time scale variable */
private int timescale;
private double ptavg;
/** delivery predictabilities */
private Map<DTNHost, Double> preds;
/** last meeting time with a node */
private Map<DTNHost, Double> meetings;
private int nrofSamples;
private double meanIET;
/** last delivery predictability update (sim)time */
private double lastAgeUpdate;
/**
* Constructor. Creates a new message router based on the settings in
* the given Settings object.
* @param s The settings object
*/
public ProphetRouterWithEstimation(Settings s) {
super(s);
Settings prophetSettings = new Settings(PROPHET_NS);
timescale = prophetSettings.getInt(TIME_SCALE_S);
if (prophetSettings.contains(P_AVG_TARGET_S)) {
ptavg = prophetSettings.getDouble(P_AVG_TARGET_S);
} else {
ptavg = DEFAULT_PTARGET;
}
if (prophetSettings.contains(BETA_S)) {
beta = prophetSettings.getDouble(BETA_S);
} else {
beta = DEFAULT_BETA;
}
gamma = GAMMA;
pinit = P_INIT;
initPreds();
initMeetings();
}
/**
* Copyconstructor.
* @param r The router prototype where setting values are copied from
*/
protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) {
super(r);
this.timescale = r.timescale;
this.ptavg = r.ptavg;
this.beta = r.beta;
initPreds();
initMeetings();
}
/**
* Initializes predictability hash
*/
private void initPreds() {
this.preds = new HashMap<DTNHost, Double>();
}
/**
* Initializes interencounter time estimator
*/
private void initMeetings() {
this.meetings = new HashMap<DTNHost, Double>();
this.meanIET = 0;
this.nrofSamples = 0;
}
@Override
public void changedConnection(Connection con) {
if (con.isUp()) {
DTNHost otherHost = con.getOtherNode(getHost());
if (updateIET(otherHost)) {
updateParams();
}
updateDeliveryPredFor(otherHost);
updateTransitivePreds(otherHost);
}
}
/**
* Updates the interencounter time estimates
* @param host
*/
private boolean updateIET(DTNHost host) {
/* First estimate the mean InterEncounter Time */
double currentTime = SimClock.getTime();
if (meetings.containsKey(host)) {
double timeDiff = currentTime - meetings.get(host);
// System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host));
nrofSamples++;
meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET
+ (1 / (double)nrofSamples) * timeDiff;
meetings.put(host, currentTime);
return true;
} else {
/* nothing to update */
meetings.put(host,currentTime);
return false;
}
}
/**
* update PROPHET parameters
*
*/
private void updateParams()
{
double b;
double zeta;
double err;
boolean cond;
int ntarg;
double zetadiff;
int ozeta;
double pstable;
double pavg;
double ee;
double bdiff;
int ob;
int zcount;
boolean bcheck;
double pnzero;
double pnone;
double eezero;
double eeone;
/*
* the estimation algorith does not work for timescales
* shorter than the mean IET - so use defaults
*/
if (meanIET > (double)timescale) {
System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale);
return;
}
if (meanIET == 0) {
System.out.printf("Mean IET == 0\n");
return;
}
System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET);
b = 1e-5;
zeta = .9;
err = 0.005;
zetadiff = .1;
ozeta = 0;
cond = false;
ntarg = (int)Math.ceil((double)timescale/(double)meanIET);
while (cond == false) {
pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta);
pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) *
(1- Math.exp( -b*meanIET));
if (Double.isNaN(pavg)) {
pavg = 1;
}
if (pavg > ptavg) {
//System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg);
if (ozeta == 2) {
zetadiff = zetadiff / 2.0;
}
ozeta = 1;
zeta = zeta + zetadiff;
if (zeta >= 1) {
zeta = 1-zetadiff;
zetadiff = zetadiff / 2.0;
ozeta = 0;
}
} else {
if (pavg < ptavg * (1-err)) {
// System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg);
if (ozeta == 1) {
zetadiff = zetadiff / 2.0;
}
ozeta = 2;
zeta = zeta-zetadiff;
if (zeta <= 0) {
zeta = 0 + zetadiff;
zetadiff = zetadiff / 2.0;
ozeta = 0;
}
} else {
cond = true;
}
}
//System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff);
ee = 1;
bdiff = .1;
ob = 0;
zcount = 0; // if 100 iterations won't help, lets increase zeta...
bcheck = false;
while (bcheck == false) {
pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta);
pnzero = Math.exp(-b*meanIET) * (1-zeta) *
((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/
(1-zeta*Math.exp(-b*meanIET)));
pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero;
eezero = Math.abs(pnzero-pstable);
eeone = Math.abs(pnone -pstable);
ee = Math.max(eezero,eeone);
// System.out.printf("Zeta: %f\n", zeta);
// System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable);
// System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone);
// System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone);
if (ee > err) {
if (ob == 2) {
bdiff = bdiff / 2.0;
}
ob = 1;
b = b+bdiff;
} else {
if (ee < (err*(1-err))) {
if (ob == 1) {
bdiff = bdiff / 2.0;
}
ob = 2;
b = b-bdiff;
if (b <= 0) {
b = 0 + bdiff;
bdiff = bdiff / 1.5;
ob = 0;
}
} else {
bcheck = true;
// System.out.println("******");
}
}
// System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff);
zcount = zcount + 1;
if (zcount > 100) {
bcheck = true;
ozeta = 0;
}
}
}
gamma = Math.exp(-b);
pinit = 1-zeta;
}
/**
* Updates delivery predictions for a host.
* <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE>
* @param host The host we just met
*/
private void updateDeliveryPredFor(DTNHost host) {
double oldValue = getPredFor(host);
double newValue = oldValue + (1 - oldValue) * pinit;
preds.put(host, newValue);
}
/**
* Returns the current prediction (P) value for a host or 0 if entry for
* the host doesn't exist.
* @param host The host to look the P for
* @return the current P value
*/
public double getPredFor(DTNHost host) {
ageDeliveryPreds(); // make sure preds are updated before getting
if (preds.containsKey(host)) {
return preds.get(host);
}
else {
return 0;
}
}
/**
* Updates transitive (A->B->C) delivery predictions.
* <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA
* </CODE>
* @param host The B host who we just met
*/
private void updateTransitivePreds(DTNHost host) {
MessageRouter otherRouter = host.getRouter();
assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " +
" with other routers of same type";
double pForHost = getPredFor(host); // P(a,b)
Map<DTNHost, Double> othersPreds =
((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds();
for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) {
if (e.getKey() == getHost()) {
continue; // don't add yourself
}
double pOld = getPredFor(e.getKey()); // P(a,c)_old
double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta;
preds.put(e.getKey(), pNew);
}
}
/**
* Ages all entries in the delivery predictions.
* <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of
* time units that have elapsed since the last time the metric was aged.
* @see #SECONDS_IN_UNIT_S
*/
private void ageDeliveryPreds() {
double timeDiff = (SimClock.getTime() - this.lastAgeUpdate);
if (timeDiff == 0) {
return;
}
double mult = Math.pow(gamma, timeDiff);
for (Map.Entry<DTNHost, Double> e : preds.entrySet()) {
e.setValue(e.getValue()*mult);
}
this.lastAgeUpdate = SimClock.getTime();
}
/**
* Returns a map of this router's delivery predictions
* @return a map of this router's delivery predictions
*/
private Map<DTNHost, Double> getDeliveryPreds() {
ageDeliveryPreds(); // make sure the aging is done
return this.preds;
}
@Override
public void update() {
super.update();
if (!canStartTransfer() ||isTransferring()) {
return; // nothing to transfer or is currently transferring
}
// try messages that could be delivered to final recipient
if (exchangeDeliverableMessages() != null) {
return;
}
tryOtherMessages();
}
/**
* Tries to send all other messages to all connected hosts ordered by
* their delivery probability
* @return The return value of {@link #tryMessagesForConnected(List)}
*/
private Tuple<Message, Connection> tryOtherMessages() {
List<Tuple<Message, Connection>> messages =
new ArrayList<Tuple<Message, Connection>>();
Collection<Message> msgCollection = getMessageCollection();
/* for all connected hosts collect all messages that have a higher
probability of delivery by the other host */
for(Connection con : getHost()) {
// for (Connection con : getConnections()) {
DTNHost other = con.getOtherNode(getHost());
ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter();
if (othRouter.isTransferring()) {
continue; // skip hosts that are transferring
}
for (Message m : msgCollection) {
if (othRouter.hasMessage(m.getId())) {
continue; // skip messages that the other one has
}
if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) {
// the other node has higher probability of delivery
messages.add(new Tuple<Message, Connection>(m,con));
}
}
}
if (messages.size() == 0) {
return null;
}
// sort the message-connection tuples
Collections.sort(messages, new TupleComparator());
return tryMessagesForConnected(messages); // try to send messages
}
/**
* Comparator for Message-Connection-Tuples that orders the tuples by
* their delivery probability by the host on the other side of the
* connection (GRTRMax)
*/
private class TupleComparator implements Comparator
<Tuple<Message, Connection>> {
public int compare(Tuple<Message, Connection> tuple1,
Tuple<Message, Connection> tuple2) {
// delivery probability of tuple1's message with tuple1's connection
double p1 = ((ProphetRouterWithEstimation)tuple1.getValue().
getOtherNode(getHost()).getRouter()).getPredFor(
tuple1.getKey().getTo());
// -"- tuple2...
double p2 = ((ProphetRouterWithEstimation)tuple2.getValue().
getOtherNode(getHost()).getRouter()).getPredFor(
tuple2.getKey().getTo());
// bigger probability should come first
if (p2-p1 == 0) {
/* equal probabilities -> let queue mode decide */
return compareByQueueMode(tuple1.getKey(), tuple2.getKey());
}
else if (p2-p1 < 0) {
return -1;
}
else {
return 1;
}
}
}
@Override
public RoutingInfo getRoutingInfo() {
ageDeliveryPreds();
RoutingInfo top = super.getRoutingInfo();
RoutingInfo ri = new RoutingInfo(preds.size() +
" delivery prediction(s)");
for (Map.Entry<DTNHost, Double> e : preds.entrySet()) {
DTNHost host = e.getKey();
Double value = e.getValue();
ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f",
host, value)));
}
ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples)));
ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma)));
ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit)));
top.addMoreInfo(ri);
return top;
}
@Override
public MessageRouter replicate() {
ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this);
return r;
}
}
| knightcode/the-one-pitt | routing/ProphetRouterWithEstimation.java |
704 | package edu.stanford.nlp.simple;
import edu.stanford.nlp.coref.data.CorefChain;
import edu.stanford.nlp.ie.util.RelationTriple;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.tokensregex.TokenSequenceMatcher;
import edu.stanford.nlp.ling.tokensregex.TokenSequencePattern;
import edu.stanford.nlp.naturalli.OperatorSpec;
import edu.stanford.nlp.naturalli.Polarity;
import edu.stanford.nlp.naturalli.SentenceFragment;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.Annotator;
import edu.stanford.nlp.pipeline.CoreNLPProtos;
import edu.stanford.nlp.pipeline.ProtobufAnnotationSerializer;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.semgraph.SemanticGraphFactory;
import edu.stanford.nlp.semgraph.semgrex.SemgrexMatcher;
import edu.stanford.nlp.semgraph.semgrex.SemgrexPattern;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
/**
* A representation of a single Sentence.
* Although it is possible to create a sentence directly from text, it is advisable to
* create a document instead and operate on the document directly.
*
* @author Gabor Angeli
*/
@SuppressWarnings({"UnusedDeclaration", "WeakerAccess"})
public class Sentence {
/** A Properties object for creating a document from a single sentence. Used in the constructor {@link Sentence#Sentence(String)} */
static Properties SINGLE_SENTENCE_DOCUMENT = PropertiesUtils.asProperties(
"language", "english",
"ssplit.isOneSentence", "true",
"tokenize.class", "PTBTokenizer",
"tokenize.language", "en",
"mention.type", "dep",
"coref.mode", "statistical", // Use the new coref
"coref.md.type", "dep"
);
/** A Properties object for creating a document from a single tokenized sentence. */
private static Properties SINGLE_SENTENCE_TOKENIZED_DOCUMENT = PropertiesUtils.asProperties(
"language", "english",
"ssplit.isOneSentence", "true",
"tokenize.class", "WhitespaceTokenizer",
"tokenize.language", "en",
"tokenize.whitespace", "true",
"mention.type", "dep",
"coref.mode", "statistical", // Use the new coref
"coref.md.type", "dep"
); // redundant?
/**
* The protobuf representation of a Sentence.
* Note that this does not necessarily have up to date token information.
*/
private final CoreNLPProtos.Sentence.Builder impl;
/** The protobuf representation of the tokens of a sentence. This has up-to-date information on the tokens */
private final List<CoreNLPProtos.Token.Builder> tokensBuilders;
/** The document this sentence is derived from */
public final Document document;
/** The default properties to use for annotators. */
private final Properties defaultProps;
/** The function to use to create a new document. This is used for the cased() and caseless() functions. */
private final BiFunction<Properties, String, Document> docFn;
/**
* Create a new sentence, using the specified properties as the default properties.
* @param doc The document to link this sentence to.
* @param props The properties to use for tokenizing the sentence.
*/
protected Sentence(Document doc, Properties props) {
// Set document
this.document = doc;
// Set sentence
if (props.containsKey("ssplit.isOneSentence")) {
this.impl = this.document.sentence(0, props).impl;
} else {
Properties modProps = new Properties(props);
modProps.setProperty("ssplit.isOneSentence", "true");
this.impl = this.document.sentence(0, modProps).impl;
}
// Set tokens
this.tokensBuilders = document.sentence(0).tokensBuilders;
// Asserts
assert (this.document.sentence(0).impl == this.impl);
assert (this.document.sentence(0).tokensBuilders == this.tokensBuilders);
// Set the default properties
if (props == SINGLE_SENTENCE_TOKENIZED_DOCUMENT) {
this.defaultProps = SINGLE_SENTENCE_DOCUMENT; // no longer care about tokenization
} else {
this.defaultProps = props;
}
this.docFn = Document::new;
}
/**
* Create a new sentence from some text, and some properties.
* @param text The text of the sentence.
* @param props The properties to use for the annotators.
*/
public Sentence(String text, Properties props) {
this(new Document(props, text), props);
}
/**
* Create a new sentence from the given text, assuming the entire text is just one sentence.
* @param text The text of the sentence.
*/
public Sentence(String text) {
this(text, SINGLE_SENTENCE_DOCUMENT);
}
/** The actual implementation of a tokenized sentence constructor */
protected Sentence(Function<String, Document> doc, List<String> tokens, Properties props) {
this(doc.apply(StringUtils.join(tokens.stream().map(x -> x.replace(' ', 'ߝ' /* some random character */)), " ")), props);
// Clean up whitespace
for (int i = 0; i < impl.getTokenCount(); ++i) {
this.impl.getTokenBuilder(i).setWord(this.impl.getTokenBuilder(i).getWord().replace('ߝ', ' '));
this.impl.getTokenBuilder(i).setValue(this.impl.getTokenBuilder(i).getValue().replace('ߝ', ' '));
this.tokensBuilders.get(i).setWord(this.tokensBuilders.get(i).getWord().replace('ߝ', ' '));
this.tokensBuilders.get(i).setValue(this.tokensBuilders.get(i).getValue().replace('ߝ', ' '));
}
}
/**
* Create a new sentence from the given tokenized text, assuming the entire text is just one sentence.
* WARNING: This method may in rare cases (mostly when tokens themselves have whitespace in them)
* produce strange results; it's a bit of a hack around the default tokenizer.
*
* @param tokens The text of the sentence.
*/
public Sentence(List<String> tokens) {
this(Document::new, tokens, SINGLE_SENTENCE_TOKENIZED_DOCUMENT);
}
/**
* Create a sentence from a saved protocol buffer.
*/
protected Sentence(BiFunction<Properties, String, Document> docFn, CoreNLPProtos.Sentence proto, Properties props) {
this.impl = proto.toBuilder();
// Set tokens
tokensBuilders = new ArrayList<>(this.impl.getTokenCount());
for (int i = 0; i < this.impl.getTokenCount(); ++i) {
tokensBuilders.add(this.impl.getToken(i).toBuilder());
}
// Initialize document
this.document = docFn.apply(props, proto.getText());
this.document.forceSentences(Collections.singletonList(this));
// Asserts
assert (this.document.sentence(0).impl == this.impl);
assert (this.document.sentence(0).tokensBuilders == this.tokensBuilders);
// Set default props
this.defaultProps = props;
this.docFn = docFn;
}
/**
* Create a sentence from a saved protocol buffer.
*/
public Sentence(CoreNLPProtos.Sentence proto) {
this(Document::new, proto, SINGLE_SENTENCE_DOCUMENT);
}
/** Helper for creating a sentence from a document at a given index */
protected Sentence(Document doc, int sentenceIndex) {
this.document = doc;
this.impl = doc.sentence(sentenceIndex).impl;
// Set tokens
this.tokensBuilders = doc.sentence(sentenceIndex).tokensBuilders;
// Asserts
assert (this.document.sentence(sentenceIndex).impl == this.impl);
assert (this.document.sentence(sentenceIndex).tokensBuilders == this.tokensBuilders);
// Set default props
this.defaultProps = Document.EMPTY_PROPS;
this.docFn = doc.sentence(sentenceIndex).docFn;
}
/**
* The canonical constructor of a sentence from a {@link edu.stanford.nlp.simple.Document}.
* @param doc The document to link this sentence to.
* @param proto The sentence implementation to use for this sentence.
*/
protected Sentence(Document doc, CoreNLPProtos.Sentence.Builder proto, Properties defaultProps) {
this.document = doc;
this.impl = proto;
this.defaultProps = defaultProps;
// Set tokens
// This is the _only_ place we are allowed to construct tokens builders
tokensBuilders = new ArrayList<>(this.impl.getTokenCount());
for (int i = 0; i < this.impl.getTokenCount(); ++i) {
tokensBuilders.add(this.impl.getToken(i).toBuilder());
}
this.docFn = (props, text) -> MetaClass.create(doc.getClass().getName()).createInstance(props, text);
}
/**
* Also sets the the text of the sentence. Used by {@link Document} internally
*
* @param doc The document to link this sentence to.
* @param proto The sentence implementation to use for this sentence.
* @param text The text for the sentence
* @param defaultProps The default properties to use when annotating this sentence.
*/
Sentence(Document doc, CoreNLPProtos.Sentence.Builder proto, String text, Properties defaultProps) {
this(doc, proto, defaultProps);
this.impl.setText(text);
}
/** Helper for creating a sentence from a document and a CoreMap representation */
protected Sentence(Document doc, CoreMap sentence) {
this.document = doc;
assert ! doc.sentences().isEmpty();
this.impl = doc.sentence(0).impl;
this.tokensBuilders = doc.sentence(0).tokensBuilders;
this.defaultProps = Document.EMPTY_PROPS;
this.docFn = (props, text) -> MetaClass.create(doc.getClass().getName()).createInstance(props, text);
}
/**
* Convert a CoreMap into a simple Sentence object.
* Note that this is a copy operation -- the implementing CoreMap will not be updated, and all of its
* contents are copied over to the protocol buffer format backing the {@link Sentence} object.
*
* @param sentence The CoreMap representation of the sentence.
*/
public Sentence(CoreMap sentence) {
this(new Document(new Annotation(sentence.get(CoreAnnotations.TextAnnotation.class)) {{
set(CoreAnnotations.SentencesAnnotation.class, Collections.singletonList(sentence));
if (sentence.containsKey(CoreAnnotations.DocIDAnnotation.class)) {
set(CoreAnnotations.DocIDAnnotation.class, sentence.get(CoreAnnotations.DocIDAnnotation.class));
}
}}), sentence);
}
/**
* Convert a sentence fragment (i.e., entailed sentence) into a simple sentence object.
* Like {@link Sentence#Sentence(CoreMap)}, this copies the information in the fragment into the underlying
* protobuf backed format.
*
* @param sentence The sentence fragment to convert.
*/
public Sentence(SentenceFragment sentence) {
this(new ArrayCoreMap(32) {{
set(CoreAnnotations.TokensAnnotation.class, sentence.words);
set(CoreAnnotations.TextAnnotation.class, StringUtils.join(sentence.words.stream().map(CoreLabel::originalText), " "));
if (sentence.words.isEmpty()) {
set(CoreAnnotations.TokenBeginAnnotation.class, 0);
set(CoreAnnotations.TokenEndAnnotation.class, 0);
} else {
set(CoreAnnotations.TokenBeginAnnotation.class, sentence.words.get(0).get(CoreAnnotations.IndexAnnotation.class));
set(CoreAnnotations.TokenEndAnnotation.class, sentence.words.get(sentence.words.size() - 1).get(CoreAnnotations.IndexAnnotation.class) + 1);
}
set(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class, sentence.parseTree);
set(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class, sentence.parseTree);
set(SemanticGraphCoreAnnotations.EnhancedPlusPlusDependenciesAnnotation.class, sentence.parseTree);
}});
}
/**
* Make this sentence caseless. That is, from now on, run the caseless models
* on the sentence by default rather than the standard CoreNLP models.
*
* @return A new sentence with the default properties swapped out.
*/
public Sentence caseless() {
return new Sentence(this.docFn, impl.build(), Document.CASELESS_PROPS);
}
/**
* Make this sentence case sensitive.
* A sentence is case sensitive by default; this only has an effect if you have previously
* called {@link Sentence#caseless()}.
*
* @return A new sentence with the default properties swapped out.
*/
public Sentence cased() {
return new Sentence(this.docFn, impl.build(), Document.EMPTY_PROPS);
}
/**
* Serialize the given sentence (but not the associated document!) into a Protocol Buffer.
*
* @return The Protocol Buffer representing this sentence.
*/
public CoreNLPProtos.Sentence serialize() {
synchronized (impl) {
this.impl.clearToken();
for (CoreNLPProtos.Token.Builder token : this.tokensBuilders) {
this.impl.addToken(token.build());
}
return impl.build();
}
}
/**
* Write this sentence to an output stream.
* Internally, this stores the sentence as a protocol buffer, and saves that buffer to the output stream.
* This method does not close the stream after writing.
*
* @param out The output stream to write to. The stream is not closed after the method returns.
* @throws IOException Thrown from the underlying write() implementation.
*/
public void serialize(OutputStream out) throws IOException {
serialize().writeDelimitedTo(out);
out.flush();
}
/**
* Read a sentence from an input stream.
* This does not close the input stream.
*
* @param in The input stream to deserialize from.
* @return The next sentence encoded in the input stream.
* @throws IOException Thrown by the underlying parse() implementation.
*
* @see Document#serialize(java.io.OutputStream)
*/
public static Sentence deserialize(InputStream in) throws IOException {
return new Sentence(CoreNLPProtos.Sentence.parseDelimitedFrom(in));
}
/**
* Return a class that can perform common algorithms on this sentence.
*/
public SentenceAlgorithms algorithms() {
return new SentenceAlgorithms(this);
}
/** The raw text of the sentence, as input by, e.g., {@link Sentence#Sentence(String)}. */
public String text() {
synchronized (impl) {
return impl.getText();
}
}
//
// SET AXIOMATICALLY
//
/** The index of the sentence within the document. */
public int sentenceIndex() {
synchronized (impl) {
return impl.getSentenceIndex();
}
}
/** THe token offset of the sentence within the document. */
public int sentenceTokenOffsetBegin() {
synchronized (impl) {
return impl.getTokenOffsetBegin();
}
}
/** The token offset of the end of this sentence within the document. */
public int sentenceTokenOffsetEnd() {
synchronized (impl) {
return impl.getTokenOffsetEnd();
}
}
//
// SET BY TOKENIZER
//
/** The words of the sentence, as per {@link edu.stanford.nlp.ling.CoreLabel#word()}. */
public List<String> words() {
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getWord);
}
}
/** The word at the given index of the sentence. @see Sentence#words() */
public String word(int index) {
return words().get(index);
}
/** The original (unprocessed) words of the sentence, as per {@link edu.stanford.nlp.ling.CoreLabel#originalText()}. */
public List<String> originalTexts() {
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getOriginalText);
}
}
/** The original word at the given index. @see Sentence#originalTexts() */
public String originalText(int index) {
return originalTexts().get(index);
}
/** The character offset of each token in the sentence, as per {@link edu.stanford.nlp.ling.CoreLabel#beginPosition()}. */
public List<Integer> characterOffsetBegin() {
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getBeginChar);
}
}
/** The character offset of the given index in the sentence. @see Sentence#characterOffsetBegin(). */
public int characterOffsetBegin(int index) {
return characterOffsetBegin().get(index);
}
/** The end character offset of each token in the sentence, as per {@link edu.stanford.nlp.ling.CoreLabel#endPosition()}. */
public List<Integer> characterOffsetEnd() {
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getEndChar);
}
}
/** The end character offset of the given index in the sentence. @see Sentence#characterOffsetEnd(). */
public int characterOffsetEnd(int index) {
return characterOffsetEnd().get(index);
}
/** The whitespace before each token in the sentence. This will match {@link #after()} of the previous token. */
public List<String> before() {
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getBefore);
}
}
/** The whitespace before this token in the sentence. This will match {@link #after()} of the previous token. */
public String before(int index) {
return before().get(index);
}
/** The whitespace after each token in the sentence. This will match {@link #before()} of the next token. */
public List<String> after() {
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getAfter);
}
}
/** The whitespace after this token in the sentence. This will match {@link #before()} of the next token. */
public String after(int index) {
return after().get(index);
}
/** The tokens in this sentence. Each token class is just a helper for the methods in this class. */
public List<Token> tokens() {
ArrayList<Token> tokens = new ArrayList<>(this.length());
for (int i = 0; i < length(); ++i) {
tokens.add(new Token(this, i));
}
return tokens;
}
//
// SET BY ANNOTATORS
//
/**
* The part of speech tags of the sentence.
* @param props The properties to use for the {@link edu.stanford.nlp.pipeline.POSTaggerAnnotator}.
* @return A list of part of speech tags, one for each token in the sentence.
*/
public List<String> posTags(Properties props) {
document.runPOS(props);
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getPos);
}
}
/** @see Sentence#posTags(java.util.Properties) */
public List<String> posTags() {
return posTags(this.defaultProps);
}
/** @see Sentence#posTags(java.util.Properties) */
public String posTag(int index) {
return posTags().get(index);
}
/**
* The lemmas of the sentence.
* @param props The properties to use for the {@link edu.stanford.nlp.pipeline.MorphaAnnotator}.
* @return A list of lemmatized words, one for each token in the sentence.
*/
public List<String> lemmas(Properties props) {
document.runLemma(props);
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getLemma);
}
}
/** @see Sentence#lemmas(java.util.Properties) */
public List<String> lemmas() {
return lemmas(this.defaultProps);
}
/** @see Sentence#lemmas(java.util.Properties) */
public String lemma(int index) {
return lemmas().get(index);
}
/**
* The named entity tags of the sentence.
* @param props The properties to use for the {@link edu.stanford.nlp.pipeline.NERCombinerAnnotator}.
* @return A list of named entity tags, one for each token in the sentence.
*/
public List<String> nerTags(Properties props) {
document.runNER(props);
synchronized (impl) {
return lazyList(tokensBuilders, CoreNLPProtos.Token.Builder::getNer);
}
}
/** @see Sentence#nerTags(java.util.Properties) */
public List<String> nerTags() {
return nerTags(this.defaultProps);
}
/**
* Run RegexNER over this sentence. Note that this is an in place operation, and simply
* updates the NER tags.
* Therefore, every time this function is called, it re-runs the annotator!
*
* @param mappingFile The regexner mapping file.
* @param ignorecase If true, run a caseless match on the regexner file.
*/
public void regexner(String mappingFile, boolean ignorecase) {
Properties props = new Properties();
for (Object prop : this.defaultProps.keySet()) {
props.setProperty(prop.toString(), this.defaultProps.getProperty(prop.toString()));
}
props.setProperty(Annotator.STANFORD_REGEXNER + ".mapping", mappingFile);
props.setProperty(Annotator.STANFORD_REGEXNER + ".ignorecase", Boolean.toString(ignorecase));
this.document.runRegexner(props);
}
/** @see Sentence#nerTags(java.util.Properties) */
public String nerTag(int index) {
return nerTags().get(index);
}
/**
* Get all mentions of the given NER tag, as a list of surface forms.
* @param nerTag The ner tag to search for, case sensitive.
* @return A list of surface forms of the entities of this tag. This is using the {@link Sentence#word(int)} function.
*/
public List<String> mentions(String nerTag) {
List<String> mentionsOfTag = new ArrayList<>();
StringBuilder lastMention = new StringBuilder();
String lastTag = "O";
for (int i = 0; i < length(); ++i) {
String ner = nerTag(i);
if (ner.equals(nerTag) && !lastTag.equals(nerTag)) {
// case: beginning of span
lastMention.append(word(i)).append(' ');
} else if (ner.equals(nerTag) && lastTag.equals(nerTag)) {
// case: in span
lastMention.append(word(i)).append(' ');
} else if (!ner.equals(nerTag) && lastTag.equals(nerTag)) {
// case: end of span
if (lastMention.length() > 0) {
mentionsOfTag.add(lastMention.toString().trim());
}
lastMention.setLength(0);
}
lastTag = ner;
}
if (lastMention.length() > 0) {
mentionsOfTag.add(lastMention.toString().trim());
}
return mentionsOfTag;
}
/**
* Get all mentions of any NER tag, as a list of surface forms.
* @return A list of surface forms of the entities in this sentence. This is using the {@link Sentence#word(int)} function.
*/
public List<String> mentions() {
List<String> mentionsOfTag = new ArrayList<>();
StringBuilder lastMention = new StringBuilder();
String lastTag = "O";
for (int i = 0; i < length(); ++i) {
String ner = nerTag(i);
if (!ner.equals("O") && !lastTag.equals(ner)) {
// case: beginning of span
if (lastMention.length() > 0) {
mentionsOfTag.add(lastMention.toString().trim());
}
lastMention.setLength(0);
lastMention.append(word(i)).append(' ');
} else if (!ner.equals("O") && lastTag.equals(ner)) {
// case: in span
lastMention.append(word(i)).append(' ');
} else if (ner.equals("O") && !lastTag.equals("O")) {
// case: end of span
if (lastMention.length() > 0) {
mentionsOfTag.add(lastMention.toString().trim());
}
lastMention.setLength(0);
}
lastTag = ner;
}
if (lastMention.length() > 0) {
mentionsOfTag.add(lastMention.toString().trim());
}
return mentionsOfTag;
}
/**
* Returns the constituency parse of this sentence.
*
* @param props The properties to use in the parser annotator.
* @return A parse tree object.
*/
public Tree parse(Properties props) {
document.runParse(props);
synchronized (document.serializer) {
return document.serializer.fromProto(impl.getParseTree());
}
}
/** @see Sentence#parse(java.util.Properties) */
public Tree parse() {
return parse(this.defaultProps);
}
/** An internal helper to get the dependency tree of the given type. */
private CoreNLPProtos.DependencyGraph dependencies(SemanticGraphFactory.Mode mode) {
switch (mode) {
case BASIC:
return impl.getBasicDependencies();
case ENHANCED:
return impl.getEnhancedDependencies();
case ENHANCED_PLUS_PLUS:
return impl.getEnhancedPlusPlusDependencies();
default:
throw new IllegalArgumentException("Unsupported dependency type: " + mode);
}
}
/**
* Returns the governor of the given index, according to the passed dependency type.
* The root has index -1.
*
* @param props The properties to use in the parser annotator.
* @param index The index of the dependent word ZERO INDEXED. That is, the first word of the sentence
* is index 0, not 1 as it would be in the {@link edu.stanford.nlp.semgraph.SemanticGraph} framework.
* @param mode The type of dependency to use (e.g., basic, collapsed, collapsed cc processed).
* @return The index of the governor, if one exists. A value of -1 indicates the root node.
*/
public Optional<Integer> governor(Properties props, int index, SemanticGraphFactory.Mode mode) {
document.runDepparse(props);
for (CoreNLPProtos.DependencyGraph.Edge edge : dependencies(mode).getEdgeList()) {
if (edge.getTarget() - 1 == index) {
return Optional.of(edge.getSource() - 1);
}
}
for (int root : impl.getBasicDependencies().getRootList()) {
if (index == root - 1) { return Optional.of(-1); }
}
return Optional.empty();
}
/** @see Sentence#governor(java.util.Properties, int, SemanticGraphFactory.Mode) */
public Optional<Integer> governor(Properties props, int index) {
return governor(props, index, SemanticGraphFactory.Mode.ENHANCED);
}
/** @see Sentence#governor(java.util.Properties, int, SemanticGraphFactory.Mode) */
public Optional<Integer> governor(int index, SemanticGraphFactory.Mode mode) {
return governor(this.defaultProps, index, mode);
}
/** @see Sentence#governor(java.util.Properties, int) */
public Optional<Integer> governor(int index) {
return governor(this.defaultProps, index);
}
/**
* Returns the governors of a sentence, according to the passed dependency type.
* The resulting list is of the same size as the original sentence, with each element being either
* the governor (index), or empty if the node has no known governor.
* The root has index -1.
*
* @param props The properties to use in the parser annotator.
* @param mode The type of dependency to use (e.g., basic, collapsed, collapsed cc processed).
* @return A list of the (optional) governors of each token in the sentence.
*/
public List<Optional<Integer>> governors(Properties props, SemanticGraphFactory.Mode mode) {
document.runDepparse(props);
List<Optional<Integer>> governors = new ArrayList<>(this.length());
for (int i = 0; i < this.length(); ++i) { governors.add(Optional.empty()); }
for (CoreNLPProtos.DependencyGraph.Edge edge : dependencies(mode).getEdgeList()) {
governors.set(edge.getTarget() - 1, Optional.of(edge.getSource() - 1));
}
for (int root : impl.getBasicDependencies().getRootList()) {
governors.set(root - 1, Optional.of(-1));
}
return governors;
}
/** @see Sentence#governors(java.util.Properties, SemanticGraphFactory.Mode) */
public List<Optional<Integer>> governors(Properties props) {
return governors(props, SemanticGraphFactory.Mode.ENHANCED);
}
/** @see Sentence#governors(java.util.Properties, SemanticGraphFactory.Mode) */
public List<Optional<Integer>> governors(SemanticGraphFactory.Mode mode) {
return governors(this.defaultProps, mode);
}
/** @see Sentence#governors(java.util.Properties, SemanticGraphFactory.Mode) */
public List<Optional<Integer>> governors() {
return governors(this.defaultProps, SemanticGraphFactory.Mode.ENHANCED);
}
/**
* Returns the incoming dependency label to a particular index, according to the Basic Dependencies.
*
* @param props The properties to use in the parser annotator.
* @param index The index of the dependent word ZERO INDEXED. That is, the first word of the sentence
* is index 0, not 1 as it would be in the {@link edu.stanford.nlp.semgraph.SemanticGraph} framework.
* @param mode The type of dependency to use (e.g., basic, collapsed, collapsed cc processed).
* @return The incoming dependency label, if it exists.
*/
public Optional<String> incomingDependencyLabel(Properties props, int index, SemanticGraphFactory.Mode mode) {
document.runDepparse(props);
for (CoreNLPProtos.DependencyGraph.Edge edge : dependencies(mode).getEdgeList()) {
if (edge.getTarget() - 1 == index) {
return Optional.of(edge.getDep());
}
}
for (int root : impl.getBasicDependencies().getRootList()) {
if (index == root - 1) { return Optional.of("root"); }
}
return Optional.empty();
}
/** @see Sentence#incomingDependencyLabel(java.util.Properties, int, SemanticGraphFactory.Mode) */
public Optional<String> incomingDependencyLabel(Properties props, int index) {
return incomingDependencyLabel(props, index, SemanticGraphFactory.Mode.ENHANCED);
}
/** @see Sentence#incomingDependencyLabel(java.util.Properties, int, SemanticGraphFactory.Mode) */
public Optional<String> incomingDependencyLabel(int index, SemanticGraphFactory.Mode mode) {
return incomingDependencyLabel(this.defaultProps, index, mode);
}
/** @see Sentence#incomingDependencyLabel(java.util.Properties, int) */
public Optional<String> incomingDependencyLabel(int index) {
return incomingDependencyLabel(this.defaultProps, index);
}
/** @see Sentence#incomingDependencyLabel(java.util.Properties, int) */
public List<Optional<String>> incomingDependencyLabels(Properties props, SemanticGraphFactory.Mode mode) {
document.runDepparse(props);
List<Optional<String>> labels = new ArrayList<>(this.length());
for (int i = 0; i < this.length(); ++i) { labels.add(Optional.empty()); }
for (CoreNLPProtos.DependencyGraph.Edge edge : dependencies(mode).getEdgeList()) {
labels.set(edge.getTarget() - 1, Optional.of(edge.getDep()));
}
for (int root : impl.getBasicDependencies().getRootList()) {
labels.set(root - 1, Optional.of("root"));
}
return labels;
}
/** @see Sentence#incomingDependencyLabels(java.util.Properties, SemanticGraphFactory.Mode) */
public List<Optional<String>> incomingDependencyLabels(SemanticGraphFactory.Mode mode) {
return incomingDependencyLabels(this.defaultProps, mode);
}
/** @see Sentence#incomingDependencyLabels(java.util.Properties, SemanticGraphFactory.Mode) */
public List<Optional<String>> incomingDependencyLabels(Properties props) {
return incomingDependencyLabels(props, SemanticGraphFactory.Mode.ENHANCED);
}
/** @see Sentence#incomingDependencyLabels(java.util.Properties, SemanticGraphFactory.Mode) */
public List<Optional<String>> incomingDependencyLabels() {
return incomingDependencyLabels(this.defaultProps, SemanticGraphFactory.Mode.ENHANCED);
}
/**
* Returns the dependency graph of the sentence, as a raw {@link SemanticGraph} object.
* Note that this method is slower than you may expect, as it has to convert the underlying protocol
* buffer back into a list of CoreLabels with which to populate the {@link SemanticGraph}.
*
* @param props The properties to use for running the dependency parser annotator.
* @param mode The type of graph to return (e.g., basic, collapsed, etc).
*
* @return The dependency graph of the sentence.
*/
public SemanticGraph dependencyGraph(Properties props, SemanticGraphFactory.Mode mode) {
document.runDepparse(props);
return ProtobufAnnotationSerializer.fromProto(dependencies(mode), asCoreLabels(), document.docid().orElse(null));
}
/** @see Sentence#dependencyGraph(Properties, SemanticGraphFactory.Mode) */
public SemanticGraph dependencyGraph(Properties props) {
return dependencyGraph(props, SemanticGraphFactory.Mode.ENHANCED);
}
/** @see Sentence#dependencyGraph(Properties, SemanticGraphFactory.Mode) */
public SemanticGraph dependencyGraph() {
return dependencyGraph(this.defaultProps, SemanticGraphFactory.Mode.ENHANCED);
}
/** @see Sentence#dependencyGraph(Properties, SemanticGraphFactory.Mode) */
public SemanticGraph dependencyGraph(SemanticGraphFactory.Mode mode) {
return dependencyGraph(this.defaultProps, mode);
}
/** The length of the sentence, in tokens */
public int length() {
return impl.getTokenCount();
}
/**
* Get a list of the (possible) Natural Logic operators on each node of the sentence.
* At each index, the list contains an operator spec if that index is the head word of an operator in the
* sentence.
*
* @param props The properties to pass to the natural logic annotator.
* @return A list of Optionals, where each element corresponds to a token in the sentence, and the optional is nonempty
* if that index is an operator.
*/
public List<Optional<OperatorSpec>> operators(Properties props) {
document.runNatlog(props);
synchronized (impl) {
return lazyList(tokensBuilders, x -> x.hasOperator() ? Optional.of(ProtobufAnnotationSerializer.fromProto(x.getOperator())) : Optional.empty());
}
}
/** @see Sentence#operators(Properties) */
public List<Optional<OperatorSpec>> operators() {
return operators(this.defaultProps);
}
/** @see Sentence#operators(Properties) */
public Optional<OperatorSpec> operatorAt(Properties props, int i) {
return operators(props).get(i);
}
/** @see Sentence#operators(Properties) */
public Optional<OperatorSpec> operatorAt(int i) {
return operators(this.defaultProps).get(i);
}
/**
* Returns the list of non-empty Natural Logic operator specifications.
* This amounts to the actual list of operators in the sentence.
* Note that the spans of the operators can be retrieved with
* {@link OperatorSpec#quantifierBegin} and
* {@link OperatorSpec#quantifierEnd}.
*
* @param props The properties to use for the natlog annotator.
* @return A list of operators in the sentence.
*/
public List<OperatorSpec> operatorsNonempty(Properties props) {
return operators(props).stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}
/** @see Sentence#operatorsNonempty(Properties) */
public List<OperatorSpec> operatorsNonempty() {
return operatorsNonempty(this.defaultProps);
}
/**
* The Natural Logic notion of polarity for each token in a sentence.
* @param props The properties to use for the natural logic annotator.
* @return A list of Polarity objects, one for each token of the sentence.
*/
public List<Polarity> natlogPolarities(Properties props) {
document.runNatlog(props);
synchronized (impl) {
return lazyList(tokensBuilders, x -> ProtobufAnnotationSerializer.fromProto(x.getPolarity()));
}
}
/** @see Sentence#natlogPolarities(Properties) */
public List<Polarity> natlogPolarities() {
return natlogPolarities(this.defaultProps);
}
/**
* Get the polarity (the Natural Logic notion of polarity) for a given token in the sentence.
* @param props The properties to use for the natural logic annotator.
* @param index The index to return the polarity of.
* @return A list of Polarity objects, one for each token of the sentence.
*/
public Polarity natlogPolarity(Properties props, int index) {
document.runNatlog(props);
synchronized (impl) {
return ProtobufAnnotationSerializer.fromProto(tokensBuilders.get(index).getPolarity());
}
}
/** @see Sentence#natlogPolarity(Properties, int) */
public Polarity natlogPolarity(int index) {
return natlogPolarity(this.defaultProps, index);
}
/**
* Get the OpenIE triples associated with this sentence.
* Note that this function may be slower than you would expect, as it has to
* convert the underlying Protobuf representation back into {@link CoreLabel}s.
*
* @param props The properties to use for the OpenIE annotator.
* @return A collection of {@link RelationTriple} objects representing the OpenIE triples in the sentence.
*/
public Collection<RelationTriple> openieTriples(Properties props) {
document.runOpenie(props);
synchronized (impl) {
List<CoreLabel> tokens = asCoreLabels();
Annotation doc = document.asAnnotation();
return impl.getOpenieTripleList().stream().map(x -> ProtobufAnnotationSerializer.fromProto(x, doc, this.sentenceIndex())).collect(Collectors.toList());
}
}
/** @see Sentence@openieTriples(Properties) */
public Collection<RelationTriple> openieTriples() {
return openieTriples(this.defaultProps);
}
/**
* Get a list of Open IE triples as flat (subject, relation, object, confidence) quadruples.
* This is substantially faster than returning {@link RelationTriple} objects, as it doesn't
* require converting the underlying representation into {@link CoreLabel}s; but, it also contains
* significantly less information about the sentence.
*
* @see Sentence@openieTriples(Properties)
*/
public Collection<Quadruple<String, String, String, Double>> openie() {
document.runOpenie(this.defaultProps);
return impl.getOpenieTripleList().stream()
.filter(proto -> proto.hasSubject() && proto.hasRelation() && proto.hasObject())
.map(proto -> Quadruple.makeQuadruple(proto.getSubject(), proto.getRelation(), proto.getObject(),
proto.hasConfidence() ? proto.getConfidence() : 1.0))
.collect(Collectors.toList());
}
/**
* Get the KBP triples associated with this sentence.
* Note that this function may be slower than you would expect, as it has to
* convert the underlying Protobuf representation back into {@link CoreLabel}s.
*
* @param props The properties to use for the KBP annotator.
* @return A collection of {@link RelationTriple} objects representing the KBP triples in the sentence.
*/
public Collection<RelationTriple> kbpTriples(Properties props) {
document.runKBP(props);
synchronized (impl) {
List<CoreLabel> tokens = asCoreLabels();
Annotation doc = document.asAnnotation();
return impl.getKbpTripleList().stream().map(x -> ProtobufAnnotationSerializer.fromProto(x, doc, this.sentenceIndex())).collect(Collectors.toList());
}
}
/** @see Sentence@kbpTriples(Properties) */
public Collection<RelationTriple> kbpTriples() {
return kbpTriples(this.defaultProps);
}
/**
* Get a list of KBP triples as flat (subject, relation, object, confidence) quadruples.
* This is substantially faster than returning {@link RelationTriple} objects, as it doesn't
* require converting the underlying representation into {@link CoreLabel}s; but, it also contains
* significantly less information about the sentence.
*
* @see Sentence@kbpTriples(Properties)
*/
public Collection<Quadruple<String, String, String, Double>> kbp() {
document.runKBP(this.defaultProps);
return impl.getKbpTripleList().stream()
.filter(proto -> proto.hasSubject() && proto.hasRelation() && proto.hasObject())
.map(proto -> Quadruple.makeQuadruple(proto.getSubject(), proto.getRelation(), proto.getObject(),
proto.hasConfidence() ? proto.getConfidence() : 1.0))
.collect(Collectors.toList());
}
/**
* The sentiment of this sentence (e.g., positive / negative).
*
* @return The {@link SentimentClass} of this sentence, as an enum value.
*/
public SentimentClass sentiment() {
return sentiment(this.defaultProps);
}
/**
* The sentiment of this sentence (e.g., positive / negative).
*
* @param props The properties to pass to the sentiment classifier.
*
* @return The {@link SentimentClass} of this sentence, as an enum value.
*/
public SentimentClass sentiment(Properties props) {
document.runSentiment(props);
switch (impl.getSentiment().toLowerCase()) {
case "very positive":
return SentimentClass.VERY_POSITIVE;
case "positive":
return SentimentClass.POSITIVE;
case "negative":
return SentimentClass.NEGATIVE;
case "very negative":
return SentimentClass.VERY_NEGATIVE;
case "neutral":
return SentimentClass.NEUTRAL;
default:
throw new IllegalStateException("Unknown sentiment class: " + impl.getSentiment());
}
}
/**
* Get the coreference chain for just this sentence.
* Note that this method is actually fairly computationally expensive to call, as it constructs and prunes
* the coreference data structure for the entire document.
*
* @return A coreference chain, but only for this sentence
*/
public Map<Integer, CorefChain> coref() {
// Get the raw coref structure
Map<Integer, CorefChain> allCorefs = document.coref();
// Delete coreference chains not in this sentence
Set<Integer> toDeleteEntirely = new HashSet<>();
for (Map.Entry<Integer, CorefChain> integerCorefChainEntry : allCorefs.entrySet()) {
CorefChain chain = integerCorefChainEntry.getValue();
List<CorefChain.CorefMention> mentions = new ArrayList<>(chain.getMentionsInTextualOrder());
mentions.stream().filter(m -> m.sentNum != this.sentenceIndex() + 1).forEach(chain::deleteMention);
if (chain.getMentionsInTextualOrder().isEmpty()) {
toDeleteEntirely.add(integerCorefChainEntry.getKey());
}
}
// Clean up dangling empty chains
toDeleteEntirely.forEach(allCorefs::remove);
// Return
return allCorefs;
}
//
// Helpers for CoreNLP interoperability
//
/**
* Returns this sentence as a CoreNLP CoreMap object.
* Note that, importantly, only the fields which have already been called will be populated in
* the CoreMap!
*
* Therefore, this method is generally NOT recommended.
*
* @param functions A list of functions to call before populating the CoreMap.
* For example, you can specify mySentence::posTags, and then posTags will
* be populated.
*/
@SuppressWarnings("TypeParameterExplicitlyExtendsObject")
@SafeVarargs
public final CoreMap asCoreMap(Function<Sentence,Object>... functions) {
for (Function<Sentence, Object> function : functions) {
function.apply(this);
}
return this.document.asAnnotation(true).get(CoreAnnotations.SentencesAnnotation.class).get(this.sentenceIndex());
}
/**
* Returns this sentence as a list of CoreLabels representing the sentence.
* Note that, importantly, only the fields which have already been called will be populated in
* the CoreMap!
*
* Therefore, this method is generally NOT recommended.
*
* @param functions A list of functions to call before populating the CoreMap.
* For example, you can specify mySentence::posTags, and then posTags will
* be populated.
*/
@SuppressWarnings("TypeParameterExplicitlyExtendsObject")
@SafeVarargs
public final List<CoreLabel> asCoreLabels(Function<Sentence,Object>... functions) {
for (Function<Sentence, Object> function : functions) {
function.apply(this);
}
return asCoreMap().get(CoreAnnotations.TokensAnnotation.class);
}
//
// HELPERS FROM DOCUMENT
//
/**
* A helper to get the raw Protobuf builder for a given token.
* Primarily useful for cache checks.
* @param i The index of the token to retrieve.
* @return A Protobuf builder for that token.
*/
public CoreNLPProtos.Token.Builder rawToken(int i) {
return tokensBuilders.get(i);
}
/**
* Get the backing protocol buffer for this sentence.
* @return The raw backing protocol buffer builder for this sentence.
*/
public CoreNLPProtos.Sentence.Builder rawSentence() {
return this.impl;
}
/**
* Update each token in the sentence with the given information.
* @param tokens The CoreNLP tokens returned by the {@link edu.stanford.nlp.pipeline.Annotator}.
* @param setter The function to set a Protobuf object with the given field.
* @param getter The function to get the given field from the {@link CoreLabel}.
* @param <E> The type of the given field we are setting in the protocol buffer and reading from the {@link CoreLabel}.
*/
protected <E> void updateTokens(List<CoreLabel> tokens,
Consumer<Pair<CoreNLPProtos.Token.Builder, E>> setter,
Function<CoreLabel, E> getter) {
synchronized (this.impl) {
for (int i = 0; i < tokens.size(); ++i) {
E value = getter.apply(tokens.get(i));
if (value != null) {
setter.accept(Pair.makePair(tokensBuilders.get(i), value));
}
}
}
}
/**
* Update the parse tree for this sentence.
* @param parse The parse tree to update.
* @param binary The binary parse tree to update.
*/
protected void updateParse(
CoreNLPProtos.ParseTree parse,
CoreNLPProtos.ParseTree binary) {
synchronized (this.impl) {
this.impl.setParseTree(parse);
if (binary != null) {
this.impl.setBinarizedParseTree(binary);
}
}
}
/**
* Update the dependencies of the sentence.
*
* @param basic The basic dependencies to update.
* @param enhanced The enhanced dependencies to update.
* @param enhancedPlusPlus The enhanced plus plus dependencies to update.
*/
protected void updateDependencies(CoreNLPProtos.DependencyGraph basic,
CoreNLPProtos.DependencyGraph enhanced,
CoreNLPProtos.DependencyGraph enhancedPlusPlus) {
synchronized (this.impl) {
this.impl.setBasicDependencies(basic);
this.impl.setEnhancedDependencies(enhanced);
this.impl.setEnhancedPlusPlusDependencies(enhancedPlusPlus);
}
}
/**
* Update the Open IE relation triples for this sentence.
*
* @param triples The stream of relation triples to add to the sentence.
*/
protected void updateOpenIE(Stream<CoreNLPProtos.RelationTriple> triples) {
synchronized (this.impl) {
triples.forEach(this.impl::addOpenieTriple);
}
}
/**
* Update the Open IE relation triples for this sentence.
*
* @param triples The stream of relation triples to add to the sentence.
*/
protected void updateKBP(Stream<CoreNLPProtos.RelationTriple> triples) {
synchronized (this.impl) {
triples.forEach(this.impl::addKbpTriple);
}
}
/**
* Update the Sentiment class for this sentence.
*
* @param sentiment The sentiment of the sentence.
*/
protected void updateSentiment(String sentiment) {
synchronized (this.impl) {
this.impl.setSentiment(sentiment);
}
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Sentence)) return false;
Sentence sentence = (Sentence) o;
// Short circuit for fast equals check
if (impl.hasText() && !impl.getText().equals(sentence.impl.getText())) {
return false;
}
if (this.tokensBuilders.size() != sentence.tokensBuilders.size()) {
return false;
}
// Check the implementation of the sentence
if (!impl.build().equals(sentence.impl.build())) {
return false;
}
// Check each token
for (int i = 0, sz = tokensBuilders.size(); i < sz; ++i) {
if (!tokensBuilders.get(i).build().equals(sentence.tokensBuilders.get(i).build())) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
if (this.impl.hasText()) {
return this.impl.getText().hashCode() * 31 + this.tokensBuilders.size();
} else {
return impl.build().hashCode();
}
}
/** {@inheritDoc} */
@Override
public String toString() {
return impl.getText();
}
/**
* @param start - inclusive
* @param end - exclusive
* @return - the text for the provided token span.
*/
public String substring(int start, int end) {
StringBuilder sb = new StringBuilder();
for(CoreLabel word : asCoreLabels().subList(start, end)) {
sb.append(word.word());
sb.append(word.after());
}
return sb.toString();
}
private static <E> List<E> lazyList(final List<CoreNLPProtos.Token.Builder> tokens, final Function<CoreNLPProtos.Token.Builder,E> fn) {
return new AbstractList<E>() {
@Override
public E get(int index) {
return fn.apply(tokens.get(index));
}
@Override
public int size() {
return tokens.size();
}
};
}
/** Returns the sentence id of the sentence, if one was found */
public Optional<String> sentenceid() {
synchronized (impl) {
if (impl.hasSentenceID()) {
return Optional.of(impl.getSentenceID());
} else {
return Optional.empty();
}
}
}
/**
* Apply a TokensRegex pattern to the sentence.
*
* @param pattern The TokensRegex pattern to match against.
* @return the matcher.
*/
public boolean matches(TokenSequencePattern pattern) {
return pattern.getMatcher(asCoreLabels()).matches();
}
/**
* Apply a TokensRegex pattern to the sentence.
*
* @param pattern The TokensRegex pattern to match against.
* @return True if the tokensregex pattern matches.
*/
public boolean matches(String pattern) {
return matches(TokenSequencePattern.compile(pattern));
}
/**
* Apply a TokensRegex pattern to the sentence.
*
* @param pattern The TokensRegex pattern to match against.
* @param fn The action to do on each match.
* @return the list of matches, after run through the function.
*/
public <T> List<T> find(TokenSequencePattern pattern, Function<TokenSequenceMatcher, T> fn) {
TokenSequenceMatcher matcher = pattern.matcher(asCoreLabels());
List<T> lst = new ArrayList<>();
while(matcher.find()) {
lst.add(fn.apply(matcher));
}
return lst;
}
public <T> List<T> find(String pattern, Function<TokenSequenceMatcher, T> fn) {
return find(TokenSequencePattern.compile(pattern), fn);
}
/**
* Apply a semgrex pattern to the sentence
* @param pattern The Semgrex pattern to match against.
* @param fn The action to do on each match.
* @return the list of matches, after run through the function.
*/
public <T> List<T> semgrex(SemgrexPattern pattern, Function<SemgrexMatcher, T> fn) {
SemgrexMatcher matcher = pattern.matcher(dependencyGraph());
List<T> lst = new ArrayList<>();
while(matcher.findNextMatchingNode()) {
lst.add(fn.apply(matcher));
}
return lst;
}
/**
* Apply a semgrex pattern to the sentence
* @param pattern The Semgrex pattern to match against.
* @param fn The action to do on each match.
* @return the list of matches, after run through the function.
*/
public <T> List<T> semgrex(String pattern, Function<SemgrexMatcher, T> fn) {
return semgrex(SemgrexPattern.compile(pattern), fn);
}
}
| stanfordnlp/CoreNLP | src/edu/stanford/nlp/simple/Sentence.java |
705 | import java.util.*;
public class bst {
public static class Node {
int data;
Node left;
Node right;
Node() {
// default constructor
}
Node(int data) {
this.data = data;
this.left = this.right = null;
}
Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
public static void display(Node root) {
if(root == null) return;
// self print
String str = root.left != null ? "" + root.left.data : ".";
str += " <- " + root.data + " -> ";
str += root.right != null ? "" + root.right.data : ".";
System.out.println(str);
// left print
display(root.left);
// right print
display(root.right);
}
public static Node construct(int[] data, int lo, int hi) {
if(lo > hi) {
return null;
}
int mid = (lo + hi) / 2;
Node midNode = new Node(data[mid]);
midNode.left = construct(data, lo, mid - 1);
midNode.right = construct(data, mid + 1, hi);
return midNode;
}
public static int size(Node node) {
if(node == null) return 0;
return size(node.left) + size(node.right) + 1;
}
public static int sum(Node node) {
if(node == null) return 0;
return sum(node.left) + sum(node.right) + node.data;
}
public static int max(Node node) {
// move toward right for max in bst
if(node == null) return Integer.MIN_VALUE;
if(node.right == null) return node.data;
return max(node.right);
}
public static int min(Node node) {
if(node == null) return Integer.MAX_VALUE;
if(node.left == null) return node.data;
return min(node.left);
}
public static boolean find(Node node, int data) {
if(node == null) return false;
if(node.data == data) {
return true;
} else if(node.data < data) {
return find(node.right, data);
} else {
return find(node.left, data);
}
}
public static Node add(Node node, int data) {
if(node == null) {
return new Node(data);
} else if(node.data < data) {
node.right = add(node.right, data);
} else {
node.left = add(node.left, data);
}
return node;
}
public static Node remove(Node node, int data) {
if(node == null) return null;
if(node.data == data) {
if(node.left != null && node.right != null) {
// have both child
int lmax = max(node.left);
node.data = lmax;
node.left = remove(node.left, lmax);
return node;
} else if(node.left != null) {
// have only left child
return node.left;
} else if(node.right != null) {
// have only right child
return node.right;
} else {
// leaf node
return null;
}
} else if(node.data > data) {
node.left = remove(node.left, data);
} else {
node.right = remove(node.right, data);
}
return node;
}
static int sum = 0;
public static void rwsol(Node node){
if(node == null) return;
rwsol(node.right);
// reverse inorder area
int data = node.data;
node.data = sum; // set
sum += data; // add in sum
rwsol(node.left);
}
public static int lca(Node node, int d1, int d2) {
if(node == null) return -1;
if(d1 < node.data && d2 < node.data) {
// lca exist in left
return lca(node.left, d1, d2);
} else if(d1 > node.data && d2 > node.data) {
// lca exist in right
return lca(node.right, d1, d2);
} else {
// node is LCA
return node.data;
}
}
public static void pir(Node node, int d1, int d2) {
if(node == null) return;
if(d1 < node.data && d2 < node.data) {
// print segment is appears in left
pir(node.left, d1, d2);
} else if(d1 > node.data && d2 > node.data) {
// print segment is appears in right side
pir(node.right, d1, d2);
} else {
// move toward left, print yourself then move toward right
pir(node.left, d1, d2);
System.out.println(node.data);
pir(node.right, d1, d2);
}
}
public static void targetSumPairUsingFind(Node node, Node root, int target) {
if(node == null) return;
targetSumPairUsingFind(node.left, root, target);
int val1 = node.data;
int val2 = target - node.data;
if(val2 > val1) {
if(find(root, val2)) {
System.out.println(val1 + " " + val2);
}
}
targetSumPairUsingFind(node.right, root, target);
}
public static void fun() {
int[] data = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
Node root = construct(data, 0, data.length - 1);
display(root);
}
public static void main(String[] args) {
fun();
}
} | shreeshPepcoding/code | pp/NIET/02_BST/bst.java |
706 | package com.baidu.paddle.paddlenlp.app.ernie_tiny;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.baidu.paddle.paddlenlp.app.R;
import com.baidu.paddle.paddlenlp.ernie_tiny.RuntimeOption;
import com.baidu.paddle.paddlenlp.ernie_tiny.Predictor;
import com.baidu.paddle.paddlenlp.ernie_tiny.IntentDetAndSlotFillResult;
import com.baidu.paddle.paddlenlp.ui.Utils;
public class ERNIETinyMainActivity extends Activity implements View.OnClickListener {
private static final String TAG = ERNIETinyMainActivity.class.getSimpleName();
private ImageView back;
private ImageButton btnSettings;
private EditText etERNIETinyInput;
private EditText etERNIETinyOutput;
private Button btnERNIETinyAnalysis;
private String[] inputTexts;
// Call 'init' and 'release' manually later
Predictor predictor = new Predictor();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ernie_tiny_activity_main);
// Clear all setting items to avoid app crashing due to the incorrect settings
initSettings();
// Check and request WRITE_EXTERNAL_STORAGE permissions
if (!checkAllPermissions()) {
requestAllPermissions();
}
// Init the camera preview and UI components
initView();
}
@Override
protected void onResume() {
super.onResume();
// Reload settings and re-initialize the predictor
checkAndUpdateSettings();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
if (predictor != null) {
predictor.release();
}
super.onDestroy();
}
private void initView() {
// Back from setting page to main page
back = findViewById(R.id.iv_back);
back.setOnClickListener(this);
// Apply ERNIE Tiny predict
btnERNIETinyAnalysis = findViewById(R.id.btn_ernie_tiny_analysis);
btnERNIETinyAnalysis.setOnClickListener(this);
// ERNIE Tiny input and output texts
etERNIETinyInput = findViewById(R.id.et_ernie_tiny_input);
etERNIETinyOutput = findViewById(R.id.et_ernie_tiny_output);
// Setting page
btnSettings = findViewById(R.id.btn_settings);
btnSettings.setOnClickListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_settings:
startActivity(new Intent(ERNIETinyMainActivity.this, ERNIETinySettingsActivity.class));
break;
case R.id.iv_back:
finish();
break;
case R.id.btn_ernie_tiny_analysis:
extractTextsIntentAndSlot();
break;
default:
break;
}
}
public void extractTextsIntentAndSlot() {
if (updateInputTexts()) {
IntentDetAndSlotFillResult[] results = predictor.predict(inputTexts);
updateOutputTexts(results);
}
}
public void updateOutputTexts(IntentDetAndSlotFillResult[] results) {
if (results == null) {
etERNIETinyOutput.setText("分析结果为空");
return;
}
if (inputTexts == null) {
etERNIETinyOutput.setText("输入文本为空");
return;
}
if (inputTexts.length != results.length) {
String info = "输入文本数量与分析结果数量不一致!"
+ inputTexts.length + "!=" + results.length;
etERNIETinyOutput.setText(info);
return;
}
// Merge Result Str
StringBuilder resultStrBuffer = new StringBuilder();
for (int i = 0; i < results.length; ++i) {
resultStrBuffer
.append("NO.")
.append(i)
.append(" text = ")
.append(inputTexts[i])
.append("\n")
.append(results[i].mStr)
.append("\n");
}
// Update output text view (EditText)
etERNIETinyOutput.setText(resultStrBuffer.toString());
}
public boolean updateInputTexts() {
String combinedInputText = etERNIETinyInput.getText().toString();
if (combinedInputText == null || combinedInputText.length() == 0) {
// Use default text if no custom text
combinedInputText = getString(R.string.ERNIE_TINY_INPUT_TEXTS_DEFAULT);
}
String[] texts = combinedInputText.split("[。!!:;:;]");
if (texts.length <= 0) {
return false;
}
for (int i = 0; i < texts.length; ++i) {
texts[i] = texts[i].trim();
}
// Update input texts
inputTexts = texts;
return true;
}
@SuppressLint("ApplySharedPref")
public void initSettings() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
ERNIETinySettingsActivity.resetSettings();
}
public void checkAndUpdateSettings() {
if (ERNIETinySettingsActivity.checkAndUpdateSettings(this)) {
// Clear output text first
etERNIETinyOutput.setText("");
// Update predictor
String realModelDir = getCacheDir() + "/" + ERNIETinySettingsActivity.modelDir;
Utils.copyDirectoryFromAssets(this, ERNIETinySettingsActivity.modelDir, realModelDir);
String modelFile = realModelDir + "/" + "infer_model.pdmodel";
String paramsFile = realModelDir + "/" + "infer_model.pdiparams";
String vocabFile = realModelDir + "/" + "vocab.txt";
String slotLabelsFile = realModelDir + "/" + "slots_label.txt";
String intentLabelsFile = realModelDir + "/" + "intent_label.txt";
String addedTokensFile = realModelDir + "/" + "added_tokens.json";
RuntimeOption option = new RuntimeOption();
option.setCpuThreadNum(ERNIETinySettingsActivity.cpuThreadNum);
option.setLitePowerMode(ERNIETinySettingsActivity.cpuPowerMode);
if (Boolean.parseBoolean(ERNIETinySettingsActivity.enableLiteInt8)) {
option.enableLiteInt8(); // For quantized models
} else {
// Enable FP16 if Int8 option is not ON.
if (Boolean.parseBoolean(ERNIETinySettingsActivity.enableLiteFp16)) {
option.enableLiteFp16();
}
}
predictor.init(modelFile, paramsFile, vocabFile, slotLabelsFile,
intentLabelsFile, addedTokensFile, option, 16);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(ERNIETinyMainActivity.this)
.setTitle("Permission denied")
.setMessage("Click to force quit the app, then open Settings->Apps & notifications->Target " +
"App->Permissions to grant all of the permissions.")
.setCancelable(false)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ERNIETinyMainActivity.this.finish();
}
}).show();
}
}
private void requestAllPermissions() {
ActivityCompat.requestPermissions(
this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
0);
}
private boolean checkAllPermissions() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
}
}
| PaddlePaddle/PaddleNLP | model_zoo/ernie-3.0-tiny/deploy/android/app/src/main/java/com/baidu/paddle/paddlenlp/app/ernie_tiny/ERNIETinyMainActivity.java |
707 | /* Automatically generated by GNU msgfmt. Do not modify! */
public class openehrArchie_nl extends java.util.ResourceBundle {
private static final java.lang.String[] table;
static {
java.lang.String[] t = new java.lang.String[602];
t[0] = "";
t[1] = "Project-Id-Version: \nReport-Msgid-Bugs-To: \nPO-Revision-Date: \nLast-Translator: Pieter Bos <[email protected]>\nLanguage-Team: \nLanguage: nl\nMIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: 8bit\nX-Generator: Poedit 2.4.2\n";
t[8] = "Type name {0} does not exist";
t[9] = "Type met naam {0} bestaat niet";
t[10] = "The validation of a template overlay failed";
t[11] = "De validate van een template overlay is niet geslaagd";
t[12] = "Attribute cardinality {0} does not conform to parent cardinality {1}";
t[13] = "De cardinaliteit {0} van dit attribuut komt niet overeen met de cardinaliteit van het attribuut dat gespecializeerd wordt: {1}";
t[20] = "Assumed value {0} from the C_TERMINOLOGY_CODE is not part of value set {1}. Expected one of {2}";
t[21] = "De assumed value {0} van de C_TERMINOLOGY_CODE is geen onderdeel van value set/codelijst {1}. Verwacht was een van de codes {2}";
t[24] = "The existence of attribute {0}.{1} is the same as in the reference model - this is not allowed due to strict existence validation being enabled";
t[25] = "De existence van attribuut {0}.{1} is hetzelfde als in het referentiemodel. Dit is niet toegestaan als strikte validatie ingeschakeld is";
t[28] = "The value {0} must be one of:";
t[29] = "De waarde {0} moet aan een van de volgende voorwaarden voldoen:";
t[30] = "BMM Schema load error";
t[31] = "Fout bij het laden van een BMM schema";
t[32] = "child terminology constraint value set code {0} does not conform to parent constraint with value set code {1}";
t[33] = "child terminology constraint value set code {0} komt niet overeen de parent constraint met value set code {1}";
t[38] = "The cardinality {0} of attribute {2}.{3} does not match cardinality {1} of the reference model";
t[39] = "De cardinaliteit {0} van attribuut {2}.{3} klopt niet met de cardinaliteit {1} uit het referentiemodel";
t[40] = "Object should be type {0}, but was {1}";
t[41] = "Object moet van type {0} zijn, maar is van type {1}";
t[46] = "an error occurred that has no standard codes";
t[47] = "er is een fout opgetreden zonder standaard-code";
t[56] = "value-set id defined. The identifying code of a value set must be defined in the term definitions of the terminology of the current archetype";
t[57] = "value-set id gedefinieerd. De identificerende code van een value set moet in de termdefinities van de terminologie van dit archetype opgenomen zijn.";
t[58] = "Attribute {0} of class {1} does not match existence {2}";
t[59] = "Attribuut {0} van class {1} komt niet overeen met existence {2}";
t[60] = "The primitive object of type {0} does not conform to non-primitive object with type {1}";
t[61] = "Het primitieve object van type {0} komt niet overeen met het niet-primitieve object met type {1}";
t[62] = "Archetype root must have an archetype reference or be prohibited (occurrences matches 0)";
t[63] = "Use_archetype moet verwijzen naar een archetype, of beperkt zijn tot occurrences 0";
t[66] = "C_OBJECT in this archetype with node id {0} is prohibited, which means its node id must be the same as parent {1}";
t[67] = "Het C_OBJECT in dit archetype met node id {0} heeft 0 als maximum occurrences (prohibited), maar het node id is anders dan die van het C_OBJECT dat gespecialiseerd wordt {1}";
t[70] = "The archetype id {0} does not match the possible archetype ids.";
t[71] = "Het archetype id {0} komt niet overeen met de mogelijke archetype ids";
t[72] = "Node id {0} is not valid here";
t[73] = "Node id {0} is hier niet geldig";
t[74] = "Id code {0} in terminology is not a valid term code, should be id, ac or at, followed by digits";
t[75] = "Id code {0} in de terminology is geen geldige term-code. De code zou moeten beginnen met id, ac of at, gevolgd door getallen";
t[88] = "Duplicate Reference Model schema found for model ''{0}'' in file {1}, ignoring latter";
t[89] = "Meer dan \u00e9\u00e9n Reference Model schema gevonden voor model ''{0}'' in bestand {1}. De tweede en volgende worden genegeerd";
t[90] = "The specialisation depth of the archetype, {0}, must be one greater than the specialisation depth of the parent archetype, {1}";
t[91] = "De specialisation depth van het archetype, {0}, moet \u00e9\u00e9n groter zijn dan die van het gespecialiseerde archetype, {1}";
t[92] = "RM Release version {0} is an invalid format for a version, should be x.x.x-(rc|alpha(x)?)?";
t[93] = "Het formaat van de RM release version {0} klopt niet. dit moet in het formaat x.x.x-(rc|alpha(x)?)? zijn";
t[94] = "{0} and {1}";
t[95] = "{0} en {1}";
t[100] = "Use_node (C_COMPLEX_OBJECT_PROXY) must point to a C_COMPLEX_OBJECT, but points to a {0}";
t[101] = "Use_node, hergebruik van een deel van het archetype, moet naar een C_COMPLEX_OBJECT verwijzen, maar verwijst naar een {0}";
t[104] = "code in terminology not used in archetype definition";
t[105] = "code uit terminologie is niet gebruikt in de definitie van het archetype";
t[110] = "value-set members defined. The member codes of a value set must be defined in the term definitions of the terminology of the flattened form of the current archetype";
t[111] = "value-set waardes gedefinieerd. De waardes uit een value-set moeten in de terminology opgenomen zijn van de flat form van dit archetype.";
t[112] = "Object does not match tuple: {0}";
t[113] = "Object komt niet overeen met tupel: {0}";
t[120] = "The code specialization depth of code {0} is {1}, which is greater than archetype specialization depth {2}";
t[121] = "De specialization depth of code {0} is {1}, maar mag niet groter zijn dan {2}, de specialization depth van het archetype";
t[124] = "An archetype slot was used in the archetype, but no archetype id was present in the data.";
t[125] = "Een archetype slot is gebruikt in het archetype, maar er is geen archetype id aanwezig in de data.";
t[130] = "{0} is not a known attribute of {1}";
t[131] = "{0} is niet een bekend attribuut van {1}";
t[140] = "The occurrences of all C_OBJECTS under this attributes is at least {0}, which does not fit in the upper limit of the cardinality of the attribute, {1}";
t[141] = "De occurrences van alle C_OBJECTS onder dit attribuut is ten minste {0}. Dat past niet in de maximale cardinaliteit van het attibruut {1}";
t[144] = "Archetype root must reference an existing archetype";
t[145] = "Use_archetype moet verwijzen naar een bestaand archetype";
t[164] = "The node id is not in the form id1.1....1: {0}";
t[165] = "De node id is niet in de form id1(.1)*: {0}";
t[166] = "Attribute {0} is a non-tuple attribute in the parent archetype, but a tuple attribute in the current archetype. That is not allowed";
t[167] = "Attribuut {0} is geen tuple in het archetype dat gespecializeerd wordt, maar wel een tuple attribuut in het huidige archetype. Dat is niet toegestaan";
t[170] = "The occurrences upper limit of the C_OBJECT {0} was {1}, which is greater than the parent attribute cardinality {2}";
t[171] = "De bovenste limiet van de occurrences van dit C_OBJECT {0} was {1}. Dat is groter dan de cardinaliteit van het attribuut dat deze C_OBJECT bevat, {2}";
t[172] = "The node_id of the root object of the archetype must be of the form id1'{.1}'*, where the number of .1 components equals the specalisation depth, and must be defined in the terminology";
t[173] = "De node id van het bovenste object van het archetype moet van de form id'{.1}'* zijn, waar het aantal van .1 onderdelen gelijk is aan de specialization depth, and de code moet bestaan in de terminologie";
t[174] = "Node id {0} already used in path {1}";
t[175] = "Node id {0} is al gebruikt in pad {1}";
t[176] = "Syntax error: existence must be one of 0..0, 0..1, or 1..1, but was {0}";
t[177] = "Syntaxfout: existence moet een van 0..0, 0..1 of 1..1 zijn, maar was {0}";
t[208] = "Use_archetype references archetype id {0}, but no archetype was found";
t[209] = "Use_archetype verwijst naar archetype met id {0}, maar dit archetype kon niet gevonden worden";
t[216] = "greater than {0}";
t[217] = "groter dan {0}";
t[220] = "Translation details language {0} has an incorrect key: {1}";
t[221] = "De beschrijving van de vertaling {0} zou een gelijke sleutelwaarde als de taal moeten hebben, maar heeft de waarde {1}";
t[224] = "Schema {0} archetype parent class {1} not defined in schema";
t[225] = "Schema {0} archetype parent class {1} niet gedefinieerd in schema";
t[226] = "Archetype terminology not defined";
t[227] = "Archetype terminology ontbreekt";
t[228] = "Code {0} is in the terminology, but not used in the archetype";
t[229] = "Code {0} uit de terminologie is niet gebruikt in de definitie van het archetype";
t[232] = "Id code {0} in terminology is of a different specialization depth than the archetype";
t[233] = "Id code {0} uit de terminologie heeft een andere specialization depth dan het archetype";
t[234] = "anything";
t[235] = "willekeurig";
t[240] = "Incorrect root node id {0}: it must match the specialization depth of the archetype, which is {1}";
t[241] = "Fout in root node id {0}: Dit moet kloppen met de specialization depth van het archetype, {1}";
t[246] = "C_OBJECT in this archetype with class {0} is prohibited, which means its class must be the same as parent type {1}";
t[247] = "Het C_OBJECT in dit archetype met klasse {0} heeft 0 als maximum occurrences (prohibited), maar heeft niet dezelfde klasse als het C_OBJECT dat gespecializeerd wordt: {1}";
t[250] = "Original language is missing in archetype";
t[251] = "Archetype heeft geen originele taal";
t[252] = "Attribute existence is {0}, which does not conform to parent existince {1}";
t[253] = "De existence {0} van dit attribuut komt niet overeen met die de existence van het attribuut dat gespecializeerd wordt: {1}";
t[254] = "C_OBJECT with RM type {0} must have a node id";
t[255] = "C_OBJECT met RM type {0} moet een node id hebben, maar heeft dat niet";
t[256] = "Use_node (C_COMPLEX_OBJECT_PROXY) points to a path that cannot be found: {0}";
t[257] = "Use_node, hergebruik van een deel van het archetype, verwijst naar een pad dat niet kan worden gevonden: {0}";
t[258] = "Reference Model BMM schema {0} incompatible with current release {1} of the tool; obtain up to date schemas";
t[259] = "Bmm Schema {0} kan niet worden geladen met versie {1} van deze software";
t[260] = "Node id numbers should be unique without their ac, at or id-prefix, to ensure the possibility of converting the archetype to ADL 1.4";
t[261] = "Node id nummers moeten uniek zijn zonder hun ac, at of id-prefix, om conversie van het archetype naar ADL 1.4 mogelijk te maken";
t[262] = "Message at {0} ({1}): {2}";
t[263] = "Bericht bij {0} ({1}): {2}";
t[264] = "Differential path {0} was not found in the parent archetype";
t[265] = "Differential path {0} is niet gevonden in het archetype dat gespecialiseerd wordt";
t[270] = "at path: ";
t[271] = "op het pad: ";
t[274] = "No Reference Model schema found for package ''{0}''";
t[275] = "Geen referentiemodel-schema gevonden voor package \u201c{0}\u201d";
t[280] = "Node id {0} is not valid here because it redefines an object illegally";
t[281] = "Node id {0} is hier niet geldig omdat het een object herdefinieert waar dat niet is toegestaan";
t[282] = "In the attribute tuple {0} members were specified, but the primitive tuple has {1} members instead";
t[283] = "In het attribuut tupel zijn {0} members opgenomen, maar het primitive tuple heeft {1} members. Dit moet gelijk zijn";
t[286] = "Occurrences {0}, which is the sum of {1}, does not conform to {2}";
t[287] = "Occurrences {0}, dat de som is van {1}, komt niet overeen met {2}";
t[294] = "Code {0} from the C_TERMINOLOGY_CODE constraint is not defined in the terminology";
t[295] = "Code {0} van deze C_TERMINOLOGY_CODE bestaat niet in de terminology";
t[304] = "Original language {0} is not defined in the terminology";
t[305] = "Originele taal {0} ontbreekt in de terminologie";
t[312] = "at most {0}";
t[313] = "maximaal {0}";
t[314] = "Term binding key {0} in path format is not present in archetype";
t[315] = "Het pad {0} uit een term binding kan niet worden gevonden in het archetype";
t[320] = "Node id {0} does not conform to {1}";
t[321] = "Node id {0} komt niet overeen met {1}";
t[326] = "Multiple values for Tuple constraint {0}: {1}";
t[327] = "Meerdere waarden voor Tuple constraint {0}: {1}";
t[328] = "Sibling order {0} refers to missing node id";
t[329] = "Sibling order {0} verwijst naar een ontbrekende node id";
t[330] = "Node id {0} is used in the archetype, but missing in the terminology";
t[331] = "Node id {0} is gebruikt in het archetype, maar ontbreekt in de terminologie";
t[336] = "Attribute {0}.{1} cannot be constrained by a {2}";
t[337] = "Attribuut {0}.{1} kan niet worden beperkt met een {2}";
t[338] = "The existence {0} of attribute {2}.{3} does not match existence {1} of the reference model";
t[339] = "De existence {0} van attribuut {2}.{3} klopt niet bij existence {1} van het referentiemodel";
t[342] = "Attribute does not match cardinality {0}";
t[343] = "Attribuut moet {0} waarden bevatten";
t[344] = "The use_archetype with type {0} does not match the archetype slow (allow_archetype) with type {1}";
t[345] = "Use_archetype met {0} klopt niet met het archetype slot met type {1} uit het gespecialiseerde archetype";
t[348] = "The specialisation depth of the archetypes must be one greater than the specialisation depth of the parent archetype";
t[349] = "De specialisation depth van het archetype moet \u00e9\u00e9n groter zijn dan die van het gespecialiseerde archetype";
t[350] = "Node id {0} already used in archetype as {1} with a different at, id or ac prefix. The archetype will not be convertible to ADL 1.4";
t[351] = "Node id {0} wordt al gebruikt in het archetype als {1} met een andere at, id of ac prefix. Het archetype kan niet naar ADL 1.4 geconverteerd worden";
t[354] = "less than {0}";
t[355] = "kleiner dan {0}";
t[358] = "the given id code is not valid";
t[359] = "de gegeven id code is niet geldig";
t[360] = "value-set members unique. The member codes of a value set must be unique within the value set";
t[361] = "value-set waardes uniek. Elke waarde mag maar \u00e9\u00e9n keer gebruikt worden in een value-set";
t[362] = "Duplicate instance of Reference Model model {0} found; original schema {1}; ignoring instance from schema {2}";
t[363] = "Dubbele instantie van reference model {0} gevonden. Het originele schema is {1}. Het schema van instantie {2} wordt genegeerd";
t[364] = "an tuple member cannot specialize an attribute that is a non-tuple attribute in its parent";
t[365] = "een onderdeel van een tupel kan geen attribuut specialiseren die geen tupel is";
t[368] = "Language {0} is defined in the translations, but is not present in the terminology";
t[369] = "Taal {0} is opgenomen bij de vertalingen, maar ontbreekt in de terminologie";
t[378] = "Use_archetype specializes an archetype root pointing to {0}, but the archetype {1} is not a descendant";
t[379] = "Use_archetype {1} specialiseert een andere use_archetype die verwijst naar {0}. Maar het archeytpe {1} specialiseert niet {0}";
t[380] = "value code {0} is used in value set {1}, but not present in terminology";
t[381] = "de code {0} is gebruikt in value set {1}, maar bestaat niet in de terminologie";
t[382] = "The path {0} referenced in the annotations does not exist in the flat archetype or reference model";
t[383] = "Het pad {0} gebruikt in de annotations bestaat niet in het flattened archetype of referentiemodel";
t[384] = "Object with node id {0} should be specialized before excluding the parent node";
t[385] = "Object met node id {0} moet gespecialiseerd worden voordat de parent node excluded wordt";
t[386] = "Archetype terminology contains no term definitions";
t[387] = "De terminologie van dit archetype bevat geen termdefinities";
t[396] = "node id must be defined in flat terminology";
t[397] = "node id ontbreekt in de flat terminologie";
t[398] = "Differential path must point to a C_ATTRIBUTE in the flat parent, but it pointed instead to a {0}";
t[399] = "Het differential pad moet naar een C_ATTRIBUTE verwijzen in het archetype dat gespecialiseerd wordt, maar in plaats daarvan verwijst het naar een {0}";
t[404] = "Duplicate attribute constraint with name {0}";
t[405] = "Attribuut met naam {0} is twee keer gedefinieerd - dit mag maar \u00e9\u00e9n keer zijn";
t[414] = "value code validity. Each value code (at-code) used in a term constraint in the archetype definition must be defined in the term_definitions part of the terminology of the flattened form of the current archetype.";
t[415] = "Geldigheid van een value code. Elke value code (at-code) gebruikt in een term constraint in de definitie van het archetype moet in de term definities van de flat form van dit archetype opgenomen zijn.";
t[416] = "Term binding key {0} is not present in terminology";
t[417] = "De code {0} van een term binding bestaat niet in de terminologie";
t[424] = "Archetype with id {0} used in use_archetype, but it was not found";
t[425] = "Archetype met id {0} is gebruikt met use_archetype, maar het archetype kon niet worden gevonden";
t[432] = "A {0} cannot specialize a {1}";
t[433] = "Een {0} kan niet een {1} specialiseren";
t[436] = "Parent archetype {0} not found or can not be flattened";
t[437] = "Parent archetype {0} niet gevonden, of het bevat een fout waardoor het niet kan worden geflattened";
t[442] = "A specialized archetype slot must have the same id as the parent id {0}, but it was {1}";
t[443] = "Een specialiserend archetype slot moet dezelfde id hebben als in het gespecialiseerde archetype {0}, maar het was {1}";
t[444] = "The value {0} must be {1}";
t[445] = "De waarde {0} moet {1} zijn";
t[452] = "Cannot redefine a closed archetype slot";
t[453] = "Een gesloten archetype slot kan niet worden hergedefinieerd";
t[454] = "Warning";
t[455] = "Waarschuwing";
t[458] = "The attribute {0} of type {1} can only have a single value, but the occurrences of the C_OBJECTS below has an upper limit of more than 1";
t[459] = "Het attribuut {0} van type {1} kan maar \u00e9\u00e9n waarde hebben, maar de occurrences van de C_OBJECTS in dit attibuut heeft een maximale limiet van meer dan 1";
t[460] = "Use_node (C_COMPLEX_OBJECT_PROXY) points to a path that resolves to more than one object";
t[461] = "Use_node, hergebruik van een deel van het archetype, verwijst naar een pad dat verwijst naar meer dan \u00e9\u00e9n object";
t[462] = "type name {0} does not conform to {1}";
t[463] = "Naam type {0} komt niet overeen met {1}";
t[466] = "Syntax error: terminology not specified";
t[467] = "Syntaxfout: terminologie ontbreekt";
t[468] = "Syntax error: existence must be one of 0..0, 0..1, or 1..1";
t[469] = "Syntaxfout: existence moet een van 0..0, 0..1 of 1..1 zijn";
t[470] = "Occurrences {0} does not conform to {1}";
t[471] = "Occurrences {0} komt niet overeen met {1}";
t[472] = "The validation of the parent archetype failed";
t[473] = "Het bovenliggende archetype bevat een fout, en valideert daardoor niet. Daardoor kan dit archetype niet gevalideerd worden.";
t[474] = "Could not find parent object for {0} but it should have been prechecked. Could you report this as a bug?";
t[475] = "Kan parent object voor {0} niet vinden. Deze melding is waarschijnlijk een bug, zou u dat kunnen melden?";
t[480] = "Original language not defined in terminology";
t[481] = "Originele taal bestaat niet in de terminologie";
t[486] = "Tuple member attribute {0} is not an attribute of type {1}";
t[487] = "Onderdeel van tupel {0} is geen attribuut van type {1}";
t[488] = "Term binding key {0} is not present in the terminology";
t[489] = "De code {0} van een term binding bestaat niet in de terminologie";
t[490] = "The path {0} referenced in the rm visibility does not exist in the flat archetype";
t[491] = "Het pad {0} gebruikt in de rm zichtbaarheid bestaat niet in het flattened archetype";
t[492] = "empty";
t[493] = "leeg";
t[494] = "A closed archetype slot cannot have its includes or excludes assertions modified";
t[495] = "Een gesloten archetype slot kan geen wijzigingen meer bevatten aan de includes en excludes-onderdelen";
t[496] = "The cardinality of Attribute {0}.{1} is the same as in the reference model - this is not allowed due to strict multiplicities validation being enabled";
t[497] = "De cardinaliteit van attribuut {0}.{1} is hetzelfde als in het referentiemodel. Dit is niet toegestaan als strikte validatie is ingeschakeld";
t[500] = "Documentation";
t[501] = "Documentatie";
t[506] = "Attribute tuple with members {0} does not conform to parent attribute tuple";
t[507] = "Atribuut-tupel met members {0} komt niet overeen met attribuut-tupel dat gespecializeerd wordt";
t[508] = "The attribute contains {0} objects that are required, but only has an upper cardinality of {1}";
t[509] = "Het attribuut bevat {0} waarden die verplicht zijn, maar heeft een maximale cardinaliteit van {1}";
t[510] = "Use_archetype points to type {0}, which is not conformant for type {1} of the archetype root used";
t[511] = "Use_archetype verwijst naar een pad met type {0}. Dit komt niet overeen met type {1} zoals opgegeven in use_archetype";
t[516] = "An object with the new node id {0} cannot be prohibited";
t[517] = "Een object met een nieuw node id {0} mag geen occurrences van maximaal 0 hebben";
t[520] = "Single valued attributes can not have a cardinality";
t[521] = "Attributen die maar \u00e9\u00e9n waarde kunnen bevatten mogen geen cardinaliteit hebben";
t[522] = "Error in parent archetype. Fix those errors before continuing with this archetype: {0}";
t[523] = "Fout in het gespecialiseerde archetype. Los deze fout in het bovenliggende archetype eerst op, alvorens verder te gaan met dit archetype. De gevonden fouten: {0}";
t[524] = "child terminology constraint value code {0} does not conform to parent constraint with value code {1}";
t[525] = "child terminology constraint value code {0} komt niet overeen met dat van de parent constraint met value code {1}";
t[526] = "value set code {0} is not present in terminology";
t[527] = "de code {0} van een value set bestaat niet in de terminologie";
t[528] = "Use_archetype {0} does not match the expression of the archetype slot it specialized in the parent";
t[529] = "Use_archetype {0} komt niet overeen met de restricties van het archetype slot dat het specialiseert";
t[532] = "Attribute has {0} occurrences, but must be {1}";
t[533] = "Attribuut komt {0} keer voor, maar dit moet {1} zijn";
t[536] = "Multiple values for Primitive Object constraint {0}: {1}";
t[537] = "Meerdere waarden voor Primitive Object constraint {0}: {1}";
t[540] = "Error";
t[541] = "Fout";
t[542] = "A differential path was used in an attribute, but this is not allowed in an archetype that has no parent";
t[543] = "In dit attribuut is een differential path gebruikt, maar dat is niet toegestaan in een niet specialiserend archetype";
t[544] = "equal to {0}";
t[545] = "gelijk aan {0}";
t[548] = "Node ID {0} specialization depth does not conform to the archetype specialization depth {1}";
t[549] = "De specialization depth van node id {0} klopt niet bij de specialization depth {1} van het archetype";
t[554] = "Use_node (C_COMPLEX_OBJECT_PROXY) points to type {0}, which does not conform to type {1}";
t[555] = "Use_node, hergebruik van een deel van het archetype, verwijst naar type {0}, maar dat klopt niet met type {1} zoals gevonden uit het pad";
t[566] = "Code {0} from the C_TERMINOLOGY_CODE constraint has specialization depth {1}, but this must be no greater than {2}";
t[567] = "Code {0} van de C_TERMINOLOGY_CODE heeft specialization depth {1}, maar dit mag niet groter dan {2} zijn voor dit archetype";
t[576] = "Code {0} from C_TERMINOLOGY_CODE constraint is not defined in the terminology";
t[577] = "Code {0} van deze C_TERMINOLOGY_CODE bestaat niet in de terminologie";
t[578] = "Attribute {0}.{1} cannot contain type {2}";
t[579] = "Attribuut {0}.{1} mag geen type {2} bevatten";
t[580] = "ADL version {0} is an invalid format for a version, should be x.x.x-(rc|alpha(x)?)?";
t[581] = "ADL-versie {0} is in een incorrect formaat. Dit zou een versie in het formaat x.x.x-(rc|alpha(x)?)? moeten zijn";
t[582] = "RM type in id {0} does not match RM type in definition {1}";
t[583] = "Reference model type {0} correspondeert niet met het reference model type {1} in de definitie van het archetype";
t[586] = "at least {0}";
t[587] = "minimaal {0}";
t[588] = "Template overlay {0} had validation errors";
t[589] = "Template overlay {0} heeft validatiefouten";
t[592] = "Merged schema {0} into schema {1}";
t[593] = "Schema {0} samengevoegd in schema {1}";
t[594] = "Archetype referenced in use_archetype points to class {0}, which does not exist in this reference model";
t[595] = "Het archetype waarnaar use_archetype verwijst, verwijst naar klasse {0}. Deze klasse bestaat niet in het referentiemodel";
t[596] = "Term binding key {0} points to a path that cannot be found in the archetype";
t[597] = "Het pad {0} uit een term binding kan niet worden gevonden in het archetype";
t[598] = "value set code {0} is used in value set {1}, but not present in terminology";
t[599] = "de value set code {0} is gebruikt in value set {1}, maar bestaat niet in de terminologie";
t[600] = "The Archetype with id {0} cannot be found";
t[601] = "Het Archetype met id {0} kan niet worden gevonden";
table = t;
}
public java.lang.Object handleGetObject (java.lang.String msgid) throws java.util.MissingResourceException {
int hash_val = msgid.hashCode() & 0x7fffffff;
int idx = (hash_val % 301) << 1;
{
java.lang.Object found = table[idx];
if (found == null)
return null;
if (msgid.equals(found))
return table[idx + 1];
}
int incr = ((hash_val % 299) + 1) << 1;
for (;;) {
idx += incr;
if (idx >= 602)
idx -= 602;
java.lang.Object found = table[idx];
if (found == null)
return null;
if (msgid.equals(found))
return table[idx + 1];
}
}
public java.util.Enumeration getKeys () {
return
new java.util.Enumeration() {
private int idx = 0;
{ while (idx < 602 && table[idx] == null) idx += 2; }
public boolean hasMoreElements () {
return (idx < 602);
}
public java.lang.Object nextElement () {
java.lang.Object key = table[idx];
do idx += 2; while (idx < 602 && table[idx] == null);
return key;
}
};
}
public java.util.ResourceBundle getParent () {
return parent;
}
}
| openEHR/archie | i18n/src/main/java/openehrArchie_nl.java |
708 | 404: Not Found | nitrite/nitrite-java | nitrite/src/main/java/org/dizitart/no2/index/fulltext/languages/Dutch.java |
709 | package nl.openconvert.tei;
import java.util.List;
import nl.openconvert.util.XML;
import org.w3c.dom.Element;
public class Paragraph
{
public String id = null;
boolean decent=true;
public int numTokens=-1;
public Paragraph(Element p)
{
this.id = p.getAttribute("id");
if (this.id==null)
this.id = p.getAttribute("xml:id");
String s = p.getTextContent();
String[] tokens = s.split("\\s+");
this.numTokens = tokens.length;
}
/**
* Een heuristiekje om de meest verknipte alinea's uit te sluiten.
* Voorlopig ook de alinea's met andere dan NE tags eruit gooien omdat de attestatie tool
* niet zo van die tagjes houdt en ik dan gewoon de hele inhoud van de p kan vervangen?
* @param p
* @return
*/
public static boolean isDecentParagraph(Element p)
{
String s = p.getTextContent();
boolean startsOK = s.matches("^\\s*\\p{P}*\\s*\\p{Lu}.*");
boolean endsOK = s.matches(".*[.?!]\\p{P}*\\s*$");
List<Element> subElements = XML.getAllSubelements(p, true);
boolean subsOK=true;
for (Element e: subElements)
{
String n = e.getNodeName();
if (! (n.contains("Name") || n.contains("name")))
{
subsOK=false;
}
}
return (subsOK && startsOK && endsOK);
}
}
| INL/OpenConvert | src/nl/openconvert/tei/Paragraph.java |
710 | // Note: on this program, VeriFast/Redux is much faster than VeriFast/Z3! (2s versus 70s). To use Redux, use:
// vfide -prover redux NewEidCard.java
// verifast -c -prover redux NewEidCard.java
/*
@@@@
@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@.....@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@.............@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@.........................@@@@@@@@@@@@@@@
@@@@@............................................@@@@@
@@@@@............................................@@@@
@@@@@............................................@@@@
@@@@............................................@@@@
@@@@......::::.................::::::::::::.....@@@@
@@@@......'@@@,...............'@@@@@@@@@@@@,...@@@@@
@@@@......#@@@..............:@@@,.............@@@@
@@@@.......@@@#.............@@@'..............@@@@
@@@@.......,@@@;...........#@@#..............@@@@@
@@@@.......;@@@..........'@@@@@@@@@+........@@@@
@@@@........+@@@........:@@@''''''';........@@@@
@@@@........@@@+.......@@@:...............@@@@
@@@@.........@@@,.....#@@'................@@@@
@@@@........,@@@....'@@#................@@@@
@@@@........'@@#..,@@@................@@@@
@@@@.........#@@;.@@@................@@@@
@@@@.........@@@+@@:...............@@@@@
@@@@........,@@@@+...............@@@@@
@@@@@..........................@@@@@
@@@@@........................@@@@@
@@@@@......................@@@@
@@@@@..................@@@@@
@@@@@@..............@@@@@@
@@@@@@..........@@@@@@
@@@@@@@......@@@@@@
@@@@@@@@@@@@@@@
@@@@@@@@@@
Powered by VeriFast (c)
*/
/*
* Quick-Key Toolset Project.
* Copyright (C) 2010 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.neweidapplet;
import javacard.security.KeyPair;
import javacard.security.RSAPrivateKey;
import javacard.security.RSAPrivateCrtKey;
import javacard.security.RSAPublicKey;
import javacard.security.RandomData;
import javacardx.crypto.Cipher;
import org.globalplatform.GPSystem;
import newepurse.IEPurseServicesCredit;
/*VF*ADDED FOLLOWING IMPORTS*/
import javacard.framework.*;
import javacard.security.PrivateKey;
import javacard.security.PublicKey;
/*VF*ADDED FOLLOWING CLASSES*/
/*VF*DONE ADDING CLASSES*/
/*@
predicate array_pointer(byte[] buffer, short length) =
buffer == null ?
true
:
array_slice(buffer, 0, buffer.length, _) &*& buffer.length == length;
predicate transient_array_pointer(byte[] buffer, short length) =
buffer == null ?
true
:
array_slice(buffer, 0, buffer.length, _) &*& buffer.length == length &*& is_transient_byte_array(buffer) == true;
predicate selected_file_types(File theSelectedFile, MasterFile theMasterFile, DedicatedFile theBelpicDirectory, DedicatedFile theIdDirectory, ElementaryFile theIdentityFile, ElementaryFile theIdentityFileSignature, ElementaryFile theAddressFile, ElementaryFile theAddressFileSignature, ElementaryFile thePhotoFile,
ElementaryFile thecaRoleIDFile, ElementaryFile theDirFile, ElementaryFile theTokenInfo, ElementaryFile theObjectDirectoryFile, ElementaryFile theAuthenticationObjectDirectoryFile, ElementaryFile thePrivateKeyDirectoryFile, ElementaryFile theCaCertificate, ElementaryFile theCertificateDirectoryFile, ElementaryFile theRrnCertificate, ElementaryFile theRootCaCertificate, ElementaryFile theAuthenticationCertificate, ElementaryFile theNonRepudationCertificate, ElementaryFile thePreferencesFile; ElementaryFile theSelectedFile2) =
theSelectedFile == theMasterFile || theSelectedFile == theBelpicDirectory || theSelectedFile == theIdDirectory ? theSelectedFile2 == null :
theSelectedFile == theIdentityFile ? theSelectedFile2 == theIdentityFile :
theSelectedFile == theIdentityFileSignature ? theSelectedFile2 == theIdentityFileSignature :
theSelectedFile == theAddressFile ? theSelectedFile2 == theAddressFile :
theSelectedFile == theAddressFileSignature ? theSelectedFile2 == theAddressFileSignature :
theSelectedFile == thePhotoFile ? theSelectedFile2 == thePhotoFile :
theSelectedFile == thecaRoleIDFile ? theSelectedFile2 == thecaRoleIDFile :
theSelectedFile == theDirFile ? theSelectedFile2 == theDirFile :
theSelectedFile == theTokenInfo ? theSelectedFile2 == theTokenInfo :
theSelectedFile == theObjectDirectoryFile ? theSelectedFile2 == theObjectDirectoryFile :
theSelectedFile == theAuthenticationObjectDirectoryFile ? theSelectedFile2 == theAuthenticationObjectDirectoryFile :
theSelectedFile == thePrivateKeyDirectoryFile ? theSelectedFile2 == thePrivateKeyDirectoryFile :
theSelectedFile == theCaCertificate ? theSelectedFile2 == theCaCertificate :
theSelectedFile == theRrnCertificate ? theSelectedFile2 == theRrnCertificate :
theSelectedFile == theRootCaCertificate ? theSelectedFile2 == theRootCaCertificate :
theSelectedFile == theAuthenticationCertificate ? theSelectedFile2 == theAuthenticationCertificate :
theSelectedFile == theNonRepudationCertificate ? theSelectedFile2 == theNonRepudationCertificate :
theSelectedFile == thePreferencesFile ? theSelectedFile2 == thePreferencesFile :
(theSelectedFile == theCertificateDirectoryFile &*& theSelectedFile2 == theCertificateDirectoryFile);
@*/
//@ predicate eq<T>(T t1; T t2) = t2 == t1;
//@ predicate selected_file_class(File theSelectedFile;) = (theSelectedFile.getClass() == ElementaryFile.class || theSelectedFile.getClass() == MasterFile.class || theSelectedFile.getClass() == DedicatedFile.class);
public final class NewEidCard extends Applet {
/*@
predicate valid() =
randomBuffer |-> ?theRandomBuffer &*& theRandomBuffer != null &*& array_slice(theRandomBuffer, 0, theRandomBuffer.length, _) &*& theRandomBuffer.length == 256 &*&
responseBuffer |-> ?theResponseBuffer &*& theResponseBuffer != null &*& array_slice(theResponseBuffer, 0, theResponseBuffer.length, _) &*& theResponseBuffer.length == 128 &*&
randomData |-> ?theRandomData &*& theRandomData != null &*&
cipher |-> ?theCipher &*& theCipher != null &*&
messageBuffer |-> ?theMessageBuffer &*& theMessageBuffer != null &*& theMessageBuffer.length == 128 &*& is_transient_byte_array(theMessageBuffer) == true &*&
previousApduType |-> ?thePreviousApduType &*& thePreviousApduType != null &*& thePreviousApduType.length == 1 &*& is_transient_byte_array(thePreviousApduType) == true &*&
signatureType |-> ?theSignatureType &*& theSignatureType != null &*& theSignatureType.length == 1 &*& is_transient_byte_array(theSignatureType) == true &*&
masterFile |-> ?theMasterFile &*& theMasterFile.MasterFile(0x3F00, null, _, ?masterSibs, _) &*& theMasterFile != null &*& theMasterFile.getClass() == MasterFile.class &*&
cardholderPin |-> ?theCardholderPin &*& OwnerPIN(theCardholderPin, _, _) &*& theCardholderPin != null &*&
resetPin |-> ?theResetPin &*& OwnerPIN(theResetPin, _, _) &*& theResetPin != null &*&
unblockPin |-> ?theUnblockPin &*& OwnerPIN(theUnblockPin, _, _) &*& theUnblockPin != null &*&
activationPin |-> ?theActivationPin &*& OwnerPIN(theActivationPin, _, _) &*& theActivationPin != null &*&
identityFile |-> ?theIdentityFile &*& theIdentityFile.ElementaryFile(_, _, ?identityData, _, _, _) &*& theIdentityFile != null &*& identityData != null &*& identityData.length == 0xD0 &*& theIdentityFile.getClass() == ElementaryFile.class &*&
identityFileSignature |-> ?theIdentityFileSignature &*& theIdentityFileSignature.ElementaryFile(_, _, ?theIdentityFileSignatureData, _, _, _) &*& theIdentityFileSignature != null &*& theIdentityFileSignatureData != null &*& theIdentityFileSignatureData.length == 0x80 &*& theIdentityFileSignature.getClass() == ElementaryFile.class &*&
addressFile |-> ?theAddressFile &*& theAddressFile.ElementaryFile(_, _, ?theAddressFileData, _, _, _) &*& theAddressFile != null &*& theAddressFileData != null &*& theAddressFileData.length == 117 &*& theAddressFile.getClass() == ElementaryFile.class &*&
addressFileSignature |-> ?theAddressFileSignature &*& theAddressFileSignature.ElementaryFile(_, _, ?theAddressFileSignatureData, _, _, _) &*& theAddressFileSignature != null &*& theAddressFileSignatureData != null &*& theAddressFileSignatureData.length == 128 &*& theAddressFileSignature.getClass() == ElementaryFile.class &*&
photoFile |-> ?thePhotoFile &*& thePhotoFile.ElementaryFile(_, _, _, _, _, _) &*& thePhotoFile != null &*& thePhotoFile.getClass() == ElementaryFile.class &*&
caRoleIDFile |-> ?thecaRoleIDFile &*& thecaRoleIDFile.ElementaryFile(_, _, ?theCaRoleIDFileData, _, _, _) &*& thecaRoleIDFile != null &*& theCaRoleIDFileData != null &*& theCaRoleIDFileData.length == 0x20 &*& thecaRoleIDFile.getClass() == ElementaryFile.class &*&
dirFile |-> ?theDirFile &*& theDirFile.ElementaryFile(_, _, ?theDirFileData, _, _, _) &*& theDirFile != null &*& theDirFileData != null &*& theDirFileData.length == 0x25 &*& theDirFile.getClass() == ElementaryFile.class &*&
tokenInfo |-> ?theTokenInfo &*& theTokenInfo.ElementaryFile(_, _, ?theTokenInfoData, _, _, _) &*& theTokenInfo != null &*& theTokenInfoData != null &*& theTokenInfoData.length == 0x30 &*& theTokenInfo.getClass() == ElementaryFile.class &*&
objectDirectoryFile |-> ?theObjectDirectoryFile &*& theObjectDirectoryFile.ElementaryFile(_, _, ?theObjectDirectoryFileData, _, _, _) &*& theObjectDirectoryFile != null &*& theObjectDirectoryFileData != null &*& theObjectDirectoryFileData.length == 40 &*& theObjectDirectoryFile.getClass() == ElementaryFile.class &*&
authenticationObjectDirectoryFile |-> ?theAuthenticationObjectDirectoryFile &*& theAuthenticationObjectDirectoryFile.ElementaryFile(_, _, ?theAuthenticationObjectDirectoryFileData, _, _, _) &*& theAuthenticationObjectDirectoryFile != null &*& theAuthenticationObjectDirectoryFileData != null &*& theAuthenticationObjectDirectoryFileData.length == 0x40 &*& theAuthenticationObjectDirectoryFile.getClass() == ElementaryFile.class &*&
privateKeyDirectoryFile |-> ?thePrivateKeyDirectoryFile &*& thePrivateKeyDirectoryFile.ElementaryFile(_, _, ?thePrivateKeyDirectoryFileData, _, _, _) &*& thePrivateKeyDirectoryFile != null &*& thePrivateKeyDirectoryFileData != null &*& thePrivateKeyDirectoryFileData.length == 0xB0 &*& thePrivateKeyDirectoryFile.getClass() == ElementaryFile.class &*&
certificateDirectoryFile |-> ?theCertificateDirectoryFile &*& theCertificateDirectoryFile.ElementaryFile(_, _, ?theCertificateDirectoryFileData, _, _, _) &*& theCertificateDirectoryFile != null &*& theCertificateDirectoryFileData != null &*& theCertificateDirectoryFileData.length == 0xB0 &*& theCertificateDirectoryFile.getClass() == ElementaryFile.class &*&
belpicDirectory |-> ?theBelpicDirectory &*& theBelpicDirectory.DedicatedFile(_, _, _, ?belpicSibs, _) &*& theBelpicDirectory != null &*& theBelpicDirectory.getClass() == DedicatedFile.class &*&
idDirectory |-> ?theIdDirectory &*& theIdDirectory.DedicatedFile(_, _, _, ?idSibs, _) &*& theIdDirectory != null &*& theIdDirectory.getClass() == DedicatedFile.class &*&
caCertificate |-> ?theCaCertificate &*& theCaCertificate.ElementaryFile(_, _, _, _, _, _) &*& theCaCertificate.getClass() == ElementaryFile.class &*&
selectedFile |-> ?theSelectedFile &*& theSelectedFile != null &*&
masterSibs == cons<File>(theDirFile, cons(theBelpicDirectory, cons(theIdDirectory, nil))) &*&
rootCaCertificate |-> ?theRootCaCertificate &*& theRootCaCertificate.ElementaryFile(_, _, _, _, _, _) &*& theRootCaCertificate.getClass() == ElementaryFile.class &*&
rrnCertificate |-> ?theRrnCertificate &*& theRrnCertificate.ElementaryFile(_, _, _, _, _, _) &*& theRrnCertificate.getClass() == ElementaryFile.class &*&
authenticationCertificate |-> ?theAuthenticationCertificate &*& theAuthenticationCertificate.ElementaryFile(_, _, _, _, _, _) &*& theAuthenticationCertificate.getClass() == ElementaryFile.class &*&
nonRepudiationCertificate |-> ?theNonRepudiationCertificate &*& theNonRepudiationCertificate.ElementaryFile(_, _, _, _, _, _) &*& theNonRepudiationCertificate.getClass() == ElementaryFile.class &*&
preferencesFile |-> ?thePreferencesFile &*& thePreferencesFile != theCaCertificate &*& thePreferencesFile != theRrnCertificate &*& thePreferencesFile.ElementaryFile(_, _, ?thePreferencesFileData, _, _, _) &*& thePreferencesFile != null &*& thePreferencesFileData != null &*& thePreferencesFileData.length == 100 &*& thePreferencesFile.getClass() == ElementaryFile.class &*&
belpicSibs == cons<File>(theTokenInfo, cons(theObjectDirectoryFile, cons(theAuthenticationObjectDirectoryFile, cons(thePrivateKeyDirectoryFile, cons(theCertificateDirectoryFile, cons(theCaCertificate, cons(theRrnCertificate, cons(theRootCaCertificate, cons(theAuthenticationCertificate, cons(theNonRepudiationCertificate, nil)))))))))) &*&
idSibs == cons<File>(theIdentityFile, cons(theIdentityFileSignature, cons(theAddressFile, cons(theAddressFileSignature, cons(thecaRoleIDFile, cons(thePreferencesFile, cons(thePhotoFile, nil))))))) &*&
selected_file_types(theSelectedFile, theMasterFile, theBelpicDirectory, theIdDirectory, theIdentityFile, theIdentityFileSignature, theAddressFile, theAddressFileSignature, thePhotoFile, thecaRoleIDFile, theDirFile, theTokenInfo, theObjectDirectoryFile, theAuthenticationObjectDirectoryFile, thePrivateKeyDirectoryFile, theCaCertificate, theCertificateDirectoryFile, theRrnCertificate, theRootCaCertificate, theAuthenticationCertificate, theNonRepudiationCertificate, thePreferencesFile, _) &*&
selected_file_class(theSelectedFile) &*&
signatureAlgorithm |-> ?theSignatureAlgorithm &*&
nonRepKeyPair |-> ?theNonRepKeyPair &*& theNonRepKeyPair != null &*&
authKeyPair |-> ?theAuthKeyPair &*& theAuthKeyPair != null &*&
basicKeyPair |-> ?theBasicKeyPair &*&
PKCS1_HEADER |-> ?thePKCS1HEADER &*& thePKCS1HEADER != null &*& array_slice(thePKCS1HEADER, 0, thePKCS1HEADER.length, _) &*& thePKCS1HEADER.length == 1 &*&
PKCS1_SHA1_HEADER |-> ?thePKCS1SHA1HEADER &*& thePKCS1SHA1HEADER != null &*& array_slice(thePKCS1SHA1HEADER, 0, thePKCS1SHA1HEADER.length, _) &*& thePKCS1SHA1HEADER.length == 16 &*&
PKCS1_MD5_HEADER |-> ?thePKCS1MD5HEADER &*& thePKCS1MD5HEADER != null &*& array_slice(thePKCS1MD5HEADER, 0, thePKCS1MD5HEADER.length, _) &*& thePKCS1MD5HEADER.length == 19 &*&
theDirFile != thePreferencesFile &*& theTokenInfo != thePreferencesFile &*& thePreferencesFile != theObjectDirectoryFile &*& thePreferencesFile != theAuthenticationObjectDirectoryFile &*& thePreferencesFile != thePrivateKeyDirectoryFile &*&
NewEidPointsObject |-> ?pointsObject &*& [_]pointsObject.applet |-> this &*&
NewEPurseAID |-> ?newEPurseAid &*& array_slice(newEPurseAid, 0, newEPurseAid.length, _) &*& newEPurseAid.length == 6 &*&
Points |-> _;
@*/
/* APDU header related constants */
// codes of CLA byte in the command APDUs
private final static byte EIDCARD_CLA_2 = (byte) 0x80;
private final static byte EIDCARD_CLA_1 = (byte) 0x00;
// codes of INS byte in the command APDUs
private final static byte INS_GET_RESPONSE = (byte) 0xC0;
private final static byte INS_SELECT_FILE = (byte) 0xA4;
private final static byte INS_ACTIVATE_FILE = (byte) 0x44;
private final static byte INS_DEACTIVATE_FILE = (byte) 0x04;
private final static byte INS_READ_BINARY = (byte) 0xB0;
private final static byte INS_UPDATE_BINARY = (byte) 0xD6;
private final static byte INS_ERASE_BINARY = (byte) 0x0E;
private final static byte INS_VERIFY_PIN = (byte) 0x20;
private final static byte INS_CHANGE_PIN = (byte) 0x24;
private final static byte INS_UNBLOCK = (byte) 0x2C;
private final static byte INS_GET_CHALLENGE = (byte) 0x84;
private final static byte INS_INTERNAL_AUTHENTICATE = (byte) 0x88;
private final static byte INS_EXTERNAL_AUTHENTICATE = (byte) 0x82;
private final static byte INS_ENVELOPE = (byte) 0xC2;
private final static byte INS_PREPARE_SIGNATURE = (byte) 0x22;
private final static byte INS_GENERATE_SIGNATURE = (byte) 0x2A;
private final static byte INS_GENERATE_KEYPAIR = (byte) 0x46;
private final static byte INS_GET_KEY = (byte) 0xE2;
private final static byte INS_PUT_KEY = (byte) 0xF2;
private final static byte INS_ERASE_KEY = (byte) 0xF4;
private final static byte INS_ACTIVATE_KEY = (byte) 0xF6;
private final static byte INS_DEACTIVATE_KEY = (byte) 0xF8;
private final static byte INS_GET_CARD_DATA = (byte) 0xE4;
private final static byte INS_LOG_OFF = (byte) 0xE6;
private final static byte INS_BLOCK = (byte) 0xE8;
private byte[] previousApduType; // transient byte array with 1 element
// "generate signature" needs to know whether the previous APDU checked the
// cardholder PIN
private final static byte VERIFY_CARDHOLDER_PIN = (byte) 0x01;
// PIN Change needs to know whether the previous APDU checked the reset PIN
private final static byte VERIFY_RESET_PIN = (byte) 0x02;
private final static byte GENERATE_KEY_PAIR = (byte) 0x03;
private final static byte OTHER = (byte) 0x00;
/* applet specific status words */
// some are defined in ISO7816, but not by JavaCard
private final static short SW_CANCELLED = (short) 0xFFFF;
private final static short SW_ALGORITHM_NOT_SUPPORTED = (short) 0x9484;
// last nibble of SW2 needs to be overwritten by the counter value/number of
// PIN tries left
private final static short SW_WRONG_PIN_0_TRIES_LEFT = (short) 0x63C0;
private final static short SW_INCONSISTENT_P1P2 = (short) 0x6A87;
private final static short SW_REFERENCE_DATA_NOT_FOUND = (short) 0x6A88;
// wrong Le field; SW2 encodes the exact number of available data bytes
private final static short SW_WRONG_LENGTH_00 = (short) 0x6C00;
/* PIN related variables */
// offsets within PIN related APDUs
private final static byte OFFSET_PIN_HEADER = ISO7816.OFFSET_CDATA;
private final static byte OFFSET_PIN_DATA = ISO7816.OFFSET_CDATA + 1;
private final static byte OFFSET_SECOND_PIN_HEADER = ISO7816.OFFSET_CDATA + 8;
private final static byte OFFSET_SECOND_PIN_DATA = ISO7816.OFFSET_CDATA + 9;
private final static byte OFFSET_SECOND_PIN_DATA_END = ISO7816.OFFSET_CDATA + 15;
// 4 different PIN codes
protected final static byte PIN_SIZE = 8;
protected final static byte CARDHOLDER_PIN = (byte) 0x01;
protected final static byte CARDHOLDER_PIN_TRY_LIMIT = 3;
protected final static byte RESET_PIN = (byte) 0x02;
protected final static byte RESET_PIN_TRY_LIMIT = 10;
protected final static byte UNBLOCK_PIN = (byte) 0x03;
protected final static byte UNBLOCK_PIN_TRY_LIMIT = 12;
protected final static byte ACTIVATE_PIN = (byte) 0x84;
protected final static byte ACTIVATE_PIN_TRY_LIMIT = 15;
protected OwnerPIN cardholderPin;
protected OwnerPIN resetPin;
protected OwnerPIN unblockPin;
protected OwnerPIN activationPin;
//protected OwnerPIN cardholderPin, resetPin, unblockPin, activationPin;
/* signature related variables */
private byte signatureAlgorithm;
private final static byte ALG_PKCS1 = (byte) 0x01;
private final static byte ALG_SHA1_PKCS1 = (byte) 0x02;
private final static byte ALG_MD5_PKCS1 = (byte) 0x04;
private final static byte[] PKCS1_HEADER = { (byte) 0x00 };
private final static byte[] PKCS1_SHA1_HEADER = { 0x00, (byte) 0x30, (byte) 0x21, (byte) 0x30, (byte) 0x09, (byte) 0x06, (byte) 0x05, (byte) 0x2b, (byte) 0x0e, (byte) 0x03, (byte) 0x02, (byte) 0x1a, (byte) 0x05, (byte) 0x00, (byte) 0x04,
(byte) 0x14 };
private final static byte[] PKCS1_MD5_HEADER = { (byte) 0x00, (byte) 0x30, (byte) 0x20, (byte) 0x30, (byte) 0x0c, (byte) 0x06, (byte) 0x08, (byte) 0x2a, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xf7, (byte) 0x0d, (byte) 0x02, (byte) 0x05,
(byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x10 };
private byte[] signatureType; // transient byte array with 1 element
private final static byte NO_SIGNATURE = (byte) 0x00;
private final static byte BASIC = (byte) 0x81;
private final static byte AUTHENTICATION = (byte) 0x82;
private final static byte NON_REPUDIATION = (byte) 0x83;
private final static byte CA_ROLE = (byte) 0x87;
// make this static to save some memory
protected static KeyPair basicKeyPair;
protected static KeyPair authKeyPair;
protected static KeyPair nonRepKeyPair;
// reuse these objects in all subclasses, otherwise we will use up all
// memory
private static Cipher cipher;
private static RandomData randomData;
// this buffer is used to correct PKCS#1 clear text message
private static byte[] messageBuffer;
/*
* "file system" related variables see Belgian Electronic Identity Card
* content
*/
protected final static short MF = (short) 0x3F00;
protected final static short EF_DIR = (short) 0x2F00;
protected final static short DF_BELPIC = (short) 0xDF00;
protected final static short DF_ID = (short) 0xDF01;
protected MasterFile masterFile;
protected DedicatedFile belpicDirectory, idDirectory;
protected ElementaryFile dirFile;
// data under BELPIC directory
protected final static short ODF = (short) 0x5031;
protected final static short TOKENINFO = (short) 0x5032;
protected final static short AODF = (short) 0x5034;
protected final static short PRKDF = (short) 0x5035;
protected final static short CDF = (short) 0x5037;
protected final static short AUTH_CERTIFICATE = (short) 0x5038;
protected final static short NONREP_CERTIFICATE = (short) 0x5039;
protected final static short CA_CERTIFICATE = (short) 0x503A;
protected final static short ROOT_CA_CERTIFICATE = (short) 0x503B;
protected final static short RRN_CERTIFICATE = (short) 0x503C;
protected ElementaryFile objectDirectoryFile, tokenInfo, authenticationObjectDirectoryFile, privateKeyDirectoryFile, certificateDirectoryFile, authenticationCertificate, nonRepudiationCertificate, caCertificate, rootCaCertificate, rrnCertificate;
// data under ID directory
protected final static short IDENTITY = (short) 0x4031;
protected final static short SGN_IDENTITY = (short) 0x4032;
protected final static short ADDRESS = (short) 0x4033;
protected final static short SGN_ADDRESS = (short) 0x4034;
protected final static short PHOTO = (short) 0x4035;
protected final static short CA_ROLE_ID = (short) 0x4038;
protected final static short PREFERENCES = (short) 0x4039;
protected ElementaryFile identityFile, identityFileSignature, addressFile, addressFileSignature, photoFile, caRoleIDFile, preferencesFile;
/*
* different file operations see ISO 7816-4 table 17+18
*/
// access mode byte for EFs
private final static byte READ_BINARY = (byte) 0x01;
private final static byte SEARCH_BINARY = (byte) 0x01;
private final static byte UPDATE_BINARY = (byte) 0x02;
private final static byte ERASE_BINARY = (byte) 0x02;
private final static byte WRITE_BINARY = (byte) 0x04;
// access mode byte for DFs
private final static byte DELETE_CHILD_FILE = (byte) 0x01;
private final static byte CREATE_EF = (byte) 0x02;
private final static byte CREATE_DF = (byte) 0x04;
// access mode byte common to DFs and EFs
private final static byte DEACTIVATE_FILE = (byte) 0x08;
private final static byte ACTIVATE_FILE = (byte) 0x10;
private final static byte TERMINATE_FILE = (byte) 0x20;
private final static byte DELETE_FILE = (byte) 0x40;
/* variables to pass information between different APDU commands */
// last generated random challenge will be stored in this buffer
private byte[] randomBuffer;
// last generated response (e.g. signature) will be stored in this buffer
private byte[] responseBuffer;
// file selected by SELECT FILE; defaults to the MF
private File selectedFile;
// only 5000 internal authenticates can be done and then the activation
// PIN needs to be checked again
private short internalAuthenticateCounter = 5000;
public static final byte INS_Credit = 0x02;
private byte[] NewEPurseAID = {0x01,0x02,0x03,0x04,0x05,0x00};
public static byte Points = 5;
NewEidPoints NewEidPointsObject;
/**
* called by the JCRE to create an applet instance
*/
public static void install(byte[] bArray, short bOffset, byte bLength)
//@ requires class_init_token(NewEidCard.class) &*& system();
//@ ensures true;
{
// create a eID card applet instance
new NewEidCard();
}
/**
* Initialise all files on the card as empty with max size
*
* see "Belgian Electronic Identity Card content" (version x)
*
* depending on the eid card version, the address is of different length
* (current: 117)
*/
private void initializeFileSystem()
/*@ requires identityFile |-> _ &*& identityFileSignature |-> _ &*& addressFile |-> _ &*& addressFileSignature |-> _
&*& caRoleIDFile |-> _ &*& preferencesFile |-> _ &*& idDirectory |-> _
&*& certificateDirectoryFile |-> _ &*& privateKeyDirectoryFile |-> _ &*& authenticationObjectDirectoryFile |-> _ &*& objectDirectoryFile |-> _
&*& tokenInfo |-> _ &*& belpicDirectory |-> _ &*& dirFile |-> _
&*& masterFile |-> _ &*& selectedFile |-> _;
@*/
/*@ ensures dirFile |-> ?theDirFile &*& theDirFile.ElementaryFile(_, _, ?dirFileData, _, _, _) &*& theDirFile != null
&*& dirFileData != null &*& dirFileData.length == 0x25
&*& belpicDirectory |-> ?theBelpicDirectory &*& theBelpicDirectory.DedicatedFile(_, _, _, ?belpic_siblings, _) &*& theBelpicDirectory != null
&*& tokenInfo |-> ?theTokenInfo &*& theTokenInfo.ElementaryFile(_, _, ?tokenInfoData, _, _, _) &*& theTokenInfo != null
&*& tokenInfoData != null &*& tokenInfoData.length == 0x30
&*& objectDirectoryFile |-> ?theObjectDirectoryFile &*& theObjectDirectoryFile.ElementaryFile(_, _, ?objectDirectoryFileData, _, _, _) &*& theObjectDirectoryFile != null
&*& objectDirectoryFileData != null &*& objectDirectoryFileData.length == 40
&*& authenticationObjectDirectoryFile |-> ?theAuthenticationObjectDirectoryFile &*& theAuthenticationObjectDirectoryFile.ElementaryFile(_, _, ?authenticationObjectDirectoryFileData, _, _, _) &*& theAuthenticationObjectDirectoryFile != null
&*& authenticationObjectDirectoryFileData != null &*& authenticationObjectDirectoryFileData.length == 0x40
&*& privateKeyDirectoryFile |-> ?thePrivateKeyDirectoryFile &*& thePrivateKeyDirectoryFile.ElementaryFile(_, _, ?privateKeyDirectoryFileData, _, _, _) &*& thePrivateKeyDirectoryFile != null
&*& privateKeyDirectoryFileData != null &*& privateKeyDirectoryFileData.length == 0xB0
&*& certificateDirectoryFile |-> ?theCertificateDirectoryFile &*& theCertificateDirectoryFile.ElementaryFile(_, _, ?certificateDirectoryFileData, _, _, _) &*& theCertificateDirectoryFile != null
&*& certificateDirectoryFileData != null &*& certificateDirectoryFileData.length == 0xB0
&*& idDirectory |-> ?theIdDirectory &*& theIdDirectory.DedicatedFile(_, _, _, ?idDirectory_siblings, _) &*& theIdDirectory != null
&*& identityFile |-> ?theIdentityFile &*& theIdentityFile.ElementaryFile(_, _, ?identityData, _, _, _) &*& theIdentityFile != null
&*& identityData != null &*& identityData.length == 0xD0
&*& identityFileSignature |-> ?theIdentityFileSignature &*& theIdentityFileSignature.ElementaryFile(_, _, ?identitySignatureData, _, _, _) &*& theIdentityFileSignature != null
&*& identitySignatureData != null &*& identitySignatureData.length == 0x80
&*& addressFile |-> ?theAddressFile &*& theAddressFile.ElementaryFile(_, _, ?addressFileData, _, _, _) &*& theAddressFile != null
&*& addressFileData != null &*& addressFileData.length == 117
&*& addressFileSignature |-> ?theAddressFileSignature &*& theAddressFileSignature.ElementaryFile(_, _, ?addressFileSignatureData, _, _, _) &*& theAddressFileSignature != null
&*& addressFileSignatureData != null &*& addressFileSignatureData.length == 128
&*& caRoleIDFile |-> ?theCaRoleIDFile &*& theCaRoleIDFile.ElementaryFile(_, _, ?caRoldIDFileData, _, _, _) &*& theCaRoleIDFile != null
&*& caRoldIDFileData != null &*& caRoldIDFileData.length == 0x20
&*& preferencesFile |-> ?thePreferencesFile &*& thePreferencesFile.ElementaryFile(_, _, ?preferencesFileData, _, _, _) &*& thePreferencesFile != null
&*& preferencesFileData != null &*& preferencesFileData.length == 100
&*& masterFile |-> ?theMasterFile &*& theMasterFile.MasterFile(0x3F00, null, _, ?master_siblings, _) &*& theMasterFile != null
&*& master_siblings == cons<File>(theDirFile, cons(theBelpicDirectory, cons(theIdDirectory, nil)))
&*& belpic_siblings == cons<File>(theTokenInfo, cons(theObjectDirectoryFile, cons(theAuthenticationObjectDirectoryFile, cons(thePrivateKeyDirectoryFile, cons(theCertificateDirectoryFile,nil)))))
&*& idDirectory_siblings == cons<File>(theIdentityFile, cons(theIdentityFileSignature, cons(theAddressFile, cons(theAddressFileSignature, cons(theCaRoleIDFile, cons(thePreferencesFile, nil))))))
&*& selectedFile |-> theMasterFile &*& theBelpicDirectory.getClass() == DedicatedFile.class &*& theIdDirectory.getClass() == DedicatedFile.class;
@*/
{
masterFile = new MasterFile();
/*
* initialize PKCS#15 data structures see
* "5. PKCS#15 information details" for more info
*/
//@ masterFile.castMasterToDedicated();
dirFile = new ElementaryFile(EF_DIR, masterFile, (short) 0x25);
belpicDirectory = new DedicatedFile(DF_BELPIC, masterFile);
tokenInfo = new ElementaryFile(TOKENINFO, belpicDirectory, (short) 0x30);
objectDirectoryFile = new ElementaryFile(ODF, belpicDirectory, (short) 40);
authenticationObjectDirectoryFile = new ElementaryFile(AODF, belpicDirectory, (short) 0x40);
privateKeyDirectoryFile = new ElementaryFile(PRKDF, belpicDirectory, (short) 0xB0);
certificateDirectoryFile = new ElementaryFile(CDF, belpicDirectory, (short) 0xB0);
idDirectory = new DedicatedFile(DF_ID, masterFile);
/*
* initialize all citizen data stored on the eID card copied from sample
* eID card 000-0000861-85
*/
// initialize ID#RN EF
identityFile = new ElementaryFile(IDENTITY, idDirectory, (short) 0xD0);
// initialize SGN#RN EF
identityFileSignature = new ElementaryFile(SGN_IDENTITY, idDirectory, (short) 0x80);
// initialize ID#Address EF
// address is 117 bytes, and should be padded with zeros
addressFile = new ElementaryFile(ADDRESS, idDirectory, (short) 117);
// initialize SGN#Address EF
addressFileSignature = new ElementaryFile(SGN_ADDRESS, idDirectory, (short) 128);
// initialize PuK#7 ID (CA Role ID) EF
caRoleIDFile = new ElementaryFile(CA_ROLE_ID, idDirectory, (short) 0x20);
// initialize Preferences EF to 100 zero bytes
preferencesFile = new ElementaryFile(PREFERENCES, idDirectory, (short) 100);
selectedFile = masterFile;
//@ masterFile.castDedicatedToMaster();
}
/**
* erase data in file that was selected with SELECT FILE
*/
private void eraseBinary(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check if access to this file is allowed
if (!fileAccessAllowed(ERASE_BINARY))
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
// use P1 and P2 as offset
short offset = Util.makeShort(buffer[ISO7816.OFFSET_P1], buffer[ISO7816.OFFSET_P2]);
JCSystem.beginTransaction();
//@ open valid();
if (selectedFile == masterFile)
ISOException.throwIt(ISO7816.SW_FILE_INVALID); //~allow_dead_code
// impossible to start erasing from offset large than size of file
//@ open selected_file_types(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _);
short size = ((ElementaryFile)selectedFile).getCurrentSize();
if (offset > size || offset < 0)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
((ElementaryFile) selectedFile).eraseData(offset);
//@ close valid();
JCSystem.commitTransaction();
}
/**
* change data in a file that was selected with SELECT FILE
*/
private void updateBinary(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check if access to this file is allowed
if (!fileAccessAllowed(UPDATE_BINARY))
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
// use P1 and P2 as offset
short offset = Util.makeShort(buffer[ISO7816.OFFSET_P1], buffer[ISO7816.OFFSET_P2]);
// impossible to start updating from offset larger than max size of file
// this however does not imply that the file length can not change
JCSystem.beginTransaction();
//@ open valid();
if (selectedFile == masterFile)
ISOException.throwIt(ISO7816.SW_FILE_INVALID); //~allow_dead_code
//@ open selected_file_types(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _);
short size = ((ElementaryFile) selectedFile).getMaxSize();
if (offset > size)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// number of bytes in file starting from offset
// short remaining = (short) (size - offset);
// get the new data
short byteRead = apdu.setIncomingAndReceive();
// check Lc
//@ positive_and(buffer[ISO7816.OFFSET_LC], 0x00FF);
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc == 0) || (byteRead == 0))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// update file
if (offset < 0 || (short) (ISO7816.OFFSET_CDATA + lc) > (short) (buffer.length) || (short) (offset + lc) > size)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
((ElementaryFile) selectedFile).updateData(offset, buffer, ISO7816.OFFSET_CDATA, lc);
//@ close valid();
JCSystem.commitTransaction();
}
/**
* checks if a certain file operation is allowed on the currently selected
* file
*
* remark 1: a very dedicated (so not generic) implementation! a more
* elegant solution would be to put (parts of) access control in File
* objects
*
* remark 2: there is a huge hack to allow some write updates. this hack is
* harmless, as these write operations happen during the copying of a card,
* not during its use
*/
private boolean fileAccessAllowed(byte mode)
//@ requires [?f]selectedFile |-> ?theSelectedFile &*& [f]this.preferencesFile |-> ?thePreferencesFile &*& [f]this.cardholderPin |-> ?theCardHolderPin &*& theCardHolderPin != null &*& [f]OwnerPIN(theCardHolderPin, _, _);
//@ ensures [f]selectedFile |-> theSelectedFile &*& [f]this.preferencesFile |-> thePreferencesFile &*& [f]this.cardholderPin |-> theCardHolderPin &*& [f]OwnerPIN(theCardHolderPin, _, _) &*& theSelectedFile instanceof ElementaryFile;
{
// if selected file is not an EF, throw "no current EF" exception
if (!(selectedFile instanceof ElementaryFile))
ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
// always allow READ BINARY
if (mode == READ_BINARY) {
return true;
}
// allow write access to the preference file if the cardholder pin was
// entered correctly
if ((selectedFile == preferencesFile) && cardholderPin.isValidated()) {
return true;
}
// we abuse the activation pin to update some of the large files (photo
// + certificates)
if (GPSystem.getCardContentState() == GPSystem.APPLICATION_SELECTABLE) {
return true;
}
// default to false
return false;
}
/**
* Gives back information on this eID
*
* @param apdu
* @param buffer
*/
private void getCardData(APDU apdu, byte[] buffer)
//@ requires [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00 || buffer[ISO7816.OFFSET_P2] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
// inform the JCRE that the applet has data to return
apdu.setOutgoing();
//@ open [1/2]valid();
byte[] data = identityFile.getData();
// Only the chip number is of importance: get this at tag position 2
short pos = 1;
//@ open [1/2]identityFile.ElementaryFile(_, _, ?identityFileData, _, _, ?info);
short dataLen = (short) data[pos];
pos = (short) (pos + 1 + dataLen + 1);
//@ close [1/2]identityFile.ElementaryFile(_, _, identityFileData, _, _, info);
if (dataLen <= (short)0 || (short)(dataLen + pos + 2) >= (short)(identityFile.getCurrentSize()))
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
//@ open [1/2]identityFile.ElementaryFile(_, _, identityFileData, _, _, info);
dataLen = (short) data[pos];
pos = (short) (pos + 1);
//@ close [1/2]identityFile.ElementaryFile(_, _, identityFileData, _, _, info);
if (dataLen < (short)0 || (short) (pos + dataLen) >= (short) (identityFile.getCurrentSize()))
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
//@ open [1/2]identityFile.ElementaryFile(_, _, identityFileData, _, _, info);
// check Le
// if (le != dataLen)
// ISOException.throwIt((short)(ISO7816.SW_WRONG_LENGTH));
/*VF*byte version[] = { (byte) 0xA5, (byte) 0x03, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x11, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x0F };*/
byte version[] = new byte[] { (byte) 0xA5, (byte) 0x03, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x11, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x0F };
byte chipNumber[] = new byte[(short) (dataLen + 12)];
Util.arrayCopy(data, pos, chipNumber, (short) 0, dataLen);
Util.arrayCopy(version, (short) 0, chipNumber, dataLen, (short) 12);
// //Set serial number
// Util.arrayCopy(tokenInfo.getData(), (short) 7, tempBuffer, (short) 0,
// (short) 16);
//
// //Set component code: TODO
//
//
// //Set OS number: TODO
//
//
// //Set OS version: TODO
// JCSystem.getVersion();
//
// //Set softmask number: TODO
//
// //Set softmask version: TODO
//
// //Set applet version: TODO : 4 bytes in file system
//
//
// //Set Interface version: TODO
//
// //Set PKCS#15 version: TODO
//
// //Set applet life cycle
// tempBuffer[(short)(le-1)] = GPSystem.getCardState();
// set the actual number of outgoing data bytes
apdu.setOutgoingLength((short) chipNumber.length);
// send content of buffer in apdu
apdu.sendBytesLong(chipNumber, (short) 0, (short) chipNumber.length);
//@ close [1/2]identityFile.ElementaryFile(_, _, identityFileData, _, _, info);
//@ close [1/2]valid();
}
/**
* put file that was selected with SELECT FILE in a response APDU
*/
private void readBinary(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
//@ open [1/2]valid();
// check if access to this file is allowed
if (!fileAccessAllowed(READ_BINARY))
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
// use P1 and P2 as offset
short offset = Util.makeShort(buffer[ISO7816.OFFSET_P1], buffer[ISO7816.OFFSET_P2]);
if (offset < 0)
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
// inform the JCRE that the applet has data to return
short le = apdu.setOutgoing();
// impossible to start reading from offset large than size of file
if (selectedFile == masterFile)
ISOException.throwIt(ISO7816.SW_FILE_INVALID); //~allow_dead_code
//@ open selected_file_types(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _);
short size = ((ElementaryFile) selectedFile).getCurrentSize();
if (offset > size)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// number of bytes in file starting from offset
short remaining = (short) (size - offset);
if (le == 0) {
if (remaining < 256) {
// wrong Le field
// SW2 encodes the exact number of available data bytes
short sw = (short) (ISO7816.SW_CORRECT_LENGTH_00 | remaining);
ISOException.throwIt(sw);
} else
// Le = 0 is interpreted as 256 bytes
le = 256;
}
// only read out the remaining bytes
if (le > remaining) {
le = remaining;
}
// set the actual number of outgoing data bytes
apdu.setOutgoingLength(le);
// write selected file in APDU
//VF bug; was apdu.sendBytesLong(((ElementaryFile) selectedFile).getData(), offset, le);
//VF probleem: originele lijn was apdu.sendBytesLong(ef.getData(), offset, le);
// het probleem hiermee is dat de getData()-methode een ElementaryFile nodig heeft, en dat
// sendBytesLong vereist dat het resultaat niet null is. De niet-null vereiste zit geencodeerd
// in ElementaryFile, dus als je dat predicaat opent, dan weet VF dat de data niet-null is, maar
// dan werkt de call op getData niet. Als je de ElementaryFile gesloten laat, dan lukt de call naar
// getData, maar weet je niet dat het niet-null is.
ElementaryFile ef = (ElementaryFile)selectedFile;
byte[] bf = ef.getData();
//@ open [1/2]ef.ElementaryFile(?d1, ?d2, ?d3, ?d4, ?d5, ?info);
apdu.sendBytesLong(bf, offset, le);
//@ close [1/2]ef.ElementaryFile(d1, d2, d3, d4, d5, info);
//@ close [1/2]valid();
}
/**
* activate a file on the eID card security conditions depend on file to
* activate: see belgian eID content file
*/
private void activateFile(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P2
if (buffer[ISO7816.OFFSET_P2] != (byte) 0x0C)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// P1 determines the select method
switch (buffer[ISO7816.OFFSET_P1]) {
case (byte) 0x02:
selectByFileIdentifier(apdu, buffer);
break;
case (byte) 0x08:
selectByPath(apdu, buffer);
break;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
break; //~allow_dead_code
}
// check if activating this file is allowed
if (!fileAccessAllowed(UPDATE_BINARY))
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
JCSystem.beginTransaction();
//@ open valid();
//@ open selected_file_types(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, ?sf2);
//@ sf2.castElementaryToFile();
selectedFile.setActive(true);
//@ sf2.castFileToElementary();
//@ close valid();
JCSystem.commitTransaction();
}
/*VF* COPIED FROM EmptyEidCard */
static byte[] dirData;
static byte[] tokenInfoData;
static byte[] odfData;
static byte[] aodfData;
static byte[] prkdfData;
static byte[] cdfData;
static byte[] citizenCaCert;
static byte[] rrnCert;
static byte[] rootCaCert;
static byte[] photoData; // save some more memory by making the photo static as well
/**
* perform any cleanup tasks and set default selectedFile
*/
private void clear()
//@ requires current_applet(this) &*& [1/2]valid();
//@ ensures current_applet(this) &*& [1/2]valid();
{
JCSystem.beginTransaction();
//@ open valid();
// clear signature and random data buffer
Util.arrayFillNonAtomic(randomBuffer, (short) 0, (short) 256, (byte) 0);
Util.arrayFillNonAtomic(responseBuffer, (short) 0, (short) 128, (byte) 0);
// no EF and DF selected yet; select MF by default
selectedFile = masterFile;
// invalidate cardholder PIN
cardholderPin.reset();
/*
* clear text message buffer, signature and previous ADPU type are
* transient so no need to reset these manually
*/
// open selectedFile.File(?d1, ?d2);
//@ close valid();
JCSystem.commitTransaction();
}
/**
* initialize empty files that need to be filled latter using UPDATE BINARY
*/
private void initializeEmptyLargeFiles()
/*@ requires belpicDirectory |-> ?bpd &*& bpd != null &*& bpd.DedicatedFile(_, _, _, ?belpic_sibs, _) &*&
length(belpic_sibs) < 6 &*&
idDirectory |-> ?idd &*& idd != null &*& idd.DedicatedFile(_, _, _, ?iddir_sibs, _) &*&
length(iddir_sibs) < 7 &*&
caCertificate |-> _ &*& rrnCertificate |-> _ &*& rootCaCertificate |-> _ &*&
photoFile |-> _ &*& authenticationCertificate |-> _ &*& nonRepudiationCertificate |-> _; @*/
/*@ ensures belpicDirectory |-> bpd &*&
idDirectory |-> idd &*&
caCertificate |-> ?cac &*& cac.ElementaryFile(CA_CERTIFICATE, bpd, ?d1, true, 0, _) &*& d1 != null &*& d1.length == 1200 &*&
rrnCertificate |-> ?rrnc &*& rrnc.ElementaryFile(RRN_CERTIFICATE, bpd, ?d2, true, 0, _) &*& d2 != null &*& d2.length == 1200 &*&
rootCaCertificate |-> ?rootcac &*& rootcac.ElementaryFile(ROOT_CA_CERTIFICATE, bpd, ?d3, true, 0, _) &*& d3 != null &*& d3.length == 1200 &*&
photoFile |-> ?pf &*& pf.ElementaryFile(PHOTO, idd, ?d4, true, 0, _) &*& d4 != null &*& d4.length == 3584 &*&
authenticationCertificate |-> ?ac &*& ac.ElementaryFile(AUTH_CERTIFICATE, bpd, ?d5, true, 0, _) &*& d5 != null &*& d5.length == 1200 &*&
nonRepudiationCertificate |-> ?nrc &*& nrc.ElementaryFile(NONREP_CERTIFICATE, bpd, ?d6, true, 0, _) &*& d6 != null &*& d6.length == 1200 &*&
idd.DedicatedFile(_, _, _, append(iddir_sibs, cons(pf, nil)), _) &*&
bpd.DedicatedFile(_, _, _, append(append(append(append(append(belpic_sibs, cons(cac, nil)), cons(rrnc, nil)), cons(rootcac, nil)), cons(ac, nil)), cons(nrc, nil)), _); @*/
{
/*
* these 3 certificates are the same for all sample eid card applets
* therefor they are made static and the data is allocated only once
*/
caCertificate = new ElementaryFile(CA_CERTIFICATE, belpicDirectory, (short) 1200);
rrnCertificate = new ElementaryFile(RRN_CERTIFICATE, belpicDirectory, (short) 1200);
rootCaCertificate = new ElementaryFile(ROOT_CA_CERTIFICATE, belpicDirectory, (short) 1200);
/*
* to save some memory we only support 1 photo for all subclasses
* ideally this should be applet specific and have max size 3584 (3.5K)
*/
photoFile = new ElementaryFile(PHOTO, idDirectory, (short) 3584);
/*
* certificate #2 and #3 are applet specific allocate enough memory
*/
authenticationCertificate = new ElementaryFile(AUTH_CERTIFICATE, belpicDirectory, (short) 1200);
nonRepudiationCertificate = new ElementaryFile(NONREP_CERTIFICATE, belpicDirectory, (short) 1200);
}
/**
* initialize basic key pair
*/
private void initializeKeyPairs()
//@ requires nonRepKeyPair |-> _ &*& authKeyPair |-> _ &*& basicKeyPair |-> _;
/*@ ensures nonRepKeyPair |-> ?theNonRepKeyPair &*& theNonRepKeyPair != null &*&
authKeyPair |-> ?theAuthKeyPair &*& theAuthKeyPair != null &*&
basicKeyPair |-> ?theBasicKeyPair &*& theBasicKeyPair != null;
@*/
{
/*
* basicKeyPair is static (so same for all applets) so only allocate
* memory once
*/
if (NewEidCard.basicKeyPair != null && authKeyPair != null && nonRepKeyPair != null) {
return;
}
basicKeyPair = new KeyPair(KeyPair.ALG_RSA_CRT, (short) 1024);
basicKeyPair.genKeyPair();
authKeyPair = new KeyPair(KeyPair.ALG_RSA_CRT, (short) (1024));
authKeyPair.genKeyPair();
//authPrivateKey = (RSAPrivateCrtKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_CRT_PRIVATE, KeyBuilder.LENGTH_RSA_1024, false);
nonRepKeyPair = new KeyPair(KeyPair.ALG_RSA_CRT, (short) (1024));
nonRepKeyPair.genKeyPair();
//nonRepPrivateKey = (RSAPrivateCrtKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_CRT_PRIVATE, KeyBuilder.LENGTH_RSA_1024, false);
}
/**
* select file under the current DF
*/
private void selectByFileIdentifier(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// receive the data to see which file needs to be selected
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc != 2) || (byteRead != 2))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// get the file identifier out of the APDU
short fid = Util.makeShort(buffer[ISO7816.OFFSET_CDATA], buffer[ISO7816.OFFSET_CDATA + 1]);
JCSystem.beginTransaction();
//@ open valid();
//@ assert selected_file_types(_, ?f1, ?f2, ?f3, ?f4, ?f5, ?f6, ?f7, ?f8, ?f9, ?f10, ?f11, ?f12, ?f13, ?f14, ?f15, ?f16, ?f17, ?f18, ?f19, ?f20, ?f21, _);
// if file identifier is the master file, select it immediately
if (fid == MF)
selectedFile = masterFile;
else {
// check if the requested file exists under the current DF
////@ close masterFile.DedicatedFile();
//@ MasterFile theMasterFile = masterFile;
//@ assert theMasterFile.MasterFile(16128, null, ?x1, ?x2, ?x3);
//@ close theMasterFile.DedicatedFile(16128, null, x1, x2, x3);
File s = ((DedicatedFile) masterFile).getSibling(fid);
//@ open theMasterFile.DedicatedFile(16128, null, x1, x2, x3);
//VF /bug
if (s != null) {
selectedFile = s;
//the fid is an elementary file:
} else {
s = belpicDirectory.getSibling(fid);
if (s != null) {
selectedFile = s;
} else {
s = idDirectory.getSibling(fid);
if (s != null) {
selectedFile = s;
} else {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
}
}
//@ close selected_file_types(s, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21, _);
}
//@ close valid();
JCSystem.commitTransaction();
}
/**
* select file by path from the MF
*/
private void selectByPath(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// receive the path name
short byteRead = apdu.setIncomingAndReceive();
// check Lc
//@ masking_and(buffer[ISO7816.OFFSET_LC], 0x00FF);
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
// it must be a multiple of 2
if (((lc & 1) == 1) || ((byteRead & 1) == 1))
ISOException.throwIt(SW_INCONSISTENT_P1P2);
if ((short) (buffer.length) < (short) (ISO7816.OFFSET_CDATA + lc + 1))
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
//@ open [1/2]valid();
// use the path name in the APDU data to select a file
File f = masterFile;
//@ assert lc <= 255;
////@ assert [1/2]masterFile |-> ?theMasterFile;
for (byte i = 0; i < lc; i += 2)
/*@ invariant array_slice(buffer, 0, buffer.length, _) &*& i >= 0 &*& i < (lc + 2) &*&
[1/2]randomBuffer |-> ?theRandomBuffer &*& theRandomBuffer != null &*& [1/2]array_slice(theRandomBuffer, 0, theRandomBuffer.length, _) &*& theRandomBuffer.length == 256 &*&
[1/2]responseBuffer |-> ?theResponseBuffer &*& theResponseBuffer != null &*& [1/2]array_slice(theResponseBuffer, 0, theResponseBuffer.length, _) &*& theResponseBuffer.length == 128 &*&
[1/2]randomData |-> ?theRandomData &*& theRandomData != null &*&
[1/2]cipher |-> ?theCipher &*& theCipher != null &*&
[1/2]messageBuffer |-> ?theMessageBuffer &*& theMessageBuffer != null &*& theMessageBuffer.length == 128 &*& is_transient_byte_array(theMessageBuffer) == true &*&
[1/2]previousApduType |-> ?thePreviousApduType &*& thePreviousApduType != null &*& thePreviousApduType.length == 1 &*& is_transient_byte_array(thePreviousApduType) == true &*&
[1/2]signatureType |-> ?theSignatureType &*& theSignatureType != null &*& theSignatureType.length == 1 &*& is_transient_byte_array(theSignatureType) == true &*&
[1/2]masterFile |-> ?theMasterFile &*& [1/2]theMasterFile.MasterFile(0x3F00, null, _, ?masterSibs, _) &*& theMasterFile != null &*& theMasterFile.getClass() == MasterFile.class &*&
[1/2]cardholderPin |-> ?theCardholderPin &*& [1/2]OwnerPIN(theCardholderPin, _, _) &*& theCardholderPin != null &*&
[1/2]resetPin |-> ?theResetPin &*& [1/2]OwnerPIN(theResetPin, _, _) &*& theResetPin != null &*&
[1/2]unblockPin |-> ?theUnblockPin &*& [1/2]OwnerPIN(theUnblockPin, _, _) &*& theUnblockPin != null &*&
[1/2]activationPin |-> ?theActivationPin &*& [1/2]OwnerPIN(theActivationPin, _, _) &*& theActivationPin != null &*&
[1/2]identityFile |-> ?theIdentityFile &*& [1/2]theIdentityFile.ElementaryFile(_, _, ?identityData, _, _, _) &*& theIdentityFile != null &*& identityData != null &*& identityData.length == 0xD0 &*& theIdentityFile.getClass() == ElementaryFile.class &*&
[1/2]identityFileSignature |-> ?theIdentityFileSignature &*& [1/2]theIdentityFileSignature.ElementaryFile(_, _, ?theIdentityFileSignatureData, _, _, _) &*& theIdentityFileSignature != null &*& theIdentityFileSignatureData != null &*& theIdentityFileSignatureData.length == 0x80 &*& theIdentityFileSignature.getClass() == ElementaryFile.class &*&
[1/2]addressFile |-> ?theAddressFile &*& [1/2]theAddressFile.ElementaryFile(_, _, ?theAddressFileData, _, _, _) &*& theAddressFile != null &*& theAddressFileData != null &*& theAddressFileData.length == 117 &*& theAddressFile.getClass() == ElementaryFile.class &*&
[1/2]addressFileSignature |-> ?theAddressFileSignature &*& [1/2]theAddressFileSignature.ElementaryFile(_, _, ?theAddressFileSignatureData, _, _, _) &*& theAddressFileSignature != null &*& theAddressFileSignatureData != null &*& theAddressFileSignatureData.length == 128 &*& theAddressFileSignature.getClass() == ElementaryFile.class &*&
[1/2]photoFile |-> ?thePhotoFile &*& [1/2]thePhotoFile.ElementaryFile(_, _, _, _, _, _) &*& thePhotoFile != null &*& thePhotoFile.getClass() == ElementaryFile.class &*&
[1/2]caRoleIDFile |-> ?thecaRoleIDFile &*& [1/2]thecaRoleIDFile.ElementaryFile(_, _, ?theCaRoleIDFileData, _, _, _) &*& thecaRoleIDFile != null &*& theCaRoleIDFileData != null &*& theCaRoleIDFileData.length == 0x20 &*& thecaRoleIDFile.getClass() == ElementaryFile.class &*&
[1/2]dirFile |-> ?theDirFile &*& [1/2]theDirFile.ElementaryFile(_, _, ?theDirFileData, _, _, _) &*& theDirFile != null &*& theDirFileData != null &*& theDirFileData.length == 0x25 &*& theDirFile.getClass() == ElementaryFile.class &*&
[1/2]tokenInfo |-> ?theTokenInfo &*& [1/2]theTokenInfo.ElementaryFile(_, _, ?theTokenInfoData, _, _, _) &*& theTokenInfo != null &*& theTokenInfoData != null &*& theTokenInfoData.length == 0x30 &*& theTokenInfo.getClass() == ElementaryFile.class &*&
[1/2]objectDirectoryFile |-> ?theObjectDirectoryFile &*& [1/2]theObjectDirectoryFile.ElementaryFile(_, _, ?theObjectDirectoryFileData, _, _, _) &*& theObjectDirectoryFile != null &*& theObjectDirectoryFileData != null &*& theObjectDirectoryFileData.length == 40 &*& theObjectDirectoryFile.getClass() == ElementaryFile.class &*&
[1/2]authenticationObjectDirectoryFile |-> ?theAuthenticationObjectDirectoryFile &*& [1/2]theAuthenticationObjectDirectoryFile.ElementaryFile(_, _, ?theAuthenticationObjectDirectoryFileData, _, _, _) &*& theAuthenticationObjectDirectoryFile != null &*& theAuthenticationObjectDirectoryFileData != null &*& theAuthenticationObjectDirectoryFileData.length == 0x40 &*& theAuthenticationObjectDirectoryFile.getClass() == ElementaryFile.class &*&
[1/2]privateKeyDirectoryFile |-> ?thePrivateKeyDirectoryFile &*& [1/2]thePrivateKeyDirectoryFile.ElementaryFile(_, _, ?thePrivateKeyDirectoryFileData, _, _, _) &*& thePrivateKeyDirectoryFile != null &*& thePrivateKeyDirectoryFileData != null &*& thePrivateKeyDirectoryFileData.length == 0xB0 &*& thePrivateKeyDirectoryFile.getClass() == ElementaryFile.class &*&
[1/2]certificateDirectoryFile |-> ?theCertificateDirectoryFile &*& [1/2]theCertificateDirectoryFile.ElementaryFile(_, _, ?theCertificateDirectoryFileData, _, _, _) &*& theCertificateDirectoryFile != null &*& theCertificateDirectoryFileData != null &*& theCertificateDirectoryFileData.length == 0xB0 &*& theCertificateDirectoryFile.getClass() == ElementaryFile.class &*&
[1/2]belpicDirectory |-> ?theBelpicDirectory &*& [1/2]theBelpicDirectory.DedicatedFile(_, _, _, ?belpicSibs, _) &*& theBelpicDirectory != null &*& theBelpicDirectory.getClass() == DedicatedFile.class &*&
[1/2]idDirectory |-> ?theIdDirectory &*& [1/2]theIdDirectory.DedicatedFile(_, _, _, ?idSibs, _) &*& theIdDirectory != null &*& theIdDirectory.getClass() == DedicatedFile.class &*&
[1/2]caCertificate |-> ?theCaCertificate &*& [1/2]theCaCertificate.ElementaryFile(_, _, _, _, _, _) &*& theCaCertificate.getClass() == ElementaryFile.class &*&
[1/2]selectedFile |-> ?theSelectedFile &*& theSelectedFile != null &*&
masterSibs == cons<File>(theDirFile, cons(theBelpicDirectory, cons(theIdDirectory, nil))) &*&
[1/2]rootCaCertificate |-> ?theRootCaCertificate &*& [1/2]theRootCaCertificate.ElementaryFile(_, _, _, _, _, _) &*& theRootCaCertificate.getClass() == ElementaryFile.class &*&
[1/2]rrnCertificate |-> ?theRrnCertificate &*& [1/2]theRrnCertificate.ElementaryFile(_, _, _, _, _, _) &*& theRrnCertificate.getClass() == ElementaryFile.class &*&
[1/2]authenticationCertificate |-> ?theAuthenticationCertificate &*& [1/2]theAuthenticationCertificate.ElementaryFile(_, _, _, _, _, _) &*& theAuthenticationCertificate.getClass() == ElementaryFile.class &*&
[1/2]nonRepudiationCertificate |-> ?theNonRepudiationCertificate &*& [1/2]theNonRepudiationCertificate.ElementaryFile(_, _, _, _, _, _) &*& theNonRepudiationCertificate.getClass() == ElementaryFile.class &*&
[1/2]preferencesFile |-> ?thePreferencesFile &*& thePreferencesFile != theCaCertificate &*& thePreferencesFile != theRrnCertificate &*& [1/2]thePreferencesFile.ElementaryFile(_, _, ?thePreferencesFileData, _, _, _) &*& thePreferencesFile != null &*& thePreferencesFileData != null &*& thePreferencesFileData.length == 100 &*& thePreferencesFile.getClass() == ElementaryFile.class &*&
belpicSibs == cons<File>(theTokenInfo, cons(theObjectDirectoryFile, cons(theAuthenticationObjectDirectoryFile, cons(thePrivateKeyDirectoryFile, cons(theCertificateDirectoryFile, cons(theCaCertificate, cons(theRrnCertificate, cons(theRootCaCertificate, cons(theAuthenticationCertificate, cons(theNonRepudiationCertificate, nil)))))))))) &*&
idSibs == cons<File>(theIdentityFile, cons(theIdentityFileSignature, cons(theAddressFile, cons(theAddressFileSignature, cons(thecaRoleIDFile, cons(thePreferencesFile, cons(thePhotoFile, nil))))))) &*&
[1/2]selected_file_types(theSelectedFile, theMasterFile, theBelpicDirectory, theIdDirectory, theIdentityFile, theIdentityFileSignature, theAddressFile, theAddressFileSignature, thePhotoFile, thecaRoleIDFile, theDirFile, theTokenInfo, theObjectDirectoryFile, theAuthenticationObjectDirectoryFile, thePrivateKeyDirectoryFile, theCaCertificate, theCertificateDirectoryFile, theRrnCertificate, theRootCaCertificate, theAuthenticationCertificate, theNonRepudiationCertificate, thePreferencesFile, _) &*&
[1/2]selected_file_class(theSelectedFile) &*&
[1/2]signatureAlgorithm |-> ?theSignatureAlgorithm &*&
[1/2]nonRepKeyPair |-> ?theNonRepKeyPair &*& theNonRepKeyPair != null &*&
[1/2]authKeyPair |-> ?theAuthKeyPair &*& theAuthKeyPair != null &*&
[1/2]basicKeyPair |-> ?theBasicKeyPair &*&
[1/2]PKCS1_HEADER |-> ?thePKCS1HEADER &*& thePKCS1HEADER != null &*& [1/2]array_slice(thePKCS1HEADER, 0, thePKCS1HEADER.length, _) &*& thePKCS1HEADER.length == 1 &*&
[1/2]PKCS1_SHA1_HEADER |-> ?thePKCS1SHA1HEADER &*& thePKCS1SHA1HEADER != null &*& [1/2]array_slice(thePKCS1SHA1HEADER, 0, thePKCS1SHA1HEADER.length, _) &*& thePKCS1SHA1HEADER.length == 16 &*&
[1/2]PKCS1_MD5_HEADER |-> ?thePKCS1MD5HEADER &*& thePKCS1MD5HEADER != null &*& [1/2]array_slice(thePKCS1MD5HEADER, 0, thePKCS1MD5HEADER.length, _) &*& thePKCS1MD5HEADER.length == 19 &*&
theDirFile != thePreferencesFile &*& theTokenInfo != thePreferencesFile &*& thePreferencesFile != theObjectDirectoryFile &*& thePreferencesFile != theAuthenticationObjectDirectoryFile &*& thePreferencesFile != thePrivateKeyDirectoryFile &*&
(f == null ?
true
:
selected_file_types(f, theMasterFile, theBelpicDirectory, theIdDirectory, theIdentityFile, theIdentityFileSignature, theAddressFile, theAddressFileSignature, thePhotoFile, thecaRoleIDFile, theDirFile, theTokenInfo, theObjectDirectoryFile, theAuthenticationObjectDirectoryFile, thePrivateKeyDirectoryFile, theCaCertificate, theCertificateDirectoryFile, theRrnCertificate, theRootCaCertificate, theAuthenticationCertificate, theNonRepudiationCertificate, thePreferencesFile, _) &*&
f.getClass() == ElementaryFile.class || f.getClass() == MasterFile.class || f.getClass() == DedicatedFile.class
) &*&
(i == 0 ?
f == theMasterFile
:
(i <= 2 ?
f == null || f == theMasterFile || mem(f, masterSibs)
:
(i <= 4 ?
f == null || mem(f, masterSibs) || mem(f, belpicSibs) || mem(f, idSibs)
:
(i <= 6 ?
f == null || mem(f, belpicSibs) || mem(f, idSibs)
:
false
)
)
)
); @*/
{
short fid = Util.makeShort(buffer[(short) (ISO7816.OFFSET_CDATA + i)], buffer[(short) (ISO7816.OFFSET_CDATA + i + 1)]);
// MF can be explicitely or implicitely in the path name
if ((i == 0) && (fid == MF))
f = masterFile;
else {
if ((f instanceof ElementaryFile) || f == null)
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
//@ open selected_file_types(f, theMasterFile, theBelpicDirectory, theIdDirectory, theIdentityFile, theIdentityFileSignature, theAddressFile, theAddressFileSignature, thePhotoFile, thecaRoleIDFile, theDirFile, theTokenInfo, theObjectDirectoryFile, theAuthenticationObjectDirectoryFile, thePrivateKeyDirectoryFile, theCaCertificate, theCertificateDirectoryFile, theRrnCertificate, theRootCaCertificate, theAuthenticationCertificate, theNonRepudiationCertificate, thePreferencesFile, _);
//@ File oldf = f;
/*@
if(f == masterFile)
{} else if (f == idDirectory) {} else {}
@*/
/*@
if(f == masterFile) {
masterFile.castMasterToDedicated();
}
@*/
f = ((DedicatedFile) f).getSibling(fid);
/*@ if(oldf == masterFile) {
masterFile.castDedicatedToMaster();
assert f == null || (f == idDirectory && f.getClass() == DedicatedFile.class) || (f == belpicDirectory && f.getClass() == DedicatedFile.class)|| (f == dirFile && f.getClass() == ElementaryFile.class);
}
@*/
/*@
if(f != null) {
close selected_file_types(f, theMasterFile, theBelpicDirectory, theIdDirectory, theIdentityFile, theIdentityFileSignature, theAddressFile, theAddressFileSignature, thePhotoFile, thecaRoleIDFile, theDirFile, theTokenInfo, theObjectDirectoryFile, theAuthenticationObjectDirectoryFile, thePrivateKeyDirectoryFile, theCaCertificate, theCertificateDirectoryFile, theRrnCertificate, theRootCaCertificate, theAuthenticationCertificate, theNonRepudiationCertificate, thePreferencesFile, _);
}
@*/
}
}
if (f == null)
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
JCSystem.beginTransaction();
//@ open [1/2]valid();
////@ open selected_file_types(f, ?g1, ?g2, ?g3, ?g4, ?g5, ?g6, ?g7, ?g8, ?g9, ?g10, ?g11, ?g12, ?g13, ?g14, ?g15, ?g16, ?g17, ?g18, ?g19, ?g20, ?g21, _);
selectedFile = f;
////@ close selected_file_types(f, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13, g14, g15, g16, g17, g18, g19, g20, g21, _);
//@ close valid();
JCSystem.commitTransaction();
}
/*VF* END COPY */
/**
* initialize all the PINs
*
* PINs are set to the same values as the sample eID card
*/
private void initializePins()
/*@ requires this.cardholderPin |-> _ &*& this.resetPin |-> _
&*& this.unblockPin |-> _ &*& this.activationPin |-> _;
@*/
/*@ ensures this.cardholderPin |-> ?theCardholderPin &*& OwnerPIN(theCardholderPin, _, _) &*& theCardholderPin != null
&*& this.resetPin |-> ?theResetPin &*& OwnerPIN(theResetPin, _, _) &*& theResetPin != null
&*& this.unblockPin |-> ?theUnblockPin &*& OwnerPIN(theUnblockPin, _, _) &*& theUnblockPin != null
&*& this.activationPin |-> ?theActivationPin &*& OwnerPIN(theActivationPin, _, _) &*& theActivationPin != null;
@*/
//this.cardholderPin |-> ?theCardholderPin &*&
{
/*
* initialize cardholder PIN (hardcoded to fixed value)
*
* PIN header is "24" (length of PIN = 4) PIN itself is "1234" (4
* digits) fill rest of PIN data with F
*/
/*VF*byte[] cardhold = { (byte) 0x24, (byte) 0x12, (byte) 0x34, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; */
byte cardhold[] = new byte[] { (byte) 0x24, (byte) 0x12, (byte) 0x34, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };
cardholderPin = new OwnerPIN(CARDHOLDER_PIN_TRY_LIMIT, PIN_SIZE);
cardholderPin.update(cardhold, (short) 0, PIN_SIZE);
/*
* initialize unblock PUK (hardcoded to fixed value)
*
* PUK header is "2c" (length of PUK = 12) PUK itself consists of 2
* parts PUK2 is "222222" (6 digits) PUK1 is "111111" (6 digits) so in
* total the PUK is "222222111111" (12 digits) fill last bye of PUK data
* with "FF"
*/
/*VF* byte[] unblock = { (byte) 0x2c, (byte) 0x22, (byte) 0x22, (byte) 0x22, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0xFF }; */
byte unblock[] = new byte[] { (byte) 0x2c, (byte) 0x22, (byte) 0x22, (byte) 0x22, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0xFF };
unblockPin = new OwnerPIN(UNBLOCK_PIN_TRY_LIMIT, PIN_SIZE);
unblockPin.update(unblock, (short) 0, PIN_SIZE);
/*
* activation PIN is same as PUK
*/
activationPin = new OwnerPIN(ACTIVATE_PIN_TRY_LIMIT, PIN_SIZE);
activationPin.update(unblock, (short) 0, PIN_SIZE);
/*
* initialize reset PIN (hardcoded to fixed value)
*
* PUK header is "2c" (length of PUK = 12) PIN itself consists of 2
* parts PUK3 is "333333" (6 digits) PUK1 is "111111" (6 digits) so in
* total the PIN is "333333111111" (12 digits) fill last bye of PIN data
* with "FF"
*/
/*VF* byte[] reset = { (byte) 0x2c, (byte) 0x33, (byte) 0x33, (byte) 0x33, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0xFF }; */
byte reset[] = new byte[] { (byte) 0x2c, (byte) 0x33, (byte) 0x33, (byte) 0x33, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0xFF };
resetPin = new OwnerPIN(RESET_PIN_TRY_LIMIT, PIN_SIZE);
resetPin.update(reset, (short) 0, PIN_SIZE);
}
/**
* private constructor - called by the install method to instantiate a
* NewEidCard instance
*
* needs to be protected so that it can be invoked by subclasses
*/
protected NewEidCard()
/*@ requires
class_init_token(NewEidCard.class) &*& system(); @*/
//@ ensures true;
{
NewEidPointsObject = new NewEidPoints();
//@ NewEidPointsObject.applet = this;
//@ init_class();
//internalAuthenticateCounter = 5000;
randomBuffer = new byte[256];
responseBuffer = new byte[128];
// initialize these objects once for the superclass
// otherwise we have RAM problems when running multiple NewEidCard applets
if (NewEidCard.randomData == null)
NewEidCard.randomData = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
if (NewEidCard.cipher == null)
NewEidCard.cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);
Cipher c = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);
if (NewEidCard.messageBuffer == null)
NewEidCard.messageBuffer = JCSystem.makeTransientByteArray((short) 128, JCSystem.CLEAR_ON_DESELECT);
// make these transient objects so that they are stored in RAM
previousApduType = JCSystem.makeTransientByteArray((short) 1, JCSystem.CLEAR_ON_DESELECT);
signatureType = JCSystem.makeTransientByteArray((short) 1, JCSystem.CLEAR_ON_DESELECT);
// register the applet instance with the JCRE
/*VF* COPIED FROM EmptyEidCard */
// initialize PINs to fixed value
initializePins();
// initialize file system
initializeFileSystem();
// initialize place holders for large files (certificates + photo)
initializeEmptyLargeFiles();
// initialize basic keys pair
initializeKeyPairs();
/*VF* END COPY */
//@ preferencesFile.neq(caCertificate);
//@ preferencesFile.neq(rrnCertificate);
//@ preferencesFile.neq(dirFile);
//@ preferencesFile.neq(tokenInfo);
//@ preferencesFile.neq(objectDirectoryFile);
//@ preferencesFile.neq(authenticationObjectDirectoryFile);
//@ preferencesFile.neq(privateKeyDirectoryFile);
//@ close valid();
register();
}
/**
* initialize the applet when it is selected
*
* select always has to happen after a reset
*/
public boolean select()
//@ requires current_applet(this) &*& [1/2]valid();
//@ ensures current_applet(this) &*& [1/2]valid();
{
// Clear data and set default selectedFile to masterFile
clear();
return true;
}
/**
* perform any cleanup and bookkeeping tasks before the applet is deselected
*/
public void deselect()
//@ requires current_applet(this) &*& [1/2]valid();
//@ ensures current_applet(this) &*& [1/2]valid();
{
clear();
return;
}
/**
* process APDUs
*/
public void process(APDU apdu)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, ?buffer_) &*& array_slice(buffer_, 0, buffer_.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer_) &*& array_slice(buffer_, 0, buffer_.length, _);
{
byte[] buffer = apdu.getBuffer();
/*
* - non repudiation signatures can only be generated if the previous
* APDU verified the cardholder PIN - administrator PIN change is only
* possible if the previous APDU verified the reset PIN
*
* so only the "generate signature" and PIN Change APDU needs to check
* the previous APDU type; in all other cases overwrite the previous
* APDU type, because this information is not needed; we do this as
* early as possible to cope with exceptions being thrown during
* processing of APDU
*
* IMPORTANT : we have to set the previous APDU type in the processing
* of a PIN Verify APDU (because the type gets overwritten to a wrong
* value) and at the end of a "generate signature" and PIN Change APDU
*/
JCSystem.beginTransaction();
//@ open valid();
if ((buffer[ISO7816.OFFSET_INS] != INS_GENERATE_SIGNATURE) && (buffer[ISO7816.OFFSET_INS] != INS_CHANGE_PIN) && (buffer[ISO7816.OFFSET_INS] != INS_GET_KEY))
setPreviousApduType(OTHER);
//@ close valid();
JCSystem.commitTransaction();
// return if the APDU is the applet SELECT command
if (selectingApplet()) {
return;
}
if (buffer[ISO7816.OFFSET_CLA] == EIDCARD_CLA_1)
// check the INS byte to decide which service method to call
switch (buffer[ISO7816.OFFSET_INS]) {
// case INS_CHANGE_ATR :
// changeATR(apdu);
// break;
case INS_VERIFY_PIN:
verifyPin(apdu, buffer);
break;
case INS_CHANGE_PIN:
changePin(apdu, buffer);
break;
case INS_UNBLOCK:
unblock(apdu, buffer);
break;
case INS_GET_CHALLENGE:
getChallenge(apdu, buffer);
break;
case INS_PREPARE_SIGNATURE:
prepareForSignature(apdu, buffer);
break;
case INS_GENERATE_SIGNATURE:
generateSignature(apdu, buffer);
break;
case INS_GENERATE_KEYPAIR:
generateKeyPair(apdu);
break;
case INS_INTERNAL_AUTHENTICATE:
internalAuthenticate(apdu, buffer);
break;
case INS_GET_RESPONSE:
// if only T=0 supported: remove
// not possible in case of T=0 protocol
if (APDU.getProtocol() == APDU.PROTOCOL_T1)
getResponse(apdu, buffer);
else
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
break;
case INS_SELECT_FILE:
selectFile(apdu, buffer);
break;
case INS_ACTIVATE_FILE:
activateFile(apdu, buffer);
break;
case INS_DEACTIVATE_FILE:
deactivateFile(apdu, buffer);
break;
case INS_READ_BINARY:
readBinary(apdu, buffer);
break;
case INS_UPDATE_BINARY:
updateBinary(apdu, buffer);
break;
case INS_ERASE_BINARY:
eraseBinary(apdu, buffer);
break;
case INS_Credit:
askForCharge();
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
break; //~allow_dead_code
}
else if (buffer[ISO7816.OFFSET_CLA] == EIDCARD_CLA_2)
switch (buffer[ISO7816.OFFSET_INS]) {
case INS_GET_KEY:
getPublicKey(apdu);
break;
case INS_PUT_KEY:
putPublicKey(apdu, buffer);
break;
case INS_ERASE_KEY:
eraseKey(apdu, buffer);
break;
case INS_ACTIVATE_KEY:
activateKey(apdu, buffer);
break;
case INS_DEACTIVATE_KEY:
deactivateKey(apdu, buffer);
break;
case INS_GET_CARD_DATA:
getCardData(apdu, buffer);
break;
case INS_LOG_OFF:
logOff(apdu, buffer);
break;
case INS_Credit:
askForCharge();
break;
// case INS_BLOCK :
// blockCard(apdu, buffer);
// break;
}
else
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
}
/**
* verify the PIN
*/
private void verifyPin(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
// receive the PIN data for validation
apdu.setIncomingAndReceive();
// check PIN depending on value of P2
JCSystem.beginTransaction();
//@ open valid();
switch (buffer[ISO7816.OFFSET_P2]) {
case CARDHOLDER_PIN:
// overwrite previous APDU type
setPreviousApduType(VERIFY_CARDHOLDER_PIN);
// check the cardholder PIN
checkPin(cardholderPin, buffer);
break;
case ACTIVATE_PIN:
// check the activation PIN
checkPin(activationPin, buffer);
// if the activation PIN was entered correctly
if (GPSystem.getCardContentState() == GPSystem.APPLICATION_SELECTABLE)
// set the applet status to personalized
GPSystem.setCardContentState(GPSystem.CARD_SECURED);
// reset internal authenticate counter
//internalAuthenticateCounter = 5000;
break;
case RESET_PIN:
// overwrite previous APDU type
setPreviousApduType(VERIFY_RESET_PIN);
// check the reset PIN
checkPin(resetPin, buffer);
break;
case UNBLOCK_PIN:
// check the unblock PIN: after this, the pin will be 'activated'
checkPin(unblockPin, buffer);
break;
default:
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
}
//@ close valid();
JCSystem.commitTransaction();
}
/**
* check the PIN
*/
private void checkPin(OwnerPIN pin, byte[] buffer)
//@ requires [1/2]cardholderPin |-> ?theCardholderPin &*& [1/2]OwnerPIN(pin, _, _) &*& pin != null &*& buffer != null &*& array_slice(buffer, 0, buffer.length, _) &*& buffer.length >= 13;
//@ ensures [1/2]cardholderPin |-> theCardholderPin &*& [1/2]OwnerPIN(pin, _, _) &*& pin != null &*& array_slice(buffer, 0, buffer.length, _) &*& buffer != null &*& buffer.length >= 13;
{
if (pin.check(buffer, OFFSET_PIN_HEADER, PIN_SIZE) == true)
return;
short tries = pin.getTriesRemaining();
// the eID card throws this exception, SW=0x63C0 would make more sense
if (tries == 0) {
// if the cardholder PIN is no longer valid (too many tries)
if (pin == cardholderPin)
// set the applet status to blocked
GPSystem.setCardContentState(GPSystem.CARD_LOCKED);
ISOException.throwIt(ISO7816.SW_FILE_INVALID);
}
/*
* create the correct exception the status word is of the form 0x63Cx
* with x the number of tries left
*/
//@ or_limits(SW_WRONG_PIN_0_TRIES_LEFT, tries, nat_of_pos(p1(p1(p1(p1_)))));
short sw = (short) (SW_WRONG_PIN_0_TRIES_LEFT | tries);
ISOException.throwIt(sw);
}
/**
* change the PIN
*/
private void changePin(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
/*
* IMPORTANT: in all other APDUs the previous APDU type gets overwritten
* in process() function; this is not the case here because the
* information is needed when processing to verify the security
* condition for administrator PIN change
*
* the previous APDU type has to be overwritten in every possible exit
* path out of this function
*/
JCSystem.beginTransaction();
//@ open valid();
// check P2
if (buffer[ISO7816.OFFSET_P2] != (byte) 0x01) {
setPreviousApduType(OTHER);
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
// P1 determines whether it is user or administrator PIN change
switch (buffer[ISO7816.OFFSET_P1]) {
case (byte) 0x00:
setPreviousApduType(OTHER);
//@ close valid();
JCSystem.commitTransaction();
userChangePin(apdu, buffer);
break;
case (byte) 0x01:
//@ close valid();
JCSystem.commitTransaction();
administratorChangePin(apdu, buffer);
break;
default:
setPreviousApduType(OTHER);
//@ close valid();
JCSystem.commitTransaction();
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
break; //~allow_dead_code
}
}
/**
* user changes the PIN
*/
private void userChangePin(APDU apdu, byte[] buffer)
//@ requires [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _) &*& buffer.length > OFFSET_SECOND_PIN_HEADER + PIN_SIZE;
//@ ensures [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _) &*& buffer.length > OFFSET_SECOND_PIN_HEADER + PIN_SIZE;
{
//@ open [1/2]valid();
// receive the PIN data
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc != 16) || (byteRead != 16))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// first check old cardholder PIN
checkPin(cardholderPin, buffer);
// do some checks on the new PIN header and data
if (!isNewPinFormattedCorrectly(buffer, OFFSET_SECOND_PIN_HEADER))
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
// include header as well in PIN object
cardholderPin.update(buffer, OFFSET_SECOND_PIN_HEADER, PIN_SIZE);
// validate cardholder PIN immediately after change PIN
// so that cardholder access rights are immediately granted
cardholderPin.check(buffer, OFFSET_SECOND_PIN_HEADER, PIN_SIZE);
//@ close [1/2]valid();
}
/**
* administrator changes the PIN
*/
private void administratorChangePin(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// The previous getChallenge() should ask for at least the length of the
// new administrator pin. Otherwise exception is thrown
/*
* IMPORTANT: the previous APDU type has to be overwritten in every
* possible exit path out of this function; therefore we check the
* security conditions as early as possible
*/
JCSystem.beginTransaction();
//@ open valid();
// previous APDU must have checked the reset PIN
if ((!resetPin.isValidated()) || (getPreviousApduType() != VERIFY_RESET_PIN)) {
setPreviousApduType(OTHER);
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
// overwrite previous ADPU type as soon as possible
setPreviousApduType(OTHER);
// receive the PIN data
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc != 8) || (byteRead != 8))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// do some checks on the new PIN header and data
if (!isNewPinFormattedCorrectly(buffer, OFFSET_PIN_HEADER))
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
// compare the new PIN with the last generated random challenge
if (!isNewPinCorrectValue(buffer))
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
// include header as well in PIN object
cardholderPin.update(buffer, OFFSET_PIN_HEADER, PIN_SIZE);
//@ close valid();
JCSystem.commitTransaction();
}
/**
* check if new PIN conforms to internal format
*
* returns false if new PIN is not formatted correctly
*/
private boolean isNewPinFormattedCorrectly(byte[] buffer, byte offset)
//@ requires buffer != null &*& array_slice(buffer, 0, buffer.length, _) &*& offset >= 0 &*& offset < buffer.length - PIN_SIZE &*& offset + PIN_SIZE <= Byte.MAX_VALUE;
//@ ensures array_slice(buffer, 0, buffer.length, _);
{
// 1st nibble of new PIN header should be 2
if ((buffer[offset] >> 4) != 2)
return false;
// 2nd nibble of new PIN header is the length (in digits)
//@ and_limits(buffer[offset], 0x0F, nat_of_pos(p1(p1(p1_))));
byte pinLength = (byte) (buffer[offset] & 0x0F);
// the new PIN should be between 4 and 12 digits
if (pinLength < 4 || pinLength > 12)
return false;
// divide PIN length by 2 to get the length in bytes
//@ shr_limits(pinLength, 1, nat_of_pos(p1(p1(p1_))));
byte pinLengthInBytes = (byte) (pinLength >> 1);
// check if PIN length is odd
if ((pinLength & (byte) 0x01) == (byte) 0x01)
pinLengthInBytes++;
// check if PIN data is padded with 0xFF
byte i = (byte) (offset + PIN_SIZE - 1);
for (; i > offset + pinLengthInBytes; i--)
/*@ invariant array_slice(buffer, 0, buffer.length, _) &*& i >= offset + pinLengthInBytes
&*& i <= offset + PIN_SIZE - 1;
@*/
{
if (buffer[i] != (byte) 0xFF)
return false;
}
// if PIN length is odd, check if last PIN data nibble is F
if ((pinLength & (byte) 0x01) == (byte) 0x01) {
if (/*@truncating@*/ (byte) (buffer[i] << 4) != (byte) 0xF0)
return false;
}
return true;
}
/**
* check if new PIN is based on the last generated random challenge
*/
private boolean isNewPinCorrectValue(byte[] buffer)
/*@ requires buffer != null &*& array_slice(buffer, 0, buffer.length, _) &*& buffer.length >= OFFSET_PIN_DATA + 8
&*& randomBuffer |-> ?theRandomBuffer &*& theRandomBuffer != null &*& array_slice(theRandomBuffer, 0, theRandomBuffer.length, _) &*& theRandomBuffer.length == 256;
@*/
//@ ensures array_slice(buffer, 0, buffer.length, _) &*& randomBuffer |-> theRandomBuffer &*& array_slice(theRandomBuffer, 0, theRandomBuffer.length, _);
{
// 2nd nibble of the PIN header is the length (in digits)
byte tmp = buffer[OFFSET_PIN_HEADER];
if(tmp < 0) { // BUG
return false;
}
byte pinLength = (byte) (buffer[OFFSET_PIN_HEADER] & 0x0F);
// check if PIN length is odd
byte oldLength = (byte) (pinLength & 0x01);
// divide PIN length by 2 to get the length in bytes
byte pinLengthInBytes = (byte) (pinLength >> 1);
//@ assert 0 <= pinLengthInBytes && pinLengthInBytes < 8;
byte i;
for (i = 0; i < pinLengthInBytes; i++)
/*@ invariant array_slice(buffer, 0, buffer.length, _) &*& i >= 0 &*& i <= pinLengthInBytes
&*& randomBuffer |-> ?theRandomBuffer2 &*& theRandomBuffer == theRandomBuffer2 &*& theRandomBuffer2 != null &*& array_slice(theRandomBuffer2, 0, theRandomBuffer2.length, _) &*& theRandomBuffer2.length >= pinLengthInBytes;
@*/
{
if (buffer[OFFSET_PIN_DATA + i] != (randomBuffer[i] & 0x77))
return false;
}
if (oldLength == (byte) 0x01) {
if ((buffer[OFFSET_PIN_DATA + pinLengthInBytes] >> 4) != ((randomBuffer[i] & 0x7F) >> 4))
return false;
}
return true;
}
/**
* Discard current fulfilled access conditions
*/
private void logOff(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00 || buffer[ISO7816.OFFSET_P2] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
// remove previous access conditions:
JCSystem.beginTransaction();
//@ open valid();
setPreviousApduType(OTHER);
setSignatureType(NO_SIGNATURE);
cardholderPin.reset();
resetPin.reset();
unblockPin.reset();
activationPin.reset();
//@ close valid();
JCSystem.commitTransaction();
}
/**
* unblock card
*/
private void unblock(APDU apdu, byte[] buffer)
//@ requires [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00 || buffer[ISO7816.OFFSET_P2] != (byte) 0x01)
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
// receive the PUK data for validation
apdu.setIncomingAndReceive();
// check PUK
//@ open valid();
checkPin(unblockPin, buffer);
// if PUK is correct, then unblock cardholder PINs
cardholderPin.resetAndUnblock();
// set the applet status back to personalized
GPSystem.setCardContentState(GPSystem.CARD_SECURED);
//@ close [1/2]valid();
}
/**
* prepare for authentication or non repudiation signature
*/
private void prepareForSignature(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x41 || buffer[ISO7816.OFFSET_P2] != (byte) 0xB6)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// receive the data to see which kind of signature
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc != 5) || (byteRead != 5))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// the first 2 bytes of the data part should be 0x04 0x80
// the fourth byte should be 0x84
if ((buffer[ISO7816.OFFSET_CDATA] != (byte) 0x04) || (buffer[ISO7816.OFFSET_CDATA + 1] != (byte) 0x80) || (buffer[ISO7816.OFFSET_CDATA + 3] != (byte) 0x84))
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
// initialize signature object depending on hash function type
JCSystem.beginTransaction();
//@ open valid();
switch (buffer[ISO7816.OFFSET_CDATA + 2]) {
case ALG_SHA1_PKCS1:
signatureAlgorithm = ALG_SHA1_PKCS1;
break;
case ALG_MD5_PKCS1:
signatureAlgorithm = ALG_MD5_PKCS1;
break;
case ALG_PKCS1:
signatureAlgorithm = ALG_PKCS1;
break;
default: // algorithm not supported (SW=9484)
ISOException.throwIt(SW_ALGORITHM_NOT_SUPPORTED);
break; //~allow_dead_code
}
// signature type is determined by the the last byte
switch (buffer[ISO7816.OFFSET_CDATA + 4]) {
case BASIC:
setSignatureType(BASIC);
break;
case AUTHENTICATION: // use authentication private key
setSignatureType(AUTHENTICATION);
break;
case NON_REPUDIATION: // use non repudiation private key
setSignatureType(NON_REPUDIATION);
break;
case CA_ROLE:
setSignatureType(NO_SIGNATURE);
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
break; //~allow_dead_code
default:
setSignatureType(NO_SIGNATURE);
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
break; //~allow_dead_code
}
//@ close valid();
JCSystem.commitTransaction();
}
/**
* generate (authentication or non repudiation) signature
*/
private void generateSignature(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
/*
* IMPORTANT: in all other APDUs the previous APDU type gets overwritten
* in process() function; this is not the case here because the
* information is needed when processing to verify the security
* condition for non repudiation signature
*
* the previous APDU type has to be overwritten in every possible exit
* path out of this function; therefore we check the security conditions
* of the non repudiation signature as early as possible, but we have to
* overwrite the previous APDU type in the 2 possible exceptions before
*/
JCSystem.beginTransaction();
//@ open valid();
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x9E || buffer[ISO7816.OFFSET_P2] != (byte) 0x9A) {
setPreviousApduType(OTHER);
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
}
// generate signature without prepare signature results:
// "conditions of use not satisfied"
if (getSignatureType() == NO_SIGNATURE) {
setPreviousApduType(OTHER);
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}
/*
* verify authentication information throw
* "security condition not satisfied" if something is wrong
*/
// check if previous APDU did a cardholder PIN verification
if ((getSignatureType() == NON_REPUDIATION) && (getPreviousApduType() != VERIFY_CARDHOLDER_PIN)) {
setPreviousApduType(OTHER);
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
// overwrite previous ADPU type as soon as possible
setPreviousApduType(OTHER);
// it is impossible to generate basic signatures with this command
if (getSignatureType() == BASIC)
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
// check if cardholder PIN was entered correctly
if (!cardholderPin.isValidated())
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
switch (signatureAlgorithm) {
case ALG_MD5_PKCS1:
//@ close [1/2]valid();
generatePkcs1Md5Signature(apdu, buffer);
//@ open [1/2]valid();
break;
case ALG_SHA1_PKCS1:
//@ close [1/2]valid();
generatePkcs1Sha1Signature(apdu, buffer);
//@ open [1/2]valid();
break;
case ALG_PKCS1:
//@ close [1/2]valid();
generatePkcs1Signature(apdu, buffer);
//@ open [1/2]valid();
break;
}
//@ close [1/2]valid();
// if T=1, store signature in sigBuffer so that it can latter be sent
if (APDU.getProtocol() == APDU.PROTOCOL_T1) {
JCSystem.beginTransaction();
//@ open valid();
Util.arrayCopy(buffer, (short) 0, responseBuffer, (short) 0, (short) 128);
//@ close valid();
JCSystem.commitTransaction();
// in case T=0 protocol, send the signature immediately in a
// response APDU
} else {
// send first 128 bytes (= 1024 bit) of buffer
apdu.setOutgoingAndSend((short) 0, (short) 128);
}
}
/**
* generate PKCS#1 MD5 signature
*/
private void generatePkcs1Md5Signature(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// receive the data that needs to be signed
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc != 16) || (byteRead != 16))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// use the correct key
//@ open [1/2]valid();
if (getSignatureType() == NON_REPUDIATION) {
cipher.init((RSAPrivateCrtKey)nonRepKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
}
if (getSignatureType() == AUTHENTICATION) {
cipher.init((RSAPrivateCrtKey)authKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
}
//@ close [1/2]valid();
JCSystem.beginTransaction();
//@ open valid();
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as);
//@ foreachp_remove(messageBuffer, as);
//@ open transient_byte_array(messageBuffer);
// prepare the message buffer to the PKCS#1 (v1.5) structure
preparePkcs1ClearText(messageBuffer, ALG_MD5_PKCS1, lc);
// copy the MD5 hash from the APDU to the message buffer
Util.arrayCopy(buffer, (short) (ISO7816.OFFSET_CDATA), messageBuffer, (short) (128 - lc), lc);
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
// generate signature
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as1);
//@ foreachp_remove(messageBuffer, as1);
//@ open transient_byte_array(messageBuffer);
cipher.doFinal(messageBuffer, (short) 0, (short) 128, buffer, (short) 0);
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as1);
//@ close [1/2]valid();
}
/**
* generate PKCS#1 SHA1 signature
*/
private void generatePkcs1Sha1Signature(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// receive the data that needs to be signed
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc != 20) || (byteRead != 20))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
//@ open [1/2]valid();
// use the correct key
if (getSignatureType() == NON_REPUDIATION) {
////cipher.init(nonRepPrivateKey, Cipher.MODE_ENCRYPT); // stond al in comments
cipher.init((RSAPrivateCrtKey)nonRepKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
}
if (getSignatureType() == AUTHENTICATION) {
cipher.init((RSAPrivateCrtKey)authKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
}
//@ close [1/2]valid();
JCSystem.beginTransaction();
//@ open valid();
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as);
//@ foreachp_remove(messageBuffer, as);
//@ open transient_byte_array(messageBuffer);
// prepare the message buffer to the PKCS#1 (v1.5) structure
preparePkcs1ClearText(messageBuffer, ALG_SHA1_PKCS1, lc);
// copy the SHA1 hash from the APDU to the message buffer
Util.arrayCopy(buffer, (short) (ISO7816.OFFSET_CDATA), messageBuffer, (short) (128 - lc), lc);
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
// generate signature
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as1);
//@ foreachp_remove(messageBuffer, as1);
//@ open transient_byte_array(messageBuffer);
cipher.doFinal(messageBuffer, (short) 0, (short) 128, buffer, (short) 0);
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as1);
//@ close [1/2]valid();
}
/**
* generate PKCS#1 signature
*/
private void generatePkcs1Signature(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// receive the data that needs to be signed
short byteRead = apdu.setIncomingAndReceive();
// check Lc
//@ positive_and(buffer[ISO7816.OFFSET_LC], 0x00FF);
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if ((lc > 117) || (byteRead > 117))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// use the correct key
//@ open [1/2]valid();
if (getSignatureType() == NON_REPUDIATION) {
cipher.init((RSAPrivateCrtKey)nonRepKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
}
if (getSignatureType() == AUTHENTICATION) {
cipher.init((RSAPrivateCrtKey)authKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
}
//@ close [1/2]valid();
JCSystem.beginTransaction();
//@ open valid();
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as);
//@ foreachp_remove(messageBuffer, as);
//@ open transient_byte_array(messageBuffer);
// prepare the message buffer to the PKCS#1 (v1.5) structure
preparePkcs1ClearText(messageBuffer, ALG_PKCS1, lc);
// copy the clear text from the APDU to the message buffer
Util.arrayCopy(buffer, (short) (ISO7816.OFFSET_CDATA), messageBuffer, (short) (128 - lc), lc);
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as1);
//@ foreachp_remove(messageBuffer, as1);
//@ open transient_byte_array(messageBuffer);
// generate signature
cipher.doFinal(messageBuffer, (short) 0, (short) 128, buffer, (short) 0);
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as1);
//@ close [1/2]valid();
}
/**
* prepare the clear text buffer with correct PKCS#1 encoding
*/
private void preparePkcs1ClearText(byte[] clearText, short type, short messageLength)
/*@ requires clearText != null &*& array_slice(clearText, 0, clearText.length, _) &*& clearText.length >= 128
&*& PKCS1_HEADER |-> ?thePKCS1HEADER &*& PKCS1_SHA1_HEADER |-> ?thePKCS1SHA1HEADER &*& PKCS1_MD5_HEADER |-> ?thePKCS1MD5HEADER
&*& thePKCS1HEADER != null &*& thePKCS1SHA1HEADER != null &*& thePKCS1MD5HEADER != null
&*& thePKCS1HEADER.length == 1 &*& thePKCS1SHA1HEADER.length == 16 &*& thePKCS1MD5HEADER.length == 19
&*& array_slice(thePKCS1HEADER, 0, thePKCS1HEADER.length, _)
&*& array_slice(thePKCS1SHA1HEADER, 0, thePKCS1SHA1HEADER.length, _)
&*& array_slice(thePKCS1MD5HEADER, 0, thePKCS1MD5HEADER.length, _)
&*& messageBuffer |-> ?theMessageBuffer &*& theMessageBuffer != null
&*& messageLength >= 0
&*& type == ALG_SHA1_PKCS1 ? messageLength == 20 || messageLength == 22 : type == ALG_MD5_PKCS1 ? messageLength == 16 : messageLength < 126; @*/
/*@ ensures array_slice(clearText, 0, clearText.length, _) &*& PKCS1_HEADER |-> thePKCS1HEADER
&*& PKCS1_SHA1_HEADER |-> thePKCS1SHA1HEADER &*& PKCS1_MD5_HEADER |-> thePKCS1MD5HEADER
&*& array_slice(thePKCS1HEADER, 0, thePKCS1HEADER.length, _)
&*& array_slice(thePKCS1SHA1HEADER, 0, thePKCS1SHA1HEADER.length, _)
&*& array_slice(thePKCS1MD5HEADER, 0, thePKCS1MD5HEADER.length, _)
&*& messageBuffer |-> theMessageBuffer ; @*/
{
// first pad the whole clear text with 0xFF
Util.arrayFillNonAtomic(clearText, (short) 0, (short) 128, (byte) 0xff);
// first 2 bytes should be 0x00 and 0x01
Util.arrayFillNonAtomic(clearText, (short) 0, (short) 1, (byte) 0x00);
Util.arrayFillNonAtomic(clearText, (short) 1, (short) 1, (byte) 0x01);
// add the PKCS#1 header at the correct location
byte[] header = PKCS1_HEADER;
if (type == ALG_SHA1_PKCS1)
header = PKCS1_SHA1_HEADER;
if (type == ALG_MD5_PKCS1)
header = PKCS1_MD5_HEADER;
Util.arrayCopy(header, (short) 0, clearText, (short) (128 - messageLength - header.length), (short) header.length);
}
/**
* generate a key pair
*
* only the private key will be stored in the eid. the get public key method
* should be called directly after this method, otherwise the public key
* will be discarded security conditions depend on the key to generate the
* role R03 (see belgian eid card content) shall be verified for changing
* authentication or non repudiation keys.
*/
private void generateKeyPair(APDU apdu)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, ?theBuffer) &*& array_slice(theBuffer, 0, theBuffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, theBuffer) &*& array_slice(theBuffer, 0, theBuffer.length, _);
{
apdu.setIncomingAndReceive();// If this was removed, function will not
// work: no data except for command will be read
byte[] buffer = apdu.getBuffer();
// check if access to this method is allowed
if (GPSystem.getCardContentState() != GPSystem.APPLICATION_SELECTABLE)
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
if (lc != (short) 11)
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
byte offset = (ISO7816.OFFSET_CDATA + 0x01);
//byte offset = (byte)(ISO7816.OFFSET_CDATA + 0x01);
// create keypair using parameters given:
// short keyLength = Util.makeShort(buffer[ISO7816.OFFSET_CDATA],
// buffer[offset]);
if (buffer[offset] != (byte) 0x80)
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// This is commented out as changing exponent makes getting modulus
// impossible on some java cards
// ((RSAPublicKey)tempkp.getPublic()).setExponent(buffer, (short)(13),
// (short)3);
JCSystem.beginTransaction();
//@ open valid();
setPreviousApduType(GENERATE_KEY_PAIR);
switch (buffer[ISO7816.OFFSET_P2]) {
case BASIC:
basicKeyPair = new KeyPair(KeyPair.ALG_RSA_CRT, (short) (1024));
basicKeyPair.genKeyPair();
break;
case AUTHENTICATION: // use authentication private key
authKeyPair = new KeyPair(KeyPair.ALG_RSA_CRT, (short) (1024));
authKeyPair.genKeyPair();
break;
case NON_REPUDIATION: // use non repudiation private key
nonRepKeyPair = new KeyPair(KeyPair.ALG_RSA_CRT, (short) (1024));
nonRepKeyPair.genKeyPair();
break;
default:
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
break; //~allow_dead_code
}
//@ close valid();
JCSystem.commitTransaction();
}
/**
* get a public key. for the authentication and non-repudiation key, this
* method can only be called after the generateKeyPair method was called
*
*/
private void getPublicKey(APDU apdu)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, ?theBuffer) &*& array_slice(theBuffer, 0, theBuffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, theBuffer) &*& array_slice(theBuffer, 0, theBuffer.length, _);
{
byte[] buffer = apdu.getBuffer();
// if this is thrown: problem accesses getPreviousapdu
// check P1
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// inform the JCRE that the applet has data to return
short le = apdu.setOutgoing();
// Le = 0 is not allowed
if (le != (short) (5 + 8 + 128))
ISOException.throwIt((short) (SW_WRONG_LENGTH_00 + (5 + 8 + 128)));
byte[] tempBuffer = new byte[le];
tempBuffer[(short) 0] = (byte) 0x02;
tempBuffer[(short) 1] = (byte) 0x08;
tempBuffer[(short) 10] = (byte) 0x03;
tempBuffer[(short) 11] = (byte) 0x81;
tempBuffer[(short) 12] = (byte) 0x80;
//@ open [1/2]valid();
if (buffer[ISO7816.OFFSET_P2] == AUTHENTICATION){
if (getPreviousApduType() != GENERATE_KEY_PAIR) {
authKeyPair.getPublic().clearKey();
//@ close [1/2]valid();
JCSystem.beginTransaction();
//@ open valid();
setPreviousApduType(OTHER);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}
((RSAPublicKey) authKeyPair.getPublic()).getExponent(tempBuffer, (short) 7);
((RSAPublicKey) authKeyPair.getPublic()).getModulus(tempBuffer, (short) 13);
}else if (buffer[ISO7816.OFFSET_P2] == NON_REPUDIATION) {
if (getPreviousApduType() != GENERATE_KEY_PAIR) {
nonRepKeyPair.getPublic().clearKey();
//@ close [1/2]valid();
JCSystem.beginTransaction();
//@ open valid();
setPreviousApduType(OTHER);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}
((RSAPublicKey) nonRepKeyPair.getPublic()).getExponent(tempBuffer, (short) 7);
((RSAPublicKey) nonRepKeyPair.getPublic()).getModulus(tempBuffer, (short) 13);
}else if (buffer[ISO7816.OFFSET_P2] == BASIC) {
if (basicKeyPair == null)
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
((RSAPublicKey) basicKeyPair.getPublic()).getExponent(tempBuffer, (short) 7);
((RSAPublicKey) basicKeyPair.getPublic()).getModulus(tempBuffer, (short) 13);
} else {
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
}
//@ close [1/2]valid();
JCSystem.beginTransaction();
//@ open valid();
setPreviousApduType(OTHER);
//@ close valid();
JCSystem.commitTransaction();
//@ open [1/2]valid();
authKeyPair.getPublic().clearKey();
nonRepKeyPair.getPublic().clearKey();
// set the actual number of outgoing data bytes
apdu.setOutgoingLength(le);
// send content of buffer in apdu
apdu.sendBytesLong(tempBuffer, (short) 0, le);
//@ close [1/2]valid();
}
/**
* put a public key as commune or role key this is not supported anymore
*/
private void putPublicKey(APDU apdu, byte[] buffer)
//@ requires [1/2]valid();
//@ ensures [1/2]valid();
{
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
}
/**
* erase a public key (basic, commune or role key) only basic supported
*/
private void eraseKey(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
switch (buffer[ISO7816.OFFSET_P2]) {
case BASIC:
JCSystem.beginTransaction();
//@ open valid();
basicKeyPair = null;
//@ close valid();
JCSystem.commitTransaction();
break;
default:
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
break; //~allow_dead_code
}
}
/**
* activate a public authentication or non repudiation key if deactivated
* keys in this applet are always active
*/
private void activateKey(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
switch (buffer[ISO7816.OFFSET_P2]) {
case AUTHENTICATION:
// activate key: key always active, do nothing
break;
case NON_REPUDIATION:
// activate key: key always active, do nothing
break;
default:
ISOException.throwIt(SW_REFERENCE_DATA_NOT_FOUND);
break; //~allow_dead_code
}
}
/**
* deactivate a public authentication or non repudiation key if activated as
* keys are always active, throw exception
*/
private void deactivateKey(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}
/**
* internal authenticate generates a signature with the basic private key no
* security conditions needed if used for internal authentication only
* (Mutual authentication not supported)
*/
private void internalAuthenticate(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1 and P2
if ((buffer[ISO7816.OFFSET_P1] != ALG_SHA1_PKCS1) || buffer[ISO7816.OFFSET_P2] != BASIC)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// receive the data that needs to be signed
short byteRead = apdu.setIncomingAndReceive();
// check Lc
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
// we do not support Lc=0x97, only Lc=0x16
if ((lc == 0x97) || (byteRead == 0x97))
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
if ((lc != 0x16) || (byteRead != 0x16))
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
// the first data byte must be "94" and the second byte is the length
// (20 bytes)
if ((buffer[ISO7816.OFFSET_CDATA] != (byte) 0x94) || (buffer[ISO7816.OFFSET_CDATA + 1] != (byte) 0x14))
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
// use the basic private key
JCSystem.beginTransaction();
//@ open valid();
//@ transient_byte_arrays_mem(messageBuffer);
//@ assert transient_byte_arrays(?as);
//@ foreachp_remove(messageBuffer, as);
//@ open transient_byte_array(messageBuffer);
if (basicKeyPair == null)
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
//VF: bovenstaande is mogelijk bug in programma!
cipher.init(basicKeyPair.getPrivate(), Cipher.MODE_ENCRYPT);
// prepare the message buffer to the PKCS#1 (v1.5) structure
preparePkcs1ClearText(messageBuffer, ALG_SHA1_PKCS1, lc);
// copy the challenge (SHA1 hash) from the APDU to the message buffer
Util.arrayCopy(buffer, (short) (ISO7816.OFFSET_CDATA + 2), messageBuffer, (short) 108, (short) 20);
// generate signature
cipher.doFinal(messageBuffer, (short) 0, (short) 128, buffer, (short) 0);
// if T=0, store signature in sigBuffer so that it can latter be sent
if (APDU.getProtocol() == APDU.PROTOCOL_T1) {
Util.arrayCopy(buffer, (short) 0, responseBuffer, (short) 0, (short) 128);
// in case T=1 protocol, send the signature immediately in a
// response APDU
} else {
// send first 128 bytes (= 1024 bit) of buffer
apdu.setOutgoingAndSend((short) 0, (short) 128);
}
// decrement internal authenticate counter
//internalAuthenticateCounter--;
//@ close transient_byte_array(messageBuffer);
//@ foreachp_unremove(messageBuffer, as);
//@ close valid();
JCSystem.commitTransaction();
}
/**
* return the generated signature in a response APDU Used in T=0 protocol
*/
private void getResponse(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
//@ open [1/2]valid();
// use P1 and P2 as offset
short offset = Util.makeShort(buffer[ISO7816.OFFSET_P1], buffer[ISO7816.OFFSET_P2]);
if (offset > responseBuffer.length)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// inform the JCRE that the applet has data to return
short le = apdu.setOutgoing();
// if Le = 0, then return the complete signature (128 bytes = 1024 bits)
// Le = 256 possible on real card
if ((le == 0) || (le == 256))
le = 128;
// set the actual number of outgoing data bytes
apdu.setOutgoingLength(le);
// send content of sigBuffer in apdu
if ((short) (offset + le) > (short)128 || offset < (short)0)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
apdu.sendBytesLong(responseBuffer, offset, le);
//@ close [1/2]valid();
}
/**
* generate a random challenge
*/
private void getChallenge(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P1 and P2
if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00 || buffer[ISO7816.OFFSET_P2] != (byte) 0x00)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// inform the JCRE that the applet has data to return
short le = apdu.setOutgoing();
// Le = 0 is not allowed
if (le == 0)
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
JCSystem.beginTransaction();
//@ open valid();
RandomData random = NewEidCard.randomData;
// generate random data and put it into buffer
random.generateData(randomBuffer, (short) 0, le);
// set the actual number of outgoing data bytes
apdu.setOutgoingLength(le);
// send content of buffer in apdu
apdu.sendBytesLong(randomBuffer, (short) 0, le);
//@ close valid();
JCSystem.commitTransaction();
}
/**
* select a file on the eID card
*
* this file can latter be read by a READ BINARY
*/
private void selectFile(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P2
if (buffer[ISO7816.OFFSET_P2] != (byte) 0x0C)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// P1 determines the select method
switch (buffer[ISO7816.OFFSET_P1]) {
case (byte) 0x02:
selectByFileIdentifier(apdu, buffer);
break;
case (byte) 0x08:
selectByPath(apdu, buffer);
break;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
break; //~allow_dead_code
}
}
/**
* set the previous APDU type to a certain value
*/
private void setPreviousApduType(byte type)
//@ requires previousApduType |-> ?thePreviousApduType &*& thePreviousApduType != null &*& thePreviousApduType.length == 1 &*& is_transient_byte_array(thePreviousApduType) == true &*& transient_byte_arrays(?ta) &*& foreachp(ta, transient_byte_array);
//@ ensures previousApduType |-> thePreviousApduType &*& thePreviousApduType != null &*& transient_byte_arrays(ta) &*& foreachp(ta, transient_byte_array);
{
//@ transient_byte_arrays_mem(thePreviousApduType);
//@ foreachp_remove(thePreviousApduType, ta);
//@ open transient_byte_array(thePreviousApduType);
previousApduType[0] = type;
//@ close transient_byte_array(thePreviousApduType);
//@ foreachp_unremove(thePreviousApduType, ta);
}
/**
* return the previous APDU type
*/
private byte getPreviousApduType()
//@ requires [?f]previousApduType |-> ?thePreviousApduType &*& thePreviousApduType != null &*& thePreviousApduType.length == 1 &*& is_transient_byte_array(thePreviousApduType) == true &*& transient_byte_arrays(?ta) &*& foreachp(ta, transient_byte_array);
//@ ensures [f]previousApduType |-> thePreviousApduType &*& transient_byte_arrays(ta) &*& foreachp(ta, transient_byte_array);
{
//@ transient_byte_arrays_mem(thePreviousApduType);
//@ foreachp_remove(thePreviousApduType, ta);
//@ open transient_byte_array(thePreviousApduType);
return previousApduType[0];
//@ close transient_byte_array(thePreviousApduType);
//@ foreachp_unremove(thePreviousApduType, ta);
}
/**
* set the signature type to a certain value
*/
private void setSignatureType(byte type)
//@ requires signatureType |-> ?theSignatureType &*& theSignatureType != null &*& theSignatureType.length == 1 &*& is_transient_byte_array(theSignatureType) == true &*& transient_byte_arrays(?ta) &*& foreachp(ta, transient_byte_array);
//@ ensures signatureType |-> theSignatureType &*& is_transient_byte_array(theSignatureType) == true &*& transient_byte_arrays(ta) &*& foreachp(ta, transient_byte_array);
{
//@ transient_byte_arrays_mem(theSignatureType);
//@ foreachp_remove(theSignatureType, ta);
//@ open transient_byte_array(theSignatureType);
signatureType[0] = type;
//@ close transient_byte_array(theSignatureType);
//@ foreachp_unremove(theSignatureType, ta);
}
/**
* return the signature type
*/
private byte getSignatureType()
//@ requires [?f]signatureType |-> ?theSignatureType &*& theSignatureType != null &*& theSignatureType.length == 1 &*& is_transient_byte_array(theSignatureType) == true &*& transient_byte_arrays(?ta) &*& foreachp(ta, transient_byte_array);
//@ ensures [f]signatureType |-> theSignatureType &*& transient_byte_arrays(ta) &*& foreachp(ta, transient_byte_array);
{
//@ transient_byte_arrays_mem(theSignatureType);
//@ foreachp_remove(theSignatureType, ta);
//@ open transient_byte_array(theSignatureType);
return signatureType[0];
//@ close transient_byte_array(theSignatureType);
//@ foreachp_unremove(theSignatureType, ta);
}
/**
* deactivate a file on the eID card security conditions depend on file to
* activate: see belgian eID content file
*/
private void deactivateFile(APDU apdu, byte[] buffer)
//@ requires current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
//@ ensures current_applet(this) &*& [1/2]valid() &*& APDU(apdu, buffer) &*& array_slice(buffer, 0, buffer.length, _);
{
// check P2
if (buffer[ISO7816.OFFSET_P2] != (byte) 0x0C)
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
// P1 determines the select method
switch (buffer[ISO7816.OFFSET_P1]) {
case (byte) 0x02:
selectByFileIdentifier(apdu, buffer);
break;
case (byte) 0x08:
selectByPath(apdu, buffer);
break;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
break; //~allow_dead_code
}
// check if deactivating this file is allowed
if (!fileAccessAllowed(UPDATE_BINARY))
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
JCSystem.beginTransaction();
//@ open valid();
//@ open selected_file_types(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, ?sf2);
//@ sf2.castElementaryToFile();
selectedFile.setActive(false);
//@ sf2.castFileToElementary();
//@ close valid();
JCSystem.commitTransaction();
}
public Shareable getShareableInterfaceObject(AID oAid, byte bArg)
//@ requires [1/2]this.valid() &*& registered_applets(?as) &*& foreachp(remove<Applet>(this, as), semi_valid) &*& mem<Applet>(this, as) == true &*& AID(oAid);
//@ ensures [1/2]this.valid() &*& registered_applets(as) &*& foreachp(remove<Applet>(this, as), semi_valid) &*& AID(oAid) &*& result == null ? true : result.Shareable(?a) &*& mem<Applet>(a, as) == true;
{
//check if AID is allowed
//@ NewEidPointsObject.getShareable();
if (bArg == (byte)0x0) // Based on argument, return
// object reference
return (Shareable) (NewEidPointsObject);
else
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
return null; //~allow_dead_code
}
private void askForCharge()
//@ requires current_applet(this) &*& [1/2]valid();
//@ ensures current_applet(this) &*& [1/2]valid();
{
AID Purse_AID = JCSystem.lookupAID(NewEPurseAID,(short)0, (byte)NewEPurseAID.length);
if (Purse_AID == null)
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
JCSystem.beginTransaction(); // Added for VeriFast
IEPurseServicesCredit NewEPurseCreditObject = (IEPurseServicesCredit)
(JCSystem.getAppletShareableInterfaceObject(Purse_AID, (byte)0x01));
short points = Points;
if (NewEPurseCreditObject != null) {
//@ Shareable epurseServiceSIO = NewEPurseCreditObject;
//@ assert epurseServiceSIO.Shareable(?epurseApplet);
//@ mem_registered_applets_is(this);
//@ assert registered_applets(?as1);
//@ foreachp_unremove<Applet>(this, as1);
//@ set_current_applet(epurseApplet);
//@ foreachp_remove(epurseApplet, as1);
NewEPurseCreditObject.charge(points);
//@ is_registered_applets_mem(this);
//@ assert registered_applets(?as2);
//@ foreachp_unremove(epurseApplet, as2);
//@ set_current_applet(this);
//@ foreachp_remove<Applet>(this, as2);
}
JCSystem.commitTransaction(); // Added for VeriFast
}
}
| verifast/verifast | examples/java/Java Card/NewEidCard/NewEidCard.java |
711 | /*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2016 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in
* http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of the Unicode data files and any associated documentation
* (the "Data Files") or Unicode software and any associated documentation
* (the "Software") to deal in the Data Files or Software
* without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, and/or sell copies of
* the Data Files or Software, and to permit persons to whom the Data Files
* or Software are furnished to do so, provided that
* (a) this copyright and permission notice appear with all copies
* of the Data Files or Software,
* (b) this copyright and permission notice appear in associated
* documentation, and
* (c) there is clear notice in each modified Data File or in the Software
* as well as in the documentation associated with the Data File(s) or
* Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
* ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT OF THIRD PARTY RIGHTS.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
* NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
* DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale,
* use or other dealings in these Data Files or Software without prior
* written authorization of the copyright holder.
*/
package sun.util.resources.cldr.ext;
import sun.util.resources.OpenListResourceBundle;
public class LocaleNames_nl extends OpenListResourceBundle {
@Override
protected final Object[][] getContents() {
final String metaValue_ar = "Arabisch";
final String metaValue_bn = "Bengaals";
final String metaValue_bo = "Tibetaans";
final String metaValue_el = "Grieks";
final String metaValue_gu = "Gujarati";
final String metaValue_he = "Hebreeuws";
final String metaValue_hy = "Armeens";
final String metaValue_ii = "Yi";
final String metaValue_ja = "Japans";
final String metaValue_jv = "Javaans";
final String metaValue_ka = "Georgisch";
final String metaValue_km = "Khmer";
final String metaValue_kn = "Kannada";
final String metaValue_ko = "Koreaans";
final String metaValue_lo = "Laotiaans";
final String metaValue_ml = "Malayalam";
final String metaValue_mn = "Mongools";
final String metaValue_my = "Birmaans";
final String metaValue_or = "Odia";
final String metaValue_sd = "Sindhi";
final String metaValue_si = "Singalees";
final String metaValue_su = "Soendanees";
final String metaValue_ta = "Tamil";
final String metaValue_te = "Telugu";
final String metaValue_th = "Thai";
final String metaValue_tl = "Tagalog";
final String metaValue_ban = "Balinees";
final String metaValue_bax = "Bamoun";
final String metaValue_bug = "Buginees";
final String metaValue_ccp = "Chakma";
final String metaValue_chr = "Cherokee";
final String metaValue_cop = "Koptisch";
final String metaValue_got = "Gothisch";
final String metaValue_kpe = "Kpelle";
final String metaValue_men = "Mende";
final String metaValue_mni = "Meitei";
final String metaValue_new = "Newari";
final String metaValue_nqo = "N\u2019Ko";
final String metaValue_osa = "Osage";
final String metaValue_peo = "Oudperzisch";
final String metaValue_phn = "Foenicisch";
final String metaValue_saz = "Saurashtra";
final String metaValue_sog = "Sogdisch";
final String metaValue_ssy = "Saho";
final String metaValue_vai = "Vai";
final String metaValue_zbl = "Blissymbolen";
final Object[][] data = new Object[][] {
{ "ksh", "K\u00f6lsch" },
{ "Ogam", "Ogham" },
{ "mwl", "Mirandees" },
{ "Zsym", "Symbolen" },
{ "cch", "Atsam" },
{ "mwr", "Marwari" },
{ "type.nu.lanatham", "Tai Tham Tham cijfers" },
{ "egl", "Emiliano" },
{ "mwv", "Mentawai" },
{ "Tagb", "Tagbanwa" },
{ "Zsye", "emoji" },
{ "%%NJIVA", "Gniva/Njiva-dialect" },
{ "xmf", "Mingreels" },
{ "ccp", metaValue_ccp },
{ "egy", "Oudegyptisch" },
{ "raj", "Rajasthani" },
{ "Phag", "Phags-pa" },
{ "tem", "Timne" },
{ "Medf", "Medefaidrin" },
{ "type.nu.sind", "Khudawadi cijfers" },
{ "teo", "Teso" },
{ "rap", "Rapanui" },
{ "ter", "Tereno" },
{ "AC", "Ascension" },
{ "rar", "Rarotongan" },
{ "tet", "Tetun" },
{ "%%BARLA", "Barlavento-dialectgroep van Kabuverdianu" },
{ "type.nu.sinh", "Sinhala Lith cijfers" },
{ "AD", "Andorra" },
{ "AE", "Verenigde Arabische Emiraten" },
{ "AF", "Afghanistan" },
{ "AG", "Antigua en Barbuda" },
{ "type.nu.mroo", "Mro cijfers" },
{ "type.ca.ethiopic", "Ethiopische kalender" },
{ "glk", "Gilaki" },
{ "AI", "Anguilla" },
{ "key.tz", "Tijdzone" },
{ "AL", "Albani\u00eb" },
{ "AM", "Armeni\u00eb" },
{ "Teng", "Tengwar" },
{ "AO", "Angola" },
{ "AQ", "Antarctica" },
{ "AR", "Argentini\u00eb" },
{ "Prti", "Inscriptioneel Parthisch" },
{ "AS", "Amerikaans-Samoa" },
{ "AT", "Oostenrijk" },
{ "AU", "Australi\u00eb" },
{ "AW", "Aruba" },
{ "AX", "\u00c5land" },
{ "mye", "Myene" },
{ "AZ", "Azerbeidzjan" },
{ "%%AREVELA", "Oost-Armeens" },
{ "BA", "Bosni\u00eb en Herzegovina" },
{ "BB", "Barbados" },
{ "ceb", "Cebuano" },
{ "BD", "Bangladesh" },
{ "kum", "Koemuks" },
{ "BE", "Belgi\u00eb" },
{ "gmh", "Middelhoogduits" },
{ "Sogo", "Oud Sogdisch" },
{ "BF", "Burkina Faso" },
{ "BG", "Bulgarije" },
{ "BH", "Bahrein" },
{ "BI", "Burundi" },
{ "BJ", "Benin" },
{ "BL", "Saint-Barth\u00e9lemy" },
{ "BM", "Bermuda" },
{ "kut", "Kutenai" },
{ "myv", "Erzja" },
{ "BN", "Brunei" },
{ "BO", "Bolivia" },
{ "BQ", "Caribisch Nederland" },
{ "BR", "Brazili\u00eb" },
{ "BS", "Bahama\u2019s" },
{ "xog", "Soga" },
{ "BT", "Bhutan" },
{ "BV", "Bouveteiland" },
{ "BW", "Botswana" },
{ "BY", "Belarus" },
{ "BZ", "Belize" },
{ "Visp", "Zichtbare spraak" },
{ "type.ca.persian", "Perzische kalender" },
{ "%%CREISS", "Creiss" },
{ "type.nu.hebr", "Hebreeuwse cijfers" },
{ "CA", "Canada" },
{ "Kits", "Kitaans kleinschrift" },
{ "CC", "Cocoseilanden" },
{ "mzn", "Mazanderani" },
{ "CD", "Congo-Kinshasa" },
{ "CF", "Centraal-Afrikaanse Republiek" },
{ "CG", "Congo-Brazzaville" },
{ "CH", "Zwitserland" },
{ "CI", "Ivoorkust" },
{ "CK", "Cookeilanden" },
{ "CL", "Chili" },
{ "Kthi", "Kaithi" },
{ "CM", "Kameroen" },
{ "CN", "China" },
{ "CO", "Colombia" },
{ "CP", "Clipperton" },
{ "CR", "Costa Rica" },
{ "CU", "Cuba" },
{ "CV", "Kaapverdi\u00eb" },
{ "CW", "Cura\u00e7ao" },
{ "CX", "Christmaseiland" },
{ "CY", "Cyprus" },
{ "type.nu.bali", "Balinese cijfers" },
{ "CZ", "Tsjechi\u00eb" },
{ "eka", "Ekajuk" },
{ "Ahom", "Ahom" },
{ "Pauc", "Pau Cin Hau" },
{ "vls", "West-Vlaams" },
{ "%%RIGIK", "Klassiek Volap\u00fck" },
{ "Sogd", metaValue_sog },
{ "DE", "Duitsland" },
{ "goh", "Oudhoogduits" },
{ "ace", "Atjehs" },
{ "cgg", "Chiga" },
{ "DG", "Diego Garcia" },
{ "gom", "Goa Konkani" },
{ "type.nu.deva", "Devanagari cijfers" },
{ "DJ", "Djibouti" },
{ "DK", "Denemarken" },
{ "ach", "Akoli" },
{ "gon", "Gondi" },
{ "Brai", "Braille" },
{ "Brah", "Brahmi" },
{ "DM", "Dominica" },
{ "type.nu.armnlow", "kleine Armeense cijfers" },
{ "DO", "Dominicaanse Republiek" },
{ "gor", "Gorontalo" },
{ "got", metaValue_got },
{ "vmf", "Opperfrankisch" },
{ "Mtei", metaValue_mni },
{ "zun", "Zuni" },
{ "tig", "Tigre" },
{ "Takr", "Takri" },
{ "DZ", "Algerije" },
{ "pag", "Pangasinan" },
{ "type.d0.hwidth", "Halve breedte" },
{ "pal", "Pahlavi" },
{ "EA", "Ceuta en Melilla" },
{ "chb", "Chibcha" },
{ "pam", "Pampanga" },
{ "EC", "Ecuador" },
{ "pap", "Papiaments" },
{ "ada", "Adangme" },
{ "EE", "Estland" },
{ "tiv", "Tiv" },
{ "EG", "Egypte" },
{ "EH", "Westelijke Sahara" },
{ "chg", "Chagatai" },
{ "pau", "Palaus" },
{ "chk", "Chuukees" },
{ "chn", "Chinook Jargon" },
{ "chm", "Mari" },
{ "chp", "Chipewyan" },
{ "cho", "Choctaw" },
{ "type.nu.mathbold", "vette wiskundige cijfers" },
{ "chr", metaValue_chr },
{ "ER", "Eritrea" },
{ "ES", "Spanje" },
{ "ET", "Ethiopi\u00eb" },
{ "EU", "Europese Unie" },
{ "elx", "Elamitisch" },
{ "type.ca.gregorian", "Gregoriaanse kalender" },
{ "EZ", "eurozone" },
{ "chy", "Cheyenne" },
{ "type.nu.gujr", "Gujarati cijfers" },
{ "Inds", "Indus" },
{ "ady", "Adygees" },
{ "aeb", "Tunesisch Arabisch" },
{ "FI", "Finland" },
{ "FJ", "Fiji" },
{ "FK", "Falklandeilanden" },
{ "FM", "Micronesia" },
{ "key.va", "Landvariant" },
{ "FO", "Faer\u00f6er" },
{ "Taml", metaValue_ta },
{ "FR", "Frankrijk" },
{ "Kpel", metaValue_kpe },
{ "%%SIMPLE", "Simpel" },
{ "pcd", "Picardisch" },
{ "tkl", "Tokelaus" },
{ "grb", "Grebo" },
{ "root", "Root" },
{ "%%DAJNKO", "Dajnko-alfabet" },
{ "type.ca.indian", "Indiase nationale kalender" },
{ "rgn", "Romagnol" },
{ "grc", "Oudgrieks" },
{ "GA", "Gabon" },
{ "tkr", "Tsakhur" },
{ "vot", "Votisch" },
{ "GB", "Verenigd Koninkrijk" },
{ "pcm", "Nigeriaans Pidgin" },
{ "GD", "Grenada" },
{ "GE", "Georgi\u00eb" },
{ "GF", "Frans-Guyana" },
{ "GG", "Guernsey" },
{ "GH", "Ghana" },
{ "Tale", "Tai Le" },
{ "GI", "Gibraltar" },
{ "afh", "Afrihili" },
{ "GL", "Groenland" },
{ "enm", "Middelengels" },
{ "GM", "Gambia" },
{ "GN", "Guinee" },
{ "GP", "Guadeloupe" },
{ "GQ", "Equatoriaal-Guinea" },
{ "GR", "Griekenland" },
{ "GS", "Zuid-Georgia en Zuidelijke Sandwicheilanden" },
{ "GT", "Guatemala" },
{ "GU", "Guam" },
{ "pdc", "Pennsylvania-Duits" },
{ "type.nu.mathmono", "niet-proportionele wiskundige cijfers" },
{ "GW", "Guinee-Bissau" },
{ "tli", "Tlingit" },
{ "tlh", "Klingon" },
{ "Talu", "Nieuw Tai Lue" },
{ "GY", "Guyana" },
{ "ckb", "Soran\u00ee" },
{ "zxx", "geen lingu\u00efstische inhoud" },
{ "Jurc", "Jurchen" },
{ "tly", "Talysh" },
{ "%%VIVARAUP", "Vivaraup" },
{ "pdt", "Plautdietsch" },
{ "Vaii", metaValue_vai },
{ "HK", "Hongkong SAR van China" },
{ "HM", "Heard en McDonaldeilanden" },
{ "HN", "Honduras" },
{ "HR", "Kroati\u00eb" },
{ "agq", "Aghem" },
{ "gsw", "Zwitserduits" },
{ "type.ca.islamic-umalqura", "Islamitische kalender (Umm al-Qura)" },
{ "HT", "Ha\u00efti" },
{ "HU", "Hongarije" },
{ "rif", "Riffijns" },
{ "tmh", "Tamashek" },
{ "IC", "Canarische Eilanden" },
{ "nan", "Minnanyu" },
{ "peo", metaValue_peo },
{ "ID", "Indonesi\u00eb" },
{ "Adlm", "Adlam" },
{ "type.nu.kali", "Kayah Li cijfers" },
{ "IE", "Ierland" },
{ "nap", "Napolitaans" },
{ "%%NDYUKA", "Ndyuka-dialect" },
{ "naq", "Nama" },
{ "type.nu.sora", "Sora Sompeng cijfers" },
{ "zza", "Zaza" },
{ "Tang", "Tangut" },
{ "IL", "Isra\u00ebl" },
{ "Nbat", "Nabateaans" },
{ "IM", "Isle of Man" },
{ "IN", "India" },
{ "type.co.eor", "Europese sorteerregels" },
{ "IO", "Brits Indische Oceaanterritorium" },
{ "IQ", "Irak" },
{ "IR", "Iran" },
{ "IS", "IJsland" },
{ "IT", "Itali\u00eb" },
{ "Zmth", "Wiskundige notatie" },
{ "type.nu.thai", "Thaise cijfers" },
{ "vro", "V\u00f5ro" },
{ "guc", "Wayuu" },
{ "%%POSIX", "Computer" },
{ "type.nu.beng", "Bengaalse cijfers" },
{ "pfl", "Paltsisch" },
{ "type.nu.cyrl", "Cyrillische cijfers" },
{ "JE", "Jersey" },
{ "type.ca.islamic", "Islamitische kalender" },
{ "Beng", metaValue_bn },
{ "JM", "Jamaica" },
{ "%%EKAVSK", "Servisch met Ekaviaanse uitspraak" },
{ "JO", "Jordani\u00eb" },
{ "gur", "Gurune" },
{ "JP", "Japan" },
{ "%%1606NICT", "Laat Middelfrans tot 1606" },
{ "ain", "Aino" },
{ "%%KOCIEWIE", "Kociewie" },
{ "Mend", metaValue_men },
{ "guz", "Gusii" },
{ "tog", "Nyasa Tonga" },
{ "type.nu.knda", "Kannada cijfers" },
{ "Kali", "Kayah Li" },
{ "Sidd", "Siddham" },
{ "type.co.phonetic", "Fonetische sorteervolgorde" },
{ "izh", "Ingrisch" },
{ "type.ca.buddhist", "Boeddhistische kalender" },
{ "KE", "Kenia" },
{ "419", "Latijns-Amerika" },
{ "KG", "Kirgizi\u00eb" },
{ "KH", "Cambodja" },
{ "KI", "Kiribati" },
{ "KM", "Comoren" },
{ "Knda", metaValue_kn },
{ "KN", "Saint Kitts en Nevis" },
{ "Zinh", "Overge\u00ebrfd" },
{ "KP", "Noord-Korea" },
{ "KR", "Zuid-Korea" },
{ "Plrd", "Pollard-fonetisch" },
{ "KW", "Koeweit" },
{ "tpi", "Tok Pisin" },
{ "KY", "Kaaimaneilanden" },
{ "KZ", "Kazachstan" },
{ "Cyrl", "Cyrillisch" },
{ "LA", "Laos" },
{ "LB", "Libanon" },
{ "phn", metaValue_phn },
{ "LC", "Saint Lucia" },
{ "Cyrs", "Oudkerkslavisch Cyrillisch" },
{ "gwi", "Gwich\u02bcin" },
{ "%%LUNA1918", "Russische spelling van 1917" },
{ "nds", "Nedersaksisch" },
{ "LI", "Liechtenstein" },
{ "LK", "Sri Lanka" },
{ "akk", "Akkadisch" },
{ "cop", metaValue_cop },
{ "Hmnp", "Nyiakeng Puachue Hmong" },
{ "LR", "Liberia" },
{ "esu", "Yupik" },
{ "LS", "Lesotho" },
{ "Phlv", "Boek Pahlavi" },
{ "LT", "Litouwen" },
{ "LU", "Luxemburg" },
{ "LV", "Letland" },
{ "Kana", "Katakana" },
{ "Sora", "Sora Sompeng" },
{ "LY", "Libi\u00eb" },
{ "lad", "Ladino" },
{ "vun", "Vunjo" },
{ "akz", "Alabama" },
{ "%%LAUKIKA", "Laukika" },
{ "lah", "Lahnda" },
{ "Mahj", "Mahajani" },
{ "lag", "Langi" },
{ "Thaa", "Thaana" },
{ "MA", "Marokko" },
{ "MC", "Monaco" },
{ "MD", "Moldavi\u00eb" },
{ "Nshu", "N\u00fcshu" },
{ "ME", "Montenegro" },
{ "MF", "Saint-Martin" },
{ "lam", "Lamba" },
{ "MG", "Madagaskar" },
{ "Thai", metaValue_th },
{ "MH", "Marshalleilanden" },
{ "ale", "Aleoetisch" },
{ "type.nu.vaii", "Vai-cijfers" },
{ "MK", "Noord-Macedoni\u00eb" },
{ "type.nu.mathdbl", "wiskundige cijfers met dubbele lijn" },
{ "ML", "Mali" },
{ "MM", "Myanmar (Birma)" },
{ "new", metaValue_new },
{ "MN", "Mongoli\u00eb" },
{ "MO", "Macau SAR van China" },
{ "aln", "Gegisch" },
{ "MP", "Noordelijke Marianen" },
{ "MQ", "Martinique" },
{ "MR", "Mauritani\u00eb" },
{ "MS", "Montserrat" },
{ "Chrs", "Chorasmisch" },
{ "MT", "Malta" },
{ "cps", "Capiznon" },
{ "type.m0.ungegn", "UNGEGN" },
{ "MU", "Mauritius" },
{ "alt", "Zuid-Alta\u00efsch" },
{ "MV", "Maldiven" },
{ "MW", "Malawi" },
{ "MX", "Mexico" },
{ "type.ca.japanese", "Japanse kalender" },
{ "MY", "Maleisi\u00eb" },
{ "MZ", "Mozambique" },
{ "Phli", "Inscriptioneel Pahlavi" },
{ "NA", "Namibi\u00eb" },
{ "%%ARANES", "Aranees" },
{ "202", "Sub-Saharaans Afrika" },
{ "type.ca.hebrew", "Hebreeuwse kalender" },
{ "type.co.dictionary", "Woordenboeksorteervolgorde" },
{ "NC", "Nieuw-Caledoni\u00eb" },
{ "%%WADEGILE", "Wade-Giles-romanisering" },
{ "tru", "Turoyo" },
{ "%%UCRCOR", "Eenvormig herziene spelling" },
{ "NE", "Niger" },
{ "NF", "Norfolk" },
{ "NG", "Nigeria" },
{ "trv", "Taroko" },
{ "Phlp", "Psalmen Pahlavi" },
{ "NI", "Nicaragua" },
{ "Hmng", "Pahawh Hmong" },
{ "NL", "Nederland" },
{ "NO", "Noorwegen" },
{ "NP", "Nepal" },
{ "NR", "Nauru" },
{ "tsd", "Tsakonisch" },
{ "Phnx", metaValue_phn },
{ "NU", "Niue" },
{ "rof", "Rombo" },
{ "tsi", "Tsimshian" },
{ "NZ", "Nieuw-Zeeland" },
{ "Merc", "Meroitisch cursief" },
{ "%%COLB1945", "Portugese-Braziliaanse spellingsverdrag van 1945" },
{ "rom", "Romani" },
{ "Mero", "Mero\u00eftisch" },
{ "crh", "Krim-Tataars" },
{ "ang", "Oudengels" },
{ "%%GRMISTR", "Grmistr" },
{ "OM", "Oman" },
{ "%%PETR1708", "Petr1708" },
{ "anp", "Angika" },
{ "crs", "Seychellencreools" },
{ "type.nu.hmnp", "Nyiakeng Puachue Hmong cijfers" },
{ "Xpeo", metaValue_peo },
{ "type.nu.hmng", "Pahawh Hmong cijfers" },
{ "PA", "Panama" },
{ "type.ca.islamic-civil", "Islamitische kalender (cyclisch)" },
{ "csb", "Kasjoebisch" },
{ "PE", "Peru" },
{ "ttt", "Moslim Tat" },
{ "PF", "Frans-Polynesi\u00eb" },
{ "PG", "Papoea-Nieuw-Guinea" },
{ "PH", "Filipijnen" },
{ "PK", "Pakistan" },
{ "%%NICARD", "Nicard" },
{ "PL", "Polen" },
{ "ewo", "Ewondo" },
{ "PM", "Saint-Pierre en Miquelon" },
{ "PN", "Pitcairneilanden" },
{ "PR", "Puerto Rico" },
{ "Bali", metaValue_ban },
{ "PS", "Palestijnse gebieden" },
{ "PT", "Portugal" },
{ "PW", "Palau" },
{ "nia", "Nias" },
{ "type.nu.greklow", "kleine Griekse cijfers" },
{ "PY", "Paraguay" },
{ "tum", "Toemboeka" },
{ "Hebr", metaValue_he },
{ "QA", "Qatar" },
{ "%%SCOTLAND", "Schots standaard-Engels" },
{ "jam", "Jamaicaans Creools" },
{ "pms", "Pi\u00ebmontees" },
{ "niu", "Niueaans" },
{ "QO", "overig Oceani\u00eb" },
{ "ext", "Extremeens" },
{ "lez", "Lezgisch" },
{ "type.nu.ahom", "Ahom cijfers" },
{ "%%FONUPA", "Oeralisch Fonetisch Alfabet" },
{ "type.nu.takr", "Takri cijfers" },
{ "tvl", "Tuvaluaans" },
{ "Tavt", "Tai Viet" },
{ "%%SOTAV", "Sotavento-dialectgroep van Kabuverdianu" },
{ "Maka", "Makasar" },
{ "001", "wereld" },
{ "002", "Afrika" },
{ "njo", "Ao Naga" },
{ "003", "Noord-Amerika" },
{ "RE", "R\u00e9union" },
{ "005", "Zuid-Amerika" },
{ "lfn", "Lingua Franca Nova" },
{ "jbo", "Lojban" },
{ "pnt", "Pontisch" },
{ "Rjng", "Rejang" },
{ "009", "Oceani\u00eb" },
{ "Elym", "Elymaisch" },
{ "%%SURSILV", "Sursilvan" },
{ "RO", "Roemeni\u00eb" },
{ "RS", "Servi\u00eb" },
{ "Mroo", "Mro" },
{ "RU", "Rusland" },
{ "RW", "Rwanda" },
{ "type.nu.talu", "nieuwe Tai Lue cijfers" },
{ "%%METELKO", "Metelko-alfabet" },
{ "Mani", "Manicheaans" },
{ "Ugar", "Ugaritisch" },
{ "Khar", "Kharoshthi" },
{ "SA", "Saoedi-Arabi\u00eb" },
{ "pon", "Pohnpeiaans" },
{ "Mand", "Mandaeans" },
{ "SB", "Salomonseilanden" },
{ "twq", "Tasawaq" },
{ "011", "West-Afrika" },
{ "SC", "Seychellen" },
{ "SD", "Soedan" },
{ "013", "Midden-Amerika" },
{ "SE", "Zweden" },
{ "014", "Oost-Afrika" },
{ "arc", "Aramees" },
{ "Loma", "Loma" },
{ "015", "Noord-Afrika" },
{ "SG", "Singapore" },
{ "SH", "Sint-Helena" },
{ "type.lb.strict", "strikte stijl regelafbreking" },
{ "017", "Centraal-Afrika" },
{ "SI", "Sloveni\u00eb" },
{ "type.nu.mymrtlng", "Myanmar Tai Laing cijfers" },
{ "018", "Zuidelijk Afrika" },
{ "SJ", "Spitsbergen en Jan Mayen" },
{ "Bamu", metaValue_bax },
{ "019", "Amerika" },
{ "SK", "Slowakije" },
{ "Wole", "Woleai" },
{ "SL", "Sierra Leone" },
{ "SM", "San Marino" },
{ "SN", "Senegal" },
{ "SO", "Somali\u00eb" },
{ "arn", "Mapudungun" },
{ "arp", "Arapaho" },
{ "type.nu.taml", "traditionele Tamil cijfers" },
{ "SR", "Suriname" },
{ "aro", "Araona" },
{ "SS", "Zuid-Soedan" },
{ "ST", "Sao Tom\u00e9 en Principe" },
{ "arq", "Algerijns Arabisch" },
{ "SV", "El Salvador" },
{ "ars", "Nadjdi-Arabisch" },
{ "SX", "Sint-Maarten" },
{ "SY", "Syri\u00eb" },
{ "yao", "Yao" },
{ "SZ", "eSwatini" },
{ "arw", "Arawak" },
{ "arz", "Egyptisch Arabisch" },
{ "ary", "Marokkaans Arabisch" },
{ "yap", "Yapees" },
{ "rtm", "Rotumaans" },
{ "TA", "Tristan da Cunha" },
{ "asa", "Asu" },
{ "type.ms.ussystem", "Amerikaans imperiaal stelsel" },
{ "021", "Noordelijk Amerika" },
{ "TC", "Turks- en Caicoseilanden" },
{ "yav", "Yangben" },
{ "TD", "Tsjaad" },
{ "Qaag", "Zawgyi" },
{ "TF", "Franse Gebieden in de zuidelijke Indische Oceaan" },
{ "ase", "Amerikaanse Gebarentaal" },
{ "TG", "Togo" },
{ "TH", "Thailand" },
{ "TJ", "Tadzjikistan" },
{ "029", "Caribisch gebied" },
{ "TK", "Tokelau" },
{ "TL", "Oost-Timor" },
{ "ybb", "Yemba" },
{ "type.co.searchjl", "Zoeken op eerste Hangul-medeklinker" },
{ "TM", "Turkmenistan" },
{ "%%BOONT", "Boontling" },
{ "TN", "Tunesi\u00eb" },
{ "TO", "Tonga" },
{ "%%NULIK", "Modern Volap\u00fck" },
{ "TR", "Turkije" },
{ "TT", "Trinidad en Tobago" },
{ "TV", "Tuvalu" },
{ "TW", "Taiwan" },
{ "ast", "Asturisch" },
{ "rue", "Roetheens" },
{ "rug", "Roviana" },
{ "Orkh", "Orkhon" },
{ "TZ", "Tanzania" },
{ "nmg", "Ngumba" },
{ "Zzzz", "onbekend schriftsysteem" },
{ "Sind", metaValue_sd },
{ "UA", "Oekra\u00efne" },
{ "lij", "Ligurisch" },
{ "rup", "Aroemeens" },
{ "030", "Oost-Azi\u00eb" },
{ "tyv", "Toevaans" },
{ "034", "Zuid-Azi\u00eb" },
{ "hai", "Haida" },
{ "035", "Zuidoost-Azi\u00eb" },
{ "UG", "Oeganda" },
{ "hak", "Hakka" },
{ "type.co.pinyin", "Pinyinvolgorde" },
{ "039", "Zuid-Europa" },
{ "Sinh", metaValue_si },
{ "UM", "Kleine afgelegen eilanden van de Verenigde Staten" },
{ "liv", "Lijfs" },
{ "UN", "Verenigde Naties" },
{ "US", "Verenigde Staten" },
{ "haw", "Hawa\u00efaans" },
{ "%%1959ACAD", "Academisch" },
{ "%%IVANCHOV", "Ivanchov" },
{ "type.co.gb2312han", "Vereenvoudigd-Chinese sorteervolgorde - GB2312" },
{ "UY", "Uruguay" },
{ "prg", "Oudpruisisch" },
{ "UZ", "Oezbekistan" },
{ "tzm", "Tamazight (Centraal-Marokko)" },
{ "type.co.stroke", "Streeksorteervolgorde" },
{ "nnh", "Ngiemboon" },
{ "VA", "Vaticaanstad" },
{ "pro", "Oudproven\u00e7aals" },
{ "VC", "Saint Vincent en de Grenadines" },
{ "%%HSISTEMO", "H-sistemo" },
{ "VE", "Venezuela" },
{ "VG", "Britse Maagdeneilanden" },
{ "VI", "Amerikaanse Maagdeneilanden" },
{ "%%LEMOSIN", "Lemosin" },
{ "Soyo", "Soyombo" },
{ "VN", "Vietnam" },
{ "VU", "Vanuatu" },
{ "Marc", "Marchen" },
{ "nog", "Nogai" },
{ "rwk", "Rwa" },
{ "non", "Oudnoors" },
{ "053", "Australazi\u00eb" },
{ "%%AREVMDA", "West-Armeens" },
{ "054", "Melanesi\u00eb" },
{ "WF", "Wallis en Futuna" },
{ "type.co.traditional", "Traditionele sorteervolgorde" },
{ "057", "Micronesische regio" },
{ "jgo", "Ngomba" },
{ "lkt", "Lakota" },
{ "nov", "Novial" },
{ "type.nu.finance", "Financi\u00eble cijfers" },
{ "avk", "Kotava" },
{ "%%HEPBURN", "Hepburn-romanisering" },
{ "type.co.compat", "vorige sorteervolgorde, voor compatibiliteit" },
{ "wae", "Walser" },
{ "WS", "Samoa" },
{ "Bass", "Bassa Vah" },
{ "type.nu.mtei", "Meetei Mayek cijfers" },
{ "wal", "Wolaytta" },
{ "was", "Washo" },
{ "XA", "Pseudo-Accenten" },
{ "war", "Waray" },
{ "XB", "Pseudo-Bidi" },
{ "awa", "Awadhi" },
{ "061", "Polynesi\u00eb" },
{ "%%KSCOR", "Standaardspelling" },
{ "XK", "Kosovo" },
{ "type.nu.brah", "Brahmi cijfers" },
{ "Gujr", metaValue_gu },
{ "Zxxx", "ongeschreven" },
{ "Olck", "Ol Chiki" },
{ "wbp", "Warlpiri" },
{ "Batk", "Batak" },
{ "Blis", metaValue_zbl },
{ "YE", "Jemen" },
{ "nqo", metaValue_nqo },
{ "type.co.standard", "standaard sorteervolgorde" },
{ "lmo", "Lombardisch" },
{ "Zanb", "vierkant Zanabazar" },
{ "fan", "Fang" },
{ "%%BALANKA", "Balanka-dialect van Anii" },
{ "%%ROZAJ", "Resiaans" },
{ "%%SUTSILV", "Sutsilvan" },
{ "fat", "Fanti" },
{ "Sgnw", "SignWriting" },
{ "YT", "Mayotte" },
{ "type.nu.cham", "Cham cijfers" },
{ "%%NEWFOUND", "Newfound" },
{ "ZA", "Zuid-Afrika" },
{ "type.nu.sund", "Sundanese cijfers" },
{ "type.lb.loose", "losse stijl regelafbreking" },
{ "Deva", "Devanagari" },
{ "type.nu.geor", "Georgische cijfers" },
{ "type.co.zhuyin", "Zhuyinvolgorde" },
{ "Hira", "Hiragana" },
{ "ZM", "Zambia" },
{ "%%PINYIN", "Pinyin" },
{ "ZW", "Zimbabwe" },
{ "ZZ", "onbekend gebied" },
{ "Runr", "Runic" },
{ "type.ms.metric", "metriek stelsel" },
{ "type.ca.iso8601", "ISO-8601-kalender" },
{ "lol", "Mongo" },
{ "nso", "Noord-Sotho" },
{ "type.nu.telu", "Telugu cijfers" },
{ "lou", "Louisiana-Creools" },
{ "loz", "Lozi" },
{ "%%FONKIRSH", "Fonkirsh" },
{ "Nkgb", "Naxi Geba" },
{ "%%ASANTE", "Asante" },
{ "%%AUVERN", "Auvern" },
{ "jmc", "Machame" },
{ "hif", "Fijisch Hindi" },
{ "type.nu.hansfin", "vereenvoudigd Chinese financi\u00eble cijfers" },
{ "hil", "Hiligaynon" },
{ "type.nu.arabext", "uitgebreide Arabisch-Indische cijfers" },
{ "nus", "Nuer" },
{ "dak", "Dakota" },
{ "type.nu.fullwide", "cijfers met volledige breedte" },
{ "hit", "Hettitisch" },
{ "dar", "Dargwa" },
{ "dav", "Taita" },
{ "Maya", "Mayahi\u00ebrogliefen" },
{ "lrc", "Noordelijk Luri" },
{ "type.co.emoji", "emojisorteervolgorde" },
{ "Copt", metaValue_cop },
{ "nwc", "Klassiek Nepalbhasa" },
{ "udm", "Oedmoerts" },
{ "Khmr", metaValue_km },
{ "%%FONNAPA", "Fonnapa" },
{ "type.ca.islamic-rgsa", "Islamitische kalender (Saudi\u2013Arabi\u00eb)" },
{ "Limb", "Limbu" },
{ "sad", "Sandawe" },
{ "type.nu.roman", "Romeinse cijfers" },
{ "sah", "Jakoets" },
{ "type.nu.shrd", "Sharada cijfers" },
{ "ltg", "Letgaals" },
{ "sam", "Samaritaans-Aramees" },
{ "Aghb", "Kaukasisch Albanees" },
{ "%%SCOUSE", "Liverpools (Scouse)" },
{ "saq", "Samburu" },
{ "sas", "Sasak" },
{ "sat", "Santali" },
{ "Tfng", "Tifinagh" },
{ "saz", metaValue_saz },
{ "jpr", "Judeo-Perzisch" },
{ "type.d0.npinyin", "Numeriek" },
{ "type.nu.native", "Binnenlandse cijfers" },
{ "sba", "Ngambay" },
{ "Guru", "Gurmukhi" },
{ "%%ALUKU", "Aloekoe-dialect" },
{ "type.nu.diak", "Dives Akuru cijfers" },
{ "lua", "Luba-Lulua" },
{ "%%BISCAYAN", "Biskajaans" },
{ "type.nu.tirh", "Tirhuta cijfers" },
{ "type.d0.fwidth", "Volledige breedte" },
{ "sbp", "Sangu" },
{ "lui", "Luiseno" },
{ "%%GRITAL", "Grital" },
{ "nyn", "Nyankole" },
{ "nym", "Nyamwezi" },
{ "lun", "Lunda" },
{ "nyo", "Nyoro" },
{ "luo", "Luo" },
{ "fil", "Filipijns" },
{ "hmn", "Hmong" },
{ "del", "Delaware" },
{ "lus", "Mizo" },
{ "bal", "Beloetsji" },
{ "den", "Slavey" },
{ "ban", metaValue_ban },
{ "uga", "Oegaritisch" },
{ "type.nu.wara", "Warang Citi cijfers" },
{ "fit", "Tornedal-Fins" },
{ "luy", "Luyia" },
{ "bar", "Beiers" },
{ "bas", "Basa" },
{ "bax", metaValue_bax },
{ "%%ABL1943", "Spellingsformulering van 1943" },
{ "jrb", "Judeo-Arabisch" },
{ "nzi", "Nzima" },
{ "sco", "Schots" },
{ "scn", "Siciliaans" },
{ "aa", "Afar" },
{ "ab", "Abchazisch" },
{ "Aran", "Nastaliq" },
{ "bbc", "Batak Toba" },
{ "ae", "Avestisch" },
{ "af", "Afrikaans" },
{ "ak", "Akan" },
{ "type.nu.cakm", "Chakma cijfers" },
{ "bbj", "Ghomala\u2019" },
{ "am", "Amhaars" },
{ "Arab", metaValue_ar },
{ "an", "Aragonees" },
{ "%%SOLBA", "Stolvizza/Solbica-dialect" },
{ "Jpan", metaValue_ja },
{ "ar", metaValue_ar },
{ "Hrkt", "Katakana of Hiragana" },
{ "as", "Assamees" },
{ "sdc", "Sassarees" },
{ "Lina", "Lineair A" },
{ "av", "Avarisch" },
{ "Linb", "Lineair B" },
{ "sdh", "Pahlavani" },
{ "ay", "Aymara" },
{ "az", "Azerbeidzjaans" },
{ "Rohg", "Hanifi Rohingya" },
{ "Khoj", "Khojki" },
{ "%%CISAUP", "Cisaup" },
{ "%%OSOJS", "Oseacco/Osojane-dialect" },
{ "%%UNIFON", "Unifon fonetisch alfabet" },
{ "ba", "Basjkiers" },
{ "type.co.unihan", "Sorteervolgorde radicalen/strepen" },
{ "be", "Wit-Russisch" },
{ "bg", "Bulgaars" },
{ "bi", "Bislama" },
{ "type.nu.java", "Javaanse cijfers" },
{ "bm", "Bambara" },
{ "bn", metaValue_bn },
{ "bo", metaValue_bo },
{ "dgr", "Dogrib" },
{ "br", "Bretons" },
{ "bs", "Bosnisch" },
{ "Bhks", "Bhaiksuki" },
{ "see", "Seneca" },
{ "Mymr", metaValue_my },
{ "sei", "Seri" },
{ "type.nu.laoo", "Laotiaanse cijfers" },
{ "seh", "Sena" },
{ "Nkoo", metaValue_nqo },
{ "sel", "Selkoeps" },
{ "ca", "Catalaans" },
{ "ses", "Koyraboro Senni" },
{ "ce", "Tsjetsjeens" },
{ "ch", "Chamorro" },
{ "%%REVISED", "Gewijzigde spelling" },
{ "co", "Corsicaans" },
{ "Orya", metaValue_or },
{ "cr", "Cree" },
{ "cs", "Tsjechisch" },
{ "cu", "Kerkslavisch" },
{ "yrl", "Nheengatu" },
{ "cv", "Tsjoevasjisch" },
{ "cy", "Welsh" },
{ "type.nu.ethi", "Ethiopische cijfers" },
{ "Yiii", metaValue_ii },
{ "da", "Deens" },
{ "de", "Duits" },
{ "type.cf.standard", "standaard valutanotatie" },
{ "bej", "Beja" },
{ "din", "Dinka" },
{ "jut", "Jutlands" },
{ "Bugi", metaValue_bug },
{ "bem", "Bemba" },
{ "sga", "Oudiers" },
{ "type.nu.mong", "Mongoolse cijfers" },
{ "dv", "Divehi" },
{ "bew", "Betawi" },
{ "dz", "Dzongkha" },
{ "bez", "Bena" },
{ "type.ca.chinese", "Chinese kalender" },
{ "lzh", "Klassiek Chinees" },
{ "Lisu", "Fraser" },
{ "dje", "Zarma" },
{ "sgs", "Samogitisch" },
{ "type.nu.grek", "Griekse cijfers" },
{ "ee", "Ewe" },
{ "bfd", "Bafut" },
{ "type.lb.normal", "normale stijl regelafbreking" },
{ "el", metaValue_el },
{ "en", "Engels" },
{ "eo", "Esperanto" },
{ "bfq", "Badaga" },
{ "lzz", "Lazisch" },
{ "type.co.big5han", "Traditioneel-Chinese sorteervolgorde - Big5" },
{ "es", "Spaans" },
{ "et", "Estisch" },
{ "Hanb", "Han met Bopomofo" },
{ "eu", "Baskisch" },
{ "Buhd", "Buhid" },
{ "Hang", "Hangul" },
{ "Samr", "Samaritaans" },
{ "shi", "Tashelhiyt" },
{ "hsb", "Oppersorbisch" },
{ "Hani", "Han" },
{ "%%ULSTER", "Ulster" },
{ "shn", "Shan" },
{ "Hano", "Hanunoo" },
{ "fa", "Perzisch" },
{ "Hans", "vereenvoudigd" },
{ "type.nu.latn", "Westerse cijfers" },
{ "Hant", "traditioneel" },
{ "ff", "Fulah" },
{ "shu", "Tsjadisch Arabisch" },
{ "hsn", "Xiangyu" },
{ "fi", "Fins" },
{ "fj", "Fijisch" },
{ "fon", "Fon" },
{ "bgn", "Westers Beloetsji" },
{ "yue", "Kantonees" },
{ "fo", "Faer\u00f6ers" },
{ "type.m0.bgn", "BGN" },
{ "umb", "Umbundu" },
{ "fr", "Frans" },
{ "%%AKUAPEM", "Akuapem" },
{ "sid", "Sidamo" },
{ "fy", "Fries" },
{ "ga", "Iers" },
{ "Wcho", "Wancho" },
{ "gd", "Schots-Gaelisch" },
{ "Gong", "Gunjala Gondi" },
{ "gl", "Galicisch" },
{ "Gonm", "Masaram Gondi" },
{ "gn", "Guaran\u00ed" },
{ "bho", "Bhojpuri" },
{ "und", "onbekende taal" },
{ "type.ca.ethiopic-amete-alem", "Ethiopische Amete Alem-kalender" },
{ "gu", metaValue_gu },
{ "type.ca.islamic-tbla", "Islamitische kalender (epoche)" },
{ "gv", "Manx" },
{ "type.nu.osma", "Osmanya cijfers" },
{ "ha", "Hausa" },
{ "he", metaValue_he },
{ "hi", "Hindi" },
{ "hup", "Hupa" },
{ "bik", "Bikol" },
{ "bin", "Bini" },
{ "ho", "Hiri Motu" },
{ "hr", "Kroatisch" },
{ "ht", "Ha\u00eftiaans Creools" },
{ "hu", "Hongaars" },
{ "hy", metaValue_hy },
{ "hz", "Herero" },
{ "frc", "Cajun-Frans" },
{ "%%FONIPA", "Internationaal Fonetisch Alfabet" },
{ "ia", "Interlingua" },
{ "Jamo", "Jamo" },
{ "id", "Indonesisch" },
{ "type.nu.tibt", "Tibetaanse cijfers" },
{ "ie", "Interlingue" },
{ "%%GASCON", "Gascon" },
{ "ig", "Igbo" },
{ "ii", metaValue_ii },
{ "frm", "Middelfrans" },
{ "%%RUMGR", "Rumgr" },
{ "%%AO1990", "Portugese spellingsovereenkomst van 1990" },
{ "ik", "Inupiaq" },
{ "fro", "Oudfrans" },
{ "frp", "Arpitaans" },
{ "io", "Ido" },
{ "frs", "Oost-Fries" },
{ "bjn", "Banjar" },
{ "frr", "Noord-Fries" },
{ "is", "IJslands" },
{ "it", "Italiaans" },
{ "iu", "Inuktitut" },
{ "sli", "Silezisch Duits" },
{ "%%CORNU", "Cornu" },
{ "%%HOGNORSK", "Hoognoors" },
{ "ja", metaValue_ja },
{ "Mlym", metaValue_ml },
{ "Sarb", "Oud Zuid-Arabisch" },
{ "Sara", "Sarati" },
{ "doi", "Dogri" },
{ "sly", "Selayar" },
{ "type.nu.lepc", "Lepcha cijfers" },
{ "bkm", "Kom" },
{ "sma", "Zuid-Samisch" },
{ "jv", metaValue_jv },
{ "Shaw", "Shavian" },
{ "%%BAUDDHA", "Bauddha" },
{ "mad", "Madoerees" },
{ "smj", "Lule-Samisch" },
{ "mag", "Magahi" },
{ "maf", "Mafa" },
{ "mai", "Maithili" },
{ "smn", "Inari-Samisch" },
{ "ka", metaValue_ka },
{ "bla", "Siksika" },
{ "mak", "Makassaars" },
{ "wuu", "Wuyu" },
{ "sms", "Skolt-Samisch" },
{ "man", "Mandingo" },
{ "kg", "Kongo" },
{ "Goth", metaValue_got },
{ "ki", "Gikuyu" },
{ "mas", "Maa" },
{ "kj", "Kuanyama" },
{ "kk", "Kazachs" },
{ "kl", "Groenlands" },
{ "km", metaValue_km },
{ "kn", metaValue_kn },
{ "ko", metaValue_ko },
{ "kr", "Kanuri" },
{ "ks", "Kasjmiri" },
{ "Cirt", "Cirth" },
{ "Lepc", "Lepcha" },
{ "Avst", "Avestaans" },
{ "ku", "Koerdisch" },
{ "kv", "Komi" },
{ "kw", "Cornish" },
{ "ky", "Kirgizisch" },
{ "snk", "Soninke" },
{ "Mult", "Multani" },
{ "la", "Latijn" },
{ "Hatr", "Hatran" },
{ "lb", "Luxemburgs" },
{ "type.nu.mlym", "Malayalam cijfers" },
{ "lg", "Luganda" },
{ "Roro", "Rongorongo" },
{ "li", "Limburgs" },
{ "Tibt", metaValue_bo },
{ "ln", "Lingala" },
{ "fur", "Friulisch" },
{ "lo", metaValue_lo },
{ "type.ms.uksystem", "Brits imperiaal stelsel" },
{ "type.nu.lana", "Tai Tham Hora cijfers" },
{ "lt", "Litouws" },
{ "lu", "Luba-Katanga" },
{ "sog", metaValue_sog },
{ "lv", "Lets" },
{ "mg", "Malagassisch" },
{ "mh", "Marshallees" },
{ "type.co.ducet", "standaard Unicode-sorteervolgorde" },
{ "mi", "Maori" },
{ "mk", "Macedonisch" },
{ "ml", metaValue_ml },
{ "mn", metaValue_mn },
{ "mr", "Marathi" },
{ "ms", "Maleis" },
{ "mt", "Maltees" },
{ "my", metaValue_my },
{ "Saur", metaValue_saz },
{ "Armn", metaValue_hy },
{ "mdf", "Moksja" },
{ "mde", "Maba" },
{ "dsb", "Nedersorbisch" },
{ "Armi", "Keizerlijk Aramees" },
{ "na", "Nauruaans" },
{ "type.co.search", "algemeen zoeken" },
{ "nb", "Noors - Bokm\u00e5l" },
{ "nd", "Noord-Ndebele" },
{ "ne", "Nepalees" },
{ "ng", "Ndonga" },
{ "mdr", "Mandar" },
{ "nl", "Nederlands" },
{ "nn", "Noors - Nynorsk" },
{ "no", "Noors" },
{ "%%PROVENC", "Provenc" },
{ "nr", "Zuid-Ndbele" },
{ "type.nu.modi", "Modi cijfers" },
{ "Osge", metaValue_osa },
{ "nv", "Navajo" },
{ "kaa", "Karakalpaks" },
{ "ny", "Nyanja" },
{ "kac", "Kachin" },
{ "kab", "Kabylisch" },
{ "%%POLYTON", "Polytonaal" },
{ "oc", "Occitaans" },
{ "kaj", "Jju" },
{ "kam", "Kamba" },
{ "men", metaValue_men },
{ "%%EMODENG", "Vroegmodern Engels" },
{ "oj", "Ojibwa" },
{ "mer", "Meru" },
{ "type.nu.armn", "Armeense cijfers" },
{ "om", "Afaan Oromo" },
{ "kaw", "Kawi" },
{ "dtp", "Dusun" },
{ "or", metaValue_or },
{ "Modi", "Modi" },
{ "os", "Ossetisch" },
{ "%%ALALC97", "Romanisering ALA-LC, editie 1997" },
{ "bpy", "Bishnupriya" },
{ "kbd", "Kabardisch" },
{ "mfe", "Morisyen" },
{ "srn", "Sranantongo" },
{ "pa", "Punjabi" },
{ "dua", "Duala" },
{ "srr", "Serer" },
{ "%%LIPAW", "Het Lipovaz-dialect van het Resiaans" },
{ "kbl", "Kanembu" },
{ "pi", "Pali" },
{ "bqi", "Bakhtiari" },
{ "pl", "Pools" },
{ "dum", "Middelnederlands" },
{ "type.nu.saur", "Saurashtra cijfers" },
{ "type.ca.dangi", "Dangi-kalender" },
{ "%%VALLADER", "Vallader" },
{ "ps", "Pasjtoe" },
{ "pt", "Portugees" },
{ "mga", "Middeliers" },
{ "key.co", "sorteervolgorde" },
{ "%%BOHORIC", "Bohori\u010d-alfabet" },
{ "kcg", "Tyap" },
{ "mgh", "Makhuwa-Meetto" },
{ "key.cf", "valutanotatie" },
{ "type.nu.nkoo", "N\u2019Ko cijfers" },
{ "bra", "Braj" },
{ "key.ca", "kalender" },
{ "%%JAUER", "Jauer" },
{ "Laoo", metaValue_lo },
{ "%%SURMIRAN", "Surmiran" },
{ "mgo", "Meta\u2019" },
{ "type.hc.h23", "24-uursysteem (0-23)" },
{ "type.hc.h24", "24-uursysteem (1-24)" },
{ "ssy", metaValue_ssy },
{ "brh", "Brahui" },
{ "type.nu.mymr", "Myanmarese cijfers" },
{ "qu", "Quechua" },
{ "zap", "Zapotec" },
{ "brx", "Bodo" },
{ "Lana", "Lanna" },
{ "kde", "Makonde" },
{ "%%VAIDIKA", "Vaidika" },
{ "stq", "Saterfries" },
{ "Ethi", "Ethiopisch" },
{ "%%JYUTPING", "Jyutping" },
{ "type.hc.h12", "12-uursysteem (1-12)" },
{ "type.hc.h11", "12-uursysteem (0-11)" },
{ "rm", "Reto-Romaans" },
{ "rn", "Kirundi" },
{ "key.cu", "valuta" },
{ "ro", "Roemeens" },
{ "%%SAAHO", metaValue_ssy },
{ "type.nu.orya", "Odia cijfers" },
{ "type.nu.hanidec", "Chinese decimale getallen" },
{ "ru", "Russisch" },
{ "bss", "Akoose" },
{ "zbl", metaValue_zbl },
{ "rw", "Kinyarwanda" },
{ "kea", "Kaapverdisch Creools" },
{ "mic", "Mi\u2019kmaq" },
{ "suk", "Sukuma" },
{ "Dupl", "Duployan snelschrift" },
{ "sa", "Sanskriet" },
{ "%%UCCOR", "Eenvormige spelling" },
{ "sc", "Sardijns" },
{ "sus", "Soesoe" },
{ "sd", metaValue_sd },
{ "se", "Noord-Samisch" },
{ "min", "Minangkabau" },
{ "sg", "Sango" },
{ "sh", "Servo-Kroatisch" },
{ "ken", "Kenyang" },
{ "si", metaValue_si },
{ "sux", "Soemerisch" },
{ "sk", "Slowaaks" },
{ "sl", "Sloveens" },
{ "Gran", "Grantha" },
{ "sm", "Samoaans" },
{ "%%BASICENG", "Standaard Engels" },
{ "sn", "Shona" },
{ "so", "Somalisch" },
{ "type.nu.arab", "Arabisch-Indische cijfers" },
{ "sq", "Albanees" },
{ "sr", "Servisch" },
{ "ss", "Swazi" },
{ "type.cf.account", "financi\u00eble valutanotatie" },
{ "Java", metaValue_jv },
{ "st", "Zuid-Sotho" },
{ "su", metaValue_su },
{ "%%NEDIS", "Natisone-dialect" },
{ "sv", "Zweeds" },
{ "sw", "Swahili" },
{ "type.nu.wcho", "Wancho cijfers" },
{ "type.nu.hantfin", "traditioneel Chinese financi\u00eble cijfers" },
{ "ibb", "Ibibio" },
{ "iba", "Iban" },
{ "ta", metaValue_ta },
{ "142", "Azi\u00eb" },
{ "bua", "Boerjatisch" },
{ "143", "Centraal-Azi\u00eb" },
{ "te", metaValue_te },
{ "145", "West-Azi\u00eb" },
{ "tg", "Tadzjieks" },
{ "th", metaValue_th },
{ "%%SPANGLIS", "Spanglis" },
{ "bug", metaValue_bug },
{ "ti", "Tigrinya" },
{ "kfo", "Koro" },
{ "tk", "Turkmeens" },
{ "tl", metaValue_tl },
{ "tn", "Tswana" },
{ "to", "Tongaans" },
{ "bum", "Bulu" },
{ "dyo", "Jola-Fonyi" },
{ "type.nu.jpan", "Japanse cijfers" },
{ "tr", "Turks" },
{ "Cakm", metaValue_ccp },
{ "ts", "Tsonga" },
{ "swb", "Shimaore" },
{ "tt", "Tataars" },
{ "%%XSISTEMO", "X-sistemo" },
{ "dyu", "Dyula" },
{ "tw", "Twi" },
{ "ty", "Tahitiaans" },
{ "%%BISKE", "San Giorgio/Bila-dialect" },
{ "150", "Europa" },
{ "151", "Oost-Europa" },
{ "type.nu.rohg", "Hanifi Rohingya cijfers" },
{ "type.nu.mathsanb", "schreefloze vette wiskundige cijfers" },
{ "154", "Noord-Europa" },
{ "dzg", "Dazaga" },
{ "155", "West-Europa" },
{ "ug", "Oeigoers" },
{ "Kore", metaValue_ko },
{ "Ital", "Oud-italisch" },
{ "kgp", "Kaingang" },
{ "Zyyy", "algemeen" },
{ "uk", "Oekra\u00efens" },
{ "zea", "Zeeuws" },
{ "type.ca.coptic", "Koptische kalender" },
{ "ur", "Urdu" },
{ "%%1994", "Gestandaardiseerde Resiaanse spelling" },
{ "xal", "Kalmuks" },
{ "zen", "Zenaga" },
{ "uz", "Oezbeeks" },
{ "kha", "Khasi" },
{ "%%1996", "Duitse spelling van 1996" },
{ "nds_NL", "Nederduits" },
{ "Sylo", "Syloti Nagri" },
{ "ve", "Venda" },
{ "Wara", "Varang Kshiti" },
{ "type.ca.roc", "Kalender van de Chinese Republiek" },
{ "vi", "Vietnamees" },
{ "kho", "Khotanees" },
{ "khq", "Koyra Chiini" },
{ "key.hc", "uursysteem (12 of 24)" },
{ "%%TARASK", "Taraskievica-spelling" },
{ "vo", "Volap\u00fck" },
{ "khw", "Khowar" },
{ "syc", "Klassiek Syrisch" },
{ "type.nu.mathsans", "schreefloze wiskundige cijfers" },
{ "Osma", "Osmanya" },
{ "quc", "K\u2019iche\u2019" },
{ "type.nu.gonm", "Masaram Gondi cijfers" },
{ "qug", "Kichwa" },
{ "Newa", metaValue_new },
{ "gaa", "Ga" },
{ "wa", "Waals" },
{ "gag", "Gagaoezisch" },
{ "syr", "Syrisch" },
{ "type.nu.gong", "Gunjala Gondi cijfers" },
{ "Grek", metaValue_el },
{ "gan", "Ganyu" },
{ "kiu", "Kirmanck\u00ee" },
{ "Lydi", "Lydisch" },
{ "Xsux", "Sumero-Akkadian Cuneiform" },
{ "wo", "Wolof" },
{ "zgh", "Standaard Marokkaanse Tamazight" },
{ "Cans", "Verenigde Canadese Aboriginal-symbolen" },
{ "%%FONXSAMP", "Transcriptie volgens X-SAMPA" },
{ "gay", "Gayo" },
{ "Mong", metaValue_mn },
{ "mnc", "Mantsjoe" },
{ "Latf", "Gotisch Latijns" },
{ "szl", "Silezisch" },
{ "Hluw", "Anatolische hi\u00ebrogliefen" },
{ "gba", "Gbaya" },
{ "mni", metaValue_mni },
{ "Latn", "Latijns" },
{ "Latg", "Gaelisch Latijns" },
{ "Nand", "Nandinagari" },
{ "type.nu.hans", "vereenvoudigd Chinese cijfers" },
{ "type.nu.hant", "traditioneel Chinese cijfers" },
{ "xh", "Xhosa" },
{ "type.nu.romanlow", "kleine Romeinse cijfers" },
{ "byn", "Blin" },
{ "Dogr", "Dogra" },
{ "%%PAMAKA", "Pamaka" },
{ "Lyci", "Lycisch" },
{ "osa", metaValue_osa },
{ "byv", "Medumba" },
{ "gbz", "Zoroastrisch Dari" },
{ "Moon", "Moon" },
{ "moh", "Mohawk" },
{ "kkj", "Kako" },
{ "%%1694ACAD", "Vroeg modern Frans" },
{ "yi", "Jiddisch" },
{ "mos", "Mossi" },
{ "Syrc", "Syriac" },
{ "Dsrt", "Deseret" },
{ "yo", "Yoruba" },
{ "type.nu.traditional", "Traditionele cijfers" },
{ "Syrj", "West-Aramees" },
{ "ota", "Ottomaans-Turks" },
{ "Syre", "Estrangelo Aramees" },
{ "vai", metaValue_vai },
{ "za", "Zhuang" },
{ "Cari", "Carisch" },
{ "kln", "Kalenjin" },
{ "zh", "Chinees" },
{ "Afak", "Defaka" },
{ "Bopo", "Bopomofo" },
{ "Perm", "Oudpermisch" },
{ "key.lb", "stijl regelafbreking" },
{ "zu", "Zoeloe" },
{ "type.co.phonebook", "Telefoonboeksorteervolgorde" },
{ "%%MONOTON", "Monotonaal" },
{ "Geor", metaValue_ka },
{ "Shrd", "Sharada" },
{ "%%LENGADOC", "Lengadoc" },
{ "kmb", "Kimbundu" },
{ "type.nu.jpanfin", "Japanse financi\u00eble cijfers" },
{ "Cham", "Cham" },
{ "gez", "Ge\u2019ez" },
{ "mrj", "West-Mari" },
{ "Syrn", "Oost-Aramees" },
{ "type.nu.mymrshan", "Myanmarese Shan cijfers" },
{ "Elba", "Elbasan" },
{ "Narb", "Oud Noord-Arabisch" },
{ "type.nu.olck", "Ol Chiki cijfers" },
{ "type.co.reformed", "Herziene sorteervolgorde" },
{ "Tglg", metaValue_tl },
{ "Egyd", "Egyptisch demotisch" },
{ "Egyh", "Egyptisch hi\u00ebratisch" },
{ "Yezi", "Jezidi" },
{ "%%ITIHASA", "Episch Sanskriet" },
{ "Palm", "Palmyreens" },
{ "ebu", "Embu" },
{ "Egyp", "Egyptische hi\u00ebrogliefen" },
{ "Geok", "Georgisch Khutsuri" },
{ "koi", "Komi-Permjaaks" },
{ "Hung", "Oudhongaars" },
{ "kok", "Konkani" },
{ "%%1901", "Traditionele Duitse spelling" },
{ "kos", "Kosraeaans" },
{ "vec", "Venetiaans" },
{ "%%PAHAWH2", "Pahawh2" },
{ "%%PAHAWH3", "Pahawh3" },
{ "%%PAHAWH4", "Pahawh4" },
{ "type.nu.limb", "Limbu cijfers" },
{ "Sund", metaValue_su },
{ "vep", "Wepsisch" },
{ "kpe", metaValue_kpe },
{ "%%GRCLASS", "Grclass" },
{ "type.nu.khmr", "Khmer cijfers" },
{ "Tirh", "Tirhuta" },
{ "ilo", "Iloko" },
{ "%%VALENCIA", "Valenciaans" },
{ "Cprt", "Cyprisch" },
{ "Diak", "Dives Akuru" },
{ "%%BAKU1926", "Eenvormig Turkse Latijnse alfabet" },
{ "%%IJEKAVSK", "Servisch met Ijekaviaanse uitspraak" },
{ "mua", "Mundang" },
{ "type.nu.guru", "Gurmukhi cijfers" },
{ "%%BORNHOLM", "Bornholms" },
{ "mul", "Meerdere talen" },
{ "%%PUTER", "Puter" },
{ "cad", "Caddo" },
{ "key.ms", "maatsysteem" },
{ "mus", "Creek" },
{ "Glag", "Glagolitisch" },
{ "gil", "Gilbertees" },
{ "%%KKCOR", "Algemene spelling" },
{ "Cher", metaValue_chr },
{ "car", "Caribisch" },
{ "cay", "Cayuga" },
{ "type.nu.tamldec", "Tamil cijfers" },
{ "krc", "Karatsjaj-Balkarisch" },
{ "inh", "Ingoesjetisch" },
{ "krj", "Kinaray-a" },
{ "kri", "Krio" },
{ "fa_AF", "Dari" },
{ "krl", "Karelisch" },
{ "%%OXENDICT", "Spelling volgens het Oxford English Dictionary" },
{ "efi", "Efik" },
{ "tcy", "Tulu" },
{ "key.nu", "cijfers" },
{ "kru", "Kurukh" },
{ "ksb", "Shambala" },
{ "Telu", metaValue_te },
{ "ksf", "Bafia" },
};
return data;
}
}
| zxiaofan/JDK | JDK-15/src/jdk.localedata/sun/util/resources/cldr/ext/LocaleNames_nl.java |
712 | package com.hartwig.hmftools.patientdb.clinical.lims;
import com.hartwig.hmftools.patientdb.clinical.lims.cohort.LimsCohortConfig;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public enum LimsGermlineReportingLevel {
REPORT_WITH_NOTIFICATION,
REPORT_WITHOUT_NOTIFICATION,
NO_REPORTING;
@NotNull
static LimsGermlineReportingLevel fromLimsInputs(boolean limsSampleReportGermlineVariants, @NotNull String germlineReportingLevelString,
@NotNull String sampleId, @Nullable LimsCohortConfig cohort) {
if (limsSampleReportGermlineVariants && cohort != null) {
// Cases "geen toevalsbevindingen: familie mag deze/wel niet opvragen" have been merged
// into a single category "geen toevalsbevindingen" per feb 1st 2020
if (cohort.reportGermline() && cohort.reportGermlineFlag()) {
switch (germlineReportingLevelString) {
case "1: Behandelbare toevalsbevindingen":
case "2: Alle toevalsbevindingen":
case "1: Yes":
return REPORT_WITH_NOTIFICATION;
case "3: Geen toevalsbevindingen":
case "3: Geen toevalsbevindingen; familie mag deze wel opvragen":
case "4: Geen toevalsbevindingen; familie mag deze niet opvragen":
case "2: No":
return REPORT_WITHOUT_NOTIFICATION;
default:
throw new IllegalStateException(
"Cannot resolve germline reporting choice " + germlineReportingLevelString + " for sample " + sampleId);
}
} else if (cohort.reportGermline() && !cohort.reportGermlineFlag()) {
return REPORT_WITHOUT_NOTIFICATION;
}
}
return NO_REPORTING;
}
}
| hartwigmedical/hmftools | patient-db/src/main/java/com/hartwig/hmftools/patientdb/clinical/lims/LimsGermlineReportingLevel.java |
713 | /**************************************************************************/
/* GodotApp.java */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
package com.godot.game;
import org.godotengine.godot.GodotActivity;
import android.os.Bundle;
/**
* Template activity for Godot Android builds.
* Feel free to extend and modify this class for your custom logic.
*/
public class GodotApp extends GodotActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.GodotAppMainTheme);
super.onCreate(savedInstanceState);
}
}
| godotengine/godot | platform/android/java/app/src/com/godot/game/GodotApp.java |
714 | package com.estrongs.android.pop.esclasses.a;
import android.util.SparseArray;
class x
{
public static SparseArray<Object> a()
{
SparseArray localSparseArray = new SparseArray(1336);
localSparseArray.put(2131231360, Integer.valueOf(0));
localSparseArray.put(2131231535, Integer.valueOf(1));
localSparseArray.put(2131231390, Integer.valueOf(2));
localSparseArray.put(2131231713, Integer.valueOf(3));
localSparseArray.put(2131231900, Integer.valueOf(4));
localSparseArray.put(2131231761, Integer.valueOf(5));
localSparseArray.put(2131231790, Integer.valueOf(6));
localSparseArray.put(2131232076, Integer.valueOf(7));
localSparseArray.put(2131232135, Integer.valueOf(8));
localSparseArray.put(2131232308, Integer.valueOf(9));
localSparseArray.put(2131231817, Integer.valueOf(10));
localSparseArray.put(2131232578, Integer.valueOf(11));
localSparseArray.put(2131232364, Integer.valueOf(12));
localSparseArray.put(2131231788, Integer.valueOf(13));
localSparseArray.put(2131231225, Integer.valueOf(14));
localSparseArray.put(2131231548, Integer.valueOf(15));
localSparseArray.put(2131232201, Integer.valueOf(16));
localSparseArray.put(2131231488, Integer.valueOf(17));
localSparseArray.put(2131231461, Integer.valueOf(18));
localSparseArray.put(2131231467, Integer.valueOf(19));
localSparseArray.put(2131231365, Integer.valueOf(20));
localSparseArray.put(2131231104, Integer.valueOf(21));
localSparseArray.put(2131231133, Integer.valueOf(22));
localSparseArray.put(2131232515, Integer.valueOf(23));
localSparseArray.put(2131232025, Integer.valueOf(24));
localSparseArray.put(2131232542, Integer.valueOf(25));
localSparseArray.put(2131230935, Integer.valueOf(26));
localSparseArray.put(2131231405, Integer.valueOf(27));
localSparseArray.put(2131232182, Integer.valueOf(28));
localSparseArray.put(2131492877, new String[] { "All", "0 – 100 KB", "100KB - 1 MB", "1 MB - 16 MB", "16 MB - 128 MB", "> 128 MB", "Input" });
localSparseArray.put(2131231839, Integer.valueOf(30));
localSparseArray.put(2131231587, Integer.valueOf(31));
localSparseArray.put(2131231440, Integer.valueOf(32));
localSparseArray.put(2131232148, Integer.valueOf(33));
localSparseArray.put(2131231167, Integer.valueOf(34));
localSparseArray.put(2131231496, Integer.valueOf(35));
localSparseArray.put(2131232192, Integer.valueOf(36));
localSparseArray.put(2131232019, Integer.valueOf(37));
localSparseArray.put(2131232102, Integer.valueOf(38));
localSparseArray.put(2131232546, Integer.valueOf(39));
localSparseArray.put(2131232093, Integer.valueOf(40));
localSparseArray.put(2131231988, Integer.valueOf(41));
localSparseArray.put(2131232552, Integer.valueOf(42));
localSparseArray.put(2131232141, Integer.valueOf(43));
localSparseArray.put(2131230941, Integer.valueOf(44));
localSparseArray.put(2131231520, Integer.valueOf(45));
localSparseArray.put(2131232263, Integer.valueOf(46));
localSparseArray.put(2131231640, Integer.valueOf(47));
localSparseArray.put(2131231808, Integer.valueOf(48));
localSparseArray.put(2131231592, Integer.valueOf(49));
localSparseArray.put(2131231826, Integer.valueOf(50));
localSparseArray.put(2131232028, Integer.valueOf(51));
localSparseArray.put(2131231383, Integer.valueOf(52));
localSparseArray.put(2131231328, Integer.valueOf(53));
localSparseArray.put(2131231427, Integer.valueOf(54));
localSparseArray.put(2131232261, Integer.valueOf(55));
localSparseArray.put(2131231560, Integer.valueOf(56));
localSparseArray.put(2131232315, Integer.valueOf(57));
localSparseArray.put(2131232088, Integer.valueOf(58));
localSparseArray.put(2131232302, Integer.valueOf(59));
localSparseArray.put(2131231279, Integer.valueOf(60));
localSparseArray.put(2131231802, Integer.valueOf(61));
localSparseArray.put(2131231179, Integer.valueOf(62));
localSparseArray.put(2131230724, Integer.valueOf(63));
localSparseArray.put(2131231352, Integer.valueOf(64));
localSparseArray.put(2131492873, new String[] { "Normale manier\n(voor MMS,Gmail,…)", "Alternatief\n(als normaal niet werkt)" });
localSparseArray.put(2131230944, Integer.valueOf(66));
localSparseArray.put(2131230959, Integer.valueOf(67));
localSparseArray.put(2131231670, Integer.valueOf(68));
localSparseArray.put(2131232155, Integer.valueOf(69));
localSparseArray.put(2131231498, Integer.valueOf(70));
localSparseArray.put(2131231730, Integer.valueOf(71));
localSparseArray.put(2131232267, Integer.valueOf(72));
localSparseArray.put(2131231112, Integer.valueOf(73));
localSparseArray.put(2131230898, Integer.valueOf(74));
localSparseArray.put(2131232532, Integer.valueOf(75));
localSparseArray.put(2131232404, Integer.valueOf(76));
localSparseArray.put(2131231211, Integer.valueOf(77));
localSparseArray.put(2131231512, Integer.valueOf(78));
localSparseArray.put(2131231789, Integer.valueOf(79));
localSparseArray.put(2131232592, Integer.valueOf(80));
localSparseArray.put(2131232511, Integer.valueOf(81));
localSparseArray.put(2131231630, Integer.valueOf(82));
localSparseArray.put(2131231707, Integer.valueOf(83));
localSparseArray.put(2131231556, Integer.valueOf(84));
localSparseArray.put(2131231649, Integer.valueOf(85));
localSparseArray.put(2131230879, Integer.valueOf(86));
localSparseArray.put(2131232065, Integer.valueOf(87));
localSparseArray.put(2131232432, Integer.valueOf(88));
localSparseArray.put(2131232359, Integer.valueOf(89));
localSparseArray.put(2131231459, Integer.valueOf(90));
localSparseArray.put(2131230914, Integer.valueOf(91));
localSparseArray.put(2131232096, Integer.valueOf(92));
localSparseArray.put(2131232376, Integer.valueOf(93));
localSparseArray.put(2131231668, Integer.valueOf(94));
localSparseArray.put(2131492868, new String[] { "DOS Terminators - CR/LF", "UNIX Terminators - LF", "MAC Terminators - CR" });
localSparseArray.put(2131232197, Integer.valueOf(96));
localSparseArray.put(2131230873, Integer.valueOf(97));
localSparseArray.put(2131231700, Integer.valueOf(98));
localSparseArray.put(2131232556, Integer.valueOf(99));
localSparseArray.put(2131232330, Integer.valueOf(100));
localSparseArray.put(2131231220, Integer.valueOf(101));
localSparseArray.put(2131232167, Integer.valueOf(102));
localSparseArray.put(2131232479, Integer.valueOf(103));
localSparseArray.put(2131231907, Integer.valueOf(104));
localSparseArray.put(2131492864, new String[] { "Naam", "Type", "Grootte" });
localSparseArray.put(2131231672, Integer.valueOf(106));
localSparseArray.put(2131231284, Integer.valueOf(107));
localSparseArray.put(2131232086, Integer.valueOf(108));
localSparseArray.put(2131230954, Integer.valueOf(109));
localSparseArray.put(2131231599, Integer.valueOf(110));
localSparseArray.put(2131231644, Integer.valueOf(111));
localSparseArray.put(2131231431, Integer.valueOf(112));
localSparseArray.put(2131231055, Integer.valueOf(113));
localSparseArray.put(2131231045, Integer.valueOf(114));
localSparseArray.put(2131232245, Integer.valueOf(115));
localSparseArray.put(2131231756, Integer.valueOf(116));
localSparseArray.put(2131232169, Integer.valueOf(117));
localSparseArray.put(2131232057, Integer.valueOf(118));
localSparseArray.put(2131231526, Integer.valueOf(119));
localSparseArray.put(2131231180, Integer.valueOf(120));
localSparseArray.put(2131231068, Integer.valueOf(121));
localSparseArray.put(2131232453, Integer.valueOf(122));
localSparseArray.put(2131231101, Integer.valueOf(123));
localSparseArray.put(2131232178, Integer.valueOf(124));
localSparseArray.put(2131232316, Integer.valueOf(125));
localSparseArray.put(2131232299, Integer.valueOf(126));
localSparseArray.put(2131232136, Integer.valueOf(127));
localSparseArray.put(2131231662, Integer.valueOf(128));
localSparseArray.put(2131231561, Integer.valueOf(129));
localSparseArray.put(2131231718, Integer.valueOf(130));
localSparseArray.put(2131232309, Integer.valueOf(131));
localSparseArray.put(2131232231, Integer.valueOf(132));
localSparseArray.put(2131231684, Integer.valueOf(133));
localSparseArray.put(2131232125, Integer.valueOf(134));
localSparseArray.put(2131231728, Integer.valueOf(135));
localSparseArray.put(2131231070, Integer.valueOf(136));
localSparseArray.put(2131232323, Integer.valueOf(137));
localSparseArray.put(2131231468, Integer.valueOf(138));
localSparseArray.put(2131231364, Integer.valueOf(139));
localSparseArray.put(2131232579, Integer.valueOf(140));
localSparseArray.put(2131232006, Integer.valueOf(141));
localSparseArray.put(2131231381, Integer.valueOf(142));
localSparseArray.put(2131232259, Integer.valueOf(143));
localSparseArray.put(2131230956, Integer.valueOf(144));
localSparseArray.put(2131231681, Integer.valueOf(145));
localSparseArray.put(2131231868, Integer.valueOf(146));
localSparseArray.put(2131231051, Integer.valueOf(147));
localSparseArray.put(2131231721, Integer.valueOf(148));
localSparseArray.put(2131231873, Integer.valueOf(149));
localSparseArray.put(2131231985, Integer.valueOf(150));
localSparseArray.put(2131230964, Integer.valueOf(151));
localSparseArray.put(2131689476, new String[] { "%1$d nummer van %2$s", "%1$d nummers van %2$s" });
localSparseArray.put(2131232438, Integer.valueOf(153));
localSparseArray.put(2131232449, Integer.valueOf(154));
localSparseArray.put(2131231898, Integer.valueOf(155));
localSparseArray.put(2131232516, Integer.valueOf(156));
localSparseArray.put(2131231447, Integer.valueOf(157));
localSparseArray.put(2131231266, Integer.valueOf(158));
localSparseArray.put(2131230886, Integer.valueOf(159));
localSparseArray.put(2131231164, Integer.valueOf(160));
localSparseArray.put(2131232417, Integer.valueOf(161));
localSparseArray.put(2131232510, Integer.valueOf(162));
localSparseArray.put(2131232143, Integer.valueOf(163));
localSparseArray.put(2131232104, Integer.valueOf(164));
localSparseArray.put(2131232437, Integer.valueOf(165));
localSparseArray.put(2131231807, Integer.valueOf(166));
localSparseArray.put(2131231704, Integer.valueOf(167));
localSparseArray.put(2131230847, Integer.valueOf(168));
localSparseArray.put(2131231443, Integer.valueOf(169));
localSparseArray.put(2131231565, Integer.valueOf(170));
localSparseArray.put(2131232208, Integer.valueOf(171));
localSparseArray.put(2131231746, Integer.valueOf(172));
localSparseArray.put(2131232074, Integer.valueOf(173));
localSparseArray.put(2131231326, Integer.valueOf(174));
localSparseArray.put(2131232137, Integer.valueOf(175));
localSparseArray.put(2131232265, Integer.valueOf(176));
localSparseArray.put(2131231008, Integer.valueOf(177));
localSparseArray.put(2131231785, Integer.valueOf(178));
localSparseArray.put(2131230893, Integer.valueOf(179));
localSparseArray.put(2131230843, Integer.valueOf(180));
localSparseArray.put(2131231794, Integer.valueOf(181));
localSparseArray.put(2131232337, Integer.valueOf(182));
localSparseArray.put(2131231069, Integer.valueOf(183));
localSparseArray.put(2131231097, Integer.valueOf(184));
localSparseArray.put(2131232583, Integer.valueOf(185));
localSparseArray.put(2131232111, Integer.valueOf(186));
localSparseArray.put(2131230916, Integer.valueOf(187));
localSparseArray.put(2131232020, Integer.valueOf(188));
localSparseArray.put(2131230919, Integer.valueOf(189));
localSparseArray.put(2131230871, Integer.valueOf(190));
localSparseArray.put(2131231530, Integer.valueOf(191));
localSparseArray.put(2131230853, Integer.valueOf(192));
localSparseArray.put(2131230979, Integer.valueOf(193));
localSparseArray.put(2131492887, new String[] { "Opslaan", "Snel", "Standaard", "Beste" });
localSparseArray.put(2131231994, Integer.valueOf(195));
localSparseArray.put(2131230970, Integer.valueOf(196));
localSparseArray.put(2131232050, Integer.valueOf(197));
localSparseArray.put(2131230837, Integer.valueOf(198));
localSparseArray.put(2131232172, Integer.valueOf(199));
localSparseArray.put(2131231183, Integer.valueOf(200));
localSparseArray.put(2131232445, Integer.valueOf(201));
localSparseArray.put(2131230902, Integer.valueOf(202));
localSparseArray.put(2131232064, Integer.valueOf(203));
localSparseArray.put(2131231596, Integer.valueOf(204));
localSparseArray.put(2131231135, Integer.valueOf(205));
localSparseArray.put(2131231869, Integer.valueOf(206));
localSparseArray.put(2131231555, Integer.valueOf(207));
localSparseArray.put(2131231867, Integer.valueOf(208));
localSparseArray.put(2131231913, Integer.valueOf(209));
localSparseArray.put(2131230829, Integer.valueOf(210));
localSparseArray.put(2131231019, Integer.valueOf(211));
localSparseArray.put(2131232090, Integer.valueOf(212));
localSparseArray.put(2131231084, Integer.valueOf(213));
localSparseArray.put(2131231851, Integer.valueOf(214));
localSparseArray.put(2131232150, Integer.valueOf(215));
localSparseArray.put(2131232085, Integer.valueOf(216));
localSparseArray.put(2131231170, Integer.valueOf(217));
localSparseArray.put(2131232021, Integer.valueOf(218));
localSparseArray.put(2131230952, Integer.valueOf(219));
localSparseArray.put(2131231821, Integer.valueOf(220));
localSparseArray.put(2131231659, Integer.valueOf(221));
localSparseArray.put(2131231539, Integer.valueOf(222));
localSparseArray.put(2131232271, Integer.valueOf(223));
localSparseArray.put(2131231270, Integer.valueOf(224));
localSparseArray.put(2131231175, Integer.valueOf(225));
localSparseArray.put(2131232485, Integer.valueOf(226));
localSparseArray.put(2131231683, Integer.valueOf(227));
localSparseArray.put(2131231203, Integer.valueOf(228));
localSparseArray.put(2131231445, Integer.valueOf(229));
localSparseArray.put(2131232191, Integer.valueOf(230));
localSparseArray.put(2131232414, Integer.valueOf(231));
localSparseArray.put(2131231269, Integer.valueOf(232));
localSparseArray.put(2131232298, Integer.valueOf(233));
localSparseArray.put(2131231712, Integer.valueOf(234));
localSparseArray.put(2131232561, Integer.valueOf(235));
localSparseArray.put(2131230969, Integer.valueOf(236));
localSparseArray.put(2131232005, Integer.valueOf(237));
localSparseArray.put(2131231402, Integer.valueOf(238));
localSparseArray.put(2131231130, Integer.valueOf(239));
localSparseArray.put(2131232372, Integer.valueOf(240));
localSparseArray.put(2131492884, new String[] { "Slecht", "Redelijk", "Goed", "Uitstekend" });
localSparseArray.put(2131231513, Integer.valueOf(242));
localSparseArray.put(2131232046, Integer.valueOf(243));
localSparseArray.put(2131232373, Integer.valueOf(244));
localSparseArray.put(2131232460, Integer.valueOf(245));
localSparseArray.put(2131689480, new String[] { "Mijn cloudaccount", "Mijn cloudaccounts" });
localSparseArray.put(2131231682, Integer.valueOf(247));
localSparseArray.put(2131232190, Integer.valueOf(248));
localSparseArray.put(2131231827, Integer.valueOf(249));
localSparseArray.put(2131231784, Integer.valueOf(250));
localSparseArray.put(2131232030, Integer.valueOf(251));
localSparseArray.put(2131230990, Integer.valueOf(252));
localSparseArray.put(2131231750, Integer.valueOf(253));
localSparseArray.put(2131231742, Integer.valueOf(254));
localSparseArray.put(2131231514, Integer.valueOf(255));
localSparseArray.put(2131232054, Integer.valueOf(256));
localSparseArray.put(2131232138, Integer.valueOf(257));
localSparseArray.put(2131232496, Integer.valueOf(258));
localSparseArray.put(2131231875, Integer.valueOf(259));
localSparseArray.put(2131232075, Integer.valueOf(260));
localSparseArray.put(2131231882, Integer.valueOf(261));
localSparseArray.put(2131231733, Integer.valueOf(262));
localSparseArray.put(2131232273, Integer.valueOf(263));
localSparseArray.put(2131230938, Integer.valueOf(264));
localSparseArray.put(2131231357, Integer.valueOf(265));
localSparseArray.put(2131232401, Integer.valueOf(266));
localSparseArray.put(2131232580, Integer.valueOf(267));
localSparseArray.put(2131232307, Integer.valueOf(268));
localSparseArray.put(2131231862, Integer.valueOf(269));
localSparseArray.put(2131231623, Integer.valueOf(270));
localSparseArray.put(2131231885, Integer.valueOf(271));
localSparseArray.put(2131232427, Integer.valueOf(272));
localSparseArray.put(2131689478, new String[] { "%1$d map van %2$s", "%1$d mappen van %2$s" });
localSparseArray.put(2131232115, Integer.valueOf(274));
localSparseArray.put(2131230720, Integer.valueOf(275));
localSparseArray.put(2131231720, Integer.valueOf(276));
localSparseArray.put(2131232045, Integer.valueOf(277));
localSparseArray.put(2131232047, Integer.valueOf(278));
localSparseArray.put(2131230988, Integer.valueOf(279));
localSparseArray.put(2131231563, Integer.valueOf(280));
localSparseArray.put(2131231510, Integer.valueOf(281));
localSparseArray.put(2131231727, Integer.valueOf(282));
localSparseArray.put(2131232566, Integer.valueOf(283));
localSparseArray.put(2131232100, Integer.valueOf(284));
localSparseArray.put(2131231048, Integer.valueOf(285));
localSparseArray.put(2131231072, Integer.valueOf(286));
localSparseArray.put(2131232587, Integer.valueOf(287));
localSparseArray.put(2131231341, Integer.valueOf(288));
localSparseArray.put(2131231181, Integer.valueOf(289));
localSparseArray.put(2131231015, Integer.valueOf(290));
localSparseArray.put(2131232016, Integer.valueOf(291));
localSparseArray.put(2131231611, Integer.valueOf(292));
localSparseArray.put(2131232407, Integer.valueOf(293));
localSparseArray.put(2131232413, Integer.valueOf(294));
localSparseArray.put(2131232114, Integer.valueOf(295));
localSparseArray.put(2131231342, Integer.valueOf(296));
localSparseArray.put(2131230924, Integer.valueOf(297));
localSparseArray.put(2131230931, Integer.valueOf(298));
localSparseArray.put(2131232565, Integer.valueOf(299));
localSparseArray.put(2131231600, Integer.valueOf(300));
localSparseArray.put(2131231506, Integer.valueOf(301));
localSparseArray.put(2131230874, Integer.valueOf(302));
localSparseArray.put(2131231701, Integer.valueOf(303));
localSparseArray.put(2131231629, Integer.valueOf(304));
localSparseArray.put(2131231013, Integer.valueOf(305));
localSparseArray.put(2131231344, Integer.valueOf(306));
localSparseArray.put(2131232551, Integer.valueOf(307));
localSparseArray.put(2131231063, Integer.valueOf(308));
localSparseArray.put(2131231888, Integer.valueOf(309));
localSparseArray.put(2131231795, Integer.valueOf(310));
localSparseArray.put(2131492886, new String[] { "", "Scannen…", "Verbinden…", "Authenticatie…", "IP-adres ontavngen van %1$s…", "Verbonden", "Hangend", "Loskoppelen…", "Losgekoppeld", "Mislukt" });
localSparseArray.put(2131231840, Integer.valueOf(312));
localSparseArray.put(2131231200, Integer.valueOf(313));
localSparseArray.put(2131232296, Integer.valueOf(314));
localSparseArray.put(2131230897, Integer.valueOf(315));
localSparseArray.put(2131231872, Integer.valueOf(316));
localSparseArray.put(2131232457, Integer.valueOf(317));
localSparseArray.put(2131232589, Integer.valueOf(318));
localSparseArray.put(2131230869, Integer.valueOf(319));
localSparseArray.put(2131231584, Integer.valueOf(320));
localSparseArray.put(2131231525, Integer.valueOf(321));
localSparseArray.put(2131231049, Integer.valueOf(322));
localSparseArray.put(2131232456, Integer.valueOf(323));
localSparseArray.put(2131231493, Integer.valueOf(324));
localSparseArray.put(2131231574, Integer.valueOf(325));
localSparseArray.put(2131231012, Integer.valueOf(326));
localSparseArray.put(2131231186, Integer.valueOf(327));
localSparseArray.put(2131231688, Integer.valueOf(328));
localSparseArray.put(2131231613, Integer.valueOf(329));
localSparseArray.put(2131231908, Integer.valueOf(330));
localSparseArray.put(2131231223, Integer.valueOf(331));
localSparseArray.put(2131231495, Integer.valueOf(332));
localSparseArray.put(2131231861, Integer.valueOf(333));
localSparseArray.put(2131231762, Integer.valueOf(334));
localSparseArray.put(2131231138, Integer.valueOf(335));
localSparseArray.put(2131231088, Integer.valueOf(336));
localSparseArray.put(2131231696, Integer.valueOf(337));
localSparseArray.put(2131231067, Integer.valueOf(338));
localSparseArray.put(2131230875, Integer.valueOf(339));
localSparseArray.put(2131230722, Integer.valueOf(340));
localSparseArray.put(2131232577, Integer.valueOf(341));
localSparseArray.put(2131231087, Integer.valueOf(342));
localSparseArray.put(2131232098, Integer.valueOf(343));
localSparseArray.put(2131232452, Integer.valueOf(344));
localSparseArray.put(2131231434, Integer.valueOf(345));
localSparseArray.put(2131232112, Integer.valueOf(346));
localSparseArray.put(2131231340, Integer.valueOf(347));
localSparseArray.put(2131231465, Integer.valueOf(348));
localSparseArray.put(2131232459, Integer.valueOf(349));
localSparseArray.put(2131231518, Integer.valueOf(350));
localSparseArray.put(2131231435, Integer.valueOf(351));
localSparseArray.put(2131231107, Integer.valueOf(352));
localSparseArray.put(2131231483, Integer.valueOf(353));
localSparseArray.put(2131231064, Integer.valueOf(354));
localSparseArray.put(2131232106, Integer.valueOf(355));
localSparseArray.put(2131231333, Integer.valueOf(356));
localSparseArray.put(2131231533, Integer.valueOf(357));
localSparseArray.put(2131231648, Integer.valueOf(358));
localSparseArray.put(2131232195, Integer.valueOf(359));
localSparseArray.put(2131231693, Integer.valueOf(360));
localSparseArray.put(2131231281, Integer.valueOf(361));
localSparseArray.put(2131232475, Integer.valueOf(362));
localSparseArray.put(2131232304, Integer.valueOf(363));
localSparseArray.put(2131232573, Integer.valueOf(364));
localSparseArray.put(2131231892, Integer.valueOf(365));
localSparseArray.put(2131231316, Integer.valueOf(366));
localSparseArray.put(2131231654, Integer.valueOf(367));
localSparseArray.put(2131232518, Integer.valueOf(368));
localSparseArray.put(2131232014, Integer.valueOf(369));
localSparseArray.put(2131232472, Integer.valueOf(370));
localSparseArray.put(2131231147, Integer.valueOf(371));
localSparseArray.put(2131231041, Integer.valueOf(372));
localSparseArray.put(2131232062, Integer.valueOf(373));
localSparseArray.put(2131231189, Integer.valueOf(374));
localSparseArray.put(2131232134, Integer.valueOf(375));
localSparseArray.put(2131232443, Integer.valueOf(376));
localSparseArray.put(2131232091, Integer.valueOf(377));
localSparseArray.put(2131230922, Integer.valueOf(378));
localSparseArray.put(2131230833, Integer.valueOf(379));
localSparseArray.put(2131230867, Integer.valueOf(380));
localSparseArray.put(2131231275, Integer.valueOf(381));
localSparseArray.put(2131231046, Integer.valueOf(382));
localSparseArray.put(2131230909, Integer.valueOf(383));
localSparseArray.put(2131232512, Integer.valueOf(384));
localSparseArray.put(2131231878, Integer.valueOf(385));
localSparseArray.put(2131231294, Integer.valueOf(386));
localSparseArray.put(2131232458, Integer.valueOf(387));
localSparseArray.put(2131230998, Integer.valueOf(388));
localSparseArray.put(2131231408, Integer.valueOf(389));
localSparseArray.put(2131231312, Integer.valueOf(390));
localSparseArray.put(2131231601, Integer.valueOf(391));
localSparseArray.put(2131231860, Integer.valueOf(392));
localSparseArray.put(2131231184, Integer.valueOf(393));
localSparseArray.put(2131232466, Integer.valueOf(394));
localSparseArray.put(2131232397, Integer.valueOf(395));
localSparseArray.put(2131231658, Integer.valueOf(396));
localSparseArray.put(2131230937, Integer.valueOf(397));
localSparseArray.put(2131230845, Integer.valueOf(398));
localSparseArray.put(2131231772, Integer.valueOf(399));
localSparseArray.put(2131231193, Integer.valueOf(400));
localSparseArray.put(2131231582, Integer.valueOf(401));
localSparseArray.put(2131232416, Integer.valueOf(402));
localSparseArray.put(2131231638, Integer.valueOf(403));
localSparseArray.put(2131231866, Integer.valueOf(404));
localSparseArray.put(2131232123, Integer.valueOf(405));
localSparseArray.put(2131492880, new String[] { "Standaard", "Geel", "Groen", "Rood", "Paars", "Zwart" });
localSparseArray.put(2131232388, Integer.valueOf(407));
localSparseArray.put(2131231691, Integer.valueOf(408));
localSparseArray.put(2131230783, Integer.valueOf(409));
localSparseArray.put(2131232210, Integer.valueOf(410));
localSparseArray.put(2131232144, Integer.valueOf(411));
localSparseArray.put(2131232471, Integer.valueOf(412));
localSparseArray.put(2131231524, Integer.valueOf(413));
localSparseArray.put(2131231020, Integer.valueOf(414));
localSparseArray.put(2131230870, Integer.valueOf(415));
localSparseArray.put(2131231272, Integer.valueOf(416));
localSparseArray.put(2131231824, Integer.valueOf(417));
localSparseArray.put(2131231187, Integer.valueOf(418));
localSparseArray.put(2131231195, Integer.valueOf(419));
localSparseArray.put(2131231433, Integer.valueOf(420));
localSparseArray.put(2131232480, Integer.valueOf(421));
localSparseArray.put(2131231226, Integer.valueOf(422));
localSparseArray.put(2131231647, Integer.valueOf(423));
localSparseArray.put(2131231622, Integer.valueOf(424));
localSparseArray.put(2131231132, Integer.valueOf(425));
localSparseArray.put(2131232531, Integer.valueOf(426));
localSparseArray.put(2131230947, Integer.valueOf(427));
localSparseArray.put(2131231595, Integer.valueOf(428));
localSparseArray.put(2131231209, Integer.valueOf(429));
localSparseArray.put(2131231079, Integer.valueOf(430));
localSparseArray.put(2131231679, Integer.valueOf(431));
localSparseArray.put(2131231407, Integer.valueOf(432));
localSparseArray.put(2131231521, Integer.valueOf(433));
localSparseArray.put(2131231887, Integer.valueOf(434));
localSparseArray.put(2131231194, Integer.valueOf(435));
localSparseArray.put(2131230915, Integer.valueOf(436));
localSparseArray.put(2131232384, Integer.valueOf(437));
localSparseArray.put(2131232313, Integer.valueOf(438));
localSparseArray.put(2131231430, Integer.valueOf(439));
localSparseArray.put(2131232341, Integer.valueOf(440));
localSparseArray.put(2131232260, Integer.valueOf(441));
localSparseArray.put(2131230974, Integer.valueOf(442));
localSparseArray.put(2131232576, Integer.valueOf(443));
localSparseArray.put(2131231522, Integer.valueOf(444));
localSparseArray.put(2131231637, Integer.valueOf(445));
localSparseArray.put(2131231027, Integer.valueOf(446));
localSparseArray.put(2131232272, Integer.valueOf(447));
localSparseArray.put(2131231650, Integer.valueOf(448));
localSparseArray.put(2131231911, Integer.valueOf(449));
localSparseArray.put(2131231579, Integer.valueOf(450));
localSparseArray.put(2131231552, Integer.valueOf(451));
localSparseArray.put(2131231486, Integer.valueOf(452));
localSparseArray.put(2131231367, Integer.valueOf(453));
localSparseArray.put(2131230976, Integer.valueOf(454));
localSparseArray.put(2131232116, Integer.valueOf(455));
localSparseArray.put(2131231274, Integer.valueOf(456));
localSparseArray.put(2131231299, Integer.valueOf(457));
localSparseArray.put(2131232073, Integer.valueOf(458));
localSparseArray.put(2131231403, Integer.valueOf(459));
localSparseArray.put(2131231529, Integer.valueOf(460));
localSparseArray.put(2131230842, Integer.valueOf(461));
localSparseArray.put(2131231083, Integer.valueOf(462));
localSparseArray.put(2131231615, Integer.valueOf(463));
localSparseArray.put(2131231557, Integer.valueOf(464));
localSparseArray.put(2131232422, Integer.valueOf(465));
localSparseArray.put(2131231562, Integer.valueOf(466));
localSparseArray.put(2131231092, Integer.valueOf(467));
localSparseArray.put(2131231639, Integer.valueOf(468));
localSparseArray.put(2131231127, Integer.valueOf(469));
localSparseArray.put(2131231025, Integer.valueOf(470));
localSparseArray.put(2131231516, Integer.valueOf(471));
localSparseArray.put(2131231829, Integer.valueOf(472));
localSparseArray.put(2131232198, Integer.valueOf(473));
localSparseArray.put(2131232403, Integer.valueOf(474));
localSparseArray.put(2131232119, Integer.valueOf(475));
localSparseArray.put(2131231856, Integer.valueOf(476));
localSparseArray.put(2131230972, Integer.valueOf(477));
localSparseArray.put(2131231642, Integer.valueOf(478));
localSparseArray.put(2131231775, Integer.valueOf(479));
localSparseArray.put(2131231169, Integer.valueOf(480));
localSparseArray.put(2131232280, Integer.valueOf(481));
localSparseArray.put(2131232175, Integer.valueOf(482));
localSparseArray.put(2131232448, Integer.valueOf(483));
localSparseArray.put(2131232444, Integer.valueOf(484));
localSparseArray.put(2131232447, Integer.valueOf(485));
localSparseArray.put(2131232218, Integer.valueOf(486));
localSparseArray.put(2131232446, Integer.valueOf(487));
localSparseArray.put(2131232346, Integer.valueOf(488));
localSparseArray.put(2131232418, Integer.valueOf(489));
localSparseArray.put(2131232219, Integer.valueOf(490));
localSparseArray.put(2131231910, Integer.valueOf(491));
localSparseArray.put(2131232184, Integer.valueOf(492));
localSparseArray.put(2131231800, Integer.valueOf(493));
localSparseArray.put(2131231379, Integer.valueOf(494));
localSparseArray.put(2131231185, Integer.valueOf(495));
localSparseArray.put(2131232203, Integer.valueOf(496));
localSparseArray.put(2131231199, Integer.valueOf(497));
localSparseArray.put(2131232350, Integer.valueOf(498));
localSparseArray.put(2131492871, new String[] { "Favorieten", "Lokaal", "Bibliotheek", "Netwerk", "Gereedschappen" });
localSparseArray.put(2131231992, Integer.valueOf(500));
localSparseArray.put(2131231899, Integer.valueOf(501));
localSparseArray.put(2131232554, Integer.valueOf(502));
localSparseArray.put(2131231993, Integer.valueOf(503));
localSparseArray.put(2131231864, Integer.valueOf(504));
localSparseArray.put(2131231017, Integer.valueOf(505));
localSparseArray.put(2131232321, Integer.valueOf(506));
localSparseArray.put(2131231912, Integer.valueOf(507));
localSparseArray.put(2131232327, Integer.valueOf(508));
localSparseArray.put(2131232168, Integer.valueOf(509));
localSparseArray.put(2131231889, Integer.valueOf(510));
localSparseArray.put(2131231372, Integer.valueOf(511));
localSparseArray.put(2131231320, Integer.valueOf(512));
localSparseArray.put(2131230920, Integer.valueOf(513));
localSparseArray.put(2131232400, Integer.valueOf(514));
localSparseArray.put(2131230896, Integer.valueOf(515));
localSparseArray.put(2131231319, Integer.valueOf(516));
localSparseArray.put(2131231345, Integer.valueOf(517));
localSparseArray.put(2131231528, Integer.valueOf(518));
localSparseArray.put(2131231421, Integer.valueOf(519));
localSparseArray.put(2131231757, Integer.valueOf(520));
localSparseArray.put(2131231327, Integer.valueOf(521));
localSparseArray.put(2131231517, Integer.valueOf(522));
localSparseArray.put(2131232406, Integer.valueOf(523));
localSparseArray.put(2131231593, Integer.valueOf(524));
localSparseArray.put(2131231086, Integer.valueOf(525));
localSparseArray.put(2131230948, Integer.valueOf(526));
localSparseArray.put(2131231636, Integer.valueOf(527));
localSparseArray.put(2131231849, Integer.valueOf(528));
localSparseArray.put(2131232037, Integer.valueOf(529));
localSparseArray.put(2131231594, Integer.valueOf(530));
localSparseArray.put(2131231308, Integer.valueOf(531));
localSparseArray.put(2131231832, Integer.valueOf(532));
localSparseArray.put(2131232361, Integer.valueOf(533));
localSparseArray.put(2131230963, Integer.valueOf(534));
localSparseArray.put(2131231469, Integer.valueOf(535));
localSparseArray.put(2131231544, Integer.valueOf(536));
localSparseArray.put(2131230876, Integer.valueOf(537));
localSparseArray.put(2131232495, Integer.valueOf(538));
localSparseArray.put(2131231871, Integer.valueOf(539));
localSparseArray.put(2131231422, Integer.valueOf(540));
localSparseArray.put(2131231356, Integer.valueOf(541));
localSparseArray.put(2131231047, Integer.valueOf(542));
localSparseArray.put(2131232033, Integer.valueOf(543));
localSparseArray.put(2131232344, Integer.valueOf(544));
localSparseArray.put(2131231177, Integer.valueOf(545));
localSparseArray.put(2131231304, Integer.valueOf(546));
localSparseArray.put(2131231021, Integer.valueOf(547));
localSparseArray.put(2131230825, Integer.valueOf(548));
localSparseArray.put(2131230852, Integer.valueOf(549));
localSparseArray.put(2131231534, Integer.valueOf(550));
localSparseArray.put(2131232383, Integer.valueOf(551));
localSparseArray.put(2131232428, Integer.valueOf(552));
localSparseArray.put(2131230883, Integer.valueOf(553));
localSparseArray.put(2131231432, Integer.valueOf(554));
localSparseArray.put(2131231339, Integer.valueOf(555));
localSparseArray.put(2131231325, Integer.valueOf(556));
localSparseArray.put(2131231166, Integer.valueOf(557));
localSparseArray.put(2131231515, Integer.valueOf(558));
localSparseArray.put(2131231813, Integer.valueOf(559));
localSparseArray.put(2131231673, Integer.valueOf(560));
localSparseArray.put(2131232246, Integer.valueOf(561));
localSparseArray.put(2131230751, Integer.valueOf(562));
localSparseArray.put(2131231566, Integer.valueOf(563));
localSparseArray.put(2131232013, Integer.valueOf(564));
localSparseArray.put(2131231110, Integer.valueOf(565));
localSparseArray.put(2131231409, Integer.valueOf(566));
localSparseArray.put(2131231090, Integer.valueOf(567));
localSparseArray.put(2131232032, Integer.valueOf(568));
localSparseArray.put(2131232297, Integer.valueOf(569));
localSparseArray.put(2131230955, Integer.valueOf(570));
localSparseArray.put(2131230832, Integer.valueOf(571));
localSparseArray.put(2131232586, Integer.valueOf(572));
localSparseArray.put(2131231291, Integer.valueOf(573));
localSparseArray.put(2131231446, Integer.valueOf(574));
localSparseArray.put(2131689474, new String[] { "%1$d min geleden", "%1$d min geleden" });
localSparseArray.put(2131230943, Integer.valueOf(576));
localSparseArray.put(2131231351, Integer.valueOf(577));
localSparseArray.put(2131232326, Integer.valueOf(578));
localSparseArray.put(2131232493, Integer.valueOf(579));
localSparseArray.put(2131231263, Integer.valueOf(580));
localSparseArray.put(2131231632, Integer.valueOf(581));
localSparseArray.put(2131231210, Integer.valueOf(582));
localSparseArray.put(2131231311, Integer.valueOf(583));
localSparseArray.put(2131230942, Integer.valueOf(584));
localSparseArray.put(2131232412, Integer.valueOf(585));
localSparseArray.put(2131231368, Integer.valueOf(586));
localSparseArray.put(2131231781, Integer.valueOf(587));
localSparseArray.put(2131232494, Integer.valueOf(588));
localSparseArray.put(2131230836, Integer.valueOf(589));
localSparseArray.put(2131230835, Integer.valueOf(590));
localSparseArray.put(2131231837, Integer.valueOf(591));
localSparseArray.put(2131231545, Integer.valueOf(592));
localSparseArray.put(2131231056, Integer.valueOf(593));
localSparseArray.put(2131232089, Integer.valueOf(594));
localSparseArray.put(2131231874, Integer.valueOf(595));
localSparseArray.put(2131231277, Integer.valueOf(596));
localSparseArray.put(2131231991, Integer.valueOf(597));
localSparseArray.put(2131232314, Integer.valueOf(598));
localSparseArray.put(2131231656, Integer.valueOf(599));
localSparseArray.put(2131232473, Integer.valueOf(600));
localSparseArray.put(2131231476, Integer.valueOf(601));
localSparseArray.put(2131230977, Integer.valueOf(602));
localSparseArray.put(2131230795, Integer.valueOf(603));
localSparseArray.put(2131230822, Integer.valueOf(604));
localSparseArray.put(2131230851, Integer.valueOf(605));
localSparseArray.put(2131231690, Integer.valueOf(606));
localSparseArray.put(2131231324, Integer.valueOf(607));
localSparseArray.put(2131232563, Integer.valueOf(608));
localSparseArray.put(2131231773, Integer.valueOf(609));
localSparseArray.put(2131230953, Integer.valueOf(610));
localSparseArray.put(2131232052, Integer.valueOf(611));
localSparseArray.put(2131232555, Integer.valueOf(612));
localSparseArray.put(2131231350, Integer.valueOf(613));
localSparseArray.put(2131231395, Integer.valueOf(614));
localSparseArray.put(2131231023, Integer.valueOf(615));
localSparseArray.put(2131231573, Integer.valueOf(616));
localSparseArray.put(2131231527, Integer.valueOf(617));
localSparseArray.put(2131231204, Integer.valueOf(618));
localSparseArray.put(2131231909, Integer.valueOf(619));
localSparseArray.put(2131231628, Integer.valueOf(620));
localSparseArray.put(2131232105, Integer.valueOf(621));
localSparseArray.put(2131231904, Integer.valueOf(622));
localSparseArray.put(2131231833, Integer.valueOf(623));
localSparseArray.put(2131232544, Integer.valueOf(624));
localSparseArray.put(2131230986, Integer.valueOf(625));
localSparseArray.put(2131231723, Integer.valueOf(626));
localSparseArray.put(2131231007, Integer.valueOf(627));
localSparseArray.put(2131231764, Integer.valueOf(628));
localSparseArray.put(2131230747, Integer.valueOf(629));
localSparseArray.put(2131231441, Integer.valueOf(630));
localSparseArray.put(2131232164, Integer.valueOf(631));
localSparseArray.put(2131232434, Integer.valueOf(632));
localSparseArray.put(2131232029, Integer.valueOf(633));
localSparseArray.put(2131231500, Integer.valueOf(634));
localSparseArray.put(2131232320, Integer.valueOf(635));
localSparseArray.put(2131231847, Integer.valueOf(636));
localSparseArray.put(2131232207, Integer.valueOf(637));
localSparseArray.put(2131230951, Integer.valueOf(638));
localSparseArray.put(2131232319, Integer.valueOf(639));
localSparseArray.put(2131231404, Integer.valueOf(640));
localSparseArray.put(2131230946, Integer.valueOf(641));
localSparseArray.put(2131230928, Integer.valueOf(642));
localSparseArray.put(2131231745, Integer.valueOf(643));
localSparseArray.put(2131232036, Integer.valueOf(644));
localSparseArray.put(2131232411, Integer.valueOf(645));
localSparseArray.put(2131231207, Integer.valueOf(646));
localSparseArray.put(2131230881, Integer.valueOf(647));
localSparseArray.put(2131231396, Integer.valueOf(648));
localSparseArray.put(2131232157, Integer.valueOf(649));
localSparseArray.put(2131232377, Integer.valueOf(650));
localSparseArray.put(2131232492, Integer.valueOf(651));
localSparseArray.put(2131232519, Integer.valueOf(652));
localSparseArray.put(2131231042, Integer.valueOf(653));
localSparseArray.put(2131230848, Integer.valueOf(654));
localSparseArray.put(2131231763, Integer.valueOf(655));
localSparseArray.put(2131232391, Integer.valueOf(656));
localSparseArray.put(2131231131, Integer.valueOf(657));
localSparseArray.put(2131232426, Integer.valueOf(658));
localSparseArray.put(2131231703, Integer.valueOf(659));
localSparseArray.put(2131232488, Integer.valueOf(660));
localSparseArray.put(2131232559, Integer.valueOf(661));
localSparseArray.put(2131689479, new String[] { "%1$d afbeelding van %2$s", "%1$d afbeeldingen van %2$s" });
localSparseArray.put(2131231192, Integer.valueOf(663));
localSparseArray.put(2131232035, Integer.valueOf(664));
localSparseArray.put(2131231271, Integer.valueOf(665));
localSparseArray.put(2131231205, Integer.valueOf(666));
localSparseArray.put(2131231161, Integer.valueOf(667));
localSparseArray.put(2131232463, Integer.valueOf(668));
localSparseArray.put(2131231358, Integer.valueOf(669));
localSparseArray.put(2131232547, Integer.valueOf(670));
localSparseArray.put(2131231624, Integer.valueOf(671));
localSparseArray.put(2131231091, Integer.valueOf(672));
localSparseArray.put(2131232165, Integer.valueOf(673));
localSparseArray.put(2131231418, Integer.valueOf(674));
localSparseArray.put(2131231734, Integer.valueOf(675));
localSparseArray.put(2131232214, Integer.valueOf(676));
localSparseArray.put(2131231989, Integer.valueOf(677));
localSparseArray.put(2131231743, Integer.valueOf(678));
localSparseArray.put(2131231065, Integer.valueOf(679));
localSparseArray.put(2131232000, Integer.valueOf(680));
localSparseArray.put(2131231626, Integer.valueOf(681));
localSparseArray.put(2131232072, Integer.valueOf(682));
localSparseArray.put(2131231776, Integer.valueOf(683));
localSparseArray.put(2131232252, Integer.valueOf(684));
localSparseArray.put(2131232220, Integer.valueOf(685));
localSparseArray.put(2131232521, Integer.valueOf(686));
localSparseArray.put(2131231774, Integer.valueOf(687));
localSparseArray.put(2131232524, Integer.valueOf(688));
localSparseArray.put(2131492881, new String[] { "Grote iconen", "Medium iconen", "Kleine iconen", "Grote lijst", "Medium lijst", "Kleine lijst", "Grote details", "Medium details", "Kleine details" });
localSparseArray.put(2131232206, Integer.valueOf(690));
localSparseArray.put(2131230895, Integer.valueOf(691));
localSparseArray.put(2131231480, Integer.valueOf(692));
localSparseArray.put(2131231273, Integer.valueOf(693));
localSparseArray.put(2131231478, Integer.valueOf(694));
localSparseArray.put(2131231479, Integer.valueOf(695));
localSparseArray.put(2131230888, Integer.valueOf(696));
localSparseArray.put(2131232023, Integer.valueOf(697));
localSparseArray.put(2131231206, Integer.valueOf(698));
localSparseArray.put(2131230723, Integer.valueOf(699));
localSparseArray.put(2131232549, Integer.valueOf(700));
localSparseArray.put(2131232464, Integer.valueOf(701));
localSparseArray.put(2131232177, Integer.valueOf(702));
localSparseArray.put(2131231188, Integer.valueOf(703));
localSparseArray.put(2131231564, Integer.valueOf(704));
localSparseArray.put(2131231298, Integer.valueOf(705));
localSparseArray.put(2131231660, Integer.valueOf(706));
localSparseArray.put(2131232366, Integer.valueOf(707));
localSparseArray.put(2131230885, Integer.valueOf(708));
localSparseArray.put(2131231822, Integer.valueOf(709));
localSparseArray.put(2131231182, Integer.valueOf(710));
localSparseArray.put(2131231834, Integer.valueOf(711));
localSparseArray.put(2131230973, Integer.valueOf(712));
localSparseArray.put(2131231491, Integer.valueOf(713));
localSparseArray.put(2131231842, Integer.valueOf(714));
localSparseArray.put(2131231901, Integer.valueOf(715));
localSparseArray.put(2131232395, Integer.valueOf(716));
localSparseArray.put(2131231680, Integer.valueOf(717));
localSparseArray.put(2131230940, Integer.valueOf(718));
localSparseArray.put(2131231711, Integer.valueOf(719));
localSparseArray.put(2131231280, Integer.valueOf(720));
localSparseArray.put(2131232122, Integer.valueOf(721));
localSparseArray.put(2131231825, Integer.valueOf(722));
localSparseArray.put(2131231128, Integer.valueOf(723));
localSparseArray.put(2131232433, Integer.valueOf(724));
localSparseArray.put(2131231282, Integer.valueOf(725));
localSparseArray.put(2131231118, Integer.valueOf(726));
localSparseArray.put(2131230930, Integer.valueOf(727));
localSparseArray.put(2131231736, Integer.valueOf(728));
localSparseArray.put(2131231651, Integer.valueOf(729));
localSparseArray.put(2131231353, Integer.valueOf(730));
localSparseArray.put(2131232387, Integer.valueOf(731));
localSparseArray.put(2131231354, Integer.valueOf(732));
localSparseArray.put(2131231674, Integer.valueOf(733));
localSparseArray.put(2131230891, Integer.valueOf(734));
localSparseArray.put(2131232244, Integer.valueOf(735));
localSparseArray.put(2131230949, Integer.valueOf(736));
localSparseArray.put(2131231414, Integer.valueOf(737));
localSparseArray.put(2131231569, Integer.valueOf(738));
localSparseArray.put(2131232335, Integer.valueOf(739));
localSparseArray.put(2131230999, Integer.valueOf(740));
localSparseArray.put(2131231265, Integer.valueOf(741));
localSparseArray.put(2131231174, Integer.valueOf(742));
localSparseArray.put(2131232117, Integer.valueOf(743));
localSparseArray.put(2131232181, Integer.valueOf(744));
localSparseArray.put(2131231005, Integer.valueOf(745));
localSparseArray.put(2131232187, Integer.valueOf(746));
localSparseArray.put(2131231386, Integer.valueOf(747));
localSparseArray.put(2131232171, Integer.valueOf(748));
localSparseArray.put(2131230925, Integer.valueOf(749));
localSparseArray.put(2131232188, Integer.valueOf(750));
localSparseArray.put(2131231880, Integer.valueOf(751));
localSparseArray.put(2131232396, Integer.valueOf(752));
localSparseArray.put(2131232454, Integer.valueOf(753));
localSparseArray.put(2131231119, Integer.valueOf(754));
localSparseArray.put(2131230855, Integer.valueOf(755));
localSparseArray.put(2131231261, Integer.valueOf(756));
localSparseArray.put(2131232333, Integer.valueOf(757));
localSparseArray.put(2131232365, Integer.valueOf(758));
localSparseArray.put(2131231292, Integer.valueOf(759));
localSparseArray.put(2131232358, Integer.valueOf(760));
localSparseArray.put(2131231081, Integer.valueOf(761));
localSparseArray.put(2131231221, Integer.valueOf(762));
localSparseArray.put(2131230868, Integer.valueOf(763));
localSparseArray.put(2131231796, Integer.valueOf(764));
localSparseArray.put(2131231791, Integer.valueOf(765));
localSparseArray.put(2131230929, Integer.valueOf(766));
localSparseArray.put(2131232481, Integer.valueOf(767));
localSparseArray.put(2131231633, Integer.valueOf(768));
localSparseArray.put(2131232560, Integer.valueOf(769));
localSparseArray.put(2131231426, Integer.valueOf(770));
localSparseArray.put(2131232232, Integer.valueOf(771));
localSparseArray.put(2131230840, Integer.valueOf(772));
localSparseArray.put(2131231760, Integer.valueOf(773));
localSparseArray.put(2131231382, Integer.valueOf(774));
localSparseArray.put(2131232216, Integer.valueOf(775));
localSparseArray.put(2131230844, Integer.valueOf(776));
localSparseArray.put(2131231806, Integer.valueOf(777));
localSparseArray.put(2131232031, Integer.valueOf(778));
localSparseArray.put(2131230932, Integer.valueOf(779));
localSparseArray.put(2131230980, Integer.valueOf(780));
localSparseArray.put(2131230725, Integer.valueOf(781));
localSparseArray.put(2131232193, Integer.valueOf(782));
localSparseArray.put(2131231692, Integer.valueOf(783));
localSparseArray.put(2131231765, Integer.valueOf(784));
localSparseArray.put(2131231487, Integer.valueOf(785));
localSparseArray.put(2131231370, Integer.valueOf(786));
localSparseArray.put(2131232440, Integer.valueOf(787));
localSparseArray.put(2131231158, Integer.valueOf(788));
localSparseArray.put(2131232061, Integer.valueOf(789));
localSparseArray.put(2131232066, Integer.valueOf(790));
localSparseArray.put(2131232160, Integer.valueOf(791));
localSparseArray.put(2131232060, Integer.valueOf(792));
localSparseArray.put(2131231667, Integer.valueOf(793));
localSparseArray.put(2131232491, Integer.valueOf(794));
localSparseArray.put(2131231618, Integer.valueOf(795));
localSparseArray.put(2131232292, Integer.valueOf(796));
localSparseArray.put(2131231747, Integer.valueOf(797));
localSparseArray.put(2131231830, Integer.valueOf(798));
localSparseArray.put(2131231625, Integer.valueOf(799));
localSparseArray.put(2131231428, Integer.valueOf(800));
localSparseArray.put(2131231078, Integer.valueOf(801));
localSparseArray.put(2131231836, Integer.valueOf(802));
localSparseArray.put(2131231116, Integer.valueOf(803));
localSparseArray.put(2131231429, Integer.valueOf(804));
localSparseArray.put(2131232202, Integer.valueOf(805));
localSparseArray.put(2131232332, Integer.valueOf(806));
localSparseArray.put(2131231607, Integer.valueOf(807));
localSparseArray.put(2131232217, Integer.valueOf(808));
localSparseArray.put(2131231678, Integer.valueOf(809));
localSparseArray.put(2131231501, Integer.valueOf(810));
localSparseArray.put(2131232194, Integer.valueOf(811));
localSparseArray.put(2131230997, Integer.valueOf(812));
localSparseArray.put(2131232357, Integer.valueOf(813));
localSparseArray.put(2131231886, Integer.valueOf(814));
localSparseArray.put(2131231702, Integer.valueOf(815));
localSparseArray.put(2131231028, Integer.valueOf(816));
localSparseArray.put(2131231884, Integer.valueOf(817));
localSparseArray.put(2131231716, Integer.valueOf(818));
localSparseArray.put(2131231717, Integer.valueOf(819));
localSparseArray.put(2131231577, Integer.valueOf(820));
localSparseArray.put(2131231570, Integer.valueOf(821));
localSparseArray.put(2131232381, Integer.valueOf(822));
localSparseArray.put(2131231576, Integer.valueOf(823));
localSparseArray.put(2131230934, Integer.valueOf(824));
localSparseArray.put(2131231583, Integer.valueOf(825));
localSparseArray.put(2131231307, Integer.valueOf(826));
localSparseArray.put(2131232360, Integer.valueOf(827));
localSparseArray.put(2131231543, Integer.valueOf(828));
localSparseArray.put(2131232156, Integer.valueOf(829));
localSparseArray.put(2131232283, Integer.valueOf(830));
localSparseArray.put(2131231117, Integer.valueOf(831));
localSparseArray.put(2131231362, Integer.valueOf(832));
localSparseArray.put(2131231986, Integer.valueOf(833));
localSparseArray.put(2131231077, Integer.valueOf(834));
localSparseArray.put(2131232058, Integer.valueOf(835));
localSparseArray.put(2131230991, Integer.valueOf(836));
localSparseArray.put(2131232145, Integer.valueOf(837));
localSparseArray.put(2131232049, Integer.valueOf(838));
localSparseArray.put(2131231804, Integer.valueOf(839));
localSparseArray.put(2131231782, Integer.valueOf(840));
localSparseArray.put(2131492885, new String[] { "", "Scannen…", "Verbinden met %1$s…", "Authenticatie met %1$s…", "Ontvangen IP van het adres %1$s…", "Verbonden met %1$s", "Hangend", "Verbinding verbreken met %1$s…", "Losgekoppeld", "Mislukt" });
localSparseArray.put(2131231213, Integer.valueOf(842));
localSparseArray.put(2131232183, Integer.valueOf(843));
localSparseArray.put(2131232002, Integer.valueOf(844));
localSparseArray.put(2131231828, Integer.valueOf(845));
localSparseArray.put(2131231801, Integer.valueOf(846));
localSparseArray.put(2131231029, Integer.valueOf(847));
localSparseArray.put(2131231162, Integer.valueOf(848));
localSparseArray.put(2131232213, Integer.valueOf(849));
localSparseArray.put(2131231374, Integer.valueOf(850));
localSparseArray.put(2131689475, new String[] { "%1$d APK van %2$s", "%1$d APK's van %2$s" });
localSparseArray.put(2131232588, Integer.valueOf(852));
localSparseArray.put(2131231471, Integer.valueOf(853));
localSparseArray.put(2131231896, Integer.valueOf(854));
localSparseArray.put(2131231054, Integer.valueOf(855));
localSparseArray.put(2131231217, Integer.valueOf(856));
localSparseArray.put(2131231634, Integer.valueOf(857));
localSparseArray.put(2131231669, Integer.valueOf(858));
localSparseArray.put(2131231731, Integer.valueOf(859));
localSparseArray.put(2131231666, Integer.valueOf(860));
localSparseArray.put(2131231536, Integer.valueOf(861));
localSparseArray.put(2131231317, Integer.valueOf(862));
localSparseArray.put(2131232004, Integer.valueOf(863));
localSparseArray.put(2131231531, Integer.valueOf(864));
localSparseArray.put(2131232084, Integer.valueOf(865));
localSparseArray.put(2131231481, Integer.valueOf(866));
localSparseArray.put(2131231482, Integer.valueOf(867));
localSparseArray.put(2131231331, Integer.valueOf(868));
localSparseArray.put(2131231329, Integer.valueOf(869));
localSparseArray.put(2131231321, Integer.valueOf(870));
localSparseArray.put(2131232582, Integer.valueOf(871));
localSparseArray.put(2131231676, Integer.valueOf(872));
localSparseArray.put(2131231322, Integer.valueOf(873));
localSparseArray.put(2131231286, Integer.valueOf(874));
localSparseArray.put(2131231652, Integer.valueOf(875));
localSparseArray.put(2131230889, Integer.valueOf(876));
localSparseArray.put(2131232107, Integer.valueOf(877));
localSparseArray.put(2131230913, Integer.valueOf(878));
localSparseArray.put(2131231276, Integer.valueOf(879));
localSparseArray.put(2131232461, Integer.valueOf(880));
localSparseArray.put(2131232408, Integer.valueOf(881));
localSparseArray.put(2131231337, Integer.valueOf(882));
localSparseArray.put(2131231523, Integer.valueOf(883));
localSparseArray.put(2131232034, Integer.valueOf(884));
localSparseArray.put(2131231437, Integer.valueOf(885));
localSparseArray.put(2131231050, Integer.valueOf(886));
localSparseArray.put(2131232568, Integer.valueOf(887));
localSparseArray.put(2131231845, Integer.valueOf(888));
localSparseArray.put(2131232394, Integer.valueOf(889));
localSparseArray.put(2131232348, Integer.valueOf(890));
localSparseArray.put(2131232415, Integer.valueOf(891));
localSparseArray.put(2131230864, Integer.valueOf(892));
localSparseArray.put(2131231010, Integer.valueOf(893));
localSparseArray.put(2131231996, Integer.valueOf(894));
localSparseArray.put(2131231373, Integer.valueOf(895));
localSparseArray.put(2131231812, Integer.valueOf(896));
localSparseArray.put(2131231567, Integer.valueOf(897));
localSparseArray.put(2131231062, Integer.valueOf(898));
localSparseArray.put(2131231653, Integer.valueOf(899));
localSparseArray.put(2131231490, Integer.valueOf(900));
localSparseArray.put(2131232300, Integer.valueOf(901));
localSparseArray.put(2131231463, Integer.valueOf(902));
localSparseArray.put(2131231323, Integer.valueOf(903));
localSparseArray.put(2131231160, Integer.valueOf(904));
localSparseArray.put(2131231085, Integer.valueOf(905));
localSparseArray.put(2131232322, Integer.valueOf(906));
localSparseArray.put(2131231655, Integer.valueOf(907));
localSparseArray.put(2131231492, Integer.valueOf(908));
localSparseArray.put(2131231891, Integer.valueOf(909));
localSparseArray.put(2131231778, Integer.valueOf(910));
localSparseArray.put(2131231706, Integer.valueOf(911));
localSparseArray.put(2131232594, Integer.valueOf(912));
localSparseArray.put(2131232331, Integer.valueOf(913));
localSparseArray.put(2131231022, Integer.valueOf(914));
localSparseArray.put(2131230838, Integer.valueOf(915));
localSparseArray.put(2131232574, Integer.valueOf(916));
localSparseArray.put(2131232131, Integer.valueOf(917));
localSparseArray.put(2131231814, Integer.valueOf(918));
localSparseArray.put(2131232071, Integer.valueOf(919));
localSparseArray.put(2131232439, Integer.valueOf(920));
localSparseArray.put(2131230817, Integer.valueOf(921));
localSparseArray.put(2131232301, Integer.valueOf(922));
localSparseArray.put(2131232053, Integer.valueOf(923));
localSparseArray.put(2131231460, Integer.valueOf(924));
localSparseArray.put(2131231641, Integer.valueOf(925));
localSparseArray.put(2131231191, Integer.valueOf(926));
localSparseArray.put(2131232571, Integer.valueOf(927));
localSparseArray.put(2131232442, Integer.valueOf(928));
localSparseArray.put(2131231732, Integer.valueOf(929));
localSparseArray.put(2131232159, Integer.valueOf(930));
localSparseArray.put(2131230917, Integer.valueOf(931));
localSparseArray.put(2131232533, Integer.valueOf(932));
localSparseArray.put(2131230926, Integer.valueOf(933));
localSparseArray.put(2131230890, Integer.valueOf(934));
localSparseArray.put(2131231489, Integer.valueOf(935));
localSparseArray.put(2131230936, Integer.valueOf(936));
localSparseArray.put(2131231905, Integer.valueOf(937));
localSparseArray.put(2131231848, Integer.valueOf(938));
localSparseArray.put(2131231484, Integer.valueOf(939));
localSparseArray.put(2131231709, Integer.valueOf(940));
localSparseArray.put(2131231420, Integer.valueOf(941));
localSparseArray.put(2131231126, Integer.valueOf(942));
localSparseArray.put(2131232264, Integer.valueOf(943));
localSparseArray.put(2131232063, Integer.valueOf(944));
localSparseArray.put(2131232237, Integer.valueOf(945));
localSparseArray.put(2131231608, Integer.valueOf(946));
localSparseArray.put(2131232291, Integer.valueOf(947));
localSparseArray.put(2131231766, Integer.valueOf(948));
localSparseArray.put(2131230854, Integer.valueOf(949));
localSparseArray.put(2131231216, Integer.valueOf(950));
localSparseArray.put(2131231120, Integer.valueOf(951));
localSparseArray.put(2131231168, Integer.valueOf(952));
localSparseArray.put(2131231202, Integer.valueOf(953));
localSparseArray.put(2131232581, Integer.valueOf(954));
localSparseArray.put(2131232352, Integer.valueOf(955));
localSparseArray.put(2131231714, Integer.valueOf(956));
localSparseArray.put(2131232465, Integer.valueOf(957));
localSparseArray.put(2131231502, Integer.valueOf(958));
localSparseArray.put(2131231099, Integer.valueOf(959));
localSparseArray.put(2131232051, Integer.valueOf(960));
localSparseArray.put(2131231990, Integer.valueOf(961));
localSparseArray.put(2131231815, Integer.valueOf(962));
localSparseArray.put(2131231394, Integer.valueOf(963));
localSparseArray.put(2131231208, Integer.valueOf(964));
localSparseArray.put(2131232451, Integer.valueOf(965));
localSparseArray.put(2131231134, Integer.valueOf(966));
localSparseArray.put(2131232110, Integer.valueOf(967));
localSparseArray.put(2131232238, Integer.valueOf(968));
localSparseArray.put(2131230834, Integer.valueOf(969));
localSparseArray.put(2131230863, Integer.valueOf(970));
localSparseArray.put(2131231102, Integer.valueOf(971));
localSparseArray.put(2131232113, Integer.valueOf(972));
localSparseArray.put(2131231212, Integer.valueOf(973));
localSparseArray.put(2131232262, Integer.valueOf(974));
localSparseArray.put(2131232118, Integer.valueOf(975));
localSparseArray.put(2131231283, Integer.valueOf(976));
localSparseArray.put(2131230982, Integer.valueOf(977));
localSparseArray.put(2131231268, Integer.valueOf(978));
localSparseArray.put(2131232022, Integer.valueOf(979));
localSparseArray.put(2131231159, Integer.valueOf(980));
localSparseArray.put(2131232174, Integer.valueOf(981));
localSparseArray.put(2131232240, Integer.valueOf(982));
localSparseArray.put(2131232514, Integer.valueOf(983));
localSparseArray.put(2131231735, Integer.valueOf(984));
localSparseArray.put(2131232173, Integer.valueOf(985));
localSparseArray.put(2131232490, Integer.valueOf(986));
localSparseArray.put(2131231606, Integer.valueOf(987));
localSparseArray.put(2131232402, Integer.valueOf(988));
localSparseArray.put(2131231551, Integer.valueOf(989));
localSparseArray.put(2131231843, Integer.valueOf(990));
localSparseArray.put(2131232153, Integer.valueOf(991));
localSparseArray.put(2131232429, Integer.valueOf(992));
localSparseArray.put(2131231876, Integer.valueOf(993));
localSparseArray.put(2131232103, Integer.valueOf(994));
localSparseArray.put(2131232435, Integer.valueOf(995));
localSparseArray.put(2131231729, Integer.valueOf(996));
localSparseArray.put(2131231609, Integer.valueOf(997));
localSparseArray.put(2131232317, Integer.valueOf(998));
localSparseArray.put(2131231787, Integer.valueOf(999));
localSparseArray.put(2131231470, Integer.valueOf(1000));
localSparseArray.put(2131231541, Integer.valueOf(1001));
localSparseArray.put(2131231799, Integer.valueOf(1002));
localSparseArray.put(2131230884, Integer.valueOf(1003));
localSparseArray.put(2131231262, Integer.valueOf(1004));
localSparseArray.put(2131231744, Integer.valueOf(1005));
localSparseArray.put(2131232124, Integer.valueOf(1006));
localSparseArray.put(2131230818, Integer.valueOf(1007));
localSparseArray.put(2131230815, Integer.valueOf(1008));
localSparseArray.put(2131231863, Integer.valueOf(1009));
localSparseArray.put(2131231113, Integer.valueOf(1010));
localSparseArray.put(2131231619, Integer.valueOf(1011));
localSparseArray.put(2131230985, Integer.valueOf(1012));
localSparseArray.put(2131231914, Integer.valueOf(1013));
localSparseArray.put(2131231290, Integer.valueOf(1014));
localSparseArray.put(2131232385, Integer.valueOf(1015));
localSparseArray.put(2131231770, Integer.valueOf(1016));
localSparseArray.put(2131231009, Integer.valueOf(1017));
localSparseArray.put(2131231612, Integer.valueOf(1018));
localSparseArray.put(2131231511, Integer.valueOf(1019));
localSparseArray.put(2131231406, Integer.valueOf(1020));
localSparseArray.put(2131231176, Integer.valueOf(1021));
localSparseArray.put(2131232130, Integer.valueOf(1022));
localSparseArray.put(2131231100, Integer.valueOf(1023));
localSparseArray.put(2131232042, Integer.valueOf(1024));
localSparseArray.put(2131232099, Integer.valueOf(1025));
localSparseArray.put(2131232163, Integer.valueOf(1026));
localSparseArray.put(2131232221, Integer.valueOf(1027));
localSparseArray.put(2131231444, Integer.valueOf(1028));
localSparseArray.put(2131231671, Integer.valueOf(1029));
localSparseArray.put(2131232338, Integer.valueOf(1030));
localSparseArray.put(2131231809, Integer.valueOf(1031));
localSparseArray.put(2131232290, Integer.valueOf(1032));
localSparseArray.put(2131231769, Integer.valueOf(1033));
localSparseArray.put(2131231559, Integer.valueOf(1034));
localSparseArray.put(2131231823, Integer.valueOf(1035));
localSparseArray.put(2131232158, Integer.valueOf(1036));
localSparseArray.put(2131232441, Integer.valueOf(1037));
localSparseArray.put(2131231073, Integer.valueOf(1038));
localSparseArray.put(2131232382, Integer.valueOf(1039));
localSparseArray.put(2131231121, Integer.valueOf(1040));
localSparseArray.put(2131231699, Integer.valueOf(1041));
localSparseArray.put(2131231178, Integer.valueOf(1042));
localSparseArray.put(2131231129, Integer.valueOf(1043));
localSparseArray.put(2131232146, Integer.valueOf(1044));
localSparseArray.put(2131231749, Integer.valueOf(1045));
localSparseArray.put(2131230960, Integer.valueOf(1046));
localSparseArray.put(2131231371, Integer.valueOf(1047));
localSparseArray.put(2131231335, Integer.valueOf(1048));
localSparseArray.put(2131231089, Integer.valueOf(1049));
localSparseArray.put(2131231293, Integer.valueOf(1050));
localSparseArray.put(2131231442, Integer.valueOf(1051));
localSparseArray.put(2131232258, Integer.valueOf(1052));
localSparseArray.put(2131230894, Integer.valueOf(1053));
localSparseArray.put(2131232139, Integer.valueOf(1054));
localSparseArray.put(2131232249, Integer.valueOf(1055));
localSparseArray.put(2131232509, Integer.valueOf(1056));
localSparseArray.put(2131231509, Integer.valueOf(1057));
localSparseArray.put(2131231631, Integer.valueOf(1058));
localSparseArray.put(2131231519, Integer.valueOf(1059));
localSparseArray.put(2131232405, Integer.valueOf(1060));
localSparseArray.put(2131232295, Integer.valueOf(1061));
localSparseArray.put(2131232179, Integer.valueOf(1062));
localSparseArray.put(2131231338, Integer.valueOf(1063));
localSparseArray.put(2131231537, Integer.valueOf(1064));
localSparseArray.put(2131232024, Integer.valueOf(1065));
localSparseArray.put(2131230865, Integer.valueOf(1066));
localSparseArray.put(2131230995, Integer.valueOf(1067));
localSparseArray.put(2131231264, Integer.valueOf(1068));
localSparseArray.put(2131230971, Integer.valueOf(1069));
localSparseArray.put(2131230828, Integer.valueOf(1070));
localSparseArray.put(2131232215, Integer.valueOf(1071));
localSparseArray.put(2131232185, Integer.valueOf(1072));
localSparseArray.put(2131231136, Integer.valueOf(1073));
localSparseArray.put(2131231798, Integer.valueOf(1074));
localSparseArray.put(2131231163, Integer.valueOf(1075));
localSparseArray.put(2131230923, Integer.valueOf(1076));
localSparseArray.put(2131230872, Integer.valueOf(1077));
localSparseArray.put(2131231816, Integer.valueOf(1078));
localSparseArray.put(2131231580, Integer.valueOf(1079));
localSparseArray.put(2131231030, Integer.valueOf(1080));
localSparseArray.put(2131231586, Integer.valueOf(1081));
localSparseArray.put(2131230721, Integer.valueOf(1082));
localSparseArray.put(2131231380, Integer.valueOf(1083));
localSparseArray.put(2131231572, Integer.valueOf(1084));
localSparseArray.put(2131231850, Integer.valueOf(1085));
localSparseArray.put(2131230975, Integer.valueOf(1086));
localSparseArray.put(2131232329, Integer.valueOf(1087));
localSparseArray.put(2131231066, Integer.valueOf(1088));
localSparseArray.put(2131231540, Integer.valueOf(1089));
localSparseArray.put(2131230726, Integer.valueOf(1090));
localSparseArray.put(2131232149, Integer.valueOf(1091));
localSparseArray.put(2131231585, Integer.valueOf(1092));
localSparseArray.put(2131232355, Integer.valueOf(1093));
localSparseArray.put(2131231677, Integer.valueOf(1094));
localSparseArray.put(2131231831, Integer.valueOf(1095));
localSparseArray.put(2131231278, Integer.valueOf(1096));
localSparseArray.put(2131231366, Integer.valueOf(1097));
localSparseArray.put(2131231916, Integer.valueOf(1098));
localSparseArray.put(2131230950, Integer.valueOf(1099));
localSparseArray.put(2131231016, Integer.valueOf(1100));
localSparseArray.put(2131230996, Integer.valueOf(1101));
localSparseArray.put(2131231903, Integer.valueOf(1102));
localSparseArray.put(2131232140, Integer.valueOf(1103));
localSparseArray.put(2131232585, Integer.valueOf(1104));
localSparseArray.put(2131232154, Integer.valueOf(1105));
localSparseArray.put(2131231361, Integer.valueOf(1106));
localSparseArray.put(2131232015, Integer.valueOf(1107));
localSparseArray.put(2131232380, Integer.valueOf(1108));
localSparseArray.put(2131231838, Integer.valueOf(1109));
localSparseArray.put(2131231571, Integer.valueOf(1110));
localSparseArray.put(2131231635, Integer.valueOf(1111));
localSparseArray.put(2131231719, Integer.valueOf(1112));
localSparseArray.put(2131231494, Integer.valueOf(1113));
localSparseArray.put(2131231627, Integer.valueOf(1114));
localSparseArray.put(2131231497, Integer.valueOf(1115));
localSparseArray.put(2131231306, Integer.valueOf(1116));
localSparseArray.put(2131232275, Integer.valueOf(1117));
localSparseArray.put(2131232068, Integer.valueOf(1118));
localSparseArray.put(2131231504, Integer.valueOf(1119));
localSparseArray.put(2131231858, Integer.valueOf(1120));
localSparseArray.put(2131230882, Integer.valueOf(1121));
localSparseArray.put(2131231508, Integer.valueOf(1122));
localSparseArray.put(2131231075, Integer.valueOf(1123));
localSparseArray.put(2131231614, Integer.valueOf(1124));
localSparseArray.put(2131231499, Integer.valueOf(1125));
localSparseArray.put(2131231218, Integer.valueOf(1126));
localSparseArray.put(2131231890, Integer.valueOf(1127));
localSparseArray.put(2131230958, Integer.valueOf(1128));
localSparseArray.put(2131230957, Integer.valueOf(1129));
localSparseArray.put(2131231111, Integer.valueOf(1130));
localSparseArray.put(2131232390, Integer.valueOf(1131));
localSparseArray.put(2131232242, Integer.valueOf(1132));
localSparseArray.put(2131232209, Integer.valueOf(1133));
localSparseArray.put(2131689477, new String[] { "%1$d document van %2$s", "%1$d documenten van %2$s" });
localSparseArray.put(2131231588, Integer.valueOf(1135));
localSparseArray.put(2131230892, Integer.valueOf(1136));
localSparseArray.put(2131232334, Integer.valueOf(1137));
localSparseArray.put(2131231578, Integer.valueOf(1138));
localSparseArray.put(2131231355, Integer.valueOf(1139));
localSparseArray.put(2131232570, Integer.valueOf(1140));
localSparseArray.put(2131230862, Integer.valueOf(1141));
localSparseArray.put(2131231359, Integer.valueOf(1142));
localSparseArray.put(2131232303, Integer.valueOf(1143));
localSparseArray.put(2131231096, Integer.valueOf(1144));
localSparseArray.put(2131231171, Integer.valueOf(1145));
localSparseArray.put(2131231389, Integer.valueOf(1146));
localSparseArray.put(2131232008, Integer.valueOf(1147));
localSparseArray.put(2131231780, Integer.valueOf(1148));
localSparseArray.put(2131232284, Integer.valueOf(1149));
localSparseArray.put(2131232055, Integer.valueOf(1150));
localSparseArray.put(2131232147, Integer.valueOf(1151));
localSparseArray.put(2131231855, Integer.valueOf(1152));
localSparseArray.put(2131232591, Integer.valueOf(1153));
localSparseArray.put(2131232239, Integer.valueOf(1154));
localSparseArray.put(2131231893, Integer.valueOf(1155));
localSparseArray.put(2131231122, Integer.valueOf(1156));
localSparseArray.put(2131231347, Integer.valueOf(1157));
localSparseArray.put(2131231393, Integer.valueOf(1158));
localSparseArray.put(2131232250, Integer.valueOf(1159));
localSparseArray.put(2131232048, Integer.valueOf(1160));
localSparseArray.put(2131232294, Integer.valueOf(1161));
localSparseArray.put(2131232204, Integer.valueOf(1162));
localSparseArray.put(2131231336, Integer.valueOf(1163));
localSparseArray.put(2131231820, Integer.valueOf(1164));
localSparseArray.put(2131689472, new String[] { "%1$d dag geleden", "%1$d dagen geleden" });
localSparseArray.put(2131232276, Integer.valueOf(1166));
localSparseArray.put(2131230945, Integer.valueOf(1167));
localSparseArray.put(2131231044, Integer.valueOf(1168));
localSparseArray.put(2131232129, Integer.valueOf(1169));
localSparseArray.put(2131231547, Integer.valueOf(1170));
localSparseArray.put(2131231507, Integer.valueOf(1171));
localSparseArray.put(2131232398, Integer.valueOf(1172));
localSparseArray.put(2131231664, Integer.valueOf(1173));
localSparseArray.put(2131231865, Integer.valueOf(1174));
localSparseArray.put(2131231095, Integer.valueOf(1175));
localSparseArray.put(2131230827, Integer.valueOf(1176));
localSparseArray.put(2131231011, Integer.valueOf(1177));
localSparseArray.put(2131231777, Integer.valueOf(1178));
localSparseArray.put(2131232374, Integer.valueOf(1179));
localSparseArray.put(2131232277, Integer.valueOf(1180));
localSparseArray.put(2131232590, Integer.valueOf(1181));
localSparseArray.put(2131232489, Integer.valueOf(1182));
localSparseArray.put(2131232343, Integer.valueOf(1183));
localSparseArray.put(2131232205, Integer.valueOf(1184));
localSparseArray.put(2131231708, Integer.valueOf(1185));
localSparseArray.put(2131232564, Integer.valueOf(1186));
localSparseArray.put(2131231643, Integer.valueOf(1187));
localSparseArray.put(2131689473, new String[] { "%1$d uur geleden", "%1$d uur geleden" });
localSparseArray.put(2131231705, Integer.valueOf(1189));
localSparseArray.put(2131230933, Integer.valueOf(1190));
localSparseArray.put(2131231385, Integer.valueOf(1191));
localSparseArray.put(2131232017, Integer.valueOf(1192));
localSparseArray.put(2131231105, Integer.valueOf(1193));
localSparseArray.put(2131231881, Integer.valueOf(1194));
localSparseArray.put(2131232312, Integer.valueOf(1195));
localSparseArray.put(2131231915, Integer.valueOf(1196));
localSparseArray.put(2131231436, Integer.valueOf(1197));
localSparseArray.put(2131232039, Integer.valueOf(1198));
localSparseArray.put(2131232142, Integer.valueOf(1199));
localSparseArray.put(2131230961, Integer.valueOf(1200));
localSparseArray.put(2131231797, Integer.valueOf(1201));
localSparseArray.put(2131232450, Integer.valueOf(1202));
localSparseArray.put(2131232517, Integer.valueOf(1203));
localSparseArray.put(2131231196, Integer.valueOf(1204));
localSparseArray.put(2131231554, Integer.valueOf(1205));
localSparseArray.put(2131231424, Integer.valueOf(1206));
localSparseArray.put(2131231043, Integer.valueOf(1207));
localSparseArray.put(2131231818, Integer.valueOf(1208));
localSparseArray.put(2131232001, Integer.valueOf(1209));
localSparseArray.put(2131230866, Integer.valueOf(1210));
localSparseArray.put(2131230978, Integer.valueOf(1211));
localSparseArray.put(2131232170, Integer.valueOf(1212));
localSparseArray.put(2131230880, Integer.valueOf(1213));
localSparseArray.put(2131230921, Integer.valueOf(1214));
localSparseArray.put(2131232003, Integer.valueOf(1215));
localSparseArray.put(2131231503, Integer.valueOf(1216));
localSparseArray.put(2131232543, Integer.valueOf(1217));
localSparseArray.put(2131232248, Integer.valueOf(1218));
localSparseArray.put(2131231883, Integer.valueOf(1219));
localSparseArray.put(2131232593, Integer.valueOf(1220));
localSparseArray.put(2131231477, Integer.valueOf(1221));
localSparseArray.put(2131232094, Integer.valueOf(1222));
localSparseArray.put(2131231663, Integer.valueOf(1223));
localSparseArray.put(2131231363, Integer.valueOf(1224));
localSparseArray.put(2131230850, Integer.valueOf(1225));
localSparseArray.put(2131232166, Integer.valueOf(1226));
localSparseArray.put(2131231346, Integer.valueOf(1227));
localSparseArray.put(2131231995, Integer.valueOf(1228));
localSparseArray.put(2131232399, Integer.valueOf(1229));
localSparseArray.put(2131232431, Integer.valueOf(1230));
localSparseArray.put(2131231538, Integer.valueOf(1231));
localSparseArray.put(2131232059, Integer.valueOf(1232));
localSparseArray.put(2131232455, Integer.valueOf(1233));
localSparseArray.put(2131231224, Integer.valueOf(1234));
localSparseArray.put(2131231462, Integer.valueOf(1235));
localSparseArray.put(2131232572, Integer.valueOf(1236));
localSparseArray.put(2131231438, Integer.valueOf(1237));
localSparseArray.put(2131232339, Integer.valueOf(1238));
localSparseArray.put(2131230994, Integer.valueOf(1239));
localSparseArray.put(2131231303, Integer.valueOf(1240));
localSparseArray.put(2131231074, Integer.valueOf(1241));
localSparseArray.put(2131231877, Integer.valueOf(1242));
localSparseArray.put(2131231854, Integer.valueOf(1243));
localSparseArray.put(2131231542, Integer.valueOf(1244));
localSparseArray.put(2131231859, Integer.valueOf(1245));
localSparseArray.put(2131232027, Integer.valueOf(1246));
localSparseArray.put(2131231617, Integer.valueOf(1247));
localSparseArray.put(2131232347, Integer.valueOf(1248));
localSparseArray.put(2131230927, Integer.valueOf(1249));
localSparseArray.put(2131232161, Integer.valueOf(1250));
localSparseArray.put(2131230841, Integer.valueOf(1251));
localSparseArray.put(2131232095, Integer.valueOf(1252));
localSparseArray.put(2131232386, Integer.valueOf(1253));
localSparseArray.put(2131232553, Integer.valueOf(1254));
localSparseArray.put(2131231715, Integer.valueOf(1255));
localSparseArray.put(2131232186, Integer.valueOf(1256));
localSparseArray.put(2131232067, Integer.valueOf(1257));
localSparseArray.put(2131231675, Integer.valueOf(1258));
localSparseArray.put(2131232056, Integer.valueOf(1259));
localSparseArray.put(2131231810, Integer.valueOf(1260));
localSparseArray.put(2131231598, Integer.valueOf(1261));
localSparseArray.put(2131230877, Integer.valueOf(1262));
localSparseArray.put(2131231109, Integer.valueOf(1263));
localSparseArray.put(2131231558, Integer.valueOf(1264));
localSparseArray.put(2131232462, Integer.valueOf(1265));
localSparseArray.put(2131232584, Integer.valueOf(1266));
localSparseArray.put(2131231423, Integer.valueOf(1267));
localSparseArray.put(2131231006, Integer.valueOf(1268));
localSparseArray.put(2131231805, Integer.valueOf(1269));
localSparseArray.put(2131232077, Integer.valueOf(1270));
localSparseArray.put(2131231857, Integer.valueOf(1271));
localSparseArray.put(2131231710, Integer.valueOf(1272));
localSparseArray.put(2131231098, Integer.valueOf(1273));
localSparseArray.put(2131232069, Integer.valueOf(1274));
localSparseArray.put(2131231698, Integer.valueOf(1275));
localSparseArray.put(2131231094, Integer.valueOf(1276));
localSparseArray.put(2131232026, Integer.valueOf(1277));
localSparseArray.put(2131231114, Integer.valueOf(1278));
localSparseArray.put(2131232356, Integer.valueOf(1279));
localSparseArray.put(2131232018, Integer.valueOf(1280));
localSparseArray.put(2131689481, new String[] { "%1$d video van %2$s", "%1$d video's van %2$s" });
localSparseArray.put(2131231895, Integer.valueOf(1282));
localSparseArray.put(2131231546, Integer.valueOf(1283));
localSparseArray.put(2131230826, Integer.valueOf(1284));
localSparseArray.put(2131232199, Integer.valueOf(1285));
localSparseArray.put(2131230939, Integer.valueOf(1286));
localSparseArray.put(2131231768, Integer.valueOf(1287));
localSparseArray.put(2131231439, Integer.valueOf(1288));
localSparseArray.put(2131231384, Integer.valueOf(1289));
localSparseArray.put(2131231392, Integer.valueOf(1290));
localSparseArray.put(2131231697, Integer.valueOf(1291));
localSparseArray.put(2131232211, Integer.valueOf(1292));
localSparseArray.put(2131231332, Integer.valueOf(1293));
localSparseArray.put(2131231397, Integer.valueOf(1294));
localSparseArray.put(2131231575, Integer.valueOf(1295));
localSparseArray.put(2131231201, Integer.valueOf(1296));
localSparseArray.put(2131232092, Integer.valueOf(1297));
localSparseArray.put(2131231748, Integer.valueOf(1298));
localSparseArray.put(2131231532, Integer.valueOf(1299));
localSparseArray.put(2131232545, Integer.valueOf(1300));
localSparseArray.put(2131231767, Integer.valueOf(1301));
localSparseArray.put(2131231581, Integer.valueOf(1302));
localSparseArray.put(2131231758, Integer.valueOf(1303));
localSparseArray.put(2131230857, Integer.valueOf(1304));
localSparseArray.put(2131231902, Integer.valueOf(1305));
localSparseArray.put(2131231076, Integer.valueOf(1306));
localSparseArray.put(2131232007, Integer.valueOf(1307));
localSparseArray.put(2131231018, Integer.valueOf(1308));
localSparseArray.put(2131232389, Integer.valueOf(1309));
localSparseArray.put(2131232575, Integer.valueOf(1310));
localSparseArray.put(2131232247, Integer.valueOf(1311));
localSparseArray.put(2131231568, Integer.valueOf(1312));
localSparseArray.put(2131231759, Integer.valueOf(1313));
localSparseArray.put(2131231082, Integer.valueOf(1314));
localSparseArray.put(2131232078, Integer.valueOf(1315));
localSparseArray.put(2131231115, Integer.valueOf(1316));
localSparseArray.put(2131232436, Integer.valueOf(1317));
localSparseArray.put(2131231645, Integer.valueOf(1318));
localSparseArray.put(2131231190, Integer.valueOf(1319));
localSparseArray.put(2131232548, Integer.valueOf(1320));
localSparseArray.put(2131232569, Integer.valueOf(1321));
localSparseArray.put(2131231343, Integer.valueOf(1322));
localSparseArray.put(2131232097, Integer.valueOf(1323));
localSparseArray.put(2131231285, Integer.valueOf(1324));
localSparseArray.put(2131231165, Integer.valueOf(1325));
localSparseArray.put(2131231369, Integer.valueOf(1326));
localSparseArray.put(2131492876, new String[] { "Alles", "Vandaag", "Gisteren", "Deze week", "Deze maand", "Dit Jaar", "> 1 jaar", "Toepassen" });
localSparseArray.put(2131230839, Integer.valueOf(1328));
localSparseArray.put(2131231349, Integer.valueOf(1329));
localSparseArray.put(2131232081, Integer.valueOf(1330));
localSparseArray.put(2131232522, Integer.valueOf(1331));
localSparseArray.put(2131231771, Integer.valueOf(1332));
localSparseArray.put(2131230887, Integer.valueOf(1333));
localSparseArray.put(2131231803, Integer.valueOf(1334));
localSparseArray.put(2131232567, Integer.valueOf(1335));
return localSparseArray;
}
public static String a(int paramInt)
{
return new String[] { "Num___Gestures staan uit___%s downloaden mislukt___Thema___Mislukt. Gebruik een andere naam.___{0} wordt niet ondersteund.___ %s taken zijn voltooid.___Bescherm uw netwerk met een wachtwoord.___Toon de vensterknop in de taakbalk___Zoeken in video('s)___Domeinnaam, kan leeg zijn.___Controleer draadloze verbinding.___Speciale dank voor de vertalers___U moet de %s plugin bijwerken, wilt u dat nu doen?___Reactie plaatsen mislukt.___Dit gesture wordt al gebruikt, probeer een ander___Verifiëren…___App gemaakt___uitpakken___Pro-thema___SD-kaart Analyse___Schrijven___Map___%s bijwerken___Afsluitopties___Versie___Rommelbestanden___Meer___Laden…___ ___Server___Verzender___Systeem AP-naam gebruiken___Nu controleren___Laatst geopend___Verborgen bestanden opnemen___Verzenden…___installeer en verwijder apk automatisch___Beveiliging___Opnieuw___Wijzig hostbestand___GID instellen___Even geduld, bestand laden…___Gereedschapsopties___Verplaatsen naar prullenbak___FTP Host Server___Weigeren___Lijn Terminator___Oud wachtwoord:___Doe mee___Wachtwoord onthouden___Geschiedenis wissen bij het afsluiten.___%s downloaden mislukt___Genomen op:___Kies doel___Dit duurt even, en hangt af van uw toestel___Alles herstellen___Inputgrootte___Toegang tot telefoon met FTP Server___Zoeken in app(s) ___Operaties___- WLAN staat uit___Prullenbak___ES File Explorer___Geheugen___ ___{0} app(s) bevat(ten) {1} (een) gevoelige machtiging(en)___Video('s) analyseren___%1$s file van %2$s___Voer een beschrijving in.___3 dagen___Verplaatsen bevestigen?___Aanmelden___Negeren___Verwijderen___Shuffle inschakelen door te schudden___,Totale grootte: %s___Totale grootte: ___Van:___Netwerk___Wachten om netwerk te gebruiken…___Gelieve het apparaat dat u wilt verwijderen te ontkoppelen.___Berekenen___Alarm instellen___Zomen___Bluetooth___Opnieuw downloaden___Maak/bewerk gestures___geleden___Aflopend___ANNULEREN___Server toevoegen…___Eén-toets installeren___Externe geheugen___%1$s APK van %2$s___ ___Overbrengen…___Pauzeren___Details___Even geduld…___\"%s\" ingesteld als start___%1$sDeelt bestand met u, klik deze link om te downloaden: %2$s___Comprimeren…___\"%1$s\" is verzonden.___Geheugen vol.___ ___%1$s document van %2$s___Kan niet kopiëren naar sub map.___Verberg lijstvescherming___Bestanden groter dan 10 MB___Hot___Meer laden…___Maak een draagbaar hotspot netwerk om te delen met anderen___Beschikbare plaats:___Onbekende artiest___Download mislukt___Bestandsnaam lezen mislukt.___Verbonden___huidige poort: ___Stoppen___Miniaturen___Wachtwoord: ___U kan nog 12 dingen selecteren.___Berkenen mislukt___Klaar___Grootte___Geavanceerd zoeken___Sorteren op___SD-kaart___Verberglijst is gewist.___Hint___Inclusief submappen___Vereist app::___Screenshots___Toon de scroll thumb bij lang scrollen.___Inladen mislukt.___Backup map: ___Verkeerd bestandstype, selecteer opnieuw___Familie___Ruimte vrij: %s___AP is gestart maar heeft geen toestemming om te controleren, vink het aan in de systeeminstellingen.___Voer hier opmerking in___Taken wissen___Redundante bestanden___{0} item(s)___FTP___U___Authentificatie mislukt. Controleer uw gebruikersnaam/wachtwoord.___Overschrijven___Nummer___Machtigingen wijzigen mislukt___Geselecteerde APK's installeren?___ ___Resterend:___Aan:___Kan niet verwijderd worden.___Auto-update uitschakelen___Willekeurige AP-naam genereren___Wilt u de huidige taak stoppen?___Zoeken___Appmuziek___Nieuwer thema beschikbaar, gelieve te updaten.___Systeemmap als alleen-lezen ingeladen.___Systeem___Wachtwoord___Deze testversie is verouderd. Werk nu bij naar de nieuwste versie.___Wachtwoord niet bevestigd.___Privacy___Downloaden___Voer a.u.b. wachtwoord in___Zelden gebruikte bestanden gevonden___Bestand:___Berekenen…___Wijzig het wachtwoord.___items___Wachtwoord is nodig om ES File Explorer te gebruiken___Registreren voltooid.___Geen back-up___Meerdere bestanden___Delen met…___Ontsleutelen___Voeg een server toe door te tikken op de functie voor een nieuwe server___Private sleutel___Optie bestand:___Favorieten___Selecteer een netwerk om te gebruiken___Kon instellingen niet herstellen___Analyseren___Sla ook appdata op bij het maken van een back-up.___Album bewerken___Plakken___ESFTP___Uitpakken naar…___Verwijderen gelukt.___ ___Lezen___Installeren voltooid.___Beheerdersaccount instellen___Verbinden___Gekopieerd___Items in deze categorie zijn de door u gedownloade bestanden.\nWeet u zeker dat u deze wilt selecteren? ___Instagram ondersteunt uploaden van hier niet.___Weergave___bezoek: ___Klik hier om ES Pro Version te downloaden.___Video's___ES FTP Server Stoppen?___Schuiven___Uploaden…___Letters en getallen___Vorige___Cache herstellen gelukt.___Start locatie___Gezondheid___Geen liedjes gevonden___Vensteropties___Zet wachtwoordbescherming aan om uw resources te beschermen.___Appvideo('s)___Back-up data___Door uw apps gemaakte tijdelijke bestanden (.tmp) en logbestanden (.log) evenals lege bestanden en mappen op uw telefoon. Het is raadzaam om ze te verwijderen.___Klik om te wijzigen. Dit kan leeg zijn.___Lokaal___Open Venster - %1$s___Remote Servers___OK___Verouderde APK's___Draai naar rechts___SD-kaart___Een must-have tool om uw apps te beschermen tegen toegang door onbevoegden!___De lengte van de naam van SSID moet minder dan 32 tekens bevatten___Zoeken…___Thema___Nee___Geavanceerd___Alles tonen___Webdav serverhost___Installeren mislukt.___Even geduld…___Dubbele bestanden___Boeken___Certificaat wordt niet vertrouwd___ ___Klik om in te stellen___FTP Server___Deze applicatie kan niet gestart worden.___Map analyse___ ___Cloud___Scannen…___Netwerk bestaat niet.___Wachtwoord is niet juist___Standaard actie wissen___Meer acculading___Weet u zeker dat u {0} … ({1} items) wilt verwijderen?___Kon nested zip-bestand niet openen___Codering___Geselecteerde charset is niet beschikbaar op uw apparaat___Start bescherming___Eenheid___OBEX FTP service succesvol gestart. U kan nu bestand overzetten op andere Bluetooth apparaten.___Wachtwoord wijzigen___Alleen u (privé)___Verplaats bestanden naar \"%1$s\".___Weet u zeker dat u de andere vensters wilt sluiten?___We laten u weten wanneer het proces is voltooid___Schijf___Huidige voortgang___Kan aangepaste AP niet gebruiken___Zoeken in afbeelding(en)___Fout, het bestand is te groot___E-mailadres:___Standaard venster instellen___Standaardopties herstellen___ ___Toon waarschuwing als er weinig geheugen is na een app is geïnstalleerd___Selecteren___Inloggen mislukt___Kies de gewenste map.___Remote Beheer___Back-up locatie:___Nu analyseren___Lege map.___Sommige onderdelen werden niet gevonden. U hebt deze nodig om alle functies te gebruiken. Wilt u ze installeren?___Netwerk gestart___Verwijder systeemapplicaties___Playlist hernoemen___Cliënt is bezig, probeer later opnieuw.___Netwerk SSID___Controleer a.u.b. uw WLAN verbinding, of maak een nieuw netwerk en nodig anderen uit___Achtergebleven rommel___Gebruikerapps___Beheerdersopties___Vul a.u.b. de downloadlocatie in___Totale voortgang___Achtergrondafbeelding___Toon weining geheugen-waarschuwing___Compressieniveau:___Apps analyseren___Aantal bestanden___WLAN hotspot instellen___Mijn___Flickr___Afspelen___Zichtbaar___Grote bestanden___Systeemapps___Nieuwe pakket___Bekijk netwerkinstellingen in systeem___Voer nieuwe naam in___Openen in browser___Dit kan zijn door:___ ___Nieuwe SFTP___Beoordeel ons___{1} vrije ruimte afgenomen in de afgelopen {0} dag(en)___Stoppen___Nu Spelen___Afspeellijst opgeslagen.___Netwerk gebruiken gestart…___Locatie openen___Logger___WLAN aanzetten___Playlist opslaan___Afspeellijst opslaan mislukt.___Vandaag___Laatste keer: %s___Geïnstalleerd op SD-kaart___Opschoning aanbevolen___Al lang niet gewijzigd bestand___Acties___Wilt u hervatten om het bestand te voltooien?___Zwart___Filteren___Succesvol opgeslagen.___Deze operatie wordt niet ondersteund.___Afbeeldingen___Randapparaten___Toevoegen aan afspeellijst___Hernoem extensienaam___Afspelen op…___ES Fotoviewer___U gebruikt een netwerk met SSID___Netwerk___Locatie___Geef een naam op.___U kan met anderen delen in dit netwerk___Herstellen gelukt. Dit zal van kracht zijn na heropstarten.___Wilt u overschrijven?___Kan bestand niet openen.___Instellen geslaagd.___Passief___Nu in het netwerk met ID:___Deze audio kan niet afgespeeld worden___Succes___Startnummer___Achtergrond wijzigen___Resolutie:___Actie: %1$s___Cloud___Succesvol___Mediafout___Kopiëren bevestigen?___Venster losmaken___Zoeken in muziek ___IP adres___Openen met___\"%1$s\" verwijderd.___Verborgen bestanden___Download voltooid___Knop voor snelle toegang tot analyseresultaten op de startpagina weergeven___Beheerders___Mij het wachtwoord e-mailen___Toevoegen aan playlist___Root locatie instellen___Mediabestanden opnemen___Vensterknop tonen___Instagram ondersteunt verwijderen van hier niet.___ROOT ENHANCEMENT___Alles analyseren___Wissen___Nieuw___Verbinding gesloten___Lied toegevoegd.___Zorg ervoor dat foutopsporing ingeschakeld is in de instellingen voor de Android TV.___Niet-opgeslagen lijst___%s niet gevonden___Het wachtwoord moet ten minste 8 tekens bevatten___Instellen mislukt.___Installeer met cachedata___Netwerk Bewerken___Weet u zeker dat u {0} wilt verwijderen?___Net___Er trad een fout op bij het opslaan van het bestand. Het zal niet opgeslagen worden.___Geschiedenis wissen___Viewer___Weet u zeker dat u deze taak wilt verwijderen?___LAN___Scannen voltooid!___Verwijderen___Het encryptie algoritme wordt niet ondersteund.___Niets geselecteerd___Netwerk___Mapweergave___Diavoorstelling___Overdracht___Snel scrollen___ ___Met mij gedeeld___Er is een nieuwe versie van de %s plugin beschikbaar, wilt u deze nu bijwerken?___Selecteer een apparaat om naartoe te sturen___Locatie:___Werk bij tot huidige versie.___Venster vastzetten___Server starten mislukt, controleer poortinstellingen.___Cache data herstellen?___Openen als…___Overslaan___IP Adr.,of IP Adr./SharedFolder___Geback-upt___Bewaren___Aanmaken, even geduld a.u.b…___Overdracht mislukt: netwerkfout of de ontvanger heeft geweigerd___Reactie geplaatst.___Klembord___ %s items___Bestanden___Schudden___Beschermingsniveau___Berichtvenster___Advies: ___Bladwijzers___DCIM___Bewerk %s Server___Geef dit adres in op uw computer: \n___Map openen___Niet geïnstalleerd___\"%s\" is toegevoegd aan de serverlijst.___Netwerkfout bij ophalen media-inhoud.___Zoek bestanden onder een specifieke server locatie.___Hotspot aanmaken___Kan Bluetooth-bestand niet delen___Enkel vernieuwen___Installeren…___Verbonden met netwerk___Er is geen verbinding,\n zet eerst WLAN aan___Checksum tonen___Herstel de cachedata___Weet u zeker dat u alle vensters wilt verwijderen?___Apparaat___Bescherming staat uit.___Appvergrendelaar___Lang drukken en slepen___Nieuwer___APPs:___Verwijderen voltooid.___SD-kaartgrootte tonen___SD-kaart is leeg of niet goed aangesloten.___Huidige start locatie:___Taal___Toevoegen aan___impliciet___Knippen___Computer___Wachtwoord___ES File Explorer Handleiding___Thema bewerken___Favorieten___Bluetooth-locatie:___Vrij:___Appspecifiek bestand___{0} app(s)___Modus___Nieuwe %s Server___Uitschakelen…___Totaal: %s items%s___Nieuwskaart uitschakelen___Wilt u opslaan?___ APKs geïnstalleerd___Voeg een server toe door te tikken op de zoekfunctie of de functie voor een nieuwe server___Exception found!___Afspeellijsten___Benodigde plaats:___Uitpakken...___Prettige kerstdagen!___Instagram ondersteunt bewerken van hier niet.___UW SYNCHRONISATIEMAP MAKEN___Grootte:___MEGA KOMT ERAAN___Naam:___Meer thema's online…___Eigenschappen:___Eigenaar___Verplaatsen…___- SMB server is buiten bereik___Taken verwijderen bevestigen? \nInclusief %1$s item(s), %2$s downloadta(a)k(en)___Rommel gevonden!___Bekeken op:___Geniet nu van meer functies___Soortgelijke afbeelding___ ___Groep___Verwijderen voltooid.___Apparaten in de buurt zoeken…___Andere___D___Verwijderen van meerdere bestanden bevestigen___Selecteer een apparaat a.u.b.___Wachtwoord moet tussen 6 - 34 tekens lang zijn.___{0} bestaat niet.___Comprimeren...___Openen in huidig venster___Foto's:___Bronnen verwijderen…___Album kiezen___Taak mislukt___Starten___Cache gewist.___zip___expliciet___Een bestand versleutelen___{0} comprimeren mislukt.___Details___Actief___Voortgang___Neem de eerste stap naar een betere planeet___Andere___Machtigingsnaam___Wachtwoord opgeven___Geen machtigingen voor deze map___Weergave___Earth Hour___Bestand niet gevonden? Probeer dieper te zoeken___Alles tonen___Bronbestand___U gebruikt een onofficiële versie van {0}! Om de veiligheid te garanderen, bezoek http://www.estrongs.com en dowload de officiële versie.___Aangeraden___Gesture inschakelen___Posten___Weet u zeker dat u een systeem applicatie wilt verwijderen?___Voltooid___Er wordt 128-bits versleuteling gebruikt om uw privacy te beschermen tegen ongewenste lezers bij het overzetten en in de cloud.___Apps___Lied toevoegen mislutk, playlist in niet wijzigbaar___Datum formaat___Kan niet meer dan 100 bestanden in één keer delen___Download(s)___Weken___Geheugengebruik___Op alles toepassen___Uitpakken___Gesture toevoegen___Niet-ondersteund mediatype.___Weet u zeker dat u %s opnieuw wilt instellen?___Opslaan___Hotspot aanmaken___Geselecteerde bestanden uitpakken naar___item___Laatst gemaakt___Selecteer codering___Account___%1$s video van %2$s___Openen___ES Opslaan als…___Ruimte analyseren___Analyseknop weergeven___UIT___Succesvol bewerkt.___Onbekend___ALGEMENE INSTELLINGEN___SD-kaart uitgeworpen.___In de afgelopen 7 dagen gemaakte bestanden___Meer opschonen___Snelheid___Snelkoppeling maken mislukt___Willekeurige AP-naam gebruiken___ ___Het resultaat bevat zowel interne SD-kaart- als externe SD-kaartbestanden___Cache___Zender heeft verbinding verloren___Kan systeem niet als schrijf baar inladen.___Compressieniveau___Foto schalen___ES Cleaner___Wilt u alle %s taken verwijderen?___Muziek analyseren___Achtergrondkleur___Audio:___Liedjes doorzoeken…___De geselecteerde apps bevatten ook systeemapps. Activeer root explorer in de opties.___Comprimeren___Sluiten___Server___App starten___Back-up applicatie___Remote Instellingen___Authenticatiepagina laden…___Spring naar…___Uitvoeren___Kan niet zoeken in systeemmap.___Home___Verwijderen van playlist___%s bestaat al, wilt u overschrijven?___ APKs verwijderen mislukt___versturen via LAN___Deze resource kan niet gevonden worden___Afsluiten___Play Store kon niet gevonden worden.___Doelbestand___Deze WLAN AP wordt niet ondersteund___De encryptie sterkte wordt niet ondersteund.___Lege bestanden op uw apparaat. Het is raadzaam om ze te verwijderen.___huisige charset: ___Wachten op verbinding met ___Verwijderen (%s)___Bron:___Net Manager___Opschonen___encryptie___Nu installeren___Hervatten___scannen…___Selecteer een achtergrondafbeelding___Meerdere operaties voltooid.___Vensters___Alle video's___Lege appspecifieke map___Opnieuw___Back-up Categorie___De naam mag geen * \\ / \" : ? | < > bevatten.___versturen via LAN___Verkrijg de systeem AP-naam om te gebruiken___Back-HP voltooid___urem___Wis de standaard applicatie actie.___Type___Select a category___Geen verdere reacties.___Gemaakt op:___%s ruimte vrijgemaakt.___Details bekijkem___Server bewerken___Beschrijving___Document(en) analyseren___{0}.{1} comprimeren.___Weergave___Wijzigingen opslaan___Zojuist___Hernoemen___Downloadbron gekopieerd___Machtigingen___Interne geheugen___Oudere versie gevonden. Deze versie verwijderen om de formele nieuwe versie te installeren?___Nieuwe versie beschikbaar,\nNu bijwerken?___Bestand verwijderen___Bewerken___Deze naam bestaat al___Waarschuwing! U moet het systeem als schrijfbaar inladen als u systeembestanden wilt wijzigen. Systeembestanden/mappen wijzigen is gevaarlijk. Doe dit alleen als u weet wat u doet.___Bestand___Download het thema eerst___Nieuwe playlist maken___Audio___Zoeken op internet___ ___Geen mediabestanden___Locatie___Opnieuw instellen___Rommel opgeschoond: ___DCIM___Locatie___Besch:___Locatie kiezen___Versleutelde naam:___Draagbaar___Back-up maken…___Miniaturen___\"{0}\" opgeslagen.___Leesbaar:___Sticky bit___{0} gekopieerd.___Originele bestandsnaam___Alle foto's___Geen WLAN, stel een netwerk in a.u.b.___Selecteer de gewenste taal___Er is een probleem met het pakket.___Ontvanger heeft geannuleerd___Type:___Dit is al de nieuwste versie.___Selecteer ten minste één {0}.___URL is ongeldig___ ___Bevat:___Sorteren___ zal u afbeelding %1$szenden___Ja___ zal u de map %1$szenden___ zal u %1$szenden___Interval selecteren___Back-up instellingen___Vandaag___ES Media Player___Geen taken meer___Vensters___Verwijderen…___Opschonen___Al vele dagen geleden sinds laatste analyse___Huidige locatie: ___Telefoon___Onbekend___Scannen___Voorbeeld___Opschonen gereed___Nieuw Netwerk___Installeren gelukt.___Systeembestanden uitsluiten___Recent gemaakte bestanden___Operatie mislukt.___Bezig…___Download(s)___Wilt u het laadscherm verbergen?___Toevoegen aan startscherm___Toevoegen aan favorieten___Scrollen aan hoge snelheid___Fout: serverlocatie is leeg.___Alle bestanden___dagen___Locatie gekopieerd.___Downloaden starten...___Hoeveelheid gebruikt geheugen___\"{0}\" opslaan mislukt.___Snelle toegang___Aantal___Mobile Foto's___Grootte___Recent bestand___Naam___Volgende___Gevoelige machtiging___.nomedia-bestanden weergeven___Grote bestanden gevonden___WLAN instellen___Geïnstalleerd___Annuleren___Reclamerommel___Toon de grootte van de SD-kaart in de geschiedenis___IP adres verkrijgen…___Geldige back-up___Ontvangen…___Nu downloaden___Verbinden met___Alle door uw apps gemaakte mappen in een lijst weergeven. U kunt onnodige content handmatig verwijderen.___hernoemen...___Officiële website___Taak centrum___U kan maximaal 12 vensters open hebben.___Nu afspelen___Volgende___Weet u zeker dat u het comprimeren wilt stoppen?___Instellen als beltoon___Niko Strijbol___Snelkoppeling gemaakt___Type___ES Downloader uitschakelen___Delen via cloud___Openen___-Geblokkeerd door firewall___ %s taken zijn bezig.___Identieke bestanden in verschillende directory's. U kunt dubbele bestanden verwijderen om ruimte vrij te maken op uw apparaat.___Bestandsoverdracht naar___Categorie___Encryptie (https)___AP-opties___Beoordelen voor steun___Kopiëren naar…___De doellocatie moet starten met /sdcard/.___Downloaddatum:___Eigenaar:___Standaard___Nieuw wachtwoord:___Opruimen___Analyseren___Verwijderen…___ES Kladblok___Verstuurd___Deze video kan niet afgespeeld worden.___Naam mag niet leeg zijn.___Toevoeging___Beschikbaar:___weken___Download(s)___Poort instellen(1025 – 65534)___Gestures Beheren___Label___Poort moet een nummer zijn (1025 – 65534)___Wissen___Video___Gebruikersnaam___Verwerken___Bestandsgrootte berekenen…___Andere sluiten___Oorspronkelijke naam:", "Kies een netwerk___Alle documenten___Nieuwe FTP___Uw eigen cloudserver beheren, zelfs met meerdere accounts___Verbinden, even geduld a.u.b…___Prompt___Instellen als meldingtoon___Playlist___Machtigingen:___Back-ups___7 dagen___Gestopt___ES FTP Server___Grootte___Bestand openen___Server bewerken___Cachedata herstellen...___Mij meldingen sturen over appmachtigingen___Fout___Druk nogmaals om af te sluiten___Scannen...: ___Nu opschonen___Bufferen…___Rommelbestanden: ___ES App Analyzer___Downloader___Decomprimeren...___Oplopend___Gesture-instellingen___Voer een titel in.___Op de achtergrond___Cloudopslag___Map grootte:___Machtigingen succesvol gewijzigd___Bluetooth-setup___huidige gebruiker: ___Appcache___Controleer om de halve maand op een nieuwe versie.___Toegang tot telefoon met FTP Server___Wachtwoord is gewijzigd.___Wallpaper instellen…___ ___Leeg___Verplaatst___Afmelden___Poort___- SMB staat uit___Gevoelige machtigingen___Foto's___Afbeeldingen:___Gebruikt:___ ___Start om netwerk te gebruiken___Systeem___Root explorer___Authorisatie mislukt, gelieve opnieuw in te loggen___Wis meldingen wanneer de taak voltooid is.___Checksum___%1$s nummer van %2$s___Kan niet verplaatsen naar sub map.___Wilt u alle logboeken wissen?___Geen gesture gedefinieerd___Verwijderen bestanden___Afspeellijst___Andere apps___Personalisatie___ %1$s ontvangen, totale grootte: %2$s___ %1$s ontvangen, %2$d item(s), totale grootte: %3$s___Fabrikant:___Geüpload op:___Wist u dat ES PRO de MEGA-cloudservice ondersteunt?___Beveiliging___Logger___Wat dacht u ervan om een map op uw telefoon te synchroniseren met uw cloudserver?___Kopieer bestanden naar \"%1$s\".___FTP___Niets selecteren___Back-up instellingen mislukt___Even geduld a.u.b…___Omwisselen___Charset___Bijna voltooid___Huidige locatie___Starten___Het standaardvenster zal geopend worden bij het opstarten___Kan apparaat niet vinden, misschien moet u vernieuwen?___Toon enkel audiobestanden >500kB in de playlist___Netwerk wachtwoord:___Niet voldoende plaats.___Voltooid___Pictogram voor map weergeven___Standaardthema___Berichtvenster___Alle APK's___Schrijven___Video's:___Verificatie mislukt___Opschoonbare bestanden gevonden___Standaard___Help___Geen bestanden gevonden___Inputdatum___{0} kopiëren mislukt.___Bestanden beheren in kerstsfeer met het Pro-thema Kleurrijke kerst___Appafbeelding(en)___Foto's___Selecteer geheugen___Geschiedenis___6 maanden___Instellen als standaard___Afspeellijst geannuleerd___Opslaan in playlist___Vul een geldig email adres in.___Instellen als alarm___Muziekspeler___Kopiëren___Gebruik een netwerk___Toon opties___Vul alle lege velden in___Automatisch___seconden___Meer apps___Datum___Charset kiezen___OPENEN___DOS/UNIX/MAC Terminator___Geïnstalleerd___Netwerk verlaten…___Facebook ondersteunt verwijderen niet.___Verplaatst naar \"%1$s\".___Privacybeleid___{0} bestand(en)/{1}___Gebruikersnaam mag niet leeg zijn.___Details___Versturen___Alleen bibliotheekbestanden weergeven___SD-kaart___Deze actie wordt niet ondersteund.___Geen gegevens meer___Het bestand is te groot.___Beltoon instellen___Versleuteld___Appspecifieke map___Registreren mislukt.___Toegang tot map limiteren___Video, kan direct afgespeeld worden___Web___Gescande apparaten___Naam te lang.___Filteren___Melding wissen___Ondersteunt lokaal afspelen en afspelen op afstand. Uw eigen afspeellijst maken___Laatst weergegeven___Vindt u ES leuk?___AP wachtwoord:___Fout: server niet gevonden.___Alarm___Speler___Alles weergeven___Omhoog___Stoppen bij afsluiten___UID instellen___Netwerkverbinding___Download %s plug-in___%d dagen geleden___Opslaangesture mislukt, gelieve te controleren of dat de SD-kaart bestaat___Mappen___Back-up instellingen succesvol___Bestanden opgeslagen in \"%1$s\".___Alles wissen___Aanmelden___Kan map niet verzenden.___Herstellen instellingen___Cache verwijderen bij afsluiten.___Meld systeem vernieuwen___Nieuwskaart voor nieuwe functies op de startpagina uitschakelen___Remonte bestand kopiëren mislukt.___Verwijder geselecteerde APKs?___ES Taakbeheer is niet geïnstalleerd.\n\nHet is een taakbeheer applicatie, om uw apps te beheren.\n\n Wilt u dit installeren?___Instellingen voor back-up en herstellen___E-books___Uitpakken…___Beschrijving:___Bestand niet gevonden? Geef dit door aan het systeem om te updaten (dit duurt even volgens uw systeem)___\"{0}\" bestaat al, overschrijven?___Kopiëren…___Tekst___Afspelen___Naam: %s___Geen bestand/map gekozen.___Geen downloadtaak gevonden___Naam mag niet leeg zijn.___Thema opties herstellen___OBEX FTP service ia gestopt.___Stel een wachtwoord in om uw resources te beschermen.___minuten___Systeemmap als schrijfbaar ingeladen.___Anoniem___Doorzoek bestanden___Alle muziek___Remote___Positie instellen___- Dit account heeft geen toegang___Opslaan als…___Comprimeren...___Checksum {0} opgeslagen in: {1}.___Scroll thumb tonen___App-pagina___Over___ES FTP Server Gestart___Details___Instagram___App Manager___Kan hier niet plakken.___Bestand maken mislukt.___Apparaat___Geen afbeeldingen meer___Categorie___Menu___Vrienden___Bewerken mislukt.___Cacherommel___Toon de knop om te selecteren in de taakbalk___Berekenen…___Bestanden___Startup Manager___Analyseren…___Schrijfbaar:___Voer a.u.b. SSID in___%1$s afbeelding van %2$s___Stel de gevoeligheid bij schudden in.___Wachtwoord kiezen___Opslaan mislukt___Geef de naam in.___Lege lijst___192.168.1.100/My Documents___Privacy-opties___De systeemtijd is onjuist, pas a.u.b. de systeemtijd aan___Uw apparaat ondersteunt geen Bluetooth.___Netwerkfout, probeer later opnieuw.___Nu analyseren___Afspeellijst verwijderen___Geheugen___APP___Automatisch___Weet u zeker dat u {0} wilt verwijderen?___Wilt u de huidige analyse stoppen?___Andere:___Selecteer codering___Speelgoed___Nieuw account___SSID en wachtwoord kunnen niet leeg zijn.___Prullenbak___Wachwoord tonen___Toon de naam in de taakbalk___U zou dit leuk vinden___Uitwerpen mislukt.___Laden mislukt.___Compressie niveau:___U kan uw telefoon beheren vanop uw computer nadat u de service inschakelt___Grootte: %s___Analyseren om ruimte vrij te maken___Downloaden…___Uitpakken in…___Maak nieuwe of verwijder gesturen in de Snelle Toegang___Bluetooth-locatie___Verplaatsen___Appmap___Compressie Manager___ APKs installatie mislukt___Back-uppen___Groep:___Gepauseerd___Muziek___- een ongeldig IP-adres___Screenshots___Alle bestanden worden weergegeven in een lijst op basis van de hoeveelheid ruimte die ze innemen. U kunt desgewenst details weergeven en bestanden verwijderen.___Alles plakken___Domein___Cloud___Geen applicatie beschikbaar.___Weergeven op pc___ES Downloader___Bronbestand ook verwijderen___Opgeschoond: ___Geen SD-kaart.___Verwijderen mislukt.___Instellen als startpagina___Batch Hernoemen___Actie selecteren___ES Zip viewer___Update instellingen___Muziek___Aangepast___Mijn server___Alles verbergen___Eigenschappen___Totaal:___De locatie die u hebt aangeven bestaat niet, wilt u deze aanmaken?___Foto's analyseren___Verwijderen bevestigen___Appspecifieke map___Netwerk locatie niet gevonden of time-out, probeer het later opnieuw.___Naam in de taakbalk tonen___Signaalsterkte___Beschrijving___Grootte___Back-up locatie___Deze media ondersteunt geen streaming. Wanneer het downloaden voltooid is zal dit automatisch openen.___Domein___Uw apparaat is opgeschoond___Naam___Verkeerde locatie___1 maand___Controleer uw draadloze verbinding.___Grootte___Weet u zeker dat u het decomprimeren wilt stoppen?___\"%1$s\" zal asynchroon \"%2$s\" genoemd worden.___Toon verborgen bestanden___Versleutelen voltooid___De tekst kon niet opgeslagen worden omdat het in een zip-bestand zit.___Herstellen___Tab___U kan geen bestanden/mappen hernoemen. Dit is een Bluetooth-beperking.___Wachtwoord___Datum___Root Explorer is geopend.___Openen in nieuw venster___Helpt u om bestanden in de huidige directory en het huidige venster te ANALYSEREN. Met slechts één tik!___U kunt meldingen uitschakelen via ALGEMENE INSTELLINGEN.___AAN___Test mislukt. Uw apparaat ondersteunt dit niet.___Versie:___Verborgen:___ ___Categorie___Delen___Instellen als wallpaper___Nu analyseren___Opnieuw scannen___Huidig netwerk verlaten___App vergrendelen___Bestand/SD___Zoeken in document(en)___Installeren___Office___Wilt u de plugin %s downloaden?___Posten...___Niet voldoende ruimte.___S3 locatie___Snelkoppeling aanmaken voor FTP server___Controleer handmatig op nieuwe updates___Weet u zeker dat u wilt verwijderen?___Nu gebruikt u een andere AP met SSID___Ontvanger heeft geweigerd___Aangeraden___Analyseren op grote bestanden die ruimte innemen___U kunt genieten van deze functie na het upgraden naar ES File Explorer Pro.___%s downloaden…___Aanbeveling___Beheer uw telefoon vanop uw computer___Versleuteling en ontsleuteling werken alleen in de interne opslagruimte. Verplaats bestanden naar de interne opslagruimte.___Bytes:___Kies locatie___Weergeven als___ ___Bestand hernoemen geslaagd___Opmerking___Geen playlist___Selecteerknop tonen___Beweging___Laden mislukt.___Locatie:___Gereedschappen___Niet in gebruik___Rapporteren___Terug___Geïnstalleerd op inwendig geheugen___Afbeeldingen niet gevonden.___Kan stream server niet starten.___\"%1$s\" hernoemd___Netwerk status___Afbeelding___Meerdere bestanden delen via remote onmogelijk___Wijzigen___Melding instellen___Netwerk annuleren___Apparaten vinden door te zoeken___ ___Verwijderen van lijst___Tik om %s te analyseren___URL niet gevonden___Back-up voor verwijderen___{0} geannuleerd.___Alleen-lezen___Geen filters___Locatie aanmaken is mislukt.___Gebruik een netwerk van iemand anders___Downloadlocatie___App manager-opties___Iedereen (publiek)___- FTP server is niet beschrikbaar___U moet dit liedje eerst downloaden.___Controleren…___Voltooid.___Lang drukken___Playlist bestaat al___Playlist verwijderen___Geëncrypteerd Transport___Afmelden bij geselecteerde accounts?___Verplaatsen naar…___ APKs verwijderd.___Verbinden…___Vernieuwen___Alle liedjes___Bestand opnemen als___Tik op Start - Alle bestanden weergeven in de versleutelingsbibliotheek___Youtube Video___Bijwerken___Melden wanneer het installeren van apps is voltooid___Zoek resultaten___ zal u mediabestand %1$szenden___Laden als R/W___Server___*Samenvatting___Versleutelen___Geannuleerd___Pro downloaden___Gebruiker___Taakdetails___Tekstkleur___Open Map - %1$s___Start de server opnieuw op om de nieuwe poort te gebruiken___Deze afspeellijst bestaat al.___Wit___Facebook___U kan delen met anderen in het netwerk___Wachten…___Schud gevoeligheid___Download Manager___Dagen___Bluetooth is niet beschikbaar in deze versie op Android 1.6. Gebruik ES File Explorer (for Cupcake) in de plaats.___\"%s\" zal asynchroon gemaakt worden.___Toon deze melding niet meer___Sleep om de startpositie van gestures in te stellen___Er trad een fout bij het openen van de bestandsinhoud: ___Cache wissen___Instellingen___Snelkoppeling___Directory analyseren___Titel___Nieuw___Back-up van app en data___Magic Briefcase___Het bestand zal tijdelijk opgeslagen worden en als ALLEEN-LEZEN geopend worden.___Bevestigen___Afspelen…___Toon bestanden die beginnen met '.' ook.___Zojuist___Snelkoppeling maken___Verificatiecode is verkeerd.___Album___Ontvangen___Kan hier niet zoeken___Verberg het klembord na kopiëren___Disks___Kon netwerk niet instellen, stel eerst de opties in___Netwerkfout, probeer later opnieuw.___Oude back-up___Wachtwoord bevestigen:___Netwerkbescherming___Annuleren___Instellen als achtergrond___Multi venster___Beheer verborgen bestanden___Reactie___Bluetooth is niet actief___Klik om het cachegeheugen (miniaturen enz.) te wissen.___Onbruikbare systeemapps, SD-kaartapps en geback-upte apps verwijderen___Naam___installeer/verwijder apps___ ___Zet de knop aan om root explorer te gebruiken, als u root toegang hebt.___Start App - %1$s___App koppelen___Aanzetten…___Het laadscherm verbergen?___Deze naam is niet toegestaan.___Netwerk gebruiken of aanmaken___Locatie:___%s downloaden mislukt omdat de locatie niet schrijfbaar is.___Toevoegen aan serverlijst___Gewijzigd op:___Model:___%s downloaden gelukt___Scannen op reclamerommel en andere rommelbestanden___Geef ons 5 sterren!___Rootverkenner___Afspeellijst maken___Gemeenschappelijk___Weet u zeker dat u wilt verwijderen?___Voltooid, opgeslagen in:\n {0}___Gecomprimeerd___Afbeelding laden mislukt.___Verbergen___\"{0}\" is aangemaakt.___Uw apparaat bevat een verouderde versie. U zal \"root\" toegang nodig hebben om bestanden te ontvangen. Als u doorgaat kunnen er onverwachte dingen gebeuren.\n\nWilt u toch proberen?___Reactie plaatsen___{0} bestaat al. \nHuidige versie: {1} \nNieuwe versie: {2} \n\nVerder gaan?___Web Archief___Ander netwerk gebruiken___Play Store___op te schonen bestanden resterend___De doel locatie mag geen * \\ \" : / ? | < > bevatten.___Audio/Video___Netwerkwachtwoord___Mijn cloud toevoegen___maanden___Ap Ingeschakeld___Mediabestanden uitsluiten___Huidige locatie___Netwerk opstarten…___Wachtwoord:___Eén-toets verwijderen___Gekopieerd naar \"%1$s\".___Opnamen___Documenten:___ ___Volledige locatie kopiëren___Bestandsanalyse___Instellingen voor meldingen___Netwerkfout, probeer latrr opnieuw.___Geen applicatie om de foto mee te delen.___Alles selecteren___Wachtwoord kan niet leeg zijn.___Netwerk opgestart, ID: " }[paramInt];
}
}
/* Location:
* Qualified Name: com.estrongs.android.pop.esclasses.a.x
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | reverseengineeringer/com.estrongs.android.pop | src/com/estrongs/android/pop/esclasses/a/x.java |
715 | /*
* Argus Open Source
* Software to apply Statistical Disclosure Control techniques
*
* Copyright 2014 Statistics Netherlands
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the European Union Public Licence
* (EUPL) version 1.1, as published by the European Commission.
*
* You can find the text of the EUPL v1.1 on
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
*
* This software is distributed on an "AS IS" basis without
* warranties or conditions of any kind, either express or implied.
*/
package tauargus.model;
import argus.utils.SystemUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import tauargus.extern.dataengine.TauArgus;
import tauargus.gui.DialogLinkedTables;
import tauargus.service.TableService;
import tauargus.utils.ExecUtils;
import tauargus.utils.TauArgusUtils;
/**
*
* @author Hundepool
*/
public class LinkedTables {
public static String[] coverVariablesName;
public static int[] coverVariablesIndex;
public static int[] coverSourceTab;
public static int[] coverVarSize;
public static int[][] toCoverIndex;
public static int coverDim;
static String[][] coverCodelist; static int maxCoverCodeList;
private static int[][] volgNoCL;
private static final String nullen = "00000000";
private static final TauArgus tauArgus = Application.getTauArgusDll();
public static boolean TestLinkedPossible()throws ArgusException{
int i; String respVar0Name;
if( TableService.numberOfTables() < 2)
{throw new ArgusException ("For linked tables at least 2 tables are needed");}
respVar0Name= TableService.getTable(0).respVar.name;
for (i=1;i<TableService.numberOfTables();i++){
if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){
throw new ArgusException ("For linked tables the same respons variable is needed");
}
}
return true;
}
public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{
String hs = ""; int i,j; TableSet tableSet0, tableSet;
Date startDate = new Date();
if (coverDim > 10){
throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10");
}
for (i=0;i<TableService.numberOfTables();i++){
hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); }
SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+
TableService.numberOfTables()+" tables." + hs);
tableSet0 = TableService.getTable(0);
TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt"));
for (i=0;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
j = tableSet.expVar.size();
if (j > 4) {
throw new ArgusException ("The max. dimension of the individual tables must not exceed 4");
}
TableService.undoSuppress(i);
tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck;
tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck;
tableSet.minFreqCheck = tableSet0.minFreqCheck;
tableSet.maxHitasTime = tableSet0.maxHitasTime;
}
checkCodeList(); //checkCodeLists //prepareLinked
exportTables(MSC, LM, UM);//exportTables
//checkHierarchies werd in de oude versie ook niet gedaan.
runCoverTable();
readResultsBack();
Date endDate = new Date();
long diff = endDate.getTime()-startDate.getTime();
diff = diff / 1000;
if ( diff == 0){ diff = 1;}
hs = "";
for (i=0;i<TableService.numberOfTables();i++){
tableSet=TableService.getTable(i);
tableSet.processingTime = (int) diff;
tableSet.linkSuppressed = true;
hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n";
}
SystemUtils.writeLogbook("End of modular linked tables procedure\n"+
TableService.numberOfTables()+" tables.\n" +
hs +
"Processing time: " + diff + " seconds");
return true;
}
static void readResultsBack()throws ArgusException{
// in fact we convert the output into aprory files and run them
int[] codeIndex = new int[coverDim]; int j; TableSet tableSet;
String[] codes = new String[coverDim];
String[] totCodes = new String[coverDim];
String[] regel = new String[1]; Boolean Oke;
if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){
throw new ArgusException("The results of the protection of the cover table could not be found");}
for (int i=0;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
try{
for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;}
//for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;}
for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];}
BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst")));
BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt")));
regel[0] = in.readLine();
while (regel[0] != null){
if (regel[0].endsWith(",12")){ //secondary found
Oke = true;
for (j=0;j<coverDim;j++){
codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ",");
//TODO echte test op Total; dit gaat mis
if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables
}
if (Oke) {
// for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");}
for (j=0;j<tableSet.expVar.size();j++) {
if (codes[toCoverIndex[i][j]].equals("\"Total\"")){
out.write("\"\";");
} else {
out.write (codes[toCoverIndex[i][j]]+ ";");
}}
out.write("ml"); out.newLine();
}
}
regel[0] = in.readLine();
}
in.close();
out.close();
} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );}
}
// Apriory files have been made. Read them back
for (int i=0;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log");
tableSet.solverUsed = Application.solverSelected;
int[][] aPrioryStatus = new int[5][2];
if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){
TableService.undoSuppress(i);
throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1));
} else {
// tableSet.nSecond = NSec[0];
tableSet.suppressed = TableSet.SUP_HITAS;
tableSet.nSecond = aPrioryStatus[1][0];
}
}
}
static void runCoverTable()throws ArgusException{
String appDir;
ArrayList<String> commandline = new ArrayList<>();
//java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb"
//hs = "java -jar \"";
try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); }
catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");}
//hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\"";
commandline.add("java");
commandline.add("-jar");
commandline.add(appDir+"/TauArgus.jar");
commandline.add(Application.getTempFile("tempTot.arb"));
if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";}
commandline.add("/v");
}
TauArgusUtils.writeBatchFileForExec( "TempTot", commandline);
SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure");
int result = ExecUtils.execCommand(commandline, null, false, "Run cover table");
if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);}
}
static void exportTables(double MSC, double LM, double UM)throws ArgusException{
// write intermedaite files fro each table temp+i+.tab
// then merge them into one file tempTot.tab
// Then write the corresponding metadata file
int i, j; TableSet tableSet; String regelOut;
String[] codes = new String[coverDim];String [] regel = new String[1];
for (i=0;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
try{
tableSet.write(Application.getTempFile("temp"+i+".tab"),
false, false, false, false, false, null);}
catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) );
}
}
try{
BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab")));
for (i=0;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab")));
for (j=0;j<coverDim;j++){codes[j] = "\"\"";}
regel[0] = in.readLine();
while (regel[0] != null){
regelOut = "";
for(j=0;j<tableSet.expVar.size();j++){
codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";");
}
for(j=0;j<coverDim;j++){
regelOut = regelOut + codes[j] + ";";
}
regelOut = regelOut + regel[0];
regel[0] = in.readLine();
out.write(regelOut); out.newLine();
} in.close();
} out.close();
// now the RDA file
BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda")));
tableSet = TableService.getTable(0);
rda.write("<SEPARATOR> \";\""); rda.newLine();
for (i=0;i<coverDim;i++){
j=coverSourceTab[i];
BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda")));
regelOut = in.readLine();
// This assumes that the name of a variable does not appear in any text before the definition of the variable
while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();}
rda.write(regelOut); rda.newLine();
regelOut = in.readLine();
while (regelOut.indexOf("<",0) != -1) {
rda.write(regelOut); rda.newLine(); regelOut = in.readLine();
}
in.close();
}
BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda")));
regelOut = in.readLine();
while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();}
while (regelOut != null){
rda.write(regelOut); rda.newLine();
regelOut = in.readLine();
}
in.close();
rda.close();
// and now the batchfile
out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb")));
out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine();
out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine();
out.write("<SPECIFYTABLE> ");
for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");}
String hs = "|\""+tableSet.respVar.name+"\"";
out.write(hs+hs);
if (testDistFunction()){ out.write("|\"-3\"");}
else {out.write(hs);}
out.newLine();
out.write("<SAFETYRULE>"); out.newLine();
out.write("<COVER>"); out.newLine();
out.write("<READTABLE>"); out.newLine();
out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", ");
hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", ");
hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", ");
hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs);
//if (tableSet.maxScaleCost != 20000){
// out.write (", "+tableSet.maxScaleCost);
//}
out.write(", "+ String.valueOf(MSC)); // Always write, even when default
out.write(", " + String.valueOf(LM));
out.write(", " + String.valueOf(UM));
out.write (")"); out.newLine();
out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine();
out.close();
TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt"));
// out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat")));
// out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine();
// out.write ("pause"); out.newLine();
// out.close();
}
catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");}
}
private static boolean testDistFunction(){
int i; boolean b = false; TableSet tableSet;
for (i=0;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
if (tableSet.costFunc == TableSet.COST_DIST){ b = true;}
}
return b;
}
public static boolean runLinkedGHMiter() throws ArgusException{
int i, returnVal;TableSet tableSet0,tableSet; String hs;
Date startDate = new Date();
hs = "";
for (i=0;i<TableService.numberOfTables();i++){
hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); }
SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+
TableService.numberOfTables()+" tables" + hs);
checkCodeList(); //checkCodeLists //prepareLinked
//Write all EINGABEs
for (i=0;i<TableService.numberOfTables();i++){
TableService.undoSuppress(i);
returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false);
if (!(returnVal == 1)) { // Something wrong writing EINGABE
throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));}
}
//copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command
tableSet0 = TableService.getTable(0);
for (i=1;i<TableService.numberOfTables();i++){
tableSet = TableService.getTable(i);
tableSet.ratio = tableSet0.ratio;
tableSet.ghMiterSize = tableSet0.ghMiterSize;
tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton;
tableSet.ghMiterApriory =tableSet0.ghMiterApriory;
tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage;
tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode;
tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable;
}
for (i=0;i<TableService.numberOfTables();i++){
GHMiter.SchrijfSTEUER(i, "AJ"+(i+1));
tableSet=TableService.getTable(i);
GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1));
//adjustEingabe: there was a function Adjusteingabe, but what does it do?
}
GHMiter.CleanGHMiterFiles();
volgNoCL = new int[maxCoverCodeList][coverDim];
for (i=0;i<TableService.numberOfTables();i++){
AdjustEingabe(i);
AdjustSteuer(i);
TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1));
}
if (!Application.isAnco()){
Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir());
Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir());
Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir());
}
GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim);
AppendTabelle();
GHMiter.RunGHMiterEXE();
Date endDate = new Date();
long diff = endDate.getTime()-startDate.getTime();
diff = diff / 1000;
if ( diff == 0){ diff = 1;}
if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){
throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+
"see also file: "+ Application.getTempFile("proto002"));
}
hs = "";
for (i=0;i<TableService.numberOfTables();i++){
tableSet=TableService.getTable(i);
if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){
throw new ArgusException("Unable to read the hypercube results for table "+(i+1));}
tableSet.processingTime = (int) diff;
tableSet.linkSuppressed = true;
hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n";
}
SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+
hs +
(int) diff +" seconds processing time");
return true;
}
static void AppendTabelle()throws ArgusException{
int i, j, k, n; TableSet tableSet; Boolean Oke;
try{
BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true));
n = TableService.numberOfTables();
for(i=0;i<n;i++){
out.write("EINGABE"+(i+1)); out.newLine();
out.write("STEUER"+(i+1)); out.newLine();
out.write("AUSGABE"+(i+1)); out.newLine();
}
// per table list the variables of the cover table not in this table
for(i=0;i<n;i++){
tableSet = TableService.getTable(i);
j = coverDim - tableSet.expVar.size();
out.write(""+j); out.newLine();
for (k=0;k<coverDim;k++){Oke = false;
for (j=0;j<tableSet.expVar.size();j++){
if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;}
}
if (!Oke){
out.write("'"+coverVariablesName[k]+"'"); out.newLine();
out.write("00000000"); out.newLine();
}
}
}
out.close();
}catch (Exception ex){
throw new ArgusException ("An error occurred when appending the file STEUER");}
}
static void AdjustSteuer(int tabNo)throws ArgusException{
int i, j, nc; String hs;
String regelOut; String[] regel = new String[1];
TableSet tableSet=TableService.getTable(tabNo);
int nv = tableSet.expVar.size();
try{
BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1)));
BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1)));
for (i=0;i<6;i++){
regel[0]= in.readLine();
out.write(regel[0]); out.newLine();
}
for (i=0;i<nv;i++){
regel[0]= in.readLine();
out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine();
regel[0] = in.readLine();
out.write(regel[0]); out.newLine();
j = tableSet.expVar.get(i).index;
nc = TauArgusUtils.getNumberOfActiveCodes(j);
while (nc>0){
regel[0]= in.readLine();
regelOut = "";
while (!regel[0].equals("")){
hs = TauArgusUtils.GetSimpleToken(regel);
j = Integer.parseInt(hs);
regelOut = regelOut + plusNul(volgNoCL[j][i])+" ";
nc=nc-1;}
out.write(regelOut); out.newLine();
}
}
hs = in.readLine();
while (!(hs == null)){
out.write(hs); out.newLine();
hs = in.readLine();
}
in.close();
out.close();
}
catch (Exception ex){
throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+
" for linked tables");}
}
static void AdjustEingabe(int tabNo)throws ArgusException{
String[] regel = new String[1]; String regelOut, hs;
int i, j, k, c;
// replace the codes in EINGABE to correspond with the cover table
TableSet tableSet=TableService.getTable(tabNo);
int nc = tableSet.expVar.size();
String[] codes = new String[nc]; String[] volgno = new String[nc];
try{
BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1)));
BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1)));
regel[0] = in.readLine();
while (!(regel[0] == null)){
regel[0] = regel[0].trim();
regelOut = "";
for (i=0;i<7;i++){
hs = TauArgusUtils.GetSimpleToken(regel);
regelOut = regelOut + hs + " ";}
// regel[0] = regel[0].replace("'", "");
for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel);
volgno[i] = volgno[i].replace("'", "");}
for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel);
codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();}
for (i=0;i<nc;i++){
k=toCoverIndex[tabNo][i];
c=-1;
for (j=0;j<coverVarSize[k];j++){
if (codes[i].equals("")){c=0;}
else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;}
}
}
if (c==-1) {throw new ArgusException("An error occurred ");}
j = Integer.parseInt(volgno[i]);
volgNoCL[j][i] = c;
regelOut = regelOut + "'" + plusNul(c) + "' ";
}
for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";}
out.write(regelOut); out.newLine();
regel[0] = in.readLine();
}
in.close();
out.close();
}
catch (Exception ex){
throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+
" for linked tables");}
}
static String plusNul(int c){
String hs; int l;
hs = "" + c;
l = 8-hs.length();
hs = nullen.substring(0,l)+hs;
return hs;
}
static void checkCodeList()throws ArgusException{
int i, j, k, vi, nt; TableSet tableSet;
String hs, xs; Boolean found;
//Make a list of all the codes in the cover table.
//this will be used later for checking (modular) and futher processing in GHMiter.
maxCoverCodeList = 0;
nt = TableService.numberOfTables();
for (i=0;i<nt;i++){ // all tables
tableSet=TableService.getTable(i);
for (j=0;j<tableSet.expVar.size();j++){
k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index);
if (maxCoverCodeList < k) {maxCoverCodeList = k;}
}
}
coverCodelist = new String[coverDim][maxCoverCodeList];
for (i=0;i<coverDim;i++){
for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){
coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j);
}
coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode();
}
//The actual checking
for (i=0;i<nt;i++){ // all tables
tableSet=TableService.getTable(i);
for (j=0;j<tableSet.expVar.size();j++){ //all expVars
vi=tableSet.expVar.get(j).index;
for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){
hs = TauArgusUtils.getCode(vi, k);
int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]];
found = false;
while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){
xs = TauArgusUtils.getCode(cv,l);
if (xs.equals(hs)){ found = true; break;}
l++;
}
if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+
"cover var "+coverVariablesName[cv]+"\n"+
"base table "+String.valueOf(i+1));}
}
}
}
}
public static boolean buildCoverTable(){
TableSet tableSet; String hs; int found, i, j, k;
coverVariablesName = new String[10];
coverVariablesIndex = new int[10];
coverSourceTab = new int[10];
coverVarSize = new int[10];
coverDim = 0;
int n = TableService.numberOfTables();
toCoverIndex = new int [n][TableSet.MAX_RESP_VAR];
for (i=0;i<n;i++){
tableSet = TableService.getTable(i);
for (j=0;j<tableSet.expVar.size();j++){
hs = tableSet.expVar.get(j).name;
found = -1;
for (k=0;k<coverDim;k++){
if (coverVariablesName[k].equals(hs)){found = k;}
}
if (found == -1) { coverDim++;
coverVariablesName[coverDim-1] = hs;
coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index;
coverSourceTab[coverDim-1] = i;
coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index);
found = coverDim-1;
} else {
k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index);
if (coverVarSize[found]<k){
coverVarSize[found]=k;
coverSourceTab[found] = i;
coverVariablesIndex[found] = tableSet.expVar.get(j).index;
}
}
toCoverIndex[i][j] = found;
}
}
return true;
}
}
| sdcTools/tauargus | src/tauargus/model/LinkedTables.java |
716 | /**
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.identitydomains.model;
/**
* The Group resource. <br>
* Note: Objects should always be created or deserialized using the {@link Builder}. This model
* distinguishes fields that are {@code null} because they are unset from fields that are explicitly
* set to {@code null}. This is done in the setter methods of the {@link Builder}, which maintain a
* set of all explicitly set fields called {@link Builder#__explicitlySet__}. The {@link
* #hashCode()} and {@link #equals(Object)} methods are implemented to take the explicitly set
* fields into account. The constructor, on the other hand, does not take the explicitly set fields
* into account (since the constructor cannot distinguish explicit {@code null} from unset {@code
* null}).
*/
@jakarta.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: v1")
@com.fasterxml.jackson.databind.annotation.JsonDeserialize(builder = MyGroup.Builder.class)
@com.fasterxml.jackson.annotation.JsonFilter(
com.oracle.bmc.http.client.internal.ExplicitlySetBmcModel.EXPLICITLY_SET_FILTER_NAME)
public final class MyGroup extends com.oracle.bmc.http.client.internal.ExplicitlySetBmcModel {
@Deprecated
@java.beans.ConstructorProperties({
"id",
"ocid",
"schemas",
"meta",
"idcsCreatedBy",
"idcsLastModifiedBy",
"idcsPreventedOperations",
"tags",
"deleteInProgress",
"idcsLastUpgradedInRelease",
"domainOcid",
"compartmentOcid",
"tenancyOcid",
"externalId",
"displayName",
"nonUniqueDisplayName",
"members",
"urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup",
"urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup"
})
public MyGroup(
String id,
String ocid,
java.util.List<String> schemas,
Meta meta,
IdcsCreatedBy idcsCreatedBy,
IdcsLastModifiedBy idcsLastModifiedBy,
java.util.List<IdcsPreventedOperations> idcsPreventedOperations,
java.util.List<Tags> tags,
Boolean deleteInProgress,
String idcsLastUpgradedInRelease,
String domainOcid,
String compartmentOcid,
String tenancyOcid,
String externalId,
String displayName,
String nonUniqueDisplayName,
java.util.List<MyGroupMembers> members,
ExtensionGroupGroup urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup,
ExtensionPosixGroup urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup) {
super();
this.id = id;
this.ocid = ocid;
this.schemas = schemas;
this.meta = meta;
this.idcsCreatedBy = idcsCreatedBy;
this.idcsLastModifiedBy = idcsLastModifiedBy;
this.idcsPreventedOperations = idcsPreventedOperations;
this.tags = tags;
this.deleteInProgress = deleteInProgress;
this.idcsLastUpgradedInRelease = idcsLastUpgradedInRelease;
this.domainOcid = domainOcid;
this.compartmentOcid = compartmentOcid;
this.tenancyOcid = tenancyOcid;
this.externalId = externalId;
this.displayName = displayName;
this.nonUniqueDisplayName = nonUniqueDisplayName;
this.members = members;
this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup =
urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup;
this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup =
urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup;
}
@com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "")
public static class Builder {
/**
* Unique identifier for the SCIM Resource as defined by the Service Provider. Each
* representation of the Resource MUST include a non-empty id value. This identifier MUST be
* unique across the Service Provider's entire set of Resources. It MUST be a stable,
* non-reassignable identifier that does not change when the same Resource is returned in
* subsequent requests. The value of the id attribute is always issued by the Service
* Provider and MUST never be specified by the Service Consumer. bulkId: is a reserved
* keyword and MUST NOT be used in the unique identifier.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: always - type: string - uniqueness:
* global
*/
@com.fasterxml.jackson.annotation.JsonProperty("id")
private String id;
/**
* Unique identifier for the SCIM Resource as defined by the Service Provider. Each
* representation of the Resource MUST include a non-empty id value. This identifier MUST be
* unique across the Service Provider's entire set of Resources. It MUST be a stable,
* non-reassignable identifier that does not change when the same Resource is returned in
* subsequent requests. The value of the id attribute is always issued by the Service
* Provider and MUST never be specified by the Service Consumer. bulkId: is a reserved
* keyword and MUST NOT be used in the unique identifier.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: always - type: string - uniqueness:
* global
*
* @param id the value to set
* @return this builder
*/
public Builder id(String id) {
this.id = id;
this.__explicitlySet__.add("id");
return this;
}
/**
* Unique OCI identifier for the SCIM Resource.
*
* <p>*SCIM++ Properties:** - caseExact: true - idcsSearchable: true - multiValued: false -
* mutability: immutable - required: false - returned: default - type: string - uniqueness:
* global
*/
@com.fasterxml.jackson.annotation.JsonProperty("ocid")
private String ocid;
/**
* Unique OCI identifier for the SCIM Resource.
*
* <p>*SCIM++ Properties:** - caseExact: true - idcsSearchable: true - multiValued: false -
* mutability: immutable - required: false - returned: default - type: string - uniqueness:
* global
*
* @param ocid the value to set
* @return this builder
*/
public Builder ocid(String ocid) {
this.ocid = ocid;
this.__explicitlySet__.add("ocid");
return this;
}
/**
* REQUIRED. The schemas attribute is an array of Strings which allows introspection of the
* supported schema version for a SCIM representation as well any schema extensions
* supported by that representation. Each String value must be a unique URI. This
* specification defines URIs for User, Group, and a standard \\"enterprise\\" extension.
* All representations of SCIM schema MUST include a non-zero value array with value(s) of
* the URIs supported by that representation. Duplicate values MUST NOT be included. Value
* order is not specified and MUST not impact behavior.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: true -
* mutability: readWrite - required: true - returned: default - type: string - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("schemas")
private java.util.List<String> schemas;
/**
* REQUIRED. The schemas attribute is an array of Strings which allows introspection of the
* supported schema version for a SCIM representation as well any schema extensions
* supported by that representation. Each String value must be a unique URI. This
* specification defines URIs for User, Group, and a standard \\"enterprise\\" extension.
* All representations of SCIM schema MUST include a non-zero value array with value(s) of
* the URIs supported by that representation. Duplicate values MUST NOT be included. Value
* order is not specified and MUST not impact behavior.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: true -
* mutability: readWrite - required: true - returned: default - type: string - uniqueness:
* none
*
* @param schemas the value to set
* @return this builder
*/
public Builder schemas(java.util.List<String> schemas) {
this.schemas = schemas;
this.__explicitlySet__.add("schemas");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("meta")
private Meta meta;
public Builder meta(Meta meta) {
this.meta = meta;
this.__explicitlySet__.add("meta");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("idcsCreatedBy")
private IdcsCreatedBy idcsCreatedBy;
public Builder idcsCreatedBy(IdcsCreatedBy idcsCreatedBy) {
this.idcsCreatedBy = idcsCreatedBy;
this.__explicitlySet__.add("idcsCreatedBy");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("idcsLastModifiedBy")
private IdcsLastModifiedBy idcsLastModifiedBy;
public Builder idcsLastModifiedBy(IdcsLastModifiedBy idcsLastModifiedBy) {
this.idcsLastModifiedBy = idcsLastModifiedBy;
this.__explicitlySet__.add("idcsLastModifiedBy");
return this;
}
/**
* Each value of this attribute specifies an operation that only an internal client may
* perform on this particular resource.
*
* <p>*SCIM++ Properties:** - idcsSearchable: false - multiValued: true - mutability:
* readOnly - required: false - returned: request - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("idcsPreventedOperations")
private java.util.List<IdcsPreventedOperations> idcsPreventedOperations;
/**
* Each value of this attribute specifies an operation that only an internal client may
* perform on this particular resource.
*
* <p>*SCIM++ Properties:** - idcsSearchable: false - multiValued: true - mutability:
* readOnly - required: false - returned: request - type: string - uniqueness: none
*
* @param idcsPreventedOperations the value to set
* @return this builder
*/
public Builder idcsPreventedOperations(
java.util.List<IdcsPreventedOperations> idcsPreventedOperations) {
this.idcsPreventedOperations = idcsPreventedOperations;
this.__explicitlySet__.add("idcsPreventedOperations");
return this;
}
/**
* A list of tags on this resource.
*
* <p>*SCIM++ Properties:** - idcsCompositeKey: [key, value] - idcsSearchable: true -
* multiValued: true - mutability: readWrite - required: false - returned: request - type:
* complex - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("tags")
private java.util.List<Tags> tags;
/**
* A list of tags on this resource.
*
* <p>*SCIM++ Properties:** - idcsCompositeKey: [key, value] - idcsSearchable: true -
* multiValued: true - mutability: readWrite - required: false - returned: request - type:
* complex - uniqueness: none
*
* @param tags the value to set
* @return this builder
*/
public Builder tags(java.util.List<Tags> tags) {
this.tags = tags;
this.__explicitlySet__.add("tags");
return this;
}
/**
* A boolean flag indicating this resource in the process of being deleted. Usually set to
* true when synchronous deletion of the resource would take too long.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: boolean - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("deleteInProgress")
private Boolean deleteInProgress;
/**
* A boolean flag indicating this resource in the process of being deleted. Usually set to
* true when synchronous deletion of the resource would take too long.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: boolean - uniqueness:
* none
*
* @param deleteInProgress the value to set
* @return this builder
*/
public Builder deleteInProgress(Boolean deleteInProgress) {
this.deleteInProgress = deleteInProgress;
this.__explicitlySet__.add("deleteInProgress");
return this;
}
/**
* The release number when the resource was upgraded.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: request - type: string - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("idcsLastUpgradedInRelease")
private String idcsLastUpgradedInRelease;
/**
* The release number when the resource was upgraded.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: request - type: string - uniqueness:
* none
*
* @param idcsLastUpgradedInRelease the value to set
* @return this builder
*/
public Builder idcsLastUpgradedInRelease(String idcsLastUpgradedInRelease) {
this.idcsLastUpgradedInRelease = idcsLastUpgradedInRelease;
this.__explicitlySet__.add("idcsLastUpgradedInRelease");
return this;
}
/**
* OCI Domain Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: default - type: string - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("domainOcid")
private String domainOcid;
/**
* OCI Domain Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: default - type: string - uniqueness:
* none
*
* @param domainOcid the value to set
* @return this builder
*/
public Builder domainOcid(String domainOcid) {
this.domainOcid = domainOcid;
this.__explicitlySet__.add("domainOcid");
return this;
}
/**
* OCI Compartment Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: default - type: string - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("compartmentOcid")
private String compartmentOcid;
/**
* OCI Compartment Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: default - type: string - uniqueness:
* none
*
* @param compartmentOcid the value to set
* @return this builder
*/
public Builder compartmentOcid(String compartmentOcid) {
this.compartmentOcid = compartmentOcid;
this.__explicitlySet__.add("compartmentOcid");
return this;
}
/**
* OCI Tenant Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: default - type: string - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("tenancyOcid")
private String tenancyOcid;
/**
* OCI Tenant Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false
* - mutability: readOnly - required: false - returned: default - type: string - uniqueness:
* none
*
* @param tenancyOcid the value to set
* @return this builder
*/
public Builder tenancyOcid(String tenancyOcid) {
this.tenancyOcid = tenancyOcid;
this.__explicitlySet__.add("tenancyOcid");
return this;
}
/**
* An identifier for the Resource as defined by the Service Consumer. The externalId may
* simplify identification of the Resource between Service Consumer and Service Provider by
* allowing the Consumer to refer to the Resource with its own identifier, obviating the
* need to store a local mapping between the local identifier of the Resource and the
* identifier used by the Service Provider. Each Resource MAY include a non-empty externalId
* value. The value of the externalId attribute is always issued by the Service Consumer and
* can never be specified by the Service Provider. The Service Provider MUST always
* interpret the externalId as scoped to the Service Consumer's tenant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readWrite - required: false - returned: default - type: string - uniqueness:
* none
*/
@com.fasterxml.jackson.annotation.JsonProperty("externalId")
private String externalId;
/**
* An identifier for the Resource as defined by the Service Consumer. The externalId may
* simplify identification of the Resource between Service Consumer and Service Provider by
* allowing the Consumer to refer to the Resource with its own identifier, obviating the
* need to store a local mapping between the local identifier of the Resource and the
* identifier used by the Service Provider. Each Resource MAY include a non-empty externalId
* value. The value of the externalId attribute is always issued by the Service Consumer and
* can never be specified by the Service Provider. The Service Provider MUST always
* interpret the externalId as scoped to the Service Consumer's tenant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readWrite - required: false - returned: default - type: string - uniqueness:
* none
*
* @param externalId the value to set
* @return this builder
*/
public Builder externalId(String externalId) {
this.externalId = externalId;
this.__explicitlySet__.add("externalId");
return this;
}
/**
* The Group display name.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Display Name -
* idcsCsvAttributeNameMappings: [[columnHeaderName:Name, deprecatedColumnHeaderName:Display
* Name]] - idcsSearchable: true - multiValued: false - mutability: readWrite - required:
* true - returned: always - type: string - uniqueness: global
*/
@com.fasterxml.jackson.annotation.JsonProperty("displayName")
private String displayName;
/**
* The Group display name.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Display Name -
* idcsCsvAttributeNameMappings: [[columnHeaderName:Name, deprecatedColumnHeaderName:Display
* Name]] - idcsSearchable: true - multiValued: false - mutability: readWrite - required:
* true - returned: always - type: string - uniqueness: global
*
* @param displayName the value to set
* @return this builder
*/
public Builder displayName(String displayName) {
this.displayName = displayName;
this.__explicitlySet__.add("displayName");
return this;
}
/**
* A human readable name for the group as defined by the Service Consumer.
*
* <p>*Added In:** 2011192329
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Non-Unique Display
* Name - idcsSearchable: true - multiValued: false - mutability: readWrite - required:
* false - returned: always - type: string
*/
@com.fasterxml.jackson.annotation.JsonProperty("nonUniqueDisplayName")
private String nonUniqueDisplayName;
/**
* A human readable name for the group as defined by the Service Consumer.
*
* <p>*Added In:** 2011192329
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Non-Unique Display
* Name - idcsSearchable: true - multiValued: false - mutability: readWrite - required:
* false - returned: always - type: string
*
* @param nonUniqueDisplayName the value to set
* @return this builder
*/
public Builder nonUniqueDisplayName(String nonUniqueDisplayName) {
this.nonUniqueDisplayName = nonUniqueDisplayName;
this.__explicitlySet__.add("nonUniqueDisplayName");
return this;
}
/**
* The group members. <b>Important:</b> When requesting group members, a maximum of 10,000
* members can be returned in a single request. If the response contains more than 10,000
* members, the request will fail. Use 'startIndex' and 'count' to return members in pages
* instead of in a single response, for example:
* #attributes=members[startIndex=1%26count=10]. This REST API is SCIM compliant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCompositeKey: [value] -
* idcsCsvAttributeNameMappings: [[columnHeaderName:User Members,
* mapsTo:members[User].value, multiValueDelimiter:;]] - idcsSearchable: true - multiValued:
* true - mutability: readWrite - required: false - returned: request -
* idcsPaginateResponse: true - type: complex - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("members")
private java.util.List<MyGroupMembers> members;
/**
* The group members. <b>Important:</b> When requesting group members, a maximum of 10,000
* members can be returned in a single request. If the response contains more than 10,000
* members, the request will fail. Use 'startIndex' and 'count' to return members in pages
* instead of in a single response, for example:
* #attributes=members[startIndex=1%26count=10]. This REST API is SCIM compliant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCompositeKey: [value] -
* idcsCsvAttributeNameMappings: [[columnHeaderName:User Members,
* mapsTo:members[User].value, multiValueDelimiter:;]] - idcsSearchable: true - multiValued:
* true - mutability: readWrite - required: false - returned: request -
* idcsPaginateResponse: true - type: complex - uniqueness: none
*
* @param members the value to set
* @return this builder
*/
public Builder members(java.util.List<MyGroupMembers> members) {
this.members = members;
this.__explicitlySet__.add("members");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty(
"urn:ietf:params:scim:schemas:oracle:idcs:extension:group:Group")
private ExtensionGroupGroup urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup;
public Builder urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup(
ExtensionGroupGroup urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup) {
this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup =
urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup;
this.__explicitlySet__.add("urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty(
"urn:ietf:params:scim:schemas:oracle:idcs:extension:posix:Group")
private ExtensionPosixGroup urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup;
public Builder urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup(
ExtensionPosixGroup urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup) {
this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup =
urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup;
this.__explicitlySet__.add("urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup");
return this;
}
@com.fasterxml.jackson.annotation.JsonIgnore
private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>();
public MyGroup build() {
MyGroup model =
new MyGroup(
this.id,
this.ocid,
this.schemas,
this.meta,
this.idcsCreatedBy,
this.idcsLastModifiedBy,
this.idcsPreventedOperations,
this.tags,
this.deleteInProgress,
this.idcsLastUpgradedInRelease,
this.domainOcid,
this.compartmentOcid,
this.tenancyOcid,
this.externalId,
this.displayName,
this.nonUniqueDisplayName,
this.members,
this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup,
this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup);
for (String explicitlySetProperty : this.__explicitlySet__) {
model.markPropertyAsExplicitlySet(explicitlySetProperty);
}
return model;
}
@com.fasterxml.jackson.annotation.JsonIgnore
public Builder copy(MyGroup model) {
if (model.wasPropertyExplicitlySet("id")) {
this.id(model.getId());
}
if (model.wasPropertyExplicitlySet("ocid")) {
this.ocid(model.getOcid());
}
if (model.wasPropertyExplicitlySet("schemas")) {
this.schemas(model.getSchemas());
}
if (model.wasPropertyExplicitlySet("meta")) {
this.meta(model.getMeta());
}
if (model.wasPropertyExplicitlySet("idcsCreatedBy")) {
this.idcsCreatedBy(model.getIdcsCreatedBy());
}
if (model.wasPropertyExplicitlySet("idcsLastModifiedBy")) {
this.idcsLastModifiedBy(model.getIdcsLastModifiedBy());
}
if (model.wasPropertyExplicitlySet("idcsPreventedOperations")) {
this.idcsPreventedOperations(model.getIdcsPreventedOperations());
}
if (model.wasPropertyExplicitlySet("tags")) {
this.tags(model.getTags());
}
if (model.wasPropertyExplicitlySet("deleteInProgress")) {
this.deleteInProgress(model.getDeleteInProgress());
}
if (model.wasPropertyExplicitlySet("idcsLastUpgradedInRelease")) {
this.idcsLastUpgradedInRelease(model.getIdcsLastUpgradedInRelease());
}
if (model.wasPropertyExplicitlySet("domainOcid")) {
this.domainOcid(model.getDomainOcid());
}
if (model.wasPropertyExplicitlySet("compartmentOcid")) {
this.compartmentOcid(model.getCompartmentOcid());
}
if (model.wasPropertyExplicitlySet("tenancyOcid")) {
this.tenancyOcid(model.getTenancyOcid());
}
if (model.wasPropertyExplicitlySet("externalId")) {
this.externalId(model.getExternalId());
}
if (model.wasPropertyExplicitlySet("displayName")) {
this.displayName(model.getDisplayName());
}
if (model.wasPropertyExplicitlySet("nonUniqueDisplayName")) {
this.nonUniqueDisplayName(model.getNonUniqueDisplayName());
}
if (model.wasPropertyExplicitlySet("members")) {
this.members(model.getMembers());
}
if (model.wasPropertyExplicitlySet(
"urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup")) {
this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup(
model.getUrnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup());
}
if (model.wasPropertyExplicitlySet(
"urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup")) {
this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup(
model.getUrnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup());
}
return this;
}
}
/** Create a new builder. */
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder().copy(this);
}
/**
* Unique identifier for the SCIM Resource as defined by the Service Provider. Each
* representation of the Resource MUST include a non-empty id value. This identifier MUST be
* unique across the Service Provider's entire set of Resources. It MUST be a stable,
* non-reassignable identifier that does not change when the same Resource is returned in
* subsequent requests. The value of the id attribute is always issued by the Service Provider
* and MUST never be specified by the Service Consumer. bulkId: is a reserved keyword and MUST
* NOT be used in the unique identifier.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: always - type: string - uniqueness: global
*/
@com.fasterxml.jackson.annotation.JsonProperty("id")
private final String id;
/**
* Unique identifier for the SCIM Resource as defined by the Service Provider. Each
* representation of the Resource MUST include a non-empty id value. This identifier MUST be
* unique across the Service Provider's entire set of Resources. It MUST be a stable,
* non-reassignable identifier that does not change when the same Resource is returned in
* subsequent requests. The value of the id attribute is always issued by the Service Provider
* and MUST never be specified by the Service Consumer. bulkId: is a reserved keyword and MUST
* NOT be used in the unique identifier.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: always - type: string - uniqueness: global
*
* @return the value
*/
public String getId() {
return id;
}
/**
* Unique OCI identifier for the SCIM Resource.
*
* <p>*SCIM++ Properties:** - caseExact: true - idcsSearchable: true - multiValued: false -
* mutability: immutable - required: false - returned: default - type: string - uniqueness:
* global
*/
@com.fasterxml.jackson.annotation.JsonProperty("ocid")
private final String ocid;
/**
* Unique OCI identifier for the SCIM Resource.
*
* <p>*SCIM++ Properties:** - caseExact: true - idcsSearchable: true - multiValued: false -
* mutability: immutable - required: false - returned: default - type: string - uniqueness:
* global
*
* @return the value
*/
public String getOcid() {
return ocid;
}
/**
* REQUIRED. The schemas attribute is an array of Strings which allows introspection of the
* supported schema version for a SCIM representation as well any schema extensions supported by
* that representation. Each String value must be a unique URI. This specification defines URIs
* for User, Group, and a standard \\"enterprise\\" extension. All representations of SCIM
* schema MUST include a non-zero value array with value(s) of the URIs supported by that
* representation. Duplicate values MUST NOT be included. Value order is not specified and MUST
* not impact behavior.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: true -
* mutability: readWrite - required: true - returned: default - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("schemas")
private final java.util.List<String> schemas;
/**
* REQUIRED. The schemas attribute is an array of Strings which allows introspection of the
* supported schema version for a SCIM representation as well any schema extensions supported by
* that representation. Each String value must be a unique URI. This specification defines URIs
* for User, Group, and a standard \\"enterprise\\" extension. All representations of SCIM
* schema MUST include a non-zero value array with value(s) of the URIs supported by that
* representation. Duplicate values MUST NOT be included. Value order is not specified and MUST
* not impact behavior.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: true -
* mutability: readWrite - required: true - returned: default - type: string - uniqueness: none
*
* @return the value
*/
public java.util.List<String> getSchemas() {
return schemas;
}
@com.fasterxml.jackson.annotation.JsonProperty("meta")
private final Meta meta;
public Meta getMeta() {
return meta;
}
@com.fasterxml.jackson.annotation.JsonProperty("idcsCreatedBy")
private final IdcsCreatedBy idcsCreatedBy;
public IdcsCreatedBy getIdcsCreatedBy() {
return idcsCreatedBy;
}
@com.fasterxml.jackson.annotation.JsonProperty("idcsLastModifiedBy")
private final IdcsLastModifiedBy idcsLastModifiedBy;
public IdcsLastModifiedBy getIdcsLastModifiedBy() {
return idcsLastModifiedBy;
}
/**
* Each value of this attribute specifies an operation that only an internal client may perform
* on this particular resource.
*
* <p>*SCIM++ Properties:** - idcsSearchable: false - multiValued: true - mutability: readOnly -
* required: false - returned: request - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("idcsPreventedOperations")
private final java.util.List<IdcsPreventedOperations> idcsPreventedOperations;
/**
* Each value of this attribute specifies an operation that only an internal client may perform
* on this particular resource.
*
* <p>*SCIM++ Properties:** - idcsSearchable: false - multiValued: true - mutability: readOnly -
* required: false - returned: request - type: string - uniqueness: none
*
* @return the value
*/
public java.util.List<IdcsPreventedOperations> getIdcsPreventedOperations() {
return idcsPreventedOperations;
}
/**
* A list of tags on this resource.
*
* <p>*SCIM++ Properties:** - idcsCompositeKey: [key, value] - idcsSearchable: true -
* multiValued: true - mutability: readWrite - required: false - returned: request - type:
* complex - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("tags")
private final java.util.List<Tags> tags;
/**
* A list of tags on this resource.
*
* <p>*SCIM++ Properties:** - idcsCompositeKey: [key, value] - idcsSearchable: true -
* multiValued: true - mutability: readWrite - required: false - returned: request - type:
* complex - uniqueness: none
*
* @return the value
*/
public java.util.List<Tags> getTags() {
return tags;
}
/**
* A boolean flag indicating this resource in the process of being deleted. Usually set to true
* when synchronous deletion of the resource would take too long.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: boolean - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("deleteInProgress")
private final Boolean deleteInProgress;
/**
* A boolean flag indicating this resource in the process of being deleted. Usually set to true
* when synchronous deletion of the resource would take too long.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: boolean - uniqueness: none
*
* @return the value
*/
public Boolean getDeleteInProgress() {
return deleteInProgress;
}
/**
* The release number when the resource was upgraded.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: request - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("idcsLastUpgradedInRelease")
private final String idcsLastUpgradedInRelease;
/**
* The release number when the resource was upgraded.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: request - type: string - uniqueness: none
*
* @return the value
*/
public String getIdcsLastUpgradedInRelease() {
return idcsLastUpgradedInRelease;
}
/**
* OCI Domain Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("domainOcid")
private final String domainOcid;
/**
* OCI Domain Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: string - uniqueness: none
*
* @return the value
*/
public String getDomainOcid() {
return domainOcid;
}
/**
* OCI Compartment Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("compartmentOcid")
private final String compartmentOcid;
/**
* OCI Compartment Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: string - uniqueness: none
*
* @return the value
*/
public String getCompartmentOcid() {
return compartmentOcid;
}
/**
* OCI Tenant Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("tenancyOcid")
private final String tenancyOcid;
/**
* OCI Tenant Id (ocid) in which the resource lives.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: false - multiValued: false -
* mutability: readOnly - required: false - returned: default - type: string - uniqueness: none
*
* @return the value
*/
public String getTenancyOcid() {
return tenancyOcid;
}
/**
* An identifier for the Resource as defined by the Service Consumer. The externalId may
* simplify identification of the Resource between Service Consumer and Service Provider by
* allowing the Consumer to refer to the Resource with its own identifier, obviating the need to
* store a local mapping between the local identifier of the Resource and the identifier used by
* the Service Provider. Each Resource MAY include a non-empty externalId value. The value of
* the externalId attribute is always issued by the Service Consumer and can never be specified
* by the Service Provider. The Service Provider MUST always interpret the externalId as scoped
* to the Service Consumer's tenant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readWrite - required: false - returned: default - type: string - uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("externalId")
private final String externalId;
/**
* An identifier for the Resource as defined by the Service Consumer. The externalId may
* simplify identification of the Resource between Service Consumer and Service Provider by
* allowing the Consumer to refer to the Resource with its own identifier, obviating the need to
* store a local mapping between the local identifier of the Resource and the identifier used by
* the Service Provider. Each Resource MAY include a non-empty externalId value. The value of
* the externalId attribute is always issued by the Service Consumer and can never be specified
* by the Service Provider. The Service Provider MUST always interpret the externalId as scoped
* to the Service Consumer's tenant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsSearchable: true - multiValued: false -
* mutability: readWrite - required: false - returned: default - type: string - uniqueness: none
*
* @return the value
*/
public String getExternalId() {
return externalId;
}
/**
* The Group display name.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Display Name -
* idcsCsvAttributeNameMappings: [[columnHeaderName:Name, deprecatedColumnHeaderName:Display
* Name]] - idcsSearchable: true - multiValued: false - mutability: readWrite - required: true -
* returned: always - type: string - uniqueness: global
*/
@com.fasterxml.jackson.annotation.JsonProperty("displayName")
private final String displayName;
/**
* The Group display name.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Display Name -
* idcsCsvAttributeNameMappings: [[columnHeaderName:Name, deprecatedColumnHeaderName:Display
* Name]] - idcsSearchable: true - multiValued: false - mutability: readWrite - required: true -
* returned: always - type: string - uniqueness: global
*
* @return the value
*/
public String getDisplayName() {
return displayName;
}
/**
* A human readable name for the group as defined by the Service Consumer.
*
* <p>*Added In:** 2011192329
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Non-Unique Display Name -
* idcsSearchable: true - multiValued: false - mutability: readWrite - required: false -
* returned: always - type: string
*/
@com.fasterxml.jackson.annotation.JsonProperty("nonUniqueDisplayName")
private final String nonUniqueDisplayName;
/**
* A human readable name for the group as defined by the Service Consumer.
*
* <p>*Added In:** 2011192329
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCsvAttributeName: Non-Unique Display Name -
* idcsSearchable: true - multiValued: false - mutability: readWrite - required: false -
* returned: always - type: string
*
* @return the value
*/
public String getNonUniqueDisplayName() {
return nonUniqueDisplayName;
}
/**
* The group members. <b>Important:</b> When requesting group members, a maximum of 10,000
* members can be returned in a single request. If the response contains more than 10,000
* members, the request will fail. Use 'startIndex' and 'count' to return members in pages
* instead of in a single response, for example: #attributes=members[startIndex=1%26count=10].
* This REST API is SCIM compliant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCompositeKey: [value] -
* idcsCsvAttributeNameMappings: [[columnHeaderName:User Members, mapsTo:members[User].value,
* multiValueDelimiter:;]] - idcsSearchable: true - multiValued: true - mutability: readWrite -
* required: false - returned: request - idcsPaginateResponse: true - type: complex -
* uniqueness: none
*/
@com.fasterxml.jackson.annotation.JsonProperty("members")
private final java.util.List<MyGroupMembers> members;
/**
* The group members. <b>Important:</b> When requesting group members, a maximum of 10,000
* members can be returned in a single request. If the response contains more than 10,000
* members, the request will fail. Use 'startIndex' and 'count' to return members in pages
* instead of in a single response, for example: #attributes=members[startIndex=1%26count=10].
* This REST API is SCIM compliant.
*
* <p>*SCIM++ Properties:** - caseExact: false - idcsCompositeKey: [value] -
* idcsCsvAttributeNameMappings: [[columnHeaderName:User Members, mapsTo:members[User].value,
* multiValueDelimiter:;]] - idcsSearchable: true - multiValued: true - mutability: readWrite -
* required: false - returned: request - idcsPaginateResponse: true - type: complex -
* uniqueness: none
*
* @return the value
*/
public java.util.List<MyGroupMembers> getMembers() {
return members;
}
@com.fasterxml.jackson.annotation.JsonProperty(
"urn:ietf:params:scim:schemas:oracle:idcs:extension:group:Group")
private final ExtensionGroupGroup urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup;
public ExtensionGroupGroup getUrnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup() {
return urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup;
}
@com.fasterxml.jackson.annotation.JsonProperty(
"urn:ietf:params:scim:schemas:oracle:idcs:extension:posix:Group")
private final ExtensionPosixGroup urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup;
public ExtensionPosixGroup getUrnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup() {
return urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup;
}
@Override
public String toString() {
return this.toString(true);
}
/**
* Return a string representation of the object.
*
* @param includeByteArrayContents true to include the full contents of byte arrays
* @return string representation
*/
public String toString(boolean includeByteArrayContents) {
java.lang.StringBuilder sb = new java.lang.StringBuilder();
sb.append("MyGroup(");
sb.append("super=").append(super.toString());
sb.append("id=").append(String.valueOf(this.id));
sb.append(", ocid=").append(String.valueOf(this.ocid));
sb.append(", schemas=").append(String.valueOf(this.schemas));
sb.append(", meta=").append(String.valueOf(this.meta));
sb.append(", idcsCreatedBy=").append(String.valueOf(this.idcsCreatedBy));
sb.append(", idcsLastModifiedBy=").append(String.valueOf(this.idcsLastModifiedBy));
sb.append(", idcsPreventedOperations=")
.append(String.valueOf(this.idcsPreventedOperations));
sb.append(", tags=").append(String.valueOf(this.tags));
sb.append(", deleteInProgress=").append(String.valueOf(this.deleteInProgress));
sb.append(", idcsLastUpgradedInRelease=")
.append(String.valueOf(this.idcsLastUpgradedInRelease));
sb.append(", domainOcid=").append(String.valueOf(this.domainOcid));
sb.append(", compartmentOcid=").append(String.valueOf(this.compartmentOcid));
sb.append(", tenancyOcid=").append(String.valueOf(this.tenancyOcid));
sb.append(", externalId=").append(String.valueOf(this.externalId));
sb.append(", displayName=").append(String.valueOf(this.displayName));
sb.append(", nonUniqueDisplayName=").append(String.valueOf(this.nonUniqueDisplayName));
sb.append(", members=").append(String.valueOf(this.members));
sb.append(", urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup=")
.append(String.valueOf(this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup));
sb.append(", urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup=")
.append(String.valueOf(this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup));
sb.append(")");
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof MyGroup)) {
return false;
}
MyGroup other = (MyGroup) o;
return java.util.Objects.equals(this.id, other.id)
&& java.util.Objects.equals(this.ocid, other.ocid)
&& java.util.Objects.equals(this.schemas, other.schemas)
&& java.util.Objects.equals(this.meta, other.meta)
&& java.util.Objects.equals(this.idcsCreatedBy, other.idcsCreatedBy)
&& java.util.Objects.equals(this.idcsLastModifiedBy, other.idcsLastModifiedBy)
&& java.util.Objects.equals(
this.idcsPreventedOperations, other.idcsPreventedOperations)
&& java.util.Objects.equals(this.tags, other.tags)
&& java.util.Objects.equals(this.deleteInProgress, other.deleteInProgress)
&& java.util.Objects.equals(
this.idcsLastUpgradedInRelease, other.idcsLastUpgradedInRelease)
&& java.util.Objects.equals(this.domainOcid, other.domainOcid)
&& java.util.Objects.equals(this.compartmentOcid, other.compartmentOcid)
&& java.util.Objects.equals(this.tenancyOcid, other.tenancyOcid)
&& java.util.Objects.equals(this.externalId, other.externalId)
&& java.util.Objects.equals(this.displayName, other.displayName)
&& java.util.Objects.equals(this.nonUniqueDisplayName, other.nonUniqueDisplayName)
&& java.util.Objects.equals(this.members, other.members)
&& java.util.Objects.equals(
this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup,
other.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup)
&& java.util.Objects.equals(
this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup,
other.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup)
&& super.equals(other);
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result * PRIME) + (this.id == null ? 43 : this.id.hashCode());
result = (result * PRIME) + (this.ocid == null ? 43 : this.ocid.hashCode());
result = (result * PRIME) + (this.schemas == null ? 43 : this.schemas.hashCode());
result = (result * PRIME) + (this.meta == null ? 43 : this.meta.hashCode());
result =
(result * PRIME)
+ (this.idcsCreatedBy == null ? 43 : this.idcsCreatedBy.hashCode());
result =
(result * PRIME)
+ (this.idcsLastModifiedBy == null
? 43
: this.idcsLastModifiedBy.hashCode());
result =
(result * PRIME)
+ (this.idcsPreventedOperations == null
? 43
: this.idcsPreventedOperations.hashCode());
result = (result * PRIME) + (this.tags == null ? 43 : this.tags.hashCode());
result =
(result * PRIME)
+ (this.deleteInProgress == null ? 43 : this.deleteInProgress.hashCode());
result =
(result * PRIME)
+ (this.idcsLastUpgradedInRelease == null
? 43
: this.idcsLastUpgradedInRelease.hashCode());
result = (result * PRIME) + (this.domainOcid == null ? 43 : this.domainOcid.hashCode());
result =
(result * PRIME)
+ (this.compartmentOcid == null ? 43 : this.compartmentOcid.hashCode());
result = (result * PRIME) + (this.tenancyOcid == null ? 43 : this.tenancyOcid.hashCode());
result = (result * PRIME) + (this.externalId == null ? 43 : this.externalId.hashCode());
result = (result * PRIME) + (this.displayName == null ? 43 : this.displayName.hashCode());
result =
(result * PRIME)
+ (this.nonUniqueDisplayName == null
? 43
: this.nonUniqueDisplayName.hashCode());
result = (result * PRIME) + (this.members == null ? 43 : this.members.hashCode());
result =
(result * PRIME)
+ (this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup == null
? 43
: this.urnIetfParamsScimSchemasOracleIdcsExtensionGroupGroup
.hashCode());
result =
(result * PRIME)
+ (this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup == null
? 43
: this.urnIetfParamsScimSchemasOracleIdcsExtensionPosixGroup
.hashCode());
result = (result * PRIME) + super.hashCode();
return result;
}
}
| oracle/oci-java-sdk | bmc-identitydomains/src/main/java/com/oracle/bmc/identitydomains/model/MyGroup.java |
717 | import java.awt.Color;
class Minimol
{
int nvert;
pto3D miniverts[];
String minietiqs[];
String miniperss[];
float minisizes[];
Color minicolor[];
int miniselec[];
int miniconec[][];
double xmin, xmax, ymin, ymax, zmin, zmax;
Minimol (int nv)
{
nvert = nv;
miniverts = new pto3D[nvert];
minietiqs = new String[nvert];
miniperss = new String[nvert];
minisizes = new float[nvert];
minicolor = new Color[nvert];
miniselec = new int[nvert];
miniconec = new int[nvert][10];
}
Minimol (MoleculaB mo)
{
//Creacion de una minimolecula rapida para manipulacion dentro de un visor 3D
//A partir de una molecula compleja tipo MoleculaB
nvert = mo.susatomos.size ();
miniverts = new pto3D[nvert];
minietiqs = new String[nvert];
miniperss = new String[nvert];
minisizes = new float[nvert];
minicolor = new Color[nvert];
miniselec = new int[nvert];
miniconec = new int[nvert][10];
for (int i = 0; i < nvert; i++) {
Atomo at = (Atomo) mo.susatomos.get (i);
miniverts[i] = new pto3D (at.vert.x, at.vert.y, at.vert.z);
minietiqs[i] = at.etiq;
miniperss[i] = at.pers;
minisizes[i] = (float) at.r;
minicolor[i] = at.color;
miniselec[i] = 0;
for (int j = 0; j < 10; j++)
miniconec[i][j] = at.mconec[j];
}
}
void vaciar ()
{
}
//void deseleccionar(){for (int i = 0; i<susatomos.size();i++) ((Atomo)susatomos.get(i)).selec=0; nselec=0;}
//HABRIA QUE PONER HERRAMIENTAS DE SELECCIONADO
void girox (double th)
{
for (int i = 0; i < nvert; i++) {
float ct = (float) Math.cos (th / 180 * Math.PI);
float st = (float) Math.sin (th / 180 * Math.PI);
miniverts[i].rgirox (ct, st);
}}
void giroy (double th)
{
for (int i = 0; i < nvert; i++) {
float ct = (float) Math.cos (th / 180 * Math.PI);
float st = (float) Math.sin (th / 180 * Math.PI);
miniverts[i].rgiroy (ct, st);
}}
void giroz (double th)
{
for (int i = 0; i < nvert; i++) {
float ct = (float) Math.cos (th / 180 * Math.PI);
float st = (float) Math.sin (th / 180 * Math.PI);
miniverts[i].rgiroz (ct, st);
}}
double getDim ()
{
double Dim = 0.01;
for (int i = 0; i < nvert; i++) {
for (int j = i + 1; j < nvert; j++) {
pto3D v = miniverts[i];
pto3D w = miniverts[j];
double dist = v.dista (w);
if (dist > Dim)
Dim = dist;
}
}
return Dim;
}
double distancia (int a, int b)
{
pto3D v = miniverts[a];
pto3D w = miniverts[b];
return v.dista (w);
}
double angulo (int a, int b, int c) //OJO EN GRADOS
{
pto3D v = miniverts[a];
pto3D w = miniverts[b];
pto3D u = miniverts[c];
return u.menos (w).angulocong (v.menos (w));
}
double dihedro (int a, int b, int c, int d)
{
pto3D v = miniverts[a];
pto3D w = miniverts[b];
pto3D u = miniverts[c];
pto3D s = miniverts[d];
pto3D v1 = v.menos (w);
pto3D v2 = w.menos (u);
pto3D v3 = s.menos (u);
return v1.dihedrog (v2, v3);
} //OJO EN GRADOS
int selecstatus (int i)
{
return miniselec[i];
}
void selecciona (int i, int status)
{
miniselec[i] = status;
}
void deselecciona ()
{
for (int i = 0; i < nvert; i++)
miniselec[i] = 0;
}
Minimol clona ()
{
Minimol mmn = new Minimol (this.nvert);
for (int i = 0; i < this.nvert; i++) {
mmn.miniverts[i] = this.miniverts[i].clona ();
mmn.minietiqs[i] = this.minietiqs[i];
mmn.miniperss[i] = this.miniperss[i];
mmn.minisizes[i] = this.minisizes[i];
mmn.minicolor[i] = this.minicolor[i];
mmn.miniselec[i] = this.miniselec[i];
for (int j = 0; j < 10; j++)
mmn.miniconec[i][j] = this.miniconec[i][j];
}
return mmn;
}
double getLejania ()
{
double lej = 0;
if (nvert == 1)
return 0;
for (int i = 0; i < nvert; i++) {
pto3D v = miniverts[i];
pto3D c = new pto3D (0, 0, 0);
double dist = v.dista (c);
if (dist > lej)
lej = dist;
}
return lej;
}
}
| kanzure/nanoengineer | cad/src/experimental/CoNTub/Minimol.java |
718 | /*
Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank!
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.frankframework.extensions.afm;
import java.text.DecimalFormat;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import lombok.Getter;
import lombok.Setter;
import org.frankframework.core.ISender;
import org.frankframework.core.PipeLineSession;
import org.frankframework.core.SenderException;
import org.frankframework.core.SenderResult;
import org.frankframework.doc.Category;
import org.frankframework.stream.Message;
import org.frankframework.util.DateFormatUtils;
import org.frankframework.util.DomBuilderException;
import org.frankframework.util.LogUtil;
import org.frankframework.util.XmlUtils;
/**
* Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice).
*
* @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel
*/
@Category("NN-Special")
public class Afm2EdiFactSender implements ISender {
protected Logger logger = LogUtil.getLogger(this);
private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader();
private @Getter @Setter ApplicationContext applicationContext;
public static final String VERWERKTAG = "VRWRKCD";
public static final String TPNRTAG = "AL_RECCRT";
private static final String contractRoot = "Contractdocument";
private static final String mantelRoot = "Mantel";
private static final String onderdeelRoot = "Onderdeel";
private String destination = " "; // 3 tekens
private String tpnummer = "999999";
// 6 tekens indien label AL_RECCRT ontbreekt
private String postbus = " "; //16 tekens
private String name;
@Override
public void configure() {
}
@Override
public void open() {
}
@Override
public void close() {
}
@Override
public boolean isSynchronous() {
return true;
}
@Override
public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException {
try {
return new SenderResult(execute(message.asString()));
} catch (Exception e) {
throw new SenderException("transforming AFM-XML to EdiFact",e);
}
}
private void appendArray(char[] aArray, StringBuilder aRes) {
String aStr = new String(aArray);
appendString(aStr, aRes);
}
private void appendString(String aStr, StringBuilder aRes) {
if (aStr != null) {
String lHlpStr = aStr.trim(); //TODO: checken of dit wel klopt, stond zo in originele EvdW-code
if (aStr.length() > 1) {
aRes.append(aStr.intern() + "\r\n");
}
}
}
private boolean bevatWaarde(Node aNode) {
String lWaarde = getWaardeForNode(aNode);
boolean lRes = false;
if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) {
lRes = true;
}
if (!lRes) {
NodeList lList = aNode.getChildNodes();
for (int i = 0; i <= lList.getLength() - 1; i++) {
Node aSubNode = lList.item(i);
lWaarde = getWaardeForNode(aNode);
if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) {
lRes = true;
break;
} else {
boolean lHlpRes = bevatWaarde(aSubNode);
if (lHlpRes) {
lRes = lHlpRes;
break;
}
}
}
}
return lRes;
}
private void closeList(StringBuilder aRes, int regelTeller) {
// UNT
char untRegel[] = new char[21];
for (int i = 0; i < 21; i++)
untRegel[i] = ' ';
"UNT".getChars(0, "UNT".length(), untRegel, 0);
DecimalFormat df = new DecimalFormat("000000");
regelTeller++; //de UNT Regel zelf
df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3);
appendArray(untRegel, aRes);
regelTeller = 0;
}
public String execute(String aInput) throws DomBuilderException {
Document doc = XmlUtils.buildDomDocument(aInput);
NodeList contractList = doc.getElementsByTagName(contractRoot);
NodeList mantelList = doc.getElementsByTagName(mantelRoot);
NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot);
NodeList tpNr = doc.getElementsByTagName(TPNRTAG);
if (tpNr.getLength() > 0) {
Node lHlpNode = tpNr.item(0);
setTpnummer(getWaardeForNode(lHlpNode));
}
StringBuilder resultaat = new StringBuilder();
//start
this.appendArray(getInitResultaat(), resultaat);
//docs
this.HandleList(contractList, resultaat);
this.HandleList(mantelList, resultaat);
this.HandleList(onderdeelList, resultaat);
//finish
this.appendArray(getCloseResultaat(), resultaat);
return resultaat.toString();
}
public char[] getCloseResultaat() {
// UNZ
char unzRegel[] = new char[23];
for (int i = 0; i < 23; i++)
unzRegel[i] = ' ';
"UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0);
return unzRegel;
}
public char[] getInitResultaat() {
// UNB
char unbRegel[] = new char[206];
for (int i = 0; i < 206; i++)
unbRegel[i] = ' ';
String lStart = "UNBUNOC1INFONET " + getDestination() + " TP";
lStart.getChars(0, lStart.length(), unbRegel, 0);
getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26);
String lPostbus = getPostbus();
lPostbus.getChars(0, lPostbus.length(), unbRegel, 61);
String dateTime = DateFormatUtils.now("yyMMddHHmm");
dateTime.getChars(0, dateTime.length(), unbRegel, 114);
"0".getChars(0, "0".length(), unbRegel, 169);
"0".getChars(0, "0".length(), unbRegel, 205);
return unbRegel;
}
private String getLabelNaam(String aLabel) {
String lRes = aLabel;
if (lRes != null) {
if (lRes.startsWith("Q")) {
lRes = "#" + lRes.substring(1);
}
}
return lRes;
}
private char[] getNewDocInit() {
char unhRegel[] = new char[74];
for (int i = 0; i < 74; i++)
unhRegel[i] = ' ';
"UNH".getChars(0, "UNH".length(), unhRegel, 0);
"INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17);
"00".getChars(0, "00".length(), unhRegel, 72);
return unhRegel;
}
private String getVerwerkCdNaamForNode(Node aNode) {
String lRes = aNode.getNodeName() + "_" + VERWERKTAG;
return lRes;
}
private String getVerwerkCdWaarde(Node aNode) {
NodeList aList = aNode.getChildNodes();
String lRes = "";
String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode);
for (int i = 0; i <= aList.getLength() - 1; i++) {
Node aChild = aList.item(i);
if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) {
lRes = getWaardeForNode(aChild);
break;
}
}
return lRes;
}
private String getWaardeForNode(Node aNode) {
String lRes = "";
NodeList lList = aNode.getChildNodes();
for (int i = 0; i <= lList.getLength() - 1; i++) {
Node aSubNode = lList.item(i);
if ((aSubNode.getNodeType() == Node.TEXT_NODE)
|| (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) {
lRes = lRes + aSubNode.getNodeValue();
}
}
return lRes;
}
private StringBuilder HandleList(NodeList aList, StringBuilder aRes) {
if (aList != null) {
if (aList.getLength() > 0) {
for (int i = 0; i <= aList.getLength() - 1; i++) {
int regelTeller = 1;
this.appendArray(getNewDocInit(), aRes);
Node aNode = aList.item(i);
NodeList aSubList = aNode.getChildNodes();
regelTeller = HandleSubList(aSubList, aRes, regelTeller);
closeList(aRes,regelTeller);
}
}
}
return aRes;
}
private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) {
String lHlp = "";
if (aList != null) {
for (int i = 0; i <= aList.getLength() - 1; i++) {
Node aNode = aList.item(i);
if (aNode.getNodeType() == Node.ELEMENT_NODE) {
if (bevatWaarde(aNode)) {
String labelNaam =
this.getLabelNaam(aNode.getNodeName());
if (labelNaam.length() == 2) {
// Entiteit gevonden
lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode);
appendString(lHlp, aRes);
regelTeller++;
NodeList aSubList = aNode.getChildNodes();
regelTeller = HandleSubList(aSubList, aRes, regelTeller);
} else {
if (labelNaam.contains(VERWERKTAG)) {
//Verwerktags niet in edifact zetten
} else {
lHlp = "LBW" + labelNaam.substring(3);
// Spaties toevoegen
for (int lTel = lHlp.length(); lTel < 10; lTel++) {
lHlp += " ";
}
String lWaarde = this.getWaardeForNode(aNode);
if ((lWaarde != null)
&& (!"".equalsIgnoreCase(lWaarde))) {
lHlp = lHlp + lWaarde;
this.appendString(lHlp, aRes);
regelTeller++;
}
}
}
}
}
}
}
return regelTeller;
}
@Override
public void setName(String name) {
this.name=name;
}
@Override
public String getName() {
return name;
}
public void setDestination(String newDestination) {
destination = newDestination;
}
public String getDestination() {
return destination;
}
public void setPostbus(String newPostbus) {
postbus = newPostbus;
}
public String getPostbus() {
return postbus;
}
public void setTpnummer(String newTpnummer) {
logger.info("Tpnr: " + newTpnummer);
tpnummer = newTpnummer;
}
public String getTpnummer() {
return tpnummer;
}
}
| frankframework/frankframework | nn-specials/src/main/java/org/frankframework/extensions/afm/Afm2EdiFactSender.java |
719 | // *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.oci.Identity;
import com.pulumi.core.Output;
import com.pulumi.core.annotations.Export;
import com.pulumi.core.annotations.ResourceType;
import com.pulumi.core.internal.Codegen;
import com.pulumi.oci.Identity.DomainsApiKeyArgs;
import com.pulumi.oci.Identity.inputs.DomainsApiKeyState;
import com.pulumi.oci.Identity.outputs.DomainsApiKeyIdcsCreatedBy;
import com.pulumi.oci.Identity.outputs.DomainsApiKeyIdcsLastModifiedBy;
import com.pulumi.oci.Identity.outputs.DomainsApiKeyMeta;
import com.pulumi.oci.Identity.outputs.DomainsApiKeyTag;
import com.pulumi.oci.Identity.outputs.DomainsApiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUser;
import com.pulumi.oci.Identity.outputs.DomainsApiKeyUser;
import com.pulumi.oci.Utilities;
import java.lang.Boolean;
import java.lang.String;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/**
* This resource provides the Api Key resource in Oracle Cloud Infrastructure Identity Domains service.
*
* Create a user's API key.
*
* ## Example Usage
*
* <!--Start PulumiCodeChooser -->
* <pre>
* {@code
* package generated_program;
*
* import com.pulumi.Context;
* import com.pulumi.Pulumi;
* import com.pulumi.core.Output;
* import com.pulumi.oci.Identity.DomainsApiKey;
* import com.pulumi.oci.Identity.DomainsApiKeyArgs;
* import com.pulumi.oci.Identity.inputs.DomainsApiKeyTagArgs;
* import com.pulumi.oci.Identity.inputs.DomainsApiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUserArgs;
* import com.pulumi.oci.Identity.inputs.DomainsApiKeyUserArgs;
* import java.util.List;
* import java.util.ArrayList;
* import java.util.Map;
* import java.io.File;
* import java.nio.file.Files;
* import java.nio.file.Paths;
*
* public class App {
* public static void main(String[] args) {
* Pulumi.run(App::stack);
* }
*
* public static void stack(Context ctx) {
* var testApiKey = new DomainsApiKey("testApiKey", DomainsApiKeyArgs.builder()
* .idcsEndpoint(testDomain.url())
* .key(apiKeyKey)
* .schemas("urn:ietf:params:scim:schemas:oracle:idcs:apikey")
* .attributeSets()
* .attributes("")
* .authorization(apiKeyAuthorization)
* .description(apiKeyDescription)
* .id(apiKeyId)
* .ocid(apiKeyOcid)
* .resourceTypeSchemaVersion(apiKeyResourceTypeSchemaVersion)
* .tags(DomainsApiKeyTagArgs.builder()
* .key(apiKeyTagsKey)
* .value(apiKeyTagsValue)
* .build())
* .urnietfparamsscimschemasoracleidcsextensionselfChangeUser(DomainsApiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUserArgs.builder()
* .allowSelfChange(apiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUserAllowSelfChange)
* .build())
* .user(DomainsApiKeyUserArgs.builder()
* .ocid(testUser.ocid())
* .value(testUser.id())
* .build())
* .build());
*
* }
* }
* }
* </pre>
* <!--End PulumiCodeChooser -->
*
* ## Import
*
* ApiKeys can be imported using the `id`, e.g.
*
* ```sh
* $ pulumi import oci:Identity/domainsApiKey:DomainsApiKey test_api_key "idcsEndpoint/{idcsEndpoint}/apiKeys/{apiKeyId}"
* ```
*
*/
@ResourceType(type="oci:Identity/domainsApiKey:DomainsApiKey")
public class DomainsApiKey extends com.pulumi.resources.CustomResource {
/**
* A multi-valued list of strings indicating the return type of attribute definition. The specified set of attributes can be fetched by the return type of the attribute. One or more values can be given together to fetch more than one group of attributes. If 'attributes' query parameter is also available, union of the two is fetched. Valid values - all, always, never, request, default. Values are case-insensitive.
*
*/
@Export(name="attributeSets", refs={List.class,String.class}, tree="[0,1]")
private Output</* @Nullable */ List<String>> attributeSets;
/**
* @return A multi-valued list of strings indicating the return type of attribute definition. The specified set of attributes can be fetched by the return type of the attribute. One or more values can be given together to fetch more than one group of attributes. If 'attributes' query parameter is also available, union of the two is fetched. Valid values - all, always, never, request, default. Values are case-insensitive.
*
*/
public Output<Optional<List<String>>> attributeSets() {
return Codegen.optional(this.attributeSets);
}
/**
* A comma-delimited string that specifies the names of resource attributes that should be returned in the response. By default, a response that contains resource attributes contains only attributes that are defined in the schema for that resource type as returned=always or returned=default. An attribute that is defined as returned=request is returned in a response only if the request specifies its name in the value of this query parameter. If a request specifies this query parameter, the response contains the attributes that this query parameter specifies, as well as any attribute that is defined as returned=always.
*
*/
@Export(name="attributes", refs={String.class}, tree="[0]")
private Output</* @Nullable */ String> attributes;
/**
* @return A comma-delimited string that specifies the names of resource attributes that should be returned in the response. By default, a response that contains resource attributes contains only attributes that are defined in the schema for that resource type as returned=always or returned=default. An attribute that is defined as returned=request is returned in a response only if the request specifies its name in the value of this query parameter. If a request specifies this query parameter, the response contains the attributes that this query parameter specifies, as well as any attribute that is defined as returned=always.
*
*/
public Output<Optional<String>> attributes() {
return Codegen.optional(this.attributes);
}
/**
* The Authorization field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested.
*
*/
@Export(name="authorization", refs={String.class}, tree="[0]")
private Output</* @Nullable */ String> authorization;
/**
* @return The Authorization field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested.
*
*/
public Output<Optional<String>> authorization() {
return Codegen.optional(this.authorization);
}
/**
* (Updatable) Oracle Cloud Infrastructure Compartment Id (ocid) in which the resource lives.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: string
* * uniqueness: none
*
*/
@Export(name="compartmentOcid", refs={String.class}, tree="[0]")
private Output<String> compartmentOcid;
/**
* @return (Updatable) Oracle Cloud Infrastructure Compartment Id (ocid) in which the resource lives.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: string
* * uniqueness: none
*
*/
public Output<String> compartmentOcid() {
return this.compartmentOcid;
}
/**
* (Updatable) A boolean flag indicating this resource in the process of being deleted. Usually set to true when synchronous deletion of the resource would take too long.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: boolean
* * uniqueness: none
*
*/
@Export(name="deleteInProgress", refs={Boolean.class}, tree="[0]")
private Output<Boolean> deleteInProgress;
/**
* @return (Updatable) A boolean flag indicating this resource in the process of being deleted. Usually set to true when synchronous deletion of the resource would take too long.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: boolean
* * uniqueness: none
*
*/
public Output<Boolean> deleteInProgress() {
return this.deleteInProgress;
}
/**
* Description
*
* **Added In:** 2101262133
*
* **SCIM++ Properties:**
* * caseExact: false
* * type: string
* * mutability: readWrite
* * required: false
* * returned: default
*
*/
@Export(name="description", refs={String.class}, tree="[0]")
private Output<String> description;
/**
* @return Description
*
* **Added In:** 2101262133
*
* **SCIM++ Properties:**
* * caseExact: false
* * type: string
* * mutability: readWrite
* * required: false
* * returned: default
*
*/
public Output<String> description() {
return this.description;
}
/**
* (Updatable) Oracle Cloud Infrastructure Domain Id (ocid) in which the resource lives.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: string
* * uniqueness: none
*
*/
@Export(name="domainOcid", refs={String.class}, tree="[0]")
private Output<String> domainOcid;
/**
* @return (Updatable) Oracle Cloud Infrastructure Domain Id (ocid) in which the resource lives.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: string
* * uniqueness: none
*
*/
public Output<String> domainOcid() {
return this.domainOcid;
}
/**
* (Updatable) Fingerprint
*
* **Added In:** 2010242156
*
* **SCIM++ Properties:**
* * caseExact: true
* * idcsSearchable: true
* * type: string
* * mutability: readOnly
* * required: true
* * returned: default
*
*/
@Export(name="fingerprint", refs={String.class}, tree="[0]")
private Output<String> fingerprint;
/**
* @return (Updatable) Fingerprint
*
* **Added In:** 2010242156
*
* **SCIM++ Properties:**
* * caseExact: true
* * idcsSearchable: true
* * type: string
* * mutability: readOnly
* * required: true
* * returned: default
*
*/
public Output<String> fingerprint() {
return this.fingerprint;
}
/**
* (Updatable) The User or App who created the Resource
*
* **SCIM++ Properties:**
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: true
* * returned: default
* * type: complex
*
*/
@Export(name="idcsCreatedBies", refs={List.class,DomainsApiKeyIdcsCreatedBy.class}, tree="[0,1]")
private Output<List<DomainsApiKeyIdcsCreatedBy>> idcsCreatedBies;
/**
* @return (Updatable) The User or App who created the Resource
*
* **SCIM++ Properties:**
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: true
* * returned: default
* * type: complex
*
*/
public Output<List<DomainsApiKeyIdcsCreatedBy>> idcsCreatedBies() {
return this.idcsCreatedBies;
}
/**
* The basic endpoint for the identity domain
*
*/
@Export(name="idcsEndpoint", refs={String.class}, tree="[0]")
private Output<String> idcsEndpoint;
/**
* @return The basic endpoint for the identity domain
*
*/
public Output<String> idcsEndpoint() {
return this.idcsEndpoint;
}
/**
* (Updatable) The User or App who modified the Resource
*
* **SCIM++ Properties:**
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: complex
*
*/
@Export(name="idcsLastModifiedBies", refs={List.class,DomainsApiKeyIdcsLastModifiedBy.class}, tree="[0,1]")
private Output<List<DomainsApiKeyIdcsLastModifiedBy>> idcsLastModifiedBies;
/**
* @return (Updatable) The User or App who modified the Resource
*
* **SCIM++ Properties:**
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: complex
*
*/
public Output<List<DomainsApiKeyIdcsLastModifiedBy>> idcsLastModifiedBies() {
return this.idcsLastModifiedBies;
}
/**
* (Updatable) The release number when the resource was upgraded.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: request
* * type: string
* * uniqueness: none
*
*/
@Export(name="idcsLastUpgradedInRelease", refs={String.class}, tree="[0]")
private Output<String> idcsLastUpgradedInRelease;
/**
* @return (Updatable) The release number when the resource was upgraded.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: request
* * type: string
* * uniqueness: none
*
*/
public Output<String> idcsLastUpgradedInRelease() {
return this.idcsLastUpgradedInRelease;
}
/**
* (Updatable) Each value of this attribute specifies an operation that only an internal client may perform on this particular resource.
*
* **SCIM++ Properties:**
* * idcsSearchable: false
* * multiValued: true
* * mutability: readOnly
* * required: false
* * returned: request
* * type: string
* * uniqueness: none
*
*/
@Export(name="idcsPreventedOperations", refs={List.class,String.class}, tree="[0,1]")
private Output<List<String>> idcsPreventedOperations;
/**
* @return (Updatable) Each value of this attribute specifies an operation that only an internal client may perform on this particular resource.
*
* **SCIM++ Properties:**
* * idcsSearchable: false
* * multiValued: true
* * mutability: readOnly
* * required: false
* * returned: request
* * type: string
* * uniqueness: none
*
*/
public Output<List<String>> idcsPreventedOperations() {
return this.idcsPreventedOperations;
}
/**
* Key or name of the tag.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: readWrite
* * required: true
* * returned: default
* * type: string
* * uniqueness: none
*
*/
@Export(name="key", refs={String.class}, tree="[0]")
private Output<String> key;
/**
* @return Key or name of the tag.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: readWrite
* * required: true
* * returned: default
* * type: string
* * uniqueness: none
*
*/
public Output<String> key() {
return this.key;
}
/**
* (Updatable) A complex attribute that contains resource metadata. All sub-attributes are OPTIONAL.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * idcsCsvAttributeNameMappings: [[columnHeaderName:Created Date, mapsTo:meta.created]]
* * type: complex
*
*/
@Export(name="metas", refs={List.class,DomainsApiKeyMeta.class}, tree="[0,1]")
private Output<List<DomainsApiKeyMeta>> metas;
/**
* @return (Updatable) A complex attribute that contains resource metadata. All sub-attributes are OPTIONAL.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * idcsCsvAttributeNameMappings: [[columnHeaderName:Created Date, mapsTo:meta.created]]
* * type: complex
*
*/
public Output<List<DomainsApiKeyMeta>> metas() {
return this.metas;
}
/**
* The user's OCID.
*
* **SCIM++ Properties:**
* * caseExact: true
* * idcsSearchable: true
* * multiValued: false
* * mutability: immutable
* * required: false
* * returned: always
* * type: string
* * uniqueness: none
*
*/
@Export(name="ocid", refs={String.class}, tree="[0]")
private Output<String> ocid;
/**
* @return The user's OCID.
*
* **SCIM++ Properties:**
* * caseExact: true
* * idcsSearchable: true
* * multiValued: false
* * mutability: immutable
* * required: false
* * returned: always
* * type: string
* * uniqueness: none
*
*/
public Output<String> ocid() {
return this.ocid;
}
/**
* An endpoint-specific schema version number to use in the Request. Allowed version values are Earliest Version or Latest Version as specified in each REST API endpoint description, or any sequential number inbetween. All schema attributes/body parameters are a part of version 1. After version 1, any attributes added or deprecated will be tagged with the version that they were added to or deprecated in. If no version is provided, the latest schema version is returned.
*
*/
@Export(name="resourceTypeSchemaVersion", refs={String.class}, tree="[0]")
private Output</* @Nullable */ String> resourceTypeSchemaVersion;
/**
* @return An endpoint-specific schema version number to use in the Request. Allowed version values are Earliest Version or Latest Version as specified in each REST API endpoint description, or any sequential number inbetween. All schema attributes/body parameters are a part of version 1. After version 1, any attributes added or deprecated will be tagged with the version that they were added to or deprecated in. If no version is provided, the latest schema version is returned.
*
*/
public Output<Optional<String>> resourceTypeSchemaVersion() {
return Codegen.optional(this.resourceTypeSchemaVersion);
}
/**
* REQUIRED. The schemas attribute is an array of Strings which allows introspection of the supported schema version for a SCIM representation as well any schema extensions supported by that representation. Each String value must be a unique URI. This specification defines URIs for User, Group, and a standard \"enterprise\" extension. All representations of SCIM schema MUST include a non-zero value array with value(s) of the URIs supported by that representation. Duplicate values MUST NOT be included. Value order is not specified and MUST not impact behavior.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: true
* * mutability: readWrite
* * required: true
* * returned: default
* * type: string
* * uniqueness: none
*
*/
@Export(name="schemas", refs={List.class,String.class}, tree="[0,1]")
private Output<List<String>> schemas;
/**
* @return REQUIRED. The schemas attribute is an array of Strings which allows introspection of the supported schema version for a SCIM representation as well any schema extensions supported by that representation. Each String value must be a unique URI. This specification defines URIs for User, Group, and a standard \"enterprise\" extension. All representations of SCIM schema MUST include a non-zero value array with value(s) of the URIs supported by that representation. Duplicate values MUST NOT be included. Value order is not specified and MUST not impact behavior.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: true
* * mutability: readWrite
* * required: true
* * returned: default
* * type: string
* * uniqueness: none
*
*/
public Output<List<String>> schemas() {
return this.schemas;
}
/**
* A list of tags on this resource.
*
* **SCIM++ Properties:**
* * idcsCompositeKey: [key, value]
* * idcsSearchable: true
* * multiValued: true
* * mutability: readWrite
* * required: false
* * returned: request
* * type: complex
* * uniqueness: none
*
*/
@Export(name="tags", refs={List.class,DomainsApiKeyTag.class}, tree="[0,1]")
private Output<List<DomainsApiKeyTag>> tags;
/**
* @return A list of tags on this resource.
*
* **SCIM++ Properties:**
* * idcsCompositeKey: [key, value]
* * idcsSearchable: true
* * multiValued: true
* * mutability: readWrite
* * required: false
* * returned: request
* * type: complex
* * uniqueness: none
*
*/
public Output<List<DomainsApiKeyTag>> tags() {
return this.tags;
}
/**
* (Updatable) Oracle Cloud Infrastructure Tenant Id (ocid) in which the resource lives.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: string
* * uniqueness: none
*
*/
@Export(name="tenancyOcid", refs={String.class}, tree="[0]")
private Output<String> tenancyOcid;
/**
* @return (Updatable) Oracle Cloud Infrastructure Tenant Id (ocid) in which the resource lives.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: false
* * multiValued: false
* * mutability: readOnly
* * required: false
* * returned: default
* * type: string
* * uniqueness: none
*
*/
public Output<String> tenancyOcid() {
return this.tenancyOcid;
}
/**
* Controls whether a user can update themselves or not via User related APIs
*
*/
@Export(name="urnietfparamsscimschemasoracleidcsextensionselfChangeUser", refs={DomainsApiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUser.class}, tree="[0]")
private Output<DomainsApiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUser> urnietfparamsscimschemasoracleidcsextensionselfChangeUser;
/**
* @return Controls whether a user can update themselves or not via User related APIs
*
*/
public Output<DomainsApiKeyUrnietfparamsscimschemasoracleidcsextensionselfChangeUser> urnietfparamsscimschemasoracleidcsextensionselfChangeUser() {
return this.urnietfparamsscimschemasoracleidcsextensionselfChangeUser;
}
/**
* The user linked to the API key.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: immutable
* * required: false
* * returned: default
* * type: complex
* * uniqueness: none
*
*/
@Export(name="user", refs={DomainsApiKeyUser.class}, tree="[0]")
private Output<DomainsApiKeyUser> user;
/**
* @return The user linked to the API key.
*
* **SCIM++ Properties:**
* * caseExact: false
* * idcsSearchable: true
* * multiValued: false
* * mutability: immutable
* * required: false
* * returned: default
* * type: complex
* * uniqueness: none
*
*/
public Output<DomainsApiKeyUser> user() {
return this.user;
}
/**
*
* @param name The _unique_ name of the resulting resource.
*/
public DomainsApiKey(String name) {
this(name, DomainsApiKeyArgs.Empty);
}
/**
*
* @param name The _unique_ name of the resulting resource.
* @param args The arguments to use to populate this resource's properties.
*/
public DomainsApiKey(String name, DomainsApiKeyArgs args) {
this(name, args, null);
}
/**
*
* @param name The _unique_ name of the resulting resource.
* @param args The arguments to use to populate this resource's properties.
* @param options A bag of options that control this resource's behavior.
*/
public DomainsApiKey(String name, DomainsApiKeyArgs args, @Nullable com.pulumi.resources.CustomResourceOptions options) {
super("oci:Identity/domainsApiKey:DomainsApiKey", name, args == null ? DomainsApiKeyArgs.Empty : args, makeResourceOptions(options, Codegen.empty()));
}
private DomainsApiKey(String name, Output<String> id, @Nullable DomainsApiKeyState state, @Nullable com.pulumi.resources.CustomResourceOptions options) {
super("oci:Identity/domainsApiKey:DomainsApiKey", name, state, makeResourceOptions(options, id));
}
private static com.pulumi.resources.CustomResourceOptions makeResourceOptions(@Nullable com.pulumi.resources.CustomResourceOptions options, @Nullable Output<String> id) {
var defaultOptions = com.pulumi.resources.CustomResourceOptions.builder()
.version(Utilities.getVersion())
.build();
return com.pulumi.resources.CustomResourceOptions.merge(defaultOptions, options, id);
}
/**
* Get an existing Host resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state
* @param options Optional settings to control the behavior of the CustomResource.
*/
public static DomainsApiKey get(String name, Output<String> id, @Nullable DomainsApiKeyState state, @Nullable com.pulumi.resources.CustomResourceOptions options) {
return new DomainsApiKey(name, id, state, options);
}
}
| pulumi/pulumi-oci | sdk/java/src/main/java/com/pulumi/oci/Identity/DomainsApiKey.java |
720 | package domain;
import java.util.ArrayList;
public class Boekhandel {
ArrayList<Product> lijst = new ArrayList<>();
public Boekhandel(){
}
public void addProduct(Product iets){
lijst.add(iets);
}
public String geefVoorraadInString(){
String alles = "";
for(Product p : lijst){
alles += p.naarString() + "\n";
}
return alles;
}
public String geefProductVoorraad(Product p){
String uitvoer = "";
for(Product t : lijst){
if(t == p){
uitvoer += t.naarString();
}
}
return uitvoer;
}
public String printWeekbladen(int uitgifte){
String uitvoer = "";
for(Product t : lijst){
if(super.equals(t) && t instanceof Tijdschrift){
Tijdschrift p = (Tijdschrift)t;
if(p.getWeek() == uitgifte) {
uitvoer += p.naarString() + "\n";
}
}
}
return uitvoer;
}
public void verkoop(Product p, int aantal){
p.verkocht(aantal);
}
public void voegToeAanVoorraad(Product p, int aantal){
if(aantal == 0){
throw new IllegalArgumentException("Dommie, je kan niet '0' producten toevoegen aan de voorraad");
}
if(aantal < 0){
throw new IllegalArgumentException("Je kan geen negatief aantal bestellen!!!");
}
p.setVoorraad(p.getVoorraad() + aantal);
}
}
| martijnmeeldijk/TI-oplossingen | Semester_2/OOP/Boekhandel/src/domain/Boekhandel.java |
721 | /* Copyright 2009-2024 David Hadka
*
* This file is part of the MOEA Framework.
*
* The MOEA Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* The MOEA Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package org.moeaframework.algorithm.pso;
import org.moeaframework.core.PRNG;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Settings;
import org.moeaframework.core.Solution;
import org.moeaframework.core.comparator.CrowdingComparator;
import org.moeaframework.core.comparator.ParetoDominanceComparator;
import org.moeaframework.core.fitness.CrowdingDistanceFitnessEvaluator;
import org.moeaframework.core.fitness.FitnessBasedArchive;
import org.moeaframework.core.operator.real.PM;
import org.moeaframework.core.variable.EncodingUtils;
import org.moeaframework.core.variable.RealVariable;
/**
* Implementation of SMPSO, the speed-constrained multi-objective particle swarm optimizer.
* <p>
* References:
* <ol>
* <li>Nebro, A. J., J. J. Durillo, J. Garcia-Nieto, and C. A. Coello Coello (2009). SMPSO: A New PSO-based
* Metaheuristic for Multi-objective Optimization. 2009 IEEE Symposium on Computational Intelligence in
* Multi-Criteria Decision-Making, pp. 66-73.
* <li>Durillo, J. J., J. Garc�a-Nieto, A. J. Nebro, C. A. Coello Coello, F. Luna, and E. Alba (2009).
* Multi-Objective Particle Swarm Optimizers: An Experimental Comparison. Evolutionary Multi-Criterion
* Optimization, pp. 495-509.
* </ol>
*/
public class SMPSO extends AbstractPSOAlgorithm {
/**
* The minimum velocity for each variable.
*/
private double[] minimumVelocity;
/**
* The maximum velocity for each variable.
*/
private double[] maximumVelocity;
/**
* Constructs a new SMPSO instance with default settings.
*
* @param problem the problem
*/
public SMPSO(Problem problem) {
this(problem,
Settings.DEFAULT_POPULATION_SIZE,
Settings.DEFAULT_POPULATION_SIZE,
1.0 / problem.getNumberOfVariables(),
20.0);
}
/**
* Constructs a new SMPSO instance.
*
* @param problem the problem
* @param swarmSize the number of particles
* @param leaderSize the number of leaders
* @param mutationProbability the mutation probability for {@link PM}
* @param distributionIndex the distribution index for {@link PM}
*/
public SMPSO(Problem problem, int swarmSize, int leaderSize, double mutationProbability, double distributionIndex) {
super(problem, swarmSize, leaderSize,
new CrowdingComparator(),
new ParetoDominanceComparator(),
new FitnessBasedArchive(new CrowdingDistanceFitnessEvaluator(), leaderSize),
null,
new PM(mutationProbability, distributionIndex));
// initialize the minimum and maximum velocities
minimumVelocity = new double[problem.getNumberOfVariables()];
maximumVelocity = new double[problem.getNumberOfVariables()];
Solution prototypeSolution = problem.newSolution();
for (int i = 0; i < problem.getNumberOfVariables(); i++) {
RealVariable variable = (RealVariable)prototypeSolution.getVariable(i);
maximumVelocity[i] = (variable.getUpperBound() - variable.getLowerBound()) / 2.0;
minimumVelocity[i] = -maximumVelocity[i];
}
}
@Override
protected void updateVelocity(int i) {
Solution particle = particles[i];
Solution localBestParticle = localBestParticles[i];
Solution leader = selectLeader();
double r1 = PRNG.nextDouble();
double r2 = PRNG.nextDouble();
double C1 = PRNG.nextDouble(1.5, 2.5);
double C2 = PRNG.nextDouble(1.5, 2.5);
double W = PRNG.nextDouble(0.1, 0.1);
for (int j = 0; j < problem.getNumberOfVariables(); j++) {
double particleValue = EncodingUtils.getReal(particle.getVariable(j));
double localBestValue = EncodingUtils.getReal(localBestParticle.getVariable(j));
double leaderValue = EncodingUtils.getReal(leader.getVariable(j));
double velocity = constrictionCoefficient(C1, C2) *
(W * velocities[i][j] +
C1*r1*(localBestValue - particleValue) +
C2*r2*(leaderValue - particleValue));
if (velocity > maximumVelocity[j]) {
velocity = maximumVelocity[j];
} else if (velocity < minimumVelocity[j]) {
velocity = minimumVelocity[j];
}
velocities[i][j] = velocity;
}
}
/**
* Returns the velocity constriction coefficient.
*
* @param c1 the velocity coefficient for the local best
* @param c2 the velocity coefficient for the leader
* @return the velocity constriction coefficient
*/
protected double constrictionCoefficient(double c1, double c2) {
double rho = c1 + c2;
if (rho <= 4) {
return 1.0;
} else {
return 2.0 / (2.0 - rho - Math.sqrt(Math.pow(rho, 2.0) - 4.0 * rho));
}
}
@Override
protected void mutate(int i) {
// The SMPSO paper [1] states that mutation is applied 15% of the time,
// but the JMetal implementation applies to every 6th particle. Should
// the application of mutation be random instead?
if (i % 6 == 0) {
particles[i] = mutation.mutate(particles[i]);
}
}
}
| MOEAFramework/MOEAFramework | src/org/moeaframework/algorithm/pso/SMPSO.java |
722 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.jdownloader.downloader.hls.HLSDownloader;
import org.jdownloader.plugins.components.hls.HlsContainer;
/*
* vrt.be network
* old content handling --> var vars12345 = Array();
*/
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://cobradecrypted\\.be/\\d+" })
public class CobraBe extends PluginForHost {
public CobraBe(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://cobra.canvas.be/";
}
// JSARRAY removed after rev 20337
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(downloadLink.getStringProperty("mainlink", null));
// Link offline
if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || !br.containsHTML("class=\"media flashPlayer bigMediaItem\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String ext = ".mp4";
downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "") + ext);
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
final String hlsserver = br.getRegex("data-video-iphone-server=\"(https?://[^<>\"]*?)\"").getMatch(0);
final String hlsfile = br.getRegex("data-video-iphone-path=\"(mp4:[^<>\"]*?\\.m3u8)\"").getMatch(0);
if (hlsserver == null || hlsfile == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String hlsmanifest = hlsserver + "/" + hlsfile;
br.getPage(hlsmanifest);
final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br));
if (hlsbest == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
final String url_hls = hlsbest.getDownloadurl();
checkFFmpeg(downloadLink, "Download a HLS Stream");
dl = new HLSDownloader(downloadLink, br, url_hls);
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/CobraBe.java |
723 | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework.protocol.ghidra;
import java.io.File;
import java.net.*;
import java.util.Objects;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import ghidra.framework.model.ProjectLocator;
import ghidra.framework.remote.GhidraServerHandle;
/**
* Supported URL forms include:
* <ul>
* <li>{@literal ghidra://<host>:<port>/<repository-name>[/<folder-path>]/[<folderItemName>[#ref]]}</li>
* <li>{@literal ghidra:/[X:/]<project-path>/<project-name>[?[/<folder-path>]/[<folderItemName>[#ref]]]}</li>
* </ul>
*/
public class GhidraURL {
// TODO: URL encoding/decoding should be used
public static final String PROTOCOL = "ghidra";
private static final String PROTOCOL_URL_START = PROTOCOL + ":/";
private static Pattern IS_REMOTE_URL_PATTERN =
Pattern.compile("^" + PROTOCOL_URL_START + "/[^/].*"); // e.g., ghidra://path
private static Pattern IS_LOCAL_URL_PATTERN =
Pattern.compile("^" + PROTOCOL_URL_START + "[^/].*"); // e.g., ghidra:/path
public static final String MARKER_FILE_EXTENSION = ".gpr";
public static final String PROJECT_DIRECTORY_EXTENSION = ".rep";
private GhidraURL() {
}
/**
* Determine if the specified URL refers to a local project and
* it exists.
* @param url ghidra URL
* @return true if specified URL refers to a local project and
* it exists.
*/
public static boolean localProjectExists(URL url) {
ProjectLocator loc = getProjectStorageLocator(url);
return loc != null && loc.exists();
}
/**
* Determine if the specified string appears to be a possible ghidra URL
* (starts with "ghidra:/").
* @param str string to be checked
* @return true if string is possible ghidra URL
*/
public static boolean isGhidraURL(String str) {
return str != null && str.startsWith(PROTOCOL_URL_START);
}
/**
* Tests if the given url is using the Ghidra protocol
* @param url the url to test
* @return true if the url is using the Ghidra protocol
*/
public static boolean isGhidraURL(URL url) {
return url != null && url.getProtocol().equals(PROTOCOL);
}
/**
* Determine if URL string uses a local format (e.g., {@code ghidra:/path...}).
* Extensive validation is not performed. This method is intended to differentiate
* from a server URL only.
* @param str URL string
* @return true if string appears to be local Ghidra URL, else false
*/
public static boolean isLocalGhidraURL(String str) {
return IS_LOCAL_URL_PATTERN.matcher(str).matches();
}
/**
* Determine if URL string uses a remote server format (e.g., {@code ghidra://host...}).
* Extensive validation is not performed. This method is intended to differentiate
* from a local URL only.
* @param str URL string
* @return true if string appears to be remote server Ghidra URL, else false
*/
public static boolean isServerURL(String str) {
return IS_REMOTE_URL_PATTERN.matcher(str).matches();
}
/**
* Determine if the specified URL is a local project URL.
* No checking is performed as to the existence of the project.
* @param url ghidra URL
* @return true if specified URL refers to a local
* project (ghidra:/path/projectName...)
*/
public static boolean isLocalProjectURL(URL url) {
return isLocalGhidraURL(url.toExternalForm());
}
/**
* Get the project locator which corresponds to the specified local project URL.
* Confirm local project URL with {@link #isLocalProjectURL(URL)} prior to method use.
* @param localProjectURL local Ghidra project URL
* @return project locator or null if invalid path specified
* @throws IllegalArgumentException URL is not a valid
* {@link #isLocalProjectURL(URL) local project URL}.
*/
public static ProjectLocator getProjectStorageLocator(URL localProjectURL) {
if (!isLocalProjectURL(localProjectURL)) {
throw new IllegalArgumentException("Invalid local Ghidra project URL");
}
String path = localProjectURL.getPath(); // assume path always starts with '/'
// if (path.indexOf(":/") == 2 && Character.isLetter(path.charAt(1))) { // check for drive letter after leading '/'
// if (Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.WINDOWS) {
// path = path.substring(1); // Strip-off leading '/'
// }
// else {
// // assume drive letter separator ':' should be removed for non-windows
// path = path.substring(0, 2) + path.substring(3);
// }
// }
int index = path.lastIndexOf('/');
String dirPath = index != 0 ? path.substring(0, index) : "/";
String name = path.substring(index + 1);
if (name.length() == 0) {
return null;
}
return new ProjectLocator(dirPath, name);
}
/**
* Get the shared repository name associated with a repository URL or null
* if not applicable. For ghidra URL extensions it is assumed that the first path element
* corresponds to the repository name.
* @param url ghidra URL for shared project resource
* @return repository name or null if not applicable to URL
*/
public static String getRepositoryName(URL url) {
if (!isServerRepositoryURL(url)) {
return null;
}
String path = url.getPath();
if (!path.startsWith("/")) {
// handle possible ghidra protocol extension use which is assumed to encode
// repository and file path the same as standard ghidra URL.
try {
URL extensionURL = new URL(path);
path = extensionURL.getPath();
}
catch (MalformedURLException e) {
path = "";
}
}
path = path.substring(1);
int ix = path.indexOf("/");
if (ix > 0) {
path = path.substring(0, ix);
}
return path;
}
/**
* Determine if the specified URL is any type of server "repository" URL.
* No checking is performed as to the existence of the server or repository.
* NOTE: ghidra protocol extensions are not currently supported (e.g., ghidra:http://...).
* @param url ghidra URL
* @return true if specified URL refers to a Ghidra server
* repository (ghidra://host/repositoryNAME/path...)
*/
public static boolean isServerRepositoryURL(URL url) {
if (!isServerURL(url)) {
return false;
}
String path = url.getPath();
if (StringUtils.isBlank(path)) {
return false;
}
if (!path.startsWith("/")) {
try {
URL extensionURL = new URL(path);
path = extensionURL.getPath();
if (StringUtils.isBlank(path)) {
return false;
}
}
catch (MalformedURLException e) {
return false;
}
}
return path.charAt(0) == '/' && path.length() > 1 && path.charAt(1) != '/';
}
/**
* Determine if the specified URL is any type of supported server Ghidra URL.
* No checking is performed as to the existence of the server or repository.
* @param url ghidra URL
* @return true if specified URL refers to a Ghidra server
* repository (ghidra://host/repositoryNAME/path...)
*/
public static boolean isServerURL(URL url) {
if (!PROTOCOL.equals(url.getProtocol())) {
return false;
}
return Handler.isSupportedURL(url);
}
/**
* Ensure that absolute path is specified and normalize its format.
* An absolute path may start with a windows drive letter (e.g., c:/a/b, /c:/a/b)
* or without (e.g., /a/b). Although for Windows the lack of a drive letter is
* not absolute, for consistency with Linux we permit this form which on
* Windows will use the default drive for the process. If path starts with a drive
* letter (e.g., "c:/") it will have a "/" prepended (e.g., "/c:/", both forms
* are treated the same by the {@link File} class under Windows).
* @param path path to be checked and possibly modified.
* @return path to be used
* @throws IllegalArgumentException if an invalid path is specified
*/
private static String checkAbsolutePath(String path) {
int scanIndex = 0;
path = path.replace('\\', '/');
int len = path.length();
if (!path.startsWith("/")) {
// Allow paths to start with windows drive letter (e.g., c:/a/b)
if (len >= 3 && hasAbsoluteDriveLetter(path, 0)) {
path = "/" + path;
}
else {
throw new IllegalArgumentException("absolute path required");
}
scanIndex = 3;
}
else if (len >= 3 && hasDriveLetter(path, 1)) {
if (len < 4 || path.charAt(3) != '/') {
// path such as "/c:" not permitted
throw new IllegalArgumentException("absolute path required");
}
scanIndex = 4;
}
checkInvalidChar("path", path, scanIndex);
return path;
}
private static boolean hasDriveLetter(String path, int index) {
return Character.isLetter(path.charAt(index++)) && path.charAt(index) == ':';
}
private static boolean hasAbsoluteDriveLetter(String path, int index) {
int pathIndex = index + 2;
return path.length() > pathIndex && hasDriveLetter(path, index) &&
path.charAt(pathIndex) == '/';
}
/**
* Check for characters explicitly disallowed in path or project name.
* @param type type of string to include in exception
* @param str string to check
* @param startIndex index at which to start checking
* @throws IllegalArgumentException if str contains invalid character
*/
private static void checkInvalidChar(String type, String str, int startIndex) {
for (int i = startIndex; i < str.length(); i++) {
char c = str.charAt(i);
if (ProjectLocator.DISALLOWED_CHARS.contains(c)) {
throw new IllegalArgumentException(
type + " contains invalid character: '" + c + "'");
}
}
}
/**
* Create a Ghidra URL from a string form of Ghidra URL or local project path.
* This method can consume strings produced by the getDisplayString method.
* @param projectPathOrURL {@literal project path (<absolute-directory>/<project-name>)} or
* string form of Ghidra URL.
* @return local Ghidra project URL
* @see #getDisplayString(URL)
* @throws IllegalArgumentException invalid path or URL specified
*/
public static URL toURL(String projectPathOrURL) {
if (!projectPathOrURL.startsWith(PROTOCOL + ":")) {
if (projectPathOrURL.endsWith(ProjectLocator.PROJECT_DIR_SUFFIX) ||
projectPathOrURL.endsWith(ProjectLocator.PROJECT_FILE_SUFFIX)) {
String ext = projectPathOrURL.substring(projectPathOrURL.lastIndexOf('.'));
throw new IllegalArgumentException("Project path must omit extension: " + ext);
}
if (projectPathOrURL.contains("?") || projectPathOrURL.contains("#")) {
throw new IllegalArgumentException("Unsupported query/ref used with project path");
}
projectPathOrURL = checkAbsolutePath(projectPathOrURL);
int minSplitIndex = projectPathOrURL.charAt(2) == ':' ? 3 : 0;
int splitIndex = projectPathOrURL.lastIndexOf('/');
if (splitIndex < minSplitIndex || projectPathOrURL.length() == (splitIndex + 1)) {
throw new IllegalArgumentException("Absolute project path is missing project name");
}
++splitIndex;
String location = projectPathOrURL.substring(0, splitIndex);
String projectName = projectPathOrURL.substring(splitIndex);
return makeURL(location, projectName);
}
try {
return new URL(projectPathOrURL);
}
catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Get Ghidra URL which corresponds to the local-project or repository with any
* file path or query details removed.
* @param ghidraUrl ghidra file/folder URL (server-only URL not permitted)
* @return local-project or repository URL
* @throws IllegalArgumentException if URL does not specify the {@code ghidra} protocol
* or does not properly identify a remote repository or local project.
*/
public static URL getProjectURL(URL ghidraUrl) {
if (!PROTOCOL.equals(ghidraUrl.getProtocol())) {
throw new IllegalArgumentException("ghidra protocol required");
}
if (isLocalProjectURL(ghidraUrl)) {
String urlStr = ghidraUrl.toExternalForm();
int queryIx = urlStr.indexOf('?');
if (queryIx < 0) {
return ghidraUrl;
}
urlStr = urlStr.substring(0, queryIx);
try {
return new URL(urlStr);
}
catch (MalformedURLException e) {
throw new RuntimeException(e); // unexpected
}
}
if (isServerRepositoryURL(ghidraUrl)) {
String path = ghidraUrl.getPath();
// handle possible ghidra protocol extension use which is assumed to encode
// repository and file path the same as standard ghidra URL.
if (!path.startsWith("/")) {
try {
URL extensionURL = new URL(path);
path = extensionURL.getPath();
}
catch (MalformedURLException e) {
path = "/";
}
}
// Truncate ghidra URL
String urlStr = ghidraUrl.toExternalForm();
String tail = null;
int ix = path.indexOf('/', 1);
if (ix > 0) {
// identify path tail to be removed
tail = path.substring(ix);
}
int refIx = urlStr.indexOf('#');
if (refIx > 0) {
urlStr = urlStr.substring(0, refIx);
}
int queryIx = urlStr.indexOf('?');
if (queryIx > 0) {
urlStr = urlStr.substring(0, queryIx);
}
if (tail != null) {
urlStr = urlStr.substring(0, urlStr.lastIndexOf(tail));
}
try {
return new URL(urlStr);
}
catch (MalformedURLException e) {
// ignore
}
}
throw new IllegalArgumentException("Invalid project/repository URL: " + ghidraUrl);
}
/**
* Get the project pathname referenced by the specified Ghidra file/folder URL.
* If path is missing root folder is returned.
* @param ghidraUrl ghidra file/folder URL (server-only URL not permitted)
* @return pathname of file or folder
*/
public static String getProjectPathname(URL ghidraUrl) {
if (isLocalProjectURL(ghidraUrl)) {
String query = ghidraUrl.getQuery();
return StringUtils.isBlank(query) ? "/" : query;
}
if (isServerRepositoryURL(ghidraUrl)) {
String path = ghidraUrl.getPath();
// handle possible ghidra protocol extension use
if (!path.startsWith("/")) {
try {
URL extensionURL = new URL(path);
path = extensionURL.getPath();
}
catch (MalformedURLException e) {
path = "/";
}
}
// skip repo name (first path element)
int ix = path.indexOf('/', 1);
if (ix > 1) {
return path.substring(ix);
}
return "/";
}
throw new IllegalArgumentException("not project/repository URL");
}
/**
* Get hostname as an IP address if possible
* @param host hostname
* @return host IP address or original host name
*/
private static String getHostAsIpAddress(String host) {
if (!StringUtils.isBlank(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostAddress();
}
catch (UnknownHostException e) {
// just use hostname if unable to resolve
}
}
return host;
}
/**
* Force the specified URL to specify a folder. This may be neccessary when only folders
* are supported since Ghidra permits both a folder and file to have the same name within
* its parent folder. This method simply ensures that the URL path ends with a {@code /}
* character if needed.
* @param ghidraUrl ghidra URL
* @return ghidra folder URL
* @throws IllegalArgumentException if specified URL is niether a
* {@link #isServerRepositoryURL(URL) valid remote server URL}
* or {@link #isLocalProjectURL(URL) local project URL}.
*/
public static URL getFolderURL(URL ghidraUrl) {
if (!GhidraURL.isServerRepositoryURL(ghidraUrl) &&
!GhidraURL.isLocalProjectURL(ghidraUrl)) {
throw new IllegalArgumentException("Invalid Ghidra URL: " + ghidraUrl);
}
URL repoURL = GhidraURL.getProjectURL(ghidraUrl);
String path = GhidraURL.getProjectPathname(ghidraUrl);
path = path.trim();
if (!path.endsWith("/")) {
// force explicit folder path
path += "/";
try {
if (GhidraURL.isServerRepositoryURL(ghidraUrl)) {
ghidraUrl = new URL(repoURL + path);
}
else {
ghidraUrl = new URL(repoURL + "?" + path);
}
}
catch (MalformedURLException e) {
throw new AssertionError(e);
}
}
return ghidraUrl;
}
/**
* Get a normalized URL which eliminates use of host names and optional URL ref
* which may prevent direct comparison.
* @param url ghidra URL
* @return normalized url
*/
public static URL getNormalizedURL(URL url) {
String host = url.getHost();
String revisedHost = getHostAsIpAddress(host);
if (Objects.equals(host, revisedHost) && url.getRef() == null) {
return url; // no change
}
String file = url.getPath();
String query = url.getQuery();
if (!StringUtils.isBlank(query)) {
file += "?" + query;
}
try {
return new URL(PROTOCOL, revisedHost, url.getPort(), file);
}
catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
/**
* Generate preferred display string for Ghidra URLs.
* Form can be parsed by the toURL method.
* @param url ghidra URL
* @return formatted URL display string
* @see #toURL(String)
*/
public static String getDisplayString(URL url) {
if (isLocalProjectURL(url) && StringUtils.isBlank(url.getQuery()) &&
StringUtils.isBlank(url.getRef())) {
String path = url.getPath();
if (path.indexOf(":/") == 2 && Character.isLetter(path.charAt(1))) {
// assume windows path
path = path.substring(1);
path = path.replace('/', '\\');
}
return path;
}
return url.toString();
}
/**
* Create a URL which refers to a local Ghidra project
* @param dirPath absolute path of project location directory
* @param projectName name of project
* @return local Ghidra project URL
*/
public static URL makeURL(String dirPath, String projectName) {
return makeURL(dirPath, projectName, null, null);
}
/**
* Create a URL which refers to a local Ghidra project
* @param projectLocator absolute project location
* @return local Ghidra project URL
* @throws IllegalArgumentException if {@code projectLocator} does not have an absolute location
*/
public static URL makeURL(ProjectLocator projectLocator) {
return makeURL(projectLocator, null, null);
}
/**
* Create a URL which refers to a local Ghidra project with optional project file and ref
* @param projectLocation absolute path of project location directory
* @param projectName name of project
* @param projectFilePath file path (e.g., /a/b/c, may be null)
* @param ref location reference (may be null)
* @return local Ghidra project URL
* @throws IllegalArgumentException if an absolute projectLocation path is not specified
*/
public static URL makeURL(String projectLocation, String projectName, String projectFilePath,
String ref) {
if (StringUtils.isBlank(projectLocation) || StringUtils.isBlank(projectName)) {
throw new IllegalArgumentException("Invalid project location and/or name");
}
String path = checkAbsolutePath(projectLocation);
if (!path.endsWith("/")) {
path += "/";
}
StringBuilder buf = new StringBuilder(PROTOCOL);
buf.append(":");
buf.append(path);
buf.append(projectName);
if (!StringUtils.isBlank(projectFilePath)) {
if (!projectFilePath.startsWith("/") || projectFilePath.contains("\\")) {
throw new IllegalArgumentException("Invalid project file path");
}
buf.append("?");
buf.append(projectFilePath);
}
if (!StringUtils.isBlank(ref)) {
buf.append("#");
buf.append(ref);
}
try {
return new URL(buf.toString());
}
catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Create a URL which refers to a local Ghidra project with optional project file and ref
* @param projectLocator local project locator
* @param projectFilePath file path (e.g., /a/b/c, may be null)
* @param ref location reference (may be null)
* @return local Ghidra project URL
* @throws IllegalArgumentException if invalid {@code projectFilePath} specified or if URL
* instantion fails.
*/
public static URL makeURL(ProjectLocator projectLocator, String projectFilePath, String ref) {
return makeURL(projectLocator.getLocation(), projectLocator.getName(), projectFilePath,
ref);
}
private static String[] splitOffName(String path) {
String name = "";
if (!StringUtils.isBlank(path) && !path.endsWith("/")) {
int index = path.lastIndexOf('/');
if (index >= 0) {
// last name may or may not be a folder name
name = path.substring(index + 1);
path = path.substring(0, index);
}
}
return new String[] { path, name };
}
/**
* Create a URL which refers to Ghidra Server repository content. Path may correspond
* to either a file or folder.
* @param host server host name/address
* @param port optional server port (a value <= 0 refers to the default port)
* @param repositoryName repository name
* @param repositoryPath absolute folder or file path within repository.
* Folder paths should end with a '/' character.
* @return Ghidra Server repository content URL
*/
public static URL makeURL(String host, int port, String repositoryName, String repositoryPath) {
String[] splitName = splitOffName(repositoryPath);
return makeURL(host, port, repositoryName, splitName[0], splitName[1], null);
}
/**
* Create a URL which refers to Ghidra Server repository content. Path may correspond
* to either a file or folder.
* @param host server host name/address
* @param port optional server port (a value <= 0 refers to the default port)
* @param repositoryName repository name
* @param repositoryPath absolute folder or file path within repository.
* @param ref ref or null
* Folder paths should end with a '/' character.
* @return Ghidra Server repository content URL
*/
public static URL makeURL(String host, int port, String repositoryName, String repositoryPath,
String ref) {
String[] splitName = splitOffName(repositoryPath);
return makeURL(host, port, repositoryName, splitName[0], splitName[1], ref);
}
/**
* Create a URL which refers to Ghidra Server repository content. Path may correspond
* to either a file or folder.
* @param host server host name/address
* @param port optional server port (a value <= 0 refers to the default port)
* @param repositoryName repository name
* @param repositoryFolderPath absolute folder path within repository.
* @param fileName name of a file or folder contained within the specified {@code repositoryFolderPath}
* @param ref optional URL ref or null
* Folder paths should end with a '/' character.
* @return Ghidra Server repository content URL
* @throws IllegalArgumentException if required arguments are blank or invalid
*/
public static URL makeURL(String host, int port, String repositoryName,
String repositoryFolderPath, String fileName, String ref) {
if (StringUtils.isBlank(host)) {
throw new IllegalArgumentException("host required");
}
if (StringUtils.isBlank(repositoryName)) {
throw new IllegalArgumentException("repository name required");
}
if (port == 0 || port == GhidraServerHandle.DEFAULT_PORT) {
port = -1;
}
String path = "/" + repositoryName;
if (!StringUtils.isBlank(repositoryFolderPath)) {
if (!repositoryFolderPath.startsWith("/") || repositoryFolderPath.indexOf('\\') >= 0) {
throw new IllegalArgumentException("Invalid repository path");
}
path += repositoryFolderPath;
if (!path.endsWith("/")) {
path += "/";
}
}
if (!StringUtils.isBlank(fileName)) {
if (fileName.contains("/")) {
throw new IllegalArgumentException("Invalid folder/file name: " + fileName);
}
if (!path.endsWith("/")) {
path += "/";
}
path += fileName;
}
if (!StringUtils.isBlank(ref)) {
path += "#" + ref;
}
try {
return new URL(PROTOCOL, host, port, path);
}
catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Create a URL which refers to Ghidra Server repository and its root folder
* @param host server host name/address
* @param port optional server port (a value <= 0 refers to the default port)
* @param repositoryName repository name
* @return Ghidra Server repository URL
*/
public static URL makeURL(String host, int port, String repositoryName) {
return makeURL(host, port, repositoryName, null);
}
}
| NationalSecurityAgency/ghidra | Ghidra/Framework/Project/src/main/java/ghidra/framework/protocol/ghidra/GhidraURL.java |
724 | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import org.tillerino.ppaddict.chat.GameChatResponse;
import org.tillerino.ppaddict.chat.GameChatResponse.Action;
import org.tillerino.ppaddict.chat.GameChatResponse.Message;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands extends AbstractMutableLanguage {
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...ben jij dat? Dat is lang geleden!"))
.then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?"));
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
String message = messages[ThreadLocalRandom.current().nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public GameChatResponse hug(OsuApiUser apiUser) {
return new Message("Kom eens hier jij!")
.then(new Action("knuffelt " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current());
@Override
public String apiTimeoutException() {
registerModification();
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + apiTimeoutShuffler.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.",
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
}
| Tillerino/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java |
725 | package com.hbm.inventory.material;
import static com.hbm.inventory.OreDictManager.*;
import static com.hbm.inventory.material.MaterialShapes.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import com.hbm.inventory.OreDictManager.DictFrame;
import com.hbm.inventory.RecipesCommon.ComparableStack;
import com.hbm.inventory.material.NTMMaterial.SmeltingBehavior;
import com.hbm.items.ModItems;
import com.hbm.util.I18nUtil;
import com.hbm.util.ItemStackUtil;
import net.minecraft.item.ItemStack;
/* with every new rewrite, optimization and improvement, the code becomes more gregian */
/**
* Defines materials that wrap around DictFrames to more accurately describe that material.
* Direct uses are the crucible and possibly item auto-gen, depending on what traits are set.
* @author hbm
*/
public class Mats {
public static List<NTMMaterial> orderedList = new ArrayList();
public static HashMap<String, MaterialShapes> prefixByName = new HashMap();
public static HashMap<Integer, NTMMaterial> matById = new HashMap();
public static HashMap<String, NTMMaterial> matByName = new HashMap();
//public static HashMap<String, NTMMaterial> matRemap = new HashMap();
public static HashMap<ComparableStack, List<MaterialStack>> materialEntries = new HashMap();
public static HashMap<String, List<MaterialStack>> materialOreEntries = new HashMap();
/*
* ItemStacks are saved with their metadata being truncated to a short, so the max meta is 32767
* Format for elements: Atomic number *100, plus the last two digits of the mass number. Mass number is 0 for generic/undefined/mixed materials.
* Vanilla numbers are in vanilla space (0-29), basic alloys use alloy space (30-99)
*/
/* Vanilla Space, up to 30 materials, */
public static final int _VS = 0;
/* Alloy Space, up to 70 materials. Use >20_000 as an extension.*/
public static final int _AS = 30;
//Vanilla and vanilla-like
public static final NTMMaterial MAT_STONE = makeSmeltable(_VS + 00, df("Stone"), 0x4D2F23).omitAutoGen();
public static final NTMMaterial MAT_CARBON = makeAdditive( 1499, df("Carbon"), 0x404040).omitAutoGen();
public static final NTMMaterial MAT_COAL = make( 1400, COAL) .setConversion(MAT_CARBON, 2, 1).omitAutoGen();
public static final NTMMaterial MAT_LIGNITE = make( 1401, LIGNITE) .setConversion(MAT_CARBON, 3, 1);
public static final NTMMaterial MAT_COALCOKE = make( 1410, COALCOKE) .setConversion(MAT_CARBON, 4, 3);
public static final NTMMaterial MAT_PETCOKE = make( 1411, PETCOKE) .setConversion(MAT_CARBON, 4, 3);
public static final NTMMaterial MAT_LIGCOKE = make( 1412, LIGCOKE) .setConversion(MAT_CARBON, 4, 3);
public static final NTMMaterial MAT_GRAPHITE = make( 1420, GRAPHITE) .setConversion(MAT_CARBON, 1, 1);
public static final NTMMaterial MAT_IRON = makeSmeltable(2600, IRON, 0xFFA259).omitAutoGen();
public static final NTMMaterial MAT_GOLD = makeSmeltable(7900, GOLD, 0xE8D754).omitAutoGen();
public static final NTMMaterial MAT_REDSTONE = makeSmeltable(_VS + 01, REDSTONE, 0xFF1000).omitAutoGen();
public static final NTMMaterial MAT_OBSIDIAN = makeSmeltable(_VS + 02, df("Obsidian"), 0x3D234D).omitAutoGen();
public static final NTMMaterial MAT_HEMATITE = makeAdditive( 2601, HEMATITE, 0x6E463D).omitAutoGen();
public static final NTMMaterial MAT_MALACHITE = makeAdditive( 2901, MALACHITE, 0x61AF87).omitAutoGen();
//Radioactive
public static final NTMMaterial MAT_URANIUM = makeSmeltable(9200, U, 0x9AA196).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_U233 = makeSmeltable(9233, U233, 0x9AA196).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_U235 = makeSmeltable(9235, U235, 0x9AA196).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_U238 = makeSmeltable(9238, U238, 0x9AA196).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_THORIUM = makeSmeltable(9032, TH232, 0xBF825F).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_PLUTONIUM = makeSmeltable(9400, PU, 0x78817E).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_RGP = makeSmeltable(9401, PURG, 0x78817E).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_PU238 = makeSmeltable(9438, PU238, 0x78817E).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_PU239 = makeSmeltable(9439, PU239, 0x78817E).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_PU240 = makeSmeltable(9440, PU240, 0x78817E).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_PU241 = makeSmeltable(9441, PU241, 0x78817E).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_RGA = makeSmeltable(9501, AMRG, 0x93767B).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_AM241 = makeSmeltable(9541, AM241, 0x93767B).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_AM242 = makeSmeltable(9542, AM242, 0x93767B).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_NEPTUNIUM = makeSmeltable(9337, NP237, 0x647064).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_POLONIUM = makeSmeltable(8410, PO210, 0x563A26).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_TECHNIETIUM = makeSmeltable(4399, TC99, 0xCADFDF).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_RADIUM = makeSmeltable(8826, RA226, 0xE9FAF6).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_ACTINIUM = makeSmeltable(8927, AC227, 0x958989).setShapes(NUGGET, BILLET, INGOT);
public static final NTMMaterial MAT_CO60 = makeSmeltable(2760, CO60, 0x8F72AE).setShapes(NUGGET, BILLET, INGOT, DUST);
public static final NTMMaterial MAT_AU198 = makeSmeltable(7998, AU198, 0xE8D754).setShapes(NUGGET, BILLET, INGOT, DUST);
public static final NTMMaterial MAT_PB209 = makeSmeltable(8209, PB209, 0x7B535D).setShapes(NUGGET, BILLET, INGOT, DUST);
public static final NTMMaterial MAT_SCHRABIDIUM = makeSmeltable(12626, SA326, 0x32FFFF).setShapes(NUGGET, WIRE, BILLET, INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_SOLINIUM = makeSmeltable(12627, SA327, 0x72B6B0).setShapes(NUGGET, BILLET, INGOT, BLOCK);
public static final NTMMaterial MAT_SCHRABIDATE = makeSmeltable(12600, SBD, 0x6589B4).setShapes(INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_SCHRARANIUM = makeSmeltable(12601, SRN, 0x24AFAC).setShapes(INGOT, BLOCK);
public static final NTMMaterial MAT_GHIORSIUM = makeSmeltable(12836, GH336, 0xC6C6A1).setShapes(NUGGET, BILLET, INGOT, BLOCK);
//Base metals
public static final NTMMaterial MAT_TITANIUM = makeSmeltable(2200, TI, 0xA99E79).setShapes(INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_COPPER = makeSmeltable(2900, CU, 0xC18336).setShapes(WIRE, INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_TUNGSTEN = makeSmeltable(7400, W, 0x977474).setShapes(WIRE, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_ALUMINIUM = makeSmeltable(1300, AL, 0xD0B8EB).setShapes(WIRE, INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_LEAD = makeSmeltable(8200, PB, 0x646470).setShapes(NUGGET, INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_BISMUTH = makeSmeltable(8300, df("Bismuth"), 0xB200FF).setShapes(NUGGET, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_ARSENIC = makeSmeltable(3300, AS, 0x558080).setShapes(NUGGET, INGOT);
public static final NTMMaterial MAT_TANTALIUM = makeSmeltable(7300, TA, 0xA89B74).setShapes(NUGGET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_NIOBIUM = makeSmeltable(4100, NB, 0xD576B1).setShapes(NUGGET, DUSTTINY, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_BERYLLIUM = makeSmeltable(400, BE, 0xAE9572).setShapes(NUGGET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_COBALT = makeSmeltable(2700, CO, 0x8F72AE).setShapes(NUGGET, DUSTTINY, BILLET, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_BORON = makeSmeltable(500, B, 0xAD72AE).setShapes(DUSTTINY, INGOT, DUST, BLOCK);
//Alloys
public static final NTMMaterial MAT_STEEL = makeSmeltable(_AS + 0, STEEL, 0x4A4A4A).setShapes(DUSTTINY, INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_MINGRADE = makeSmeltable(_AS + 1, MINGRADE, 0xE44C0F).setShapes(WIRE, INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_ALLOY = makeSmeltable(_AS + 2, ALLOY, 0xFF7318).setShapes(WIRE, INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_DURA = makeSmeltable(_AS + 3, DURA, 0x376373).setShapes(INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_SATURN = makeSmeltable(_AS + 4, BIGMT, 0x4DA3AF).setShapes(INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_STAR = makeSmeltable(_AS + 5, STAR, 0xA5A5D3).setShapes(INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_TCALLOY = makeSmeltable(_AS + 6, TCALLOY, 0x9CA6A6).setShapes(INGOT, DUST);
public static final NTMMaterial MAT_FERRO = makeSmeltable(_AS + 7, FERRO, 0x6B6B8B).setShapes(INGOT);
public static final NTMMaterial MAT_MAGTUNG = makeSmeltable(_AS + 8, MAGTUNG, 0x22A2A2).setShapes(INGOT, DUST, BLOCK);
public static final NTMMaterial MAT_CMB = makeSmeltable(_AS + 9, CMB, 0x6F6FB4).setShapes(INGOT, DUST, PLATE, BLOCK);
public static final NTMMaterial MAT_FLUX = makeAdditive(_AS + 10, df("Flux"), 0xDECCAD).setShapes(DUST);
public static final NTMMaterial MAT_SLAG = makeSmeltable(_AS + 11, SLAG, 0x6C6562).setShapes(BLOCK);
public static NTMMaterial make(int id, DictFrame dict) {
return new NTMMaterial(id, dict);
}
public static NTMMaterial makeSmeltable(int id, DictFrame dict, int color) {
return new NTMMaterial(id, dict).smeltable(SmeltingBehavior.SMELTABLE).setMoltenColor(color);
}
public static NTMMaterial makeAdditive(int id, DictFrame dict, int color) {
return new NTMMaterial(id, dict).smeltable(SmeltingBehavior.ADDITIVE).setMoltenColor(color);
}
public static DictFrame df(String string) {
return new DictFrame(string);
}
/** will not respect stacksizes - all stacks will be treated as a singular */
public static List<MaterialStack> getMaterialsFromItem(ItemStack stack) {
List<MaterialStack> list = new ArrayList();
List<String> names = ItemStackUtil.getOreDictNames(stack);
if(!names.isEmpty()) {
outer:
for(String name : names) {
List<MaterialStack> oreEntries = materialOreEntries.get(name);
if(oreEntries != null) {
list.addAll(oreEntries);
break outer;
}
for(Entry<String, MaterialShapes> prefixEntry : prefixByName.entrySet()) {
String prefix = prefixEntry.getKey();
if(name.startsWith(prefix)) {
String materialName = name.substring(prefix.length());
NTMMaterial material = matByName.get(materialName);
if(material != null) {
list.add(new MaterialStack(material, prefixEntry.getValue().q(1)));
break outer;
}
}
}
}
}
List<MaterialStack> entries = materialEntries.get(new ComparableStack(stack).makeSingular());
if(entries != null) {
list.addAll(entries);
}
/*
for when crucible becomes real
if(stack.getItem() == ModItems.scraps) {
list.add(ItemScraps.getMats(stack));
}*/
return list;
}
public static List<MaterialStack> getSmeltingMaterialsFromItem(ItemStack stack) {
List<MaterialStack> baseMats = getMaterialsFromItem(stack);
List<MaterialStack> smelting = new ArrayList();
baseMats.forEach(x -> smelting.add(new MaterialStack(x.material.smeltsInto, (int) (x.amount * x.material.convOut / x.material.convIn))));
return smelting;
}
public static class MaterialStack {
//final fields to prevent accidental changing
public final NTMMaterial material;
public int amount;
public MaterialStack(NTMMaterial material, int amount) {
this.material = material;
this.amount = amount;
}
public MaterialStack copy() {
return new MaterialStack(material, amount);
}
}
public static String formatAmount(int amount, boolean showInMb) {
if(showInMb) {
return (amount * 2) + "mB";
}
String format = "";
int blocks = amount / BLOCK.q(1);
amount -= BLOCK.q(blocks);
int ingots = amount / INGOT.q(1);
amount -= INGOT.q(ingots);
int nuggets = amount / NUGGET.q(1);
amount -= NUGGET.q(nuggets);
int quanta = amount;
if(blocks > 0) format += (blocks == 1 ? I18nUtil.resolveKey("matshape.block", blocks) : I18nUtil.resolveKey("matshape.blocks", blocks)) + " ";
if(ingots > 0) format += (ingots == 1 ? I18nUtil.resolveKey("matshape.ingot", ingots) : I18nUtil.resolveKey("matshape.ingots", ingots)) + " ";
if(nuggets > 0) format += (nuggets == 1 ? I18nUtil.resolveKey("matshape.nugget", nuggets) : I18nUtil.resolveKey("matshape.nuggets", nuggets)) + " ";
if(quanta > 0) format += (quanta == 1 ? I18nUtil.resolveKey("matshape.quantum", quanta) : I18nUtil.resolveKey("matshape.quanta", quanta)) + " ";
return format.trim();
}
}
| Alcatergit/Hbm-s-Nuclear-Tech-GIT | src/main/java/com/hbm/inventory/material/Mats.java |
726 | public class questions {
public void dfs_numIsland(char[][] grid, int r, int c, int[][] dir) {
grid[r][c] = '0';
for (int d = 0; d < dir.length; d++) {
int x = r + dir[d][0];
int y = c + dir[d][1];
if (x >= 0 && y >= 0 && x < grid.length && y < grid[0].length && grid[x][y] == '1') {
dfs_numIsland(grid, x, y, dir);
}
}
}
public int numIslands(char[][] grid) {
int n = grid.length, m = grid[0].length, components = 0;
int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1') {
components++;
dfs_numIsland(grid, i, j, dir);
}
}
}
return components;
}
// 695
public int dfs_Area(int[][] grid, int r, int c, int[][] dir) {
grid[r][c] = 0;
int size = 0;
for (int d = 0; d < 4; d++) {
int x = r + dir[d][0];
int y = c + dir[d][1];
if (x >= 0 && y >= 0 && x < grid.length && y < grid[0].length && grid[x][y] == 1)
size += dfs_Area(grid, x, y, dir);
}
return size + 1;
}
public int maxAreaOfIsland(int[][] grid) {
int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };
int maxSize = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
maxSize = Math.max(maxSize, dfs_Area(grid, i, j, dir));
}
}
}
return maxSize;
}
// 785
public boolean isBipartite(int[][] graph, int src, int[] vis) {
LinkedList<Integer> que = new LinkedList<>();
que.addLast(src);
int color = 0;
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
if (vis[rvtx] != -1) {
if (vis[rvtx] != color)
return false;
continue;
}
vis[rvtx] = color;
for (int e : graph[rvtx])
if (vis[e] == -1)
que.addLast(e);
}
color = (color + 1) % 2;
}
return true;
}
public boolean isBipartite(int[][] graph) {
int[] vis = new int[graph.length];
Arrays.fill(vis, -1);
for (int i = 0; i < vis.length; i++) {
if (vis[i] == -1) {
if (!isBipartite(graph, i, vis))
return false;
}
}
return true;
}
// 994
public int orangesRotting(int[][] grid) {
LinkedList<Integer> que = new LinkedList<>();
int n = grid.length, m = grid[0].length;
int freshOranges = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (grid[i][j] == 1)
freshOranges++;
else if (grid[i][j] == 2)
que.addLast(i * m + j);
if (freshOranges == 0)
return 0;
int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
int time = 0;
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int idx = que.removeFirst();
int r = idx / m;
int c = idx % m;
for (int d = 0; d < 4; d++) {
int x = r + dir[d][0];
int y = c + dir[d][1];
if (x >= 0 && y >= 0 && x < n && y < m && grid[x][y] == 1) {
grid[x][y] = 2;
freshOranges--;
if (freshOranges == 0)
return time + 1;
que.addLast(x * m + y);
}
}
}
time++;
}
return -1;
}
} | pankajmahato/pepcoding-Batches | 2020/NIET/graph/questions.java |
727 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.apps;
import java.util.ListResourceBundle;
/**
* Base Resource Bundle
*
* @author Eldir Tomassen
* @version $Id: ALoginRes_nl.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $
*/
public final class ALoginRes_nl extends ListResourceBundle
{
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Verbinding" },
{ "Defaults", "Standaard" },
{ "Login", "Aanmelden bij ADempiere" },
{ "File", "Bestand" },
{ "Exit", "Afsluiten" },
{ "Help", "Help" },
{ "About", "Info" },
{ "Host", "Server" },
{ "Database", "Database" },
{ "User", "Gebruikersnaam" },
{ "EnterUser", "Voer uw gebruikersnaam in" },
{ "Password", "Wachtwoord" },
{ "EnterPassword", "Voer uw wachtwoord in" },
{ "Language", "Taal" },
{ "SelectLanguage", "Selecteer uw taal" },
{ "Role", "Rol" },
{ "Client", "Client" },
{ "Organization", "Organisatie" },
{ "Date", "Datum" },
{ "Warehouse", "Magazijn" },
{ "Printer", "Printer" },
{ "Connected", "Verbonden" },
{ "NotConnected", "Niet verbonden" },
{ "DatabaseNotFound", "Database niet gevonden" },
{ "UserPwdError", "Foute gebruikersnaam of wachtwoord" },
{ "RoleNotFound", "Rol niet gevonden of incompleet" },
{ "Authorized", "Geautoriseerd" },
{ "Ok", "Ok" },
{ "Cancel", "Annuleren" },
{ "VersionConflict", "Versie Conflict:" },
{ "VersionInfo", "Server <> Client" },
{ "PleaseUpgrade", "Uw ADempiere installatie dient te worden bijgewerkt." }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes
| alhudaghifari/adempiere | client/src/org/compiere/apps/ALoginRes_nl.java |
728 | package net.sourceforge.kolmafia.objectpool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import net.sourceforge.kolmafia.AdventureResult;
import net.sourceforge.kolmafia.KoLCharacter;
import net.sourceforge.kolmafia.KoLConstants;
import net.sourceforge.kolmafia.persistence.ItemDatabase;
import net.sourceforge.kolmafia.preferences.Preferences;
public class ItemPool {
public static final int SEAL_CLUB = 1;
public static final int SEAL_TOOTH = 2;
public static final int HELMET_TURTLE = 3;
public static final int TURTLE_TOTEM = 4;
public static final int PASTA_SPOON = 5;
public static final int RAVIOLI_HAT = 6;
public static final int SAUCEPAN = 7;
public static final int SPICES = 8;
public static final int DISCO_MASK = 9;
public static final int DISCO_BALL = 10;
public static final int STOLEN_ACCORDION = 11;
public static final int MARIACHI_PANTS = 12;
public static final int WORTHLESS_ITEM = 13; // Pseudo item
public static final int MOXIE_WEED = 14;
public static final int ASPARAGUS_KNIFE = 19;
public static final int CHEWING_GUM = 23;
public static final int TEN_LEAF_CLOVER = 24;
public static final int MEAT_PASTE = 25;
public static final int DOLPHIN_KING_MAP = 26;
public static final int SPIDER_WEB = 27;
public static final int BIG_ROCK = 30;
public static final int BJORNS_HAMMER = 32;
public static final int CASINO_PASS = 40;
public static final int SCHLITZ = 41;
public static final int HERMIT_PERMIT = 42;
public static final int WORTHLESS_TRINKET = 43;
public static final int WORTHLESS_GEWGAW = 44;
public static final int WORTHLESS_KNICK_KNACK = 45;
public static final int WOODEN_FIGURINE = 46;
public static final int BUTTERED_ROLL = 47;
public static final int ROCK_N_ROLL_LEGEND = 50;
public static final int BANJO_STRINGS = 52;
public static final int STONE_BANJO = 53;
public static final int DISCO_BANJO = 54;
public static final int JABANERO_PEPPER = 55;
public static final int FIVE_ALARM_SAUCEPAN = 57;
public static final int MACE_OF_THE_TORTOISE = 60;
public static final int FORTUNE_COOKIE = 61;
public static final int GOLDEN_TWIG = 66;
public static final int PASTA_SPOON_OF_PERIL = 68;
public static final int NEWBIESPORT_TENT = 69;
public static final int BAR_SKIN = 70;
public static final int WOODEN_STAKES = 71;
public static final int BARSKIN_TENT = 73;
public static final int SPOOKY_MAP = 74;
public static final int SPOOKY_SAPLING = 75;
public static final int SPOOKY_FERTILIZER = 76;
public static final int PRETTY_BOUQUET = 78;
public static final int GRAVY_BOAT = 80;
public static final int WILLER = 81;
public static final int LOCKED_LOCKER = 84;
public static final int TBONE_KEY = 86;
public static final int MEAT_FROM_YESTERDAY = 87;
public static final int MEAT_STACK = 88;
public static final int MEAT_GOLEM = 101;
public static final int SCARECROW = 104;
public static final int KETCHUP = 106;
public static final int CATSUP = 107;
public static final int SPRING = 118;
public static final int SPROCKET = 119;
public static final int COG = 120;
public static final int GNOLLISH_AUTOPLUNGER = 127;
public static final int FRILLY_SKIRT = 131;
public static final int BITCHIN_MEATCAR = 134;
public static final int SWEET_RIMS = 135;
public static final int ICE_COLD_SIX_PACK = 138;
public static final int VALUABLE_TRINKET = 139;
public static final int DINGY_PLANKS = 140;
public static final int DINGY_DINGHY = 141;
public static final int ANTICHEESE = 142;
public static final int COTTAGE = 143;
public static final int BARBED_FENCE = 145;
public static final int DINGHY_PLANS = 146;
public static final int SCALP_OF_GORGOLOK = 150;
public static final int ELDER_TURTLE_SHELL = 151;
public static final int COLANDER_OF_EMERIL = 152;
public static final int ANCIENT_SAUCEHELM = 153;
public static final int DISCO_FRO_PICK = 154;
public static final int EL_SOMBRERO_DE_LOPEZ = 155;
public static final int RANGE = 157;
public static final int DOUGH = 159;
public static final int SKELETON_BONE = 163;
public static final int BONE_RATTLE = 168;
public static final int TACO_SHELL = 173;
public static final int BRIEFCASE = 184;
public static final int FAT_STACKS_OF_CASH = 185;
public static final int ENCHANTED_BEAN = 186;
public static final int LOOSE_TEETH = 187;
public static final int BAT_GUANO = 188;
public static final int BATSKIN_BELT = 191;
public static final int MR_ACCESSORY = 194;
public static final int DISASSEMBLED_CLOVER = 196;
public static final int RAT_WHISKER = 197;
public static final int FENG_SHUI = 210;
public static final int FOUNTAIN = 211;
public static final int WINDCHIMES = 212;
public static final int DREADSACK = 214;
public static final int HEMP_STRING = 218;
public static final int EYEPATCH = 224;
public static final int PUNGENT_UNGUENT = 231;
public static final int COCKTAIL_KIT = 236;
public static final int TOMATO = 246;
public static final int MARTINI = 251;
public static final int DENSE_STACK = 258;
public static final int MULLET_WIG = 267;
public static final int PICKET_FENCE = 270;
public static final int MOSQUITO_LARVA = 275;
public static final int PICKOMATIC_LOCKPICKS = 280;
public static final int BORIS_KEY = 282;
public static final int JARLSBERG_KEY = 283;
public static final int SNEAKY_PETE_KEY = 284;
public static final int RUBBER_AXE = 292;
public static final int FLAT_DOUGH = 301;
public static final int DRY_NOODLES = 304;
public static final int KNOB_GOBLIN_PERFUME = 307;
public static final int KNOB_GOBLIN_HELM = 308;
public static final int KNOB_GOBLIN_PANTS = 309;
public static final int KNOB_GOBLIN_POLEARM = 310;
public static final int KNOB_GOBLIN_CROWN = 313;
public static final int GOAT_CHEESE = 322;
public static final int PLAIN_PIZZA = 323;
public static final int SAUSAGE_PIZZA = 324;
public static final int GOAT_CHEESE_PIZZA = 325;
public static final int MUSHROOM_PIZZA = 326;
public static final int TENDER_HAMMER = 338;
public static final int LAB_KEY = 339;
public static final int SELTZER = 344;
public static final int REAGENT = 346;
public static final int DYSPEPSI_COLA = 347;
public static final int MINERS_HELMET = 360;
public static final int MINERS_PANTS = 361;
public static final int MATTOCK = 362;
public static final int LINOLEUM_ORE = 363;
public static final int ASBESTOS_ORE = 364;
public static final int CHROME_ORE = 365;
public static final int YETI_FUR = 388;
public static final int PENGUIN_SKIN = 393;
public static final int YAK_SKIN = 394;
public static final int HIPPOPOTAMUS_SKIN = 395;
public static final int ACOUSTIC_GUITAR = 404;
public static final int PIRATE_CHEST = 405;
public static final int PIRATE_PELVIS = 406;
public static final int PIRATE_SKULL = 407;
public static final int JOLLY_CHARRRM = 411;
public static final int JOLLY_BRACELET = 413;
public static final int BEANBAG_CHAIR = 429;
public static final int LONG_SKINNY_BALLOON = 433;
public static final int BALLOON_MONKEY = 436;
public static final int CHEF = 438;
public static final int BARTENDER = 440;
public static final int BEER_LENS = 443;
public static final int PRETENTIOUS_PAINTBRUSH = 450;
public static final int PRETENTIOUS_PALETTE = 451;
public static final int RUSTY_SCREWDRIVER = 454;
public static final int DRY_MARTINI = 456;
public static final int TRANSFUNCTIONER = 458;
public static final int WHITE_PIXEL = 459;
public static final int BLACK_PIXEL = 460;
public static final int RED_PIXEL = 461;
public static final int GREEN_PIXEL = 462;
public static final int BLUE_PIXEL = 463;
public static final int RED_PIXEL_POTION = 464;
public static final int RUBY_W = 468;
public static final int HOT_WING = 471;
public static final int DODECAGRAM = 479;
public static final int CANDLES = 480;
public static final int BUTTERKNIFE = 481;
public static final int MR_CONTAINER = 482;
public static final int NEWBIESPORT_BACKPACK = 483;
public static final int HEMP_BACKPACK = 484;
public static final int SNAKEHEAD_CHARM = 485;
public static final int TALISMAN = 486;
public static final int KETCHUP_HOUND = 493;
public static final int PAPAYA = 498;
public static final int ELF_FARM_RAFFLE_TICKET = 500;
public static final int PAGODA_PLANS = 502;
public static final int HEAVY_METAL_GUITAR = 507;
public static final int HEY_DEZE_NUTS = 509;
public static final int BORIS_PIE = 513;
public static final int JARLSBERG_PIE = 514;
public static final int SNEAKY_PETE_PIE = 515;
public static final int HEY_DEZE_MAP = 516;
public static final int MMJ = 518;
public static final int MOXIE_MAGNET = 519;
public static final int STRANGE_LEAFLET = 520;
public static final int HOUSE = 526;
public static final int VOLLEYBALL = 527;
public static final int SPECIAL_SAUCE_GLOVE = 531;
public static final int ABRIDGED = 534;
public static final int BRIDGE = 535;
public static final int DICTIONARY = 536;
public static final int LOWERCASE_N = 539;
public static final int SCROLL_334 = 547;
public static final int SCROLL_668 = 548;
public static final int SCROLL_30669 = 549;
public static final int SCROLL_33398 = 550;
public static final int SCROLL_64067 = 551;
public static final int GATES_SCROLL = 552;
public static final int ELITE_SCROLL = 553;
public static final int CAN_LID = 559;
public static final int SONAR = 563;
public static final int HERMIT_SCRIPT = 567;
public static final int LUCIFER = 571;
public static final int HELL_RAMEN = 578;
public static final int FETTUCINI_INCONNU = 583;
public static final int SPAGHETTI_WITH_SKULLHEADS = 584;
public static final int GNOCCHETTI_DI_NIETZSCHE = 585;
public static final int REMEDY = 588;
public static final int TINY_HOUSE = 592;
public static final int PHONICS_DOWN = 593;
public static final int EXTREME_AMULET = 594;
public static final int DRASTIC_HEALING = 595;
public static final int TITANIUM_UMBRELLA = 596;
public static final int MOHAWK_WIG = 597;
public static final int SLUG_LORD_MAP = 598;
public static final int DR_HOBO_MAP = 601;
public static final int SHOPPING_LIST = 602;
public static final int TISSUE_PAPER_IMMATERIA = 605;
public static final int TIN_FOIL_IMMATERIA = 606;
public static final int GAUZE_IMMATERIA = 607;
public static final int PLASTIC_WRAP_IMMATERIA = 608;
public static final int SOCK = 609;
public static final int HEAVY_D = 611;
public static final int CHAOS_BUTTERFLY = 615;
public static final int FURRY_FUR = 616;
public static final int GIANT_NEEDLE = 619;
public static final int BLACK_CANDLE = 620;
public static final int WARM_SUBJECT = 621;
public static final int AWFUL_POETRY_JOURNAL = 622;
public static final int WA = 623;
public static final int NG = 624;
public static final int WAND_OF_NAGAMAR = 626;
public static final int ND = 627;
public static final int METALLIC_A = 628;
public static final int MEAT_GLOBE = 636;
public static final int TOASTER = 637;
public static final int TOAST = 641;
public static final int SKELETON_KEY = 642;
public static final int SKELETON_KEY_RING = 643;
public static final int ROWBOAT = 653;
public static final int STAR = 654;
public static final int LINE = 655;
public static final int STAR_CHART = 656;
public static final int STAR_SWORD = 657;
public static final int STAR_CROSSBOW = 658;
public static final int STAR_STAFF = 659;
public static final int STAR_HAT = 661;
public static final int STAR_STARFISH = 664;
public static final int STAR_KEY = 665;
public static final int STEAMING_EVIL = 666;
public static final int GIANT_CASTLE_MAP = 667;
public static final int CRANBERRIES = 672;
public static final int BONERDAGON_SKULL = 675;
public static final int DRAGONBONE_BELT_BUCKLE = 676;
public static final int BADASS_BELT = 677;
public static final int BONERDAGON_CHEST = 678;
public static final int DIGITAL_KEY = 691;
public static final int HAMETHYST = 704;
public static final int BACONSTONE = 705;
public static final int PORQUOISE = 706;
public static final int JEWELRY_PLIERS = 709;
public static final int BACONSTONE_EARRING = 715;
public static final int BACONSTONE_BRACELET = 717;
public static final int MIRROR_SHARD = 726;
public static final int PUZZLE_PIECE = 727;
public static final int HEDGE_KEY = 728;
public static final int FISHBOWL = 729;
public static final int FISHTANK = 730;
public static final int FISH_HOSE = 731;
public static final int HOSED_TANK = 732;
public static final int HOSED_FISHBOWL = 733;
public static final int SCUBA_GEAR = 734;
public static final int SINISTER_STRUMMING = 736;
public static final int SQUEEZINGS_OF_WOE = 737;
public static final int REALLY_EVIL_RHYTHM = 738;
public static final int TAMBOURINE = 740;
public static final int BROKEN_SKULL = 741;
public static final int KNOB_FIRECRACKER = 747;
public static final int FLAMING_MUSHROOM = 755;
public static final int FROZEN_MUSHROOM = 756;
public static final int STINKY_MUSHROOM = 757;
public static final int CUMMERBUND = 778;
public static final int MAFIA_ARIA = 781;
public static final int RAFFLE_TICKET = 785;
public static final int STRAWBERRY = 786;
public static final int GOLDEN_MR_ACCESSORY = 792;
public static final int ROCKIN_WAGON = 797;
public static final int PLUS_SIGN = 818;
public static final int FIRST_BANG_POTION = 819;
public static final int MILKY_POTION = 819;
public static final int SWIRLY_POTION = 820;
public static final int BUBBLY_POTION = 821;
public static final int SMOKY_POTION = 822;
public static final int CLOUDY_POTION = 823;
public static final int EFFERVESCENT_POTION = 824;
public static final int FIZZY_POTION = 825;
public static final int DARK_POTION = 826;
public static final int LAST_BANG_POTION = 827;
public static final int MURKY_POTION = 827;
public static final int ANTIDOTE = 829;
public static final int ROYAL_JELLY = 830;
public static final int SHOCK_COLLAR = 856;
public static final int MOONGLASSES = 857;
public static final int LEAD_NECKLACE = 865;
public static final int TEARS = 869;
public static final int ROLLING_PIN = 873;
public static final int UNROLLING_PIN = 874;
public static final int GOOFBALLS = 879;
public static final int YUMMY_TUMMY_BEAN = 905;
public static final int DWARF_BREAD = 910;
public static final int PLASTIC_SWORD = 938;
public static final int DIRTY_MARTINI = 948;
public static final int GROGTINI = 949;
public static final int CHERRY_BOMB = 950;
public static final int WHITE_CHOCOLATE_AND_TOMATO_PIZZA = 958;
public static final int MAID = 1000;
public static final int TEQUILA = 1004;
public static final int VODKA_MARTINI = 1009;
public static final int DRY_VODKA_MARTINI = 1019;
public static final int VESPER = 1023;
public static final int BODYSLAM = 1024;
public static final int SANGRIA_DEL_DIABLO = 1025;
public static final int VALENTINE = 1026;
public static final int TAM_O_SHANTER = 1040;
public static final int GREEN_BEER = 1041;
public static final int RED_STRIPED_EGG = 1048;
public static final int RED_POLKA_EGG = 1049;
public static final int RED_PAISLEY_EGG = 1050;
public static final int BLUE_STRIPED_EGG = 1052;
public static final int BLUE_POLKA_EGG = 1053;
public static final int BLUE_PAISLEY_EGG = 1054;
public static final int OYSTER_BASKET = 1080;
public static final int TARGETING_CHIP = 1102;
public static final int CLOCKWORK_BARTENDER = 1111;
public static final int CLOCKWORK_CHEF = 1112;
public static final int CLOCKWORK_MAID = 1113;
public static final int ANNOYING_PITCHFORK = 1116;
public static final int PREGNANT_FLAMING_MUSHROOM = 1118;
public static final int PREGNANT_FROZEN_MUSHROOM = 1119;
public static final int PREGNANT_STINKY_MUSHROOM = 1120;
public static final int INEXPLICABLY_GLOWING_ROCK = 1121;
public static final int SPOOKY_GLOVE = 1125;
public static final int SPOOKY_BICYCLE_CHAIN = 1137;
public static final int FLAMING_MUSHROOM_WINE = 1139;
public static final int ICY_MUSHROOM_WINE = 1140;
public static final int STINKY_MUSHROOM_WINE = 1141;
public static final int POINTY_MUSHROOM_WINE = 1142;
public static final int FLAT_MUSHROOM_WINE = 1143;
public static final int COOL_MUSHROOM_WINE = 1144;
public static final int KNOB_MUSHROOM_WINE = 1145;
public static final int KNOLL_MUSHROOM_WINE = 1146;
public static final int SPOOKY_MUSHROOM_WINE = 1147;
public static final int GRAVY_MAYPOLE = 1152;
public static final int GIFT1 = 1167;
public static final int GIFT2 = 1168;
public static final int GIFT3 = 1169;
public static final int GIFT4 = 1170;
public static final int GIFT5 = 1171;
public static final int GIFT6 = 1172;
public static final int GIFT7 = 1173;
public static final int GIFT8 = 1174;
public static final int GIFT9 = 1175;
public static final int GIFT10 = 1176;
public static final int GIFT11 = 1177;
public static final int POTTED_FERN = 1180;
public static final int TULIP = 1181;
public static final int VENUS_FLYTRAP = 1182;
public static final int ALL_PURPOSE_FLOWER = 1183;
public static final int EXOTIC_ORCHID = 1184;
public static final int LONG_STEMMED_ROSE = 1185;
public static final int GILDED_LILY = 1186;
public static final int DEADLY_NIGHTSHADE = 1187;
public static final int BLACK_LOTUS = 1188;
public static final int STUFFED_GHUOL_WHELP = 1191;
public static final int STUFFED_ZMOBIE = 1192;
public static final int RAGGEDY_HIPPY_DOLL = 1193;
public static final int STUFFED_STAB_BAT = 1194;
public static final int APATHETIC_LIZARDMAN_DOLL = 1195;
public static final int STUFFED_YETI = 1196;
public static final int STUFFED_MOB_PENGUIN = 1197;
public static final int STUFFED_SABRE_TOOTHED_LIME = 1198;
public static final int GIANT_STUFFED_BUGBEAR = 1199;
public static final int HAPPY_BIRTHDAY_CLAUDE_CAKE = 1202;
public static final int PERSONALIZED_BIRTHDAY_CAKE = 1203;
public static final int THREE_TIERED_WEDDING_CAKE = 1204;
public static final int BABYCAKES = 1205;
public static final int BLUE_VELVET_CAKE = 1206;
public static final int CONGRATULATORY_CAKE = 1207;
public static final int ANGEL_FOOD_CAKE = 1208;
public static final int DEVILS_FOOD_CAKE = 1209;
public static final int BIRTHDAY_PARTY_JELLYBEAN_CHEESECAKE = 1210;
public static final int HEART_SHAPED_BALLOON = 1213;
public static final int ANNIVERSARY_BALLOON = 1214;
public static final int MYLAR_BALLOON = 1215;
public static final int KEVLAR_BALLOON = 1216;
public static final int THOUGHT_BALLOON = 1217;
public static final int RAT_BALLOON = 1218;
public static final int MINI_ZEPPELIN = 1219;
public static final int MR_BALLOON = 1220;
public static final int RED_BALLOON = 1221;
public static final int STAINLESS_STEEL_SOLITAIRE = 1226;
public static final int PLEXIGLASS_PITH_HELMET = 1231;
public static final int PLEXIGLASS_POCKETWATCH = 1232;
public static final int PLEXIGLASS_PENDANT = 1235;
public static final int TOY_HOVERCRAFT = 1243;
public static final int KNOB_GOBLIN_BALLS = 1244;
public static final int KNOB_GOBLIN_CODPIECE = 1245;
public static final int BONERDAGON_VERTEBRA = 1247;
public static final int BONERDAGON_NECKLACE = 1248;
public static final int PRETENTIOUS_PAIL = 1258;
public static final int WAX_LIPS = 1260;
public static final int NOSE_BONE_FETISH = 1264;
public static final int GLOOMY_BLACK_MUSHROOM = 1266;
public static final int DEAD_MIMIC = 1267;
public static final int PINE_WAND = 1268;
public static final int EBONY_WAND = 1269;
public static final int HEXAGONAL_WAND = 1270;
public static final int ALUMINUM_WAND = 1271;
public static final int MARBLE_WAND = 1272;
public static final int MEDICINAL_HERBS = 1274;
public static final int MAKEUP_KIT = 1305;
public static final int COMFY_BLANKET = 1311;
public static final int FACSIMILE_DICTIONARY = 1316;
public static final int TIME_HELMET = 1323;
public static final int CLOACA_COLA = 1334;
public static final int FANCY_CHOCOLATE = 1382;
public static final int TOY_SOLDIER = 1397;
public static final int SNOWCONE_BOOK = 1411;
public static final int PURPLE_SNOWCONE = 1412;
public static final int GREEN_SNOWCONE = 1413;
public static final int ORANGE_SNOWCONE = 1414;
public static final int RED_SNOWCONE = 1415;
public static final int BLUE_SNOWCONE = 1416;
public static final int BLACK_SNOWCONE = 1417;
public static final int TEDDY_SEWING_KIT = 1419;
public static final int ICEBERGLET = 1423;
public static final int ICE_SICKLE = 1424;
public static final int ICE_BABY = 1425;
public static final int ICE_PICK = 1426;
public static final int ICE_SKATES = 1427;
public static final int OILY_GOLDEN_MUSHROOM = 1432;
public static final int USELESS_POWDER = 1437;
public static final int TWINKLY_WAD = 1450;
public static final int HOT_WAD = 1451;
public static final int COLD_WAD = 1452;
public static final int SPOOKY_WAD = 1453;
public static final int STENCH_WAD = 1454;
public static final int SLEAZE_WAD = 1455;
public static final int GIFTV = 1460;
public static final int LUCKY_RABBIT_FOOT = 1485;
public static final int MINIATURE_DORMOUSE = 1489;
public static final int GLOOMY_MUSHROOM_WINE = 1496;
public static final int OILY_MUSHROOM_WINE = 1497;
public static final int HILARIOUS_BOOK = 1498;
public static final int RUBBER_EMO_ROE = 1503;
public static final int FAKE_HAND = 1511;
public static final int PET_BUFFING_SPRAY = 1512;
public static final int VAMPIRE_HEART = 1518;
public static final int BAKULA = 1519;
public static final int RADIO_KOL_COFFEE_MUG = 1520;
public static final int JOYBUZZER = 1525;
public static final int SNOOTY_DISGUISE = 1526;
public static final int GIFTR = 1534;
public static final int WEEGEE_SQOUIJA = 1537;
public static final int TAM_O_SHATNER = 1539;
public static final int GRIMACITE_GOGGLES = 1540;
public static final int GRIMACITE_GLAIVE = 1541;
public static final int GRIMACITE_GREAVES = 1542;
public static final int GRIMACITE_GARTER = 1543;
public static final int GRIMACITE_GALOSHES = 1544;
public static final int GRIMACITE_GORGET = 1545;
public static final int GRIMACITE_GUAYABERA = 1546;
public static final int MSG = 1549;
public static final int BOXED_CHAMPAGNE = 1556;
public static final int COCKTAIL_ONION = 1560;
public static final int VODKA_GIBSON = 1569;
public static final int GIBSON = 1570;
public static final int HOT_HI_MEIN = 1592;
public static final int COLD_HI_MEIN = 1593;
public static final int SPOOKY_HI_MEIN = 1594;
public static final int STINKY_HI_MEIN = 1595;
public static final int SLEAZY_HI_MEIN = 1596;
public static final int CATALYST = 1605;
public static final int ULTIMATE_WAD = 1606;
public static final int C_CLOCHE = 1615;
public static final int C_CULOTTES = 1616;
public static final int C_CROSSBOW = 1617;
public static final int ICE_STEIN = 1618;
public static final int MUNCHIES_PILL = 1619;
public static final int HOMEOPATHIC = 1620;
public static final int ASTRAL_MUSHROOM = 1622;
public static final int BADGER_BADGE = 1623;
public static final int BLUE_CUPCAKE = 1624;
public static final int GREEN_CUPCAKE = 1625;
public static final int ORANGE_CUPCAKE = 1626;
public static final int PURPLE_CUPCAKE = 1627;
public static final int PINK_CUPCAKE = 1628;
public static final int SPANISH_FLY = 1633;
public static final int BRICK = 1649;
public static final int MILK_OF_MAGNESIUM = 1650;
public static final int JEWEL_EYED_WIZARD_HAT = 1653;
public static final int CITADEL_SATCHEL = 1656;
public static final int CHERRY_CLOACA_COLA = 1658;
public static final int FRAUDWORT = 1670;
public static final int SHYSTERWEED = 1671;
public static final int SWINDLEBLOSSOM = 1672;
public static final int CARDBOARD_ORE = 1675;
public static final int STYROFOAM_ORE = 1676;
public static final int BUBBLEWRAP_ORE = 1677;
public static final int GROUCHO_DISGUISE = 1678;
public static final int EXPRESS_CARD = 1687;
public static final int MUCULENT_MACHETE = 1721;
public static final int SWORD_PREPOSITIONS = 1734;
public static final int GALLERY_KEY = 1765;
public static final int BALLROOM_KEY = 1766;
public static final int PACK_OF_CHEWING_GUM = 1767;
public static final int TRAVOLTAN_TROUSERS = 1792;
public static final int POOL_CUE = 1793;
public static final int HAND_CHALK = 1794;
public static final int DUSTY_ANIMAL_SKULL = 1799;
public static final int ONE_BALL = 1900;
public static final int TWO_BALL = 1901;
public static final int FIVE_BALL = 1904;
public static final int SIX_BALL = 1905;
public static final int EIGHT_BALL = 1907;
public static final int SPOOKYRAVEN_SPECTACLES = 1916;
public static final int ENGLISH_TO_A_F_U_E_DICTIONARY = 1919;
public static final int BIZARRE_ILLEGIBLE_SHEET_MUSIC = 1920;
public static final int TOILET_PAPER = 1923;
public static final int TATTERED_WOLF_STANDARD = 1924;
public static final int TATTERED_SNAKE_STANDARD = 1925;
public static final int TUNING_FORK = 1928;
public static final int ANTIQUE_GREAVES = 1929;
public static final int ANTIQUE_HELMET = 1930;
public static final int ANTIQUE_SPEAR = 1931;
public static final int ANTIQUE_SHIELD = 1932;
public static final int CHINTZY_SEAL_PENDANT = 1941;
public static final int CHINTZY_TURTLE_BROOCH = 1942;
public static final int CHINTZY_NOODLE_RING = 1943;
public static final int CHINTZY_SAUCEPAN_EARRING = 1944;
public static final int CHINTZY_DISCO_BALL_PENDANT = 1945;
public static final int CHINTZY_ACCORDION_PIN = 1946;
public static final int MANETWICH = 1949;
public static final int VANGOGHBITUSSIN = 1950;
public static final int PINOT_RENOIR = 1951;
public static final int FLAT_CHAMPAGNE = 1953;
public static final int QUILL_PEN = 1957;
public static final int INKWELL = 1958;
public static final int SCRAP_OF_PAPER = 1959;
public static final int EVIL_SCROLL = 1960;
public static final int DANCE_CARD = 1963;
public static final int OPERA_MASK = 1964;
public static final int PUMPKIN_BUCKET = 1971;
public static final int SILVER_SHRIMP_FORK = 1972;
public static final int STUFFED_COCOABO = 1974;
public static final int RUBBER_WWTNSD_BRACELET = 1994;
public static final int SPADE_NECKLACE = 2017;
public static final int PATCHOULI_OIL_BOMB = 2040;
public static final int EXPLODING_HACKY_SACK = 2042;
public static final int MACGUFFIN_DIARY = 2044;
public static final int BROKEN_WINGS = 2050;
public static final int SUNKEN_EYES = 2051;
public static final int REASSEMBLED_BLACKBIRD = 2052;
public static final int BLACKBERRY = 2063;
public static final int FORGED_ID_DOCUMENTS = 2064;
public static final int PADL_PHONE = 2065;
public static final int TEQUILA_GRENADE = 2068;
public static final int NOVELTY_BUTTON = 2072;
public static final int MAKESHIFT_TURBAN = 2079;
public static final int MAKESHIFT_CAPE = 2080;
public static final int MAKESHIFT_SKIRT = 2081;
public static final int MAKESHIFT_CRANE = 2083;
public static final int CAN_OF_STARCH = 2084;
public static final int ANTIQUE_HAND_MIRROR = 2092;
public static final int TOWEL = 2095;
public static final int GMOB_POLLEN = 2096;
public static final int LUCRE = 2098;
public static final int ASCII_SHIRT = 2121;
public static final int TOY_MERCENARY = 2139;
public static final int EVIL_TEDDY_SEWING_KIT = 2147;
public static final int TRIANGULAR_STONE = 2173;
public static final int ANCIENT_AMULET = 2180;
public static final int HAROLDS_HAMMER_HEAD = 2182;
public static final int HAROLDS_HAMMER = 2184;
public static final int UNLIT_BIRTHDAY_CAKE = 2186;
public static final int LIT_BIRTHDAY_CAKE = 2187;
public static final int ANCIENT_CAROLS = 2191;
public static final int SHEET_MUSIC = 2192;
public static final int FANCY_EVIL_CHOCOLATE = 2197;
public static final int CRIMBO_UKELELE = 2209;
public static final int LIARS_PANTS = 2222;
public static final int JUGGLERS_BALLS = 2223;
public static final int PINK_SHIRT = 2224;
public static final int FAMILIAR_DOPPELGANGER = 2225;
public static final int EYEBALL_PENDANT = 2226;
public static final int CALAVERA_CONCERTINA = 2234;
public static final int TURTLE_PHEROMONES = 2236;
public static final int PHOTOGRAPH_OF_GOD = 2259;
public static final int WET_STUNT_NUT_STEW = 2266;
public static final int MEGA_GEM = 2267;
public static final int STAFF_OF_FATS = 2268;
public static final int DUSTY_BOTTLE_OF_MERLOT = 2271;
public static final int DUSTY_BOTTLE_OF_PORT = 2272;
public static final int DUSTY_BOTTLE_OF_PINOT_NOIR = 2273;
public static final int DUSTY_BOTTLE_OF_ZINFANDEL = 2274;
public static final int DUSTY_BOTTLE_OF_MARSALA = 2275;
public static final int DUSTY_BOTTLE_OF_MUSCAT = 2276;
public static final int FERNSWARTHYS_KEY = 2277;
public static final int DUSTY_BOOK = 2279;
public static final int MUS_MANUAL = 2280;
public static final int MYS_MANUAL = 2281;
public static final int MOX_MANUAL = 2282;
public static final int SEAL_HELMET = 2283;
public static final int PETRIFIED_NOODLES = 2284;
public static final int CHISEL = 2285;
public static final int EYE_OF_ED = 2286;
public static final int RED_PAPER_CLIP = 2289;
public static final int REALLY_BIG_TINY_HOUSE = 2290;
public static final int NONESSENTIAL_AMULET = 2291;
public static final int WHITE_WINE_VINAIGRETTE = 2292;
public static final int CUP_OF_STRONG_TEA = 2293;
public static final int CURIOUSLY_SHINY_AX = 2294;
public static final int MARINATED_STAKES = 2295;
public static final int KNOB_BUTTER = 2296;
public static final int VIAL_OF_ECTOPLASM = 2297;
public static final int BOOCK_OF_MAGIKS = 2298;
public static final int EZ_PLAY_HARMONICA_BOOK = 2299;
public static final int FINGERLESS_HOBO_GLOVES = 2300;
public static final int CHOMSKYS_COMICS = 2301;
public static final int WORM_RIDING_HOOKS = 2302;
public static final int CANDY_BOOK = 2303;
public static final int GREEN_CANDY = 2309;
public static final int ANCIENT_BRONZE_TOKEN = 2317;
public static final int ANCIENT_BOMB = 2318;
public static final int CARVED_WOODEN_WHEEL = 2319;
public static final int WORM_RIDING_MANUAL_PAGE = 2320;
public static final int HEADPIECE_OF_ED = 2323;
public static final int STAFF_OF_ED = 2325;
public static final int STONE_ROSE = 2326;
public static final int BLACK_PAINT = 2327;
public static final int DRUM_MACHINE = 2328;
public static final int CONFETTI = 2329;
public static final int CHOCOLATE_COVERED_DIAMOND_STUDDED_ROSES = 2330;
public static final int BOUQUET_OF_CIRCULAR_SAW_BLADES = 2331;
public static final int BETTER_THAN_CUDDLING_CAKE = 2332;
public static final int STUFFED_NINJA_SNOWMAN = 2333;
public static final int HOLY_MACGUFFIN = 2334;
public static final int BLACK_PUDDING = 2338;
public static final int BLACKFLY_CHARDONNAY = 2339;
public static final int FILTHWORM_QUEEN_HEART = 2347;
public static final int COMMUNICATIONS_WINDCHIMES = 2354;
public static final int ZIM_MERMANS_GUITAR = 2364;
public static final int FILTHY_POULTICE = 2369;
public static final int MOLOTOV_COCKTAIL_COCKTAIL = 2400;
public static final int GAUZE_GARTER = 2402;
public static final int GUNPOWDER = 2403;
public static final int JAM_BAND_FLYERS = 2404;
public static final int ROCK_BAND_FLYERS = 2405;
public static final int RHINO_HORMONES = 2419;
public static final int MAGIC_SCROLL = 2420;
public static final int PIRATE_JUICE = 2421;
public static final int PET_SNACKS = 2422;
public static final int INHALER = 2423;
public static final int CYCLOPS_EYEDROPS = 2424;
public static final int SPINACH = 2425;
public static final int FIRE_FLOWER = 2426;
public static final int ICE_CUBE = 2427;
public static final int FAKE_BLOOD = 2428;
public static final int GUANEAU = 2429;
public static final int LARD = 2430;
public static final int MYSTIC_SHELL = 2431;
public static final int LIP_BALM = 2432;
public static final int ANTIFREEZE = 2433;
public static final int BLACK_EYEDROPS = 2434;
public static final int DOGSGOTNONOZ = 2435;
public static final int FLIPBOOK = 2436;
public static final int NEW_CLOACA_COLA = 2437;
public static final int MASSAGE_OIL = 2438;
public static final int POLTERGEIST = 2439;
public static final int ENCRYPTION_KEY = 2441;
public static final int COBBS_KNOB_MAP = 2442;
public static final int SUPERNOVA_CHAMPAGNE = 2444;
public static final int GOATSKIN_UMBRELLA = 2451;
public static final int BAR_WHIP = 2455;
public static final int ODOR_EXTRACTOR = 2462;
public static final int OLFACTION_BOOK = 2463;
public static final int TUXEDO_SHIRT = 2489;
public static final int SHIRT_KIT = 2491;
public static final int TROPICAL_ORCHID = 2492;
public static final int MOLYBDENUM_MAGNET = 2497;
public static final int MOLYBDENUM_HAMMER = 2498;
public static final int MOLYBDENUM_SCREWDRIVER = 2499;
public static final int MOLYBDENUM_PLIERS = 2500;
public static final int MOLYBDENUM_WRENCH = 2501;
public static final int JEWELRY_BOOK = 2502;
public static final int WOVEN_BALING_WIRE_BRACELETS = 2514;
public static final int CRUELTY_FREE_WINE = 2521;
public static final int THISTLE_WINE = 2522;
public static final int FISHY_FISH_LASAGNA = 2527;
public static final int GNAT_LASAGNA = 2531;
public static final int LONG_PORK_LASAGNA = 2535;
public static final int TOMB_RATCHET = 2540;
public static final int MAYFLOWER_BOUQUET = 2541;
public static final int LESSER_GRODULATED_VIOLET = 2542;
public static final int TIN_MAGNOLIA = 2543;
public static final int BEGPWNIA = 2544;
public static final int UPSY_DAISY = 2545;
public static final int HALF_ORCHID = 2546;
public static final int OUTRAGEOUS_SOMBRERO = 2548;
public static final int SHAGADELIC_DISCO_BANJO = 2556;
public static final int SQUEEZEBOX_OF_THE_AGES = 2557;
public static final int CHELONIAN_MORNINGSTAR = 2558;
public static final int HAMMER_OF_SMITING = 2559;
public static final int SEVENTEEN_ALARM_SAUCEPAN = 2560;
public static final int GREEK_PASTA_OF_PERIL = 2561;
public static final int AZAZELS_UNICORN = 2566;
public static final int AZAZELS_LOLLIPOP = 2567;
public static final int AZAZELS_TUTU = 2568;
public static final int ANT_HOE = 2570;
public static final int ANT_RAKE = 2571;
public static final int ANT_PITCHFORK = 2572;
public static final int ANT_SICKLE = 2573;
public static final int ANT_PICK = 2574;
public static final int HANDFUL_OF_SAND = 2581;
public static final int SAND_BRICK = 2582;
public static final int TASTY_TART = 2591;
public static final int LUNCHBOX = 2592;
public static final int KNOB_PASTY = 2593;
public static final int KNOB_COFFEE = 2594;
public static final int TELESCOPE = 2599;
public static final int TUESDAYS_RUBY = 2604;
public static final int PALM_FROND = 2605;
public static final int MOJO_FILTER = 2614;
public static final int WEAVING_MANUAL = 2630;
public static final int PAT_A_CAKE_PENDANT = 2633;
public static final int MUMMY_WRAP = 2634;
public static final int GAUZE_HAMMOCK = 2638;
public static final int MAXWELL_HAMMER = 2642;
public static final int ABSINTHE = 2655;
public static final int BOTTLE_OF_REALPAGNE = 2658;
public static final int SPIKY_COLLAR = 2667;
public static final int LIBRARY_CARD = 2672;
public static final int SPECTRE_SCEPTER = 2678;
public static final int SPARKLER = 2679;
public static final int SNAKE = 2680;
public static final int M282 = 2681;
public static final int DETUNED_RADIO = 2682;
public static final int GIFTW = 2683;
public static final int MASSIVE_SITAR = 2693;
public static final int DUCT_TAPE = 2697;
public static final int SHRINKING_POWDER = 2704;
public static final int PARROT_CRACKER = 2710;
public static final int SPARE_KIDNEY = 2718;
public static final int HAND_CARVED_BOKKEN = 2719;
public static final int HAND_CARVED_BOW = 2720;
public static final int HAND_CARVED_STAFF = 2721;
public static final int PLUM_WINE = 2730;
public static final int STEEL_STOMACH = 2742;
public static final int STEEL_LIVER = 2743;
public static final int STEEL_SPLEEN = 2744;
public static final int HAROLDS_BELL = 2765;
public static final int GOLD_BOWLING_BALL = 2766;
public static final int SOLID_BACONSTONE_EARRING = 2780;
public static final int BRIMSTONE_BERET = 2813;
public static final int BRIMSTONE_BUNKER = 2815;
public static final int BRIMSTONE_BRACELET = 2818;
public static final int GRIMACITE_GASMASK = 2819;
public static final int GRIMACITE_GAT = 2820;
public static final int GRIMACITE_GAITERS = 2821;
public static final int GRIMACITE_GAUNTLETS = 2822;
public static final int GRIMACITE_GO_GO_BOOTS = 2823;
public static final int GRIMACITE_GIRDLE = 2824;
public static final int GRIMACITE_GOWN = 2825;
public static final int REALLY_DENSE_MEAT_STACK = 2829;
public static final int BOTTLE_ROCKET = 2834;
public static final int COOKING_SHERRY = 2840;
public static final int NAVEL_RING = 2844;
public static final int PLASTIC_BIB = 2846;
public static final int GNOME_DEMODULIZER = 2848;
public static final int GREAT_TREE_BRANCH = 2852;
public static final int PHIL_BUNION_AXE = 2853;
public static final int SWAMP_ROSE_BOUQUET = 2854;
public static final int PARTY_HAT = 2945;
public static final int V_MASK = 2946;
public static final int PIRATE_INSULT_BOOK = 2947;
public static final int CARONCH_MAP = 2950;
public static final int FRATHOUSE_BLUEPRINTS = 2951;
public static final int CHARRRM_BRACELET = 2953;
public static final int COCKTAIL_NAPKIN = 2956;
public static final int RUM_CHARRRM = 2957;
public static final int RUM_BRACELET = 2959;
public static final int RIGGING_SHAMPOO = 2963;
public static final int BALL_POLISH = 2964;
public static final int MIZZENMAST_MOP = 2965;
public static final int GRUMPY_CHARRRM = 2972;
public static final int GRUMPY_BRACELET = 2973;
public static final int TARRRNISH_CHARRRM = 2974;
public static final int TARRRNISH_BRACELET = 2975;
public static final int BILGE_WINE = 2976;
public static final int BOOTY_CHARRRM = 2980;
public static final int BOOTY_BRACELET = 2981;
public static final int CANNONBALL_CHARRRM = 2982;
public static final int CANNONBALL_BRACELET = 2983;
public static final int COPPER_CHARRRM = 2984;
public static final int COPPER_BRACELET = 2985;
public static final int TONGUE_CHARRRM = 2986;
public static final int TONGUE_BRACELET = 2987;
public static final int CLINGFILM = 2988;
public static final int CARONCH_NASTY_BOOTY = 2999;
public static final int CARONCH_DENTURES = 3000;
public static final int IDOL_AKGYXOTH = 3009;
public static final int EMBLEM_AKGYXOTH = 3010;
public static final int SIMPLE_CURSED_KEY = 3013;
public static final int ORNATE_CURSED_KEY = 3014;
public static final int GILDED_CURSED_KEY = 3015;
public static final int ANCIENT_CURSED_FOOTLOCKER = 3016;
public static final int ORNATE_CURSED_CHEST = 3017;
public static final int GILDED_CURSED_CHEST = 3018;
public static final int PIRATE_FLEDGES = 3033;
public static final int CURSED_PIECE_OF_THIRTEEN = 3034;
public static final int FOIL_BOW = 3043;
public static final int FOIL_RADAR = 3044;
public static final int POWER_SPHERE = 3049;
public static final int FOIL_CAT_EARS = 3056;
public static final int LASER_CANON = 3069;
public static final int CHIN_STRAP = 3070;
public static final int GLUTEAL_SHIELD = 3071;
public static final int CARBONITE_VISOR = 3072;
public static final int UNOBTAINIUM_STRAPS = 3073;
public static final int FASTENING_APPARATUS = 3074;
public static final int GENERAL_ASSEMBLY_MODULE = 3075;
public static final int LASER_TARGETING_CHIP = 3076;
public static final int LEG_ARMOR = 3077;
public static final int KEVLATEFLOCITE_HELMET = 3078;
public static final int TEDDY_BORG_SEWING_KIT = 3087;
public static final int VITACHOC_CAPSULE = 3091;
public static final int HOBBY_HORSE = 3092;
public static final int BALL_IN_A_CUP = 3093;
public static final int SET_OF_JACKS = 3094;
public static final int FISH_SCALER = 3097;
public static final int MINIBORG_STOMPER = 3109;
public static final int MINIBORG_STRANGLER = 3110;
public static final int MINIBORG_LASER = 3111;
public static final int MINIBORG_BEEPER = 3112;
public static final int MINIBORG_HIVEMINDER = 3113;
public static final int MINIBORG_DESTROYOBOT = 3114;
public static final int DIVINE_BOOK = 3117;
public static final int DIVINE_NOISEMAKER = 3118;
public static final int DIVINE_SILLY_STRING = 3119;
public static final int DIVINE_BLOWOUT = 3120;
public static final int DIVINE_CHAMPAGNE_POPPER = 3121;
public static final int DIVINE_CRACKER = 3122;
public static final int DIVINE_FLUTE = 3123;
public static final int HOBO_NICKEL = 3126;
public static final int SANDCASTLE = 3127;
public static final int MARSHMALLOW = 3128;
public static final int ROASTED_MARSHMALLOW = 3129;
public static final int TORN_PAPER_STRIP = 3144;
public static final int PUNCHCARD_ATTACK = 3146;
public static final int PUNCHCARD_REPAIR = 3147;
public static final int PUNCHCARD_BUFF = 3148;
public static final int PUNCHCARD_MODIFY = 3149;
public static final int PUNCHCARD_BUILD = 3150;
public static final int PUNCHCARD_TARGET = 3151;
public static final int PUNCHCARD_SELF = 3152;
public static final int PUNCHCARD_FLOOR = 3153;
public static final int PUNCHCARD_DRONE = 3154;
public static final int PUNCHCARD_WALL = 3155;
public static final int PUNCHCARD_SPHERE = 3156;
public static final int DRONE = 3157;
public static final int EL_VIBRATO_HELMET = 3162;
public static final int EL_VIBRATO_SPEAR = 3163;
public static final int EL_VIBRATO_PANTS = 3164;
public static final int BROKEN_DRONE = 3165;
public static final int REPAIRED_DRONE = 3166;
public static final int AUGMENTED_DRONE = 3167;
public static final int FORTUNE_TELLER = 3193;
public static final int ORIGAMI_MAGAZINE = 3194;
public static final int PAPER_SHURIKEN = 3195;
public static final int ORIGAMI_PASTIES = 3196;
public static final int RIDING_CROP = 3197;
public static final int TRAPEZOID = 3198;
public static final int LUMP_OF_COAL = 3199;
public static final int THICK_PADDED_ENVELOPE = 3201;
public static final int DWARVISH_PUNCHCARD = 3207;
public static final int SMALL_LAMINATED_CARD = 3208;
public static final int LITTLE_LAMINATED_CARD = 3209;
public static final int NOTBIG_LAMINATED_CARD = 3210;
public static final int UNLARGE_LAMINATED_CARD = 3211;
public static final int DWARVISH_DOCUMENT = 3212;
public static final int DWARVISH_PAPER = 3213;
public static final int DWARVISH_PARCHMENT = 3214;
public static final int OVERCHARGED_POWER_SPHERE = 3215;
public static final int HOBO_CODE_BINDER = 3220;
public static final int GATORSKIN_UMBRELLA = 3222;
public static final int SEWER_WAD = 3224;
public static final int OOZE_O = 3226;
public static final int DUMPLINGS = 3228;
public static final int OIL_OF_OILINESS = 3230;
public static final int TATTERED_PAPER_CROWN = 3231;
public static final int INFLATABLE_DUCK = 3233;
public static final int WATER_WINGS = 3234;
public static final int FOAM_NOODLE = 3235;
public static final int KISSIN_COUSINS = 3236;
public static final int TALES_FROM_THE_FIRESIDE = 3237;
public static final int BLIZZARDS_I_HAVE_DIED_IN = 3238;
public static final int MAXING_RELAXING = 3239;
public static final int BIDDY_CRACKERS_COOKBOOK = 3240;
public static final int TRAVELS_WITH_JERRY = 3241;
public static final int LET_ME_BE = 3242;
public static final int ASLEEP_IN_THE_CEMETERY = 3243;
public static final int SUMMER_NIGHTS = 3244;
public static final int SENSUAL_MASSAGE_FOR_CREEPS = 3245;
public static final int BAG_OF_CANDY = 3261;
public static final int TASTEFUL_BOOK = 3263;
public static final int CROTCHETY_PANTS = 3271;
public static final int SACCHARINE_MAPLE_PENDANT = 3272;
public static final int WILLOWY_BONNET = 3273;
public static final int BLACK_BLUE_LIGHT = 3276;
public static final int LOUDMOUTH_LARRY = 3277;
public static final int CHEAP_STUDDED_BELT = 3278;
public static final int PERSONAL_MASSAGER = 3279;
public static final int PLASMA_BALL = 3281;
public static final int STICK_ON_EYEBROW_PIERCING = 3282;
public static final int MACARONI_FRAGMENTS = 3287;
public static final int SHIMMERING_TENDRILS = 3288;
public static final int SCINTILLATING_POWDER = 3289;
public static final int VOLCANO_MAP = 3291;
public static final int PRETTY_PINK_BOW = 3298;
public static final int SMILEY_FACE_STICKER = 3299;
public static final int FARFALLE_BOW_TIE = 3300;
public static final int JALAPENO_SLICES = 3301;
public static final int SOLAR_PANELS = 3302;
public static final int TINY_SOMBRERO = 3303;
public static final int EPIC_WAD = 3316;
public static final int MAYFLY_BAIT_NECKLACE = 3322;
public static final int SCRATCHS_FORK = 3323;
public static final int FROSTYS_MUG = 3324;
public static final int FERMENTED_PICKLE_JUICE = 3325;
public static final int EXTRA_GREASY_SLIDER = 3327;
public static final int CRUMPLED_FELT_FEDORA = 3328;
public static final int DOUBLE_SIDED_TAPE = 3336;
public static final int HOT_BEDDING = 3344; // bed of coals
public static final int COLD_BEDDING = 3345; // frigid air mattress
public static final int STENCH_BEDDING = 3346; // filth-encrusted futon
public static final int SPOOKY_BEDDING = 3347; // comfy coffin
public static final int SLEAZE_BEDDING = 3348; // stained mattress
public static final int ZEN_MOTORCYCLE = 3352;
public static final int GONG = 3353;
public static final int GRUB = 3356;
public static final int MOTH = 3357;
public static final int FIRE_ANT = 3358;
public static final int ICE_ANT = 3359;
public static final int STINKBUG = 3360;
public static final int DEATH_WATCH_BEETLE = 3361;
public static final int LOUSE = 3362;
public static final int INTERESTING_TWIG = 3367;
public static final int TWIG_HOUSE = 3374;
public static final int RICHIE_THINGFINDER = 3375;
public static final int MEDLEY_OF_DIVERSITY = 3376;
public static final int EXPLOSIVE_ETUDE = 3377;
public static final int CHORALE_OF_COMPANIONSHIP = 3378;
public static final int PRELUDE_OF_PRECISION = 3379;
public static final int CHESTER_GLASSES = 3383;
public static final int EMPTY_EYE = 3388;
public static final int ICEBALL = 3391;
public static final int NEVERENDING_SODA = 3393;
public static final int HODGMANS_PORKPIE_HAT = 3395;
public static final int HODGMANS_LOBSTERSKIN_PANTS = 3396;
public static final int HODGMANS_BOW_TIE = 3397;
public static final int SQUEEZE = 3399;
public static final int FISHYSOISSE = 3400;
public static final int LAMP_SHADE = 3401;
public static final int GARBAGE_JUICE = 3402;
public static final int LEWD_CARD = 3403;
public static final int HODGMAN_JOURNAL_1 = 3412;
public static final int HODGMAN_JOURNAL_2 = 3413;
public static final int HODGMAN_JOURNAL_3 = 3414;
public static final int HODGMAN_JOURNAL_4 = 3415;
public static final int HOBO_FORTRESS = 3416;
public static final int FIREWORKS = 3421;
public static final int GIFTH = 3430;
public static final int SPICE_MELANGE = 3433;
public static final int RAINBOWS_GRAVITY = 3439;
public static final int COTTON_CANDY_CONDE = 3449;
public static final int COTTON_CANDY_PINCH = 3450;
public static final int COTTON_CANDY_SMIDGEN = 3451;
public static final int COTTON_CANDY_SKOSHE = 3452;
public static final int COTTON_CANDY_PLUG = 3453;
public static final int COTTON_CANDY_PILLOW = 3454;
public static final int COTTON_CANDY_BALE = 3455;
public static final int STYX_SPRAY = 3458;
public static final int HAIKU_KATANA = 3466;
public static final int BATHYSPHERE = 3470;
public static final int DAMP_OLD_BOOT = 3471;
public static final int BOXTOP = 3473;
public static final int DULL_FISH_SCALE = 3486;
public static final int ROUGH_FISH_SCALE = 3487;
public static final int PRISTINE_FISH_SCALE = 3488;
public static final int FISH_SCIMITAR = 3492;
public static final int FISH_STICK = 3493;
public static final int FISH_BAZOOKA = 3494;
public static final int SEA_SALT_CRYSTAL = 3495;
public static final int LARP_MEMBERSHIP_CARD = 3506;
public static final int STICKER_BOOK = 3507;
public static final int STICKER_SWORD = 3508;
public static final int STICKER_CROSSBOW = 3526;
public static final int GRIMACITE_HAMMER = 3542;
public static final int GRIMACITE_GRAVY_BOAT = 3543;
public static final int GRIMACITE_WEIGHTLIFTING_BELT = 3544;
public static final int GRIMACITE_GRAPPLING_HOOK = 3545;
public static final int GRIMACITE_NINJA_MASK = 3546;
public static final int GRIMACITE_SHINGUARDS = 3547;
public static final int GRIMACITE_ASTROLABE = 3548;
public static final int SEED_PACKET = 3553;
public static final int GREEN_SLIME = 3554;
public static final int SEA_CARROT = 3555;
public static final int SEA_CUCUMBER = 3556;
public static final int SEA_AVOCADO = 3557;
public static final int POTION_OF_PUISSANCE = 3561;
public static final int POTION_OF_PERSPICACITY = 3562;
public static final int POTION_OF_PULCHRITUDE = 3563;
public static final int SAND_DOLLAR = 3575;
public static final int BEZOAR_RING = 3577;
public static final int WRIGGLING_FLYTRAP_PELLET = 3580;
public static final int SUSHI_ROLLING_MAT = 3581;
public static final int WHITE_RICE = 3582;
public static final int RUSTY_BROKEN_DIVING_HELMET = 3602;
public static final int BUBBLIN_STONE = 3605;
public static final int AERATED_DIVING_HELMET = 3607;
public static final int DAS_BOOT = 3609;
public static final int IMITATION_WHETSTONE = 3610;
public static final int PARASITIC_CLAW = 3624;
public static final int PARASITIC_TENTACLES = 3625;
public static final int PARASITIC_HEADGNAWER = 3626;
public static final int PARASITIC_STRANGLEWORM = 3627;
public static final int BURROWGRUB_HIVE = 3629;
public static final int JAMFISH_JAM = 3641;
public static final int DRAGONFISH_CAVIAR = 3642;
public static final int GRIMACITE_KNEECAPPING_STICK = 3644;
public static final int CANTEEN_OF_WINE = 3645;
public static final int MADNESS_REEF_MAP = 3649;
public static final int MINIATURE_ANTLERS = 3651;
public static final int SPOOKY_PUTTY_MITRE = 3662;
public static final int SPOOKY_PUTTY_LEOTARD = 3663;
public static final int SPOOKY_PUTTY_BALL = 3664;
public static final int SPOOKY_PUTTY_SHEET = 3665;
public static final int SPOOKY_PUTTY_SNAKE = 3666;
public static final int SPOOKY_PUTTY_MONSTER = 3667;
public static final int RAGE_GLAND = 3674;
public static final int MERKIN_PRESSUREGLOBE = 3675;
public static final int GLOWING_ESCA = 3680;
public static final int MARINARA_TRENCH_MAP = 3683;
public static final int TEMPURA_CARROT = 3684;
public static final int TEMPURA_CUCUMBER = 3685;
public static final int TEMPURA_AVOCADO = 3686;
public static final int TEMPURA_BROCCOLI = 3689;
public static final int TEMPURA_CAULIFLOWER = 3690;
public static final int POTION_OF_PERCEPTION = 3693;
public static final int POTION_OF_PROFICIENCY = 3694;
public static final int VELCRO_ORE = 3698;
public static final int TEFLON_ORE = 3699;
public static final int VINYL_ORE = 3700;
public static final int ANEMONE_MINE_MAP = 3701;
public static final int VINYL_BOOTS = 3716;
public static final int GNOLL_EYE = 3731;
public static final int BOOZEHOUND_TOKEN = 3739;
public static final int UNSTABLE_QUARK = 3743;
public static final int LOVE_BOOK = 3753;
public static final int VAGUE_AMBIGUITY = 3754;
public static final int SMOLDERING_PASSION = 3755;
public static final int ICY_REVENGE = 3756;
public static final int SUGARY_CUTENESS = 3757;
public static final int DISTURBING_OBSESSION = 3758;
public static final int NAUGHTY_INNUENDO = 3759;
public static final int DIVE_BAR_MAP = 3774;
public static final int MERKIN_PINKSLIP = 3775;
public static final int PARANORMAL_RICOTTA = 3784;
public static final int SMOKING_TALON = 3785;
public static final int VAMPIRE_GLITTER = 3786;
public static final int WINE_SOAKED_BONE_CHIPS = 3787;
public static final int CRUMBLING_RAT_SKULL = 3788;
public static final int TWITCHING_TRIGGER_FINGER = 3789;
public static final int AQUAVIOLET_JUBJUB_BIRD = 3800;
public static final int CRIMSILION_JUBJUB_BIRD = 3801;
public static final int CHARPUCE_JUBJUB_BIRD = 3802;
public static final int MERKIN_LOCKKEY = 3810;
public static final int MERKIN_STASHBOX = 3811;
public static final int SEA_RADISH = 3817;
public static final int EEL_SAUCE = 3819;
public static final int FISHY_WAND = 3822;
public static final int GRANDMAS_NOTE = 3824;
public static final int FUCHSIA_YARN = 3825;
public static final int CHARTREUSE_YARN = 3826;
public static final int GRANDMAS_MAP = 3828;
public static final int TEMPURA_RADISH = 3829;
public static final int TINY_COSTUME_WARDROBE = 3835;
public static final int ELVISH_SUNGLASSES = 3836;
public static final int OOT_BIWA = 3842;
public static final int JUNGLE_DRUM = 3846;
public static final int HIPPY_BONGO = 3847;
public static final int GUITAR_4D = 3849;
public static final int HALF_GUITAR = 3852;
public static final int BASS_DRUM = 3853;
public static final int SMALLEST_VIOLIN = 3855;
public static final int PLASTIC_GUITAR = 3863;
public static final int FINGER_CYMBALS = 3864;
public static final int KETTLE_DRUM = 3865;
public static final int HELLSEAL_HIDE = 3874;
public static final int HELLSEAL_BRAIN = 3876;
public static final int HELLSEAL_SINEW = 3878;
public static final int HELLSEAL_DISGUISE = 3880;
public static final int FOUET_DE_TORTUE_DRESSAGE = 3881;
public static final int CULT_MEMO = 3883;
public static final int DECODED_CULT_DOCUMENTS = 3884;
public static final int FIRST_SLIME_VIAL = 3885;
public static final int VIAL_OF_RED_SLIME = 3885;
public static final int VIAL_OF_YELLOW_SLIME = 3886;
public static final int VIAL_OF_BLUE_SLIME = 3887;
public static final int VIAL_OF_ORANGE_SLIME = 3888;
public static final int VIAL_OF_GREEN_SLIME = 3889;
public static final int VIAL_OF_VIOLET_SLIME = 3890;
public static final int VIAL_OF_VERMILION_SLIME = 3891;
public static final int VIAL_OF_AMBER_SLIME = 3892;
public static final int VIAL_OF_CHARTREUSE_SLIME = 3893;
public static final int VIAL_OF_TEAL_SLIME = 3894;
public static final int VIAL_OF_INDIGO_SLIME = 3895;
public static final int VIAL_OF_PURPLE_SLIME = 3896;
public static final int LAST_SLIME_VIAL = 3897;
public static final int VIAL_OF_BROWN_SLIME = 3897;
public static final int BOTTLE_OF_GU_GONE = 3898;
public static final int SEAL_BLUBBER_CANDLE = 3901;
public static final int WRETCHED_SEAL = 3902;
public static final int CUTE_BABY_SEAL = 3903;
public static final int ARMORED_SEAL = 3904;
public static final int ANCIENT_SEAL = 3905;
public static final int SLEEK_SEAL = 3906;
public static final int SHADOWY_SEAL = 3907;
public static final int STINKING_SEAL = 3908;
public static final int CHARRED_SEAL = 3909;
public static final int COLD_SEAL = 3910;
public static final int SLIPPERY_SEAL = 3911;
public static final int IMBUED_SEAL_BLUBBER_CANDLE = 3912;
public static final int TURTLE_WAX = 3914;
public static final int TURTLEMAIL_BITS = 3919;
public static final int TURTLING_ROD = 3927;
public static final int SEAL_IRON_INGOT = 3932;
public static final int HYPERINFLATED_SEAL_LUNG = 3935;
public static final int VIP_LOUNGE_KEY = 3947;
public static final int STUFFED_CHEST = 3949;
public static final int STUFFED_KEY = 3950;
public static final int STUFFED_BARON = 3951;
public static final int CLAN_POOL_TABLE = 3963;
public static final int TINY_CELL_PHONE = 3964;
public static final int DUELING_BANJO = 3984;
public static final int SAMURAI_TURTLE = 3986;
public static final int SLIME_SOAKED_HYPOPHYSIS = 3991;
public static final int SLIME_SOAKED_BRAIN = 3992;
public static final int SLIME_SOAKED_SWEAT_GLAND = 3993;
public static final int DOLPHIN_WHISTLE = 3997;
public static final int AGUA_DE_VIDA = 4001;
public static final int MOONTAN_LOTION = 4003;
public static final int BALLAST_TURTLE = 4005;
public static final int AMINO_ACIDS = 4006;
public static final int CA_BASE_PAIR = 4011;
public static final int CG_BASE_PAIR = 4012;
public static final int CT_BASE_PAIR = 4013;
public static final int AG_BASE_PAIR = 4014;
public static final int AT_BASE_PAIR = 4015;
public static final int GT_BASE_PAIR = 4016;
public static final int CONTACT_LENSES = 4019;
public static final int GRAPPLING_HOOK = 4029;
public static final int SMALL_STONE_BLOCK = 4030;
public static final int LITTLE_STONE_BLOCK = 4031;
public static final int HALF_STONE_CIRCLE = 4032;
public static final int STONE_HALF_CIRCLE = 4033;
public static final int IRON_KEY = 4034;
public static final int CULTIST_ROBE = 4040;
public static final int WUMPUS_HAIR = 4044;
public static final int RING_OF_TELEPORTATION = 4051;
public static final int INDIGO_PARTY_INVITATION = 4060;
public static final int VIOLET_HUNT_INVITATION = 4061;
public static final int BLUE_MILK_CLUB_CARD = 4062;
public static final int MECHA_MAYHEM_CLUB_CARD = 4063;
public static final int SMUGGLER_SHOT_FIRST_BUTTON = 4064;
public static final int SPACEFLEET_COMMUNICATOR_BADGE = 4065;
public static final int RUBY_ROD = 4066;
public static final int ESSENCE_OF_HEAT = 4067;
public static final int ESSENCE_OF_KINK = 4068;
public static final int ESSENCE_OF_COLD = 4069;
public static final int ESSENCE_OF_STENCH = 4070;
public static final int ESSENCE_OF_FRIGHT = 4071;
public static final int ESSENCE_OF_CUTE = 4072;
public static final int SUPREME_BEING_GLOSSARY = 4073;
public static final int GRISLY_SHIELD = 4080;
public static final int CYBER_MATTOCK = 4086;
public static final int GREEN_PEAWEE_MARBLE = 4095;
public static final int BROWN_CROCK_MARBLE = 4096;
public static final int RED_CHINA_MARBLE = 4097;
public static final int LEMONADE_MARBLE = 4098;
public static final int BUMBLEBEE_MARBLE = 4099;
public static final int JET_BENNIE_MARBLE = 4100;
public static final int BEIGE_CLAMBROTH_MARBLE = 4101;
public static final int STEELY_MARBLE = 4102;
public static final int BEACH_BALL_MARBLE = 4103;
public static final int BLACK_CATSEYE_MARBLE = 4104;
public static final int BIG_BUMBOOZER_MARBLE = 4105;
public static final int MONSTROUS_MONOCLE = 4108;
public static final int MUSTY_MOCCASINS = 4109;
public static final int MOLTEN_MEDALLION = 4110;
public static final int BRAZEN_BRACELET = 4111;
public static final int BITTER_BOWTIE = 4112;
public static final int BEWITCHING_BOOTS = 4113;
public static final int SECRET_FROM_THE_FUTURE = 4114;
public static final int EMPTY_AGUA_DE_VIDA_BOTTLE = 4130;
public static final int TEMPURA_AIR = 4133;
public static final int PRESSURIZED_PNEUMATICITY = 4134;
public static final int MOVEABLE_FEAST = 4135;
public static final int BAG_O_TRICKS = 4136;
public static final int SLIME_STACK = 4137;
public static final int RUMPLED_PAPER_STRIP = 4138;
public static final int CREASED_PAPER_STRIP = 4139;
public static final int FOLDED_PAPER_STRIP = 4140;
public static final int CRINKLED_PAPER_STRIP = 4141;
public static final int CRUMPLED_PAPER_STRIP = 4142;
public static final int RAGGED_PAPER_STRIP = 4143;
public static final int RIPPED_PAPER_STRIP = 4144;
public static final int QUADROCULARS = 4149;
public static final int CAMERA = 4169;
public static final int SHAKING_CAMERA = 4170;
public static final int SPAGHETTI_CULT_ROBE = 4175;
public static final int SUGAR_SHEET = 4176;
public static final int SUGAR_BOOK = 4177;
public static final int SUGAR_SHOTGUN = 4178;
public static final int SUGAR_SHILLELAGH = 4179;
public static final int SUGAR_SHANK = 4180;
public static final int SUGAR_CHAPEAU = 4181;
public static final int SUGAR_SHORTS = 4182;
public static final int SUGAR_SHIELD = 4183;
public static final int SUGAR_SHIRT = 4191;
public static final int SUGAR_SHARD = 4192;
public static final int RAVE_VISOR = 4193;
public static final int BAGGY_RAVE_PANTS = 4194;
public static final int PACIFIER_NECKLACE = 4195;
public static final int MERKIN_CHEATSHEET = 4204;
public static final int MERKIN_WORDQUIZ = 4205;
public static final int SKATE_PARK_MAP = 4222;
public static final int AMPHIBIOUS_TOPHAT = 4229;
public static final int HACIENDA_KEY = 4233;
public static final int SILVER_PATE_KNIFE = 4234;
public static final int SILVER_CHEESE_SLICER = 4237;
public static final int SLEEP_MASK = 4241;
public static final int FISHERMANS_SACK = 4250;
public static final int FISH_OIL_SMOKE_BOMB = 4251;
public static final int VIAL_OF_SQUID_INK = 4252;
public static final int POTION_OF_FISHY_SPEED = 4253;
public static final int WOLFMAN_MASK = 4260;
public static final int PUMPKINHEAD_MASK = 4261;
public static final int MUMMY_COSTUME = 4262;
public static final int KRAKROXS_LOINCLOTH = 4267;
public static final int GALAPAGOSIAN_CUISSES = 4268;
public static final int ANGELHAIR_CULOTTES = 4269;
public static final int NEWMANS_OWN_TROUSERS = 4270;
public static final int VOLARTTAS_BELLBOTTOMS = 4271;
public static final int LEDERHOSEN_OF_THE_NIGHT = 4272;
public static final int UNDERWORLD_ACORN = 4274;
public static final int CRAPPY_MASK = 4282;
public static final int GLADIATOR_MASK = 4284;
public static final int SCHOLAR_MASK = 4285;
public static final int MERKIN_DODGEBALL = 4292;
public static final int MERKIN_DRAGNET = 4293;
public static final int MERKIN_SWITCHBLADE = 4294;
public static final int CRYSTAL_ORB = 4295;
public static final int DEPLETED_URANIUM_SEAL = 4296;
public static final int VIOLENCE_STOMPERS = 4297;
public static final int VIOLENCE_BRAND = 4298;
public static final int VIOLENCE_LENS = 4300;
public static final int VIOLENCE_PANTS = 4302;
public static final int HATRED_STONE = 4303;
public static final int HATRED_GIRDLE = 4304;
public static final int HATRED_STAFF = 4305;
public static final int HATRED_PANTS = 4306;
public static final int HATRED_SLIPPERS = 4307;
public static final int HATRED_LENS = 4308;
public static final int SLEDGEHAMMER_OF_THE_VAELKYR = 4316;
public static final int FLAIL_OF_THE_SEVEN_ASPECTS = 4317;
public static final int WRATH_OF_THE_PASTALORDS = 4318;
public static final int WINDSOR_PAN_OF_THE_SOURCE = 4319;
public static final int SEEGERS_BANJO = 4320;
public static final int TRICKSTER_TRIKITIXA = 4321;
public static final int INFERNAL_SEAL_CLAW = 4322;
public static final int TURTLE_POACHER_GARTER = 4323;
public static final int SPAGHETTI_BANDOLIER = 4324;
public static final int SAUCEBLOB_BELT = 4325;
public static final int NEW_WAVE_BLING = 4326;
public static final int BELT_BUCKLE_OF_LOPEZ = 4327;
public static final int BAG_OF_MANY_CONFECTIONS = 4329;
public static final int FANCY_CHOCOLATE_CAR = 4334;
public static final int CRIMBUCK = 4343;
public static final int GINGERBREAD_HOUSE = 4347;
public static final int CRIMBOUGH = 4353;
public static final int CRIMBO_CAROL_V1 = 4354;
public static final int CRIMBO_CAROL_V2 = 4355;
public static final int CRIMBO_CAROL_V3 = 4356;
public static final int CRIMBO_CAROL_V4 = 4357;
public static final int CRIMBO_CAROL_V5 = 4358;
public static final int CRIMBO_CAROL_V6 = 4359;
public static final int ELF_RESISTANCE_BUTTON = 4363;
public static final int WRENCH_HANDLE = 4368;
public static final int HEADLESS_BOLTS = 4369;
public static final int AGITPROP_INK = 4370;
public static final int HANDFUL_OF_WIRES = 4371;
public static final int CHUNK_OF_CEMENT = 4372;
public static final int PENGUIN_GRAPPLING_HOOK = 4373;
public static final int CARDBOARD_ELF_EAR = 4374;
public static final int SPIRALING_SHAPE = 4375;
public static final int CRIMBOMINATION_CONTRAPTION = 4376;
public static final int RED_AND_GREEN_SWEATER = 4391;
public static final int CRIMBO_CANDY_COOKBOOK = 4392;
public static final int STINKY_CHEESE_BALL = 4398;
public static final int STINKY_CHEESE_SWORD = 4399;
public static final int STINKY_CHEESE_DIAPER = 4400;
public static final int STINKY_CHEESE_WHEEL = 4401;
public static final int STINKY_CHEESE_EYE = 4402;
public static final int STINKY_CHEESE_STAFF = 4403;
public static final int SLAPFIGHTING_BOOK = 4406;
public static final int UNCLE_ROMULUS = 4407;
public static final int SNAKE_CHARMING_BOOK = 4408;
public static final int ZU_MANNKASE_DIENEN = 4409;
public static final int DYNAMITE_SUPERMAN_JONES = 4410;
public static final int INIGO_BOOK = 4411;
public static final int QUANTUM_TACO = 4412;
public static final int SCHRODINGERS_THERMOS = 4413;
public static final int BLACK_HYMNAL = 4426;
public static final int GLOWSTICK_ON_A_STRING = 4428;
public static final int CANDY_NECKLACE = 4429;
public static final int TEDDYBEAR_BACKPACK = 4430;
public static final int STRANGE_CUBE = 4436;
public static final int INSTANT_KARMA = 4448;
public static final int MACHETITO = 4452;
public static final int LEAFBLOWER = 4455;
public static final int SNAILMAIL_BITS = 4457;
public static final int CHOCOLATE_SEAL_CLUBBING_CLUB = 4462;
public static final int CHOCOLATE_TURTLE_TOTEM = 4463;
public static final int CHOCOLATE_PASTA_SPOON = 4464;
public static final int CHOCOLATE_SAUCEPAN = 4465;
public static final int CHOCOLATE_DISCO_BALL = 4466;
public static final int CHOCOLATE_STOLEN_ACCORDION = 4467;
public static final int BRICKO_BOOK = 4468;
public static final int BRICKO_EYE = 4470;
public static final int BRICKO_HAT = 4471;
public static final int BRICKO_PANTS = 4472;
public static final int BRICKO_SWORD = 4473;
public static final int BRICKO_OOZE = 4474;
public static final int BRICKO_BAT = 4475;
public static final int BRICKO_OYSTER = 4476;
public static final int BRICKO_TURTLE = 4477;
public static final int BRICKO_ELEPHANT = 4478;
public static final int BRICKO_OCTOPUS = 4479;
public static final int BRICKO_PYTHON = 4480;
public static final int BRICKO_VACUUM_CLEANER = 4481;
public static final int BRICKO_AIRSHIP = 4482;
public static final int BRICKO_CATHEDRAL = 4483;
public static final int BRICKO_CHICKEN = 4484;
public static final int BRICKO_PYRAMID = 4485;
public static final int RECORDING_BALLAD = 4497;
public static final int RECORDING_BENETTON = 4498;
public static final int RECORDING_ELRON = 4499;
public static final int RECORDING_CHORALE = 4500;
public static final int RECORDING_PRELUDE = 4501;
public static final int RECORDING_DONHO = 4502;
public static final int RECORDING_INIGO = 4503;
public static final int CLAN_LOOKING_GLASS = 4507;
public static final int DRINK_ME_POTION = 4508;
public static final int REFLECTION_OF_MAP = 4509;
public static final int WALRUS_ICE_CREAM = 4510;
public static final int BEAUTIFUL_SOUP = 4511;
public static final int HUMPTY_DUMPLINGS = 4514;
public static final int LOBSTER_QUA_GRILL = 4515;
public static final int MISSING_WINE = 4516;
public static final int ITTAH_BITTAH_HOOKAH = 4519;
public static final int STUFFED_POCKETWATCH = 4545;
public static final int JACKING_MAP = 4560;
public static final int TINY_FLY_GLASSES = 4566;
public static final int LEGENDARY_BEAT = 4573;
public static final int BUGGED_BEANIE = 4575;
public static final int BUGGED_BAIO = 4581;
public static final int PIXEL_WHIP = 4589;
public static final int PIXEL_CHAIN_WHIP = 4590;
public static final int PIXEL_MORNING_STAR = 4591;
public static final int PIXEL_ORB = 4592;
public static final int KEGGER_MAP = 4600;
public static final int ORQUETTES_PHONE_NUMBER = 4602;
public static final int BOTTLE_OF_GOLDENSCHNOCKERED = 4605;
public static final int ESSENTIAL_TOFU = 4609;
public static final int HATSEAT = 4614;
public static final int GG_TOKEN = 4621;
public static final int GG_TICKET = 4622;
public static final int COFFEE_PIXIE_STICK = 4625;
public static final int SPIDER_RING = 4629;
public static final int SINISTER_DEMON_MASK = 4637;
public static final int CHAMPION_BELT = 4638;
public static final int SPACE_TRIP_HEADPHONES = 4639;
public static final int KOL_CON_SIX_PACK = 4641;
public static final int JUJU_MOJO_MASK = 4644;
public static final int METEOID_ICE_BEAM = 4646;
public static final int DUNGEON_FIST_GAUNTLET = 4647;
public static final int IRONIC_MOUSTACHE = 4651;
public static final int ELLSBURY_BOOK = 4663;
public static final int INSULT_PUPPET = 4667;
public static final int OBSERVATIONAL_GLASSES = 4668;
public static final int COMEDY_PROP = 4669;
public static final int BEER_SCENTED_TEDDY_BEAR = 4670;
public static final int BOOZE_SOAKED_CHERRY = 4671;
public static final int COMFY_PILLOW = 4672;
public static final int GIANT_MARSHMALLOW = 4673;
public static final int SPONGE_CAKE = 4674;
public static final int GIN_SOAKED_BLOTTER_PAPER = 4675;
public static final int TREE_HOLED_COIN = 4676;
public static final int UNEARTHED_METEOROID = 4677;
public static final int VOLCANIC_ASH = 4679;
public static final int FOSSILIZED_BAT_SKULL = 4687;
public static final int FOSSILIZED_SERPENT_SKULL = 4688;
public static final int FOSSILIZED_BABOON_SKULL = 4689;
public static final int FOSSILIZED_WYRM_SKULL = 4690;
public static final int FOSSILIZED_WING = 4691;
public static final int FOSSILIZED_LIMB = 4692;
public static final int FOSSILIZED_TORSO = 4693;
public static final int FOSSILIZED_SPINE = 4694;
public static final int GREAT_PANTS = 4696;
public static final int IMP_AIR = 4698;
public static final int BUS_PASS = 4699;
public static final int FOSSILIZED_SPIKE = 4700;
public static final int ARCHAEOLOGING_SHOVEL = 4702;
public static final int FOSSILIZED_DEMON_SKULL = 4704;
public static final int FOSSILIZED_SPIDER_SKULL = 4705;
public static final int SINISTER_ANCIENT_TABLET = 4706;
public static final int OVEN = 4707;
public static final int SHAKER = 4708;
public static final int OLD_SWEATPANTS = 4711;
public static final int MARIACHI_HAT = 4718;
public static final int HOLLANDAISE_HELMET = 4719;
public static final int MICROWAVE_STOGIE = 4721;
public static final int LIVER_PIE = 4722;
public static final int BADASS_PIE = 4723;
public static final int FISH_PIE = 4724;
public static final int PIPING_PIE = 4725;
public static final int IGLOO_PIE = 4726;
public static final int TURNOVER = 4727;
public static final int DEAD_PIE = 4728;
public static final int THROBBING_PIE = 4729;
public static final int BONE_CHIPS = 4743;
public static final int STABONIC_SCROLL = 4757;
public static final int PUMPKIN_SEEDS = 4760;
public static final int PUMPKIN = 4761;
public static final int HUGE_PUMPKIN = 4762;
public static final int PUMPKIN_BOMB = 4766;
public static final int PUMPKIN_CARRIAGE = 4769;
public static final int DESERT_BUS_PASS = 4770;
public static final int GINORMOUS_PUMPKIN = 4771;
public static final int ESSENCE_OF_ANNOYANCE = 4804;
public static final int HOLIDAY_FUN_BOOK = 4810;
public static final int ANTAGONISTIC_SNOWMAN_KIT = 4812;
public static final int SLEEPING_STOCKING = 4842;
public static final int KANSAS_TOYMAKER = 4843;
public static final int WASSAILING_BOOK = 4844;
public static final int UNCLE_HOBO_BEARD = 4846;
public static final int CHOCOLATE_CIGAR = 4851;
public static final int CRIMBCO_SCRIP = 4854;
public static final int BLANK_OUT_BOTTLE = 4857;
public static final int CRIMBCO_MANUAL_1 = 4859;
public static final int CRIMBCO_MANUAL_2 = 4860;
public static final int CRIMBCO_MANUAL_3 = 4861;
public static final int CRIMBCO_MANUAL_4 = 4862;
public static final int CRIMBCO_MANUAL_5 = 4863;
public static final int PHOTOCOPIER = 4864;
public static final int CLAN_FAX_MACHINE = 4865;
public static final int WORKYTIME_TEA = 4866;
public static final int GLOB_OF_BLANK_OUT = 4872;
public static final int PHOTOCOPIED_MONSTER = 4873;
public static final int GAUDY_KEY = 4874;
public static final int CRIMBCO_MUG = 4880;
public static final int CRIMBCO_WINE = 4881;
public static final int BGE_SHOTGLASS = 4893;
public static final int BGE_TATTOO = 4900;
public static final int COAL_PAPERWEIGHT = 4905;
public static final int JINGLE_BELL = 4906;
public static final int LOATHING_LEGION_KNIFE = 4908;
public static final int LOATHING_LEGION_MANY_PURPOSE_HOOK = 4909;
public static final int LOATHING_LEGION_MOONDIAL = 4910;
public static final int LOATHING_LEGION_NECKTIE = 4911;
public static final int LOATHING_LEGION_ELECTRIC_KNIFE = 4912;
public static final int LOATHING_LEGION_CORKSCREW = 4913;
public static final int LOATHING_LEGION_CAN_OPENER = 4914;
public static final int LOATHING_LEGION_CHAINSAW = 4915;
public static final int LOATHING_LEGION_ROLLERBLADES = 4916;
public static final int LOATHING_LEGION_FLAMETHROWER = 4917;
public static final int LOATHING_LEGION_TATTOO_NEEDLE = 4918;
public static final int LOATHING_LEGION_DEFIBRILLATOR = 4919;
public static final int LOATHING_LEGION_DOUBLE_PRISM = 4920;
public static final int LOATHING_LEGION_TAPE_MEASURE = 4921;
public static final int LOATHING_LEGION_KITCHEN_SINK = 4922;
public static final int LOATHING_LEGION_ABACUS = 4923;
public static final int LOATHING_LEGION_HELICOPTER = 4924;
public static final int LOATHING_LEGION_PIZZA_STONE = 4925;
public static final int LOATHING_LEGION_UNIVERSAL_SCREWDRIVER = 4926;
public static final int LOATHING_LEGION_JACKHAMMER = 4927;
public static final int LOATHING_LEGION_HAMMER = 4928;
public static final int QUAKE_OF_ARROWS = 4938;
public static final int KNOB_CAKE = 4942;
public static final int MENAGERIE_KEY = 4947;
public static final int GOTO = 4948;
public static final int WEREMOOSE_SPIT = 4949;
public static final int ABOMINABLE_BLUBBER = 4950;
public static final int SUBJECT_37_FILE = 4961;
public static final int EVILOMETER = 4964;
public static final int CARD_GAME_BOOK = 4965;
public static final int CARD_SLEEVE = 5009;
public static final int EVIL_EYE = 5010;
public static final int SNACK_VOUCHER = 5012;
public static final int WASABI_FOOD = 5013;
public static final int TOBIKO_FOOD = 5014;
public static final int NATTO_FOOD = 5015;
public static final int WASABI_BOOZE = 5016;
public static final int TOBIKO_BOOZE = 5017;
public static final int NATTO_BOOZE = 5018;
public static final int WASABI_POTION = 5019;
public static final int TOBIKO_POTION = 5020;
public static final int NATTO_POTION = 5021;
public static final int PET_SWEATER = 5040;
public static final int ASTRAL_HOT_DOG = 5043;
public static final int ASTRAL_PILSNER = 5044;
public static final int CLAN_SHOWER = 5047;
public static final int LARS_THE_CYBERIAN = 5053;
public static final int CREEPY_VOODOO_DOLL = 5062;
public static final int SPAGHETTI_CON_CALAVERAS = 5065;
public static final int SMORE_GUN = 5066;
public static final int TINY_BLACK_HOLE = 5069;
public static final int SMORE = 5071;
public static final int RUSSIAN_ICE = 5073;
public static final int STRESS_BALL = 5109;
public static final int PEN_PAL_KIT = 5112;
public static final int RUSTY_HEDGE_TRIMMERS = 5115;
public static final int AWOL_COMMENDATION = 5116;
public static final int RECONSTITUTED_CROW = 5117;
public static final int BIRD_BRAIN = 5118;
public static final int BUSTED_WINGS = 5119;
public static final int MARAUDER_MOCKERY_MANUAL = 5120;
public static final int SKELETON_BOOK = 5124;
public static final int LUNAR_ISOTOPE = 5134;
public static final int EMU_JOYSTICK = 5135;
public static final int EMU_ROCKET = 5136;
public static final int EMU_HELMET = 5137;
public static final int EMU_HARNESS = 5138;
public static final int ASTRAL_ENERGY_DRINK = 5140;
public static final int EMU_UNIT = 5143;
public static final int HONEYPOT = 5145;
public static final int SPOOKY_LITTLE_GIRL = 5165;
public static final int SYNTHETIC_DOG_HAIR_PILL = 5167;
public static final int DISTENTION_PILL = 5168;
public static final int TRANSPORTER_TRANSPONDER = 5170;
public static final int RONALD_SHELTER_MAP = 5171;
public static final int GRIMACE_SHELTER_MAP = 5172;
public static final int MOON_BOOZE_1 = 5174;
public static final int MOON_BOOZE_2 = 5175;
public static final int MOON_BOOZE_3 = 5176;
public static final int MOON_FOOD_1 = 5177;
public static final int MOON_FOOD_2 = 5178;
public static final int MOON_FOOD_3 = 5179;
public static final int MOON_POTION_1 = 5180;
public static final int MOON_POTION_2 = 5181;
public static final int MOON_POTION_3 = 5182;
public static final int DOUBLE_ICE_GUM = 5189;
public static final int PATRIOT_SHIELD = 5190;
public static final int BIG_KNOB_SAUSAGE = 5193;
public static final int EXORCISED_SANDWICH = 5194;
public static final int GOOEY_PASTE = 5198;
public static final int BEASTLY_PASTE = 5199;
public static final int OILY_PASTE = 5200;
public static final int ECTOPLASMIC = 5201;
public static final int GREASY_PASTE = 5202;
public static final int BUG_PASTE = 5203;
public static final int HIPPY_PASTE = 5204;
public static final int ORC_PASTE = 5205;
public static final int DEMONIC_PASTE = 5206;
public static final int INDESCRIBABLY_HORRIBLE_PASTE = 5207;
public static final int FISHY_PASTE = 5208;
public static final int GOBLIN_PASTE = 5209;
public static final int PIRATE_PASTE = 5210;
public static final int CHLOROPHYLL_PASTE = 5211;
public static final int STRANGE_PASTE = 5212;
public static final int MER_KIN_PASTE = 5213;
public static final int SLIMY_PASTE = 5214;
public static final int PENGUIN_PASTE = 5215;
public static final int ELEMENTAL_PASTE = 5216;
public static final int COSMIC_PASTE = 5217;
public static final int HOBO_PASTE = 5218;
public static final int CRIMBO_PASTE = 5219;
public static final int TEACHINGS_OF_THE_FIST = 5220;
public static final int FAT_LOOT_TOKEN = 5221;
public static final int CLIP_ART_BOOK = 5223;
public static final int BUCKET_OF_WINE = 5227;
public static final int CRYSTAL_SKULL = 5231;
public static final int BORROWED_TIME = 5232;
public static final int BOX_OF_HAMMERS = 5233;
public static final int LUMINEUX_LIMNIO = 5238;
public static final int MORTO_MORETO = 5239;
public static final int TEMPS_TEMPRANILLO = 5240;
public static final int BORDEAUX_MARTEAUX = 5241;
public static final int FROMAGE_PINOTAGE = 5242;
public static final int BEIGNET_MILGRANET = 5243;
public static final int MUSCHAT = 5244;
public static final int FIELD_GAR_POTION = 5257;
public static final int DICE_BOOK = 5284;
public static final int D4 = 5285;
public static final int D6 = 5286;
public static final int D8 = 5287;
public static final int D10 = 5288;
public static final int D12 = 5289;
public static final int D20 = 5290;
public static final int PLASTIC_VAMPIRE_FANGS = 5299;
public static final int STAFF_GUIDE = 5307;
public static final int CHAINSAW_CHAIN = 5309;
public static final int SILVER_SHOTGUN_SHELL = 5310;
public static final int FUNHOUSE_MIRROR = 5311;
public static final int GHOSTLY_BODY_PAINT = 5312;
public static final int NECROTIZING_BODY_SPRAY = 5313;
public static final int BITE_LIPSTICK = 5314;
public static final int WHISKER_PENCIL = 5315;
public static final int PRESS_ON_RIBS = 5316;
public static final int BB_WINE_COOLER = 5323;
public static final int NECBRONOMICON = 5341;
public static final int NECBRONOMICON_USED = 5343;
public static final int CRIMBO_CAROL_V1_USED = 5347;
public static final int CRIMBO_CAROL_V2_USED = 5348;
public static final int CRIMBO_CAROL_V3_USED = 5349;
public static final int CRIMBO_CAROL_V4_USED = 5350;
public static final int CRIMBO_CAROL_V5_USED = 5351;
public static final int CRIMBO_CAROL_V6_USED = 5352;
public static final int JAR_OF_OIL = 5353;
public static final int SLAPFIGHTING_BOOK_USED = 5354;
public static final int UNCLE_ROMULUS_USED = 5355;
public static final int SNAKE_CHARMING_BOOK_USED = 5356;
public static final int ZU_MANNKASE_DIENEN_USED = 5357;
public static final int DYNAMITE_SUPERMAN_JONES_USED = 5358;
public static final int INIGO_BOOK_USED = 5359;
public static final int KANSAS_TOYMAKER_USED = 5360;
public static final int WASSAILING_BOOK_USED = 5361;
public static final int CRIMBCO_MANUAL_1_USED = 5362;
public static final int CRIMBCO_MANUAL_2_USED = 5363;
public static final int CRIMBCO_MANUAL_3_USED = 5364;
public static final int CRIMBCO_MANUAL_4_USED = 5365;
public static final int CRIMBCO_MANUAL_5_USED = 5366;
public static final int SKELETON_BOOK_USED = 5367;
public static final int ELLSBURY_BOOK_USED = 5368;
public static final int GROOSE_GREASE = 5379;
public static final int LOLLIPOP_STICK = 5380;
public static final int PEPPERMINT_SPROUT = 5395;
public static final int PEPPERMINT_PARASOL = 5401;
public static final int GIANT_CANDY_CANE = 5402;
public static final int PEPPERMINT_PACKET = 5404;
public static final int FUDGECULE = 5435;
public static final int FUDGE_WAND = 5441;
public static final int DEVILISH_FOLIO = 5444;
public static final int FURIOUS_STONE = 5448;
public static final int VANITY_STONE = 5449;
public static final int LECHEROUS_STONE = 5450;
public static final int JEALOUSY_STONE = 5451;
public static final int AVARICE_STONE = 5452;
public static final int GLUTTONOUS_STONE = 5453;
public static final int FUDGIE_ROLL = 5457;
public static final int FUDGE_BUNNY = 5458;
public static final int FUDGE_SPORK = 5459;
public static final int FUDGECYCLE = 5460;
public static final int FUDGE_CUBE = 5461;
public static final int RESOLUTION_BOOK = 5463;
public static final int RESOLUTION_KINDER = 5470;
public static final int RESOLUTION_ADVENTUROUS = 5471;
public static final int RESOLUTION_LUCKIER = 5472;
public static final int RED_DRUNKI_BEAR = 5482;
public static final int GREEN_DRUNKI_BEAR = 5483;
public static final int YELLOW_DRUNKI_BEAR = 5484;
public static final int ALL_YEAR_SUCKER = 5497;
public static final int DARK_CHOCOLATE_HEART = 5498;
public static final int JACKASS_PLUMBER_GAME = 5501;
public static final int TRIVIAL_AVOCATIONS_GAME = 5502;
public static final int PACK_OF_POGS = 5505;
public static final int WHAT_CARD = 5511;
public static final int WHEN_CARD = 5512;
public static final int WHO_CARD = 5513;
public static final int WHERE_CARD = 5514;
public static final int PLANT_BOOK = 5546;
public static final int CLANCY_SACKBUT = 5547;
public static final int GHOST_BOOK = 5548;
public static final int CLANCY_CRUMHORN = 5549;
public static final int TATTLE_BOOK = 5550;
public static final int CLANCY_LUTE = 5551;
public static final int TRUSTY = 5552;
public static final int RAIN_DOH_BOX = 5563;
public static final int RAIN_DOH_MONSTER = 5564;
public static final int GROARS_FUR = 5571;
public static final int GLOWING_FUNGUS = 5641;
public static final int STONE_WOOL = 5643;
public static final int NOSTRIL_OF_THE_SERPENT = 5645;
public static final int BORIS_HELM = 5648;
public static final int BORIS_HELM_ASKEW = 5650;
public static final int MIME_SOUL_FRAGMENT = 5651;
public static final int KEYOTRON = 5653;
public static final int CLAN_SWIMMING_POOL = 5662;
public static final int CURSED_MICROWAVE = 5663;
public static final int CURSED_KEG = 5664;
public static final int JERK_BOOK = 5665;
public static final int GRUDGE_BOOK = 5666;
public static final int LOST_KEY = 5680;
public static final int NOTE_FROM_CLANCY = 5682;
public static final int BURT = 5683;
public static final int AUTOPSY_TWEEZERS = 5687;
public static final int LOST_GLASSES = 5698;
public static final int LITTLE_MANNEQUIN = 5702;
public static final int CRAYON_SHAVINGS = 5703;
public static final int WAX_BUGBEAR = 5704;
public static final int FDKOL_COMMENDATION = 5707;
public static final int HJODOR_GUIDE = 5715;
public static final int HJODOR_GUIDE_USED = 5716;
public static final int LORD_FLAMEFACES_CLOAK = 5735;
public static final int CSA_FIRE_STARTING_KIT = 5739;
public static final int CRAPPY_BRAIN = 5752;
public static final int DECENT_BRAIN = 5753;
public static final int GOOD_BRAIN = 5754;
public static final int BOSS_BRAIN = 5755;
public static final int HUNTER_BRAIN = 5756;
public static final int FUZZY_BUSBY = 5764;
public static final int FUZZY_EARMUFFS = 5765;
public static final int FUZZY_MONTERA = 5766;
public static final int GNOMISH_EAR = 5768;
public static final int GNOMISH_LUNG = 5769;
public static final int GNOMISH_ELBOW = 5770;
public static final int GNOMISH_KNEE = 5771;
public static final int GNOMISH_FOOT = 5772;
public static final int SOFT_GREEN_ECHO_ANTIDOTE_MARTINI = 5781;
public static final int MORNINGWOOD_PLANK = 5782;
public static final int HARDWOOD_PLANK = 5783;
public static final int WEIRDWOOD_PLANK = 5784;
public static final int THICK_CAULK = 5785;
public static final int LONG_SCREW = 5786;
public static final int BUTT_JOINT = 5787;
public static final int BUBBLIN_CRUDE = 5789;
public static final int BOX_OF_BEAR_ARM = 5790;
public static final int RIGHT_BEAR_ARM = 5791;
public static final int LEFT_BEAR_ARM = 5792;
public static final int RAD_LIB_BOOK = 5862;
public static final int PAPIER_MACHETE = 5868;
public static final int PAPIER_MACHINE_GUN = 5869;
public static final int PAPIER_MASK = 5870;
public static final int PAPIER_MITRE = 5871;
public static final int PAPIER_MACHURIDARS = 5872;
public static final int DRAGON_TEETH = 5880;
public static final int SKELETON = 5881;
public static final int SKIFF = 5885;
public static final int LAZYBONES_RECLINER = 5888;
public static final int UNCONSCIOUS_COLLECTIVE_DREAM_JAR = 5897;
public static final int SUSPICIOUS_JAR = 5898;
public static final int GOURD_JAR = 5899;
public static final int MYSTIC_JAR = 5900;
public static final int OLD_MAN_JAR = 5901;
public static final int ARTIST_JAR = 5902;
public static final int MEATSMITH_JAR = 5903;
public static final int JICK_JAR = 5905;
public static final int CHIBIBUDDY_ON = 5908;
public static final int NANORHINO_CREDIT_CARD = 5911;
public static final int BEET_MEDIOCREBAR = 5915;
public static final int CORN_MEDIOCREBAR = 5916;
public static final int CABBAGE_MEDIOCREBAR = 5917;
public static final int CHIBIBUDDY_OFF = 5925;
public static final int BITTYCAR_MEATCAR = 5926;
public static final int BITTYCAR_HOTCAR = 5927;
public static final int ELECTRONIC_DULCIMER_PANTS = 5963;
public static final int BOO_CLUE = 5964;
public static final int INFURIATING_SILENCE_RECORD = 5971;
public static final int INFURIATING_SILENCE_RECORD_USED = 5972;
public static final int TRANQUIL_SILENCE_RECORD = 5973;
public static final int TRANQUIL_SILENCE_RECORD_USED = 5974;
public static final int MENACING_SILENCE_RECORD = 5975;
public static final int MENACING_SILENCE_RECORD_USED = 5976;
public static final int SLICE_OF_PIZZA = 5978;
public static final int BOTTLE_OF_WINE = 5990;
public static final int BOSS_HELM = 6002;
public static final int BOSS_CLOAK = 6003;
public static final int BOSS_SWORD = 6004;
public static final int BOSS_SHIELD = 6005;
public static final int BOSS_PANTS = 6006;
public static final int BOSS_GAUNTLETS = 6007;
public static final int BOSS_BOOTS = 6008;
public static final int BOSS_BELT = 6009;
public static final int TRIPPLES = 6027;
public static final int DRESS_PANTS = 6030;
public static final int INCREDIBLE_PIZZA = 6038;
public static final int OIL_PAN = 6042;
public static final int BITTYCAR_SOULCAR = 6046;
public static final int MISTY_CLOAK = 6047;
public static final int MISTY_ROBE = 6048;
public static final int MISTY_CAPE = 6049;
public static final int TACO_FLIER = 6051;
public static final int PSYCHOANALYTIC_JAR = 6055;
public static final int CRIMBO_CREEPY_HEAD = 6058;
public static final int CRIMBO_STOGIE_ODORIZER = 6059;
public static final int CRIMBO_HOT_MUG = 6060;
public static final int CRIMBO_TREE_FLOCKER = 6061;
public static final int CRIMBO_RUDOLPH_DOLL = 6062;
public static final int GEEKY_BOOK = 6071;
public static final int LED_CLOCK = 6072;
public static final int HAGGIS_SOCKS = 6080;
public static final int CLASSY_MONKEY = 6097;
public static final int CEO_OFFICE_CARD = 6116;
public static final int STRANGE_GOGGLES = 6118;
public static final int BONSAI_TREE = 6120;
public static final int LUCKY_CAT_STATUE = 6122;
public static final int GOLD_PIECE = 6130;
public static final int JICK_SWORD = 6146;
public static final int SNOW_SUIT = 6150;
public static final int CARROT_NOSE = 6151;
public static final int CARROT_CLARET = 6153;
public static final int PIXEL_POWER_CELL = 6155;
public static final int ANGER_BLASTER = 6158;
public static final int DOUBT_CANNON = 6159;
public static final int FEAR_CONDENSER = 6160;
public static final int REGRET_HOSE = 6161;
public static final int GAMEPRO_MAGAZINE = 6174;
public static final int GAMEPRO_WALKTHRU = 6175;
public static final int COSMIC_EGG = 6176;
public static final int COSMIC_VEGETABLE = 6178;
public static final int COSMIC_POTATO = 6181;
public static final int COSMIC_CREAM = 6182;
public static final int MEDIOCRE_LAGER = 6215;
public static final int COSMIC_SIX_PACK = 6237;
public static final int WALBERG_BOOK = 6253;
public static final int OCELOT_BOOK = 6254;
public static final int DRESCHER_BOOK = 6255;
public static final int STAFF_OF_BREAKFAST = 6258;
public static final int STAFF_OF_LIFE = 6259;
public static final int STAFF_OF_CHEESE = 6261;
public static final int STAFF_OF_STEAK = 6263;
public static final int STAFF_OF_CREAM = 6265;
public static final int YE_OLDE_MEAD = 6276;
public static final int MARK_V_STEAM_HAT = 6289;
public static final int ROCKETSHIP = 6290;
public static final int DRUM_N_BASS_RECORD = 6295;
public static final int JARLSBERG_SOUL_FRAGMENT = 6297;
public static final int MODEL_AIRSHIP = 6299;
public static final int RING_OF_DETECT_BORING_DOORS = 6303;
public static final int JARLS_COSMIC_PAN = 6304;
public static final int JARLS_PAN = 6305;
public static final int UNCLE_BUCK = 6311;
public static final int FISH_MEAT_CRATE = 6312;
public static final int DAMP_WALLET = 6313;
public static final int FISHY_PIPE = 6314;
public static final int OLD_SCUBA_TANK = 6315;
public static final int SUSHI_DOILY = 6328;
public static final int COZY_SCIMITAR = 6332;
public static final int COZY_STAFF = 6333;
public static final int COZY_BAZOOKA = 6334;
public static final int SALTWATERBED = 6338;
public static final int DREADSCROLL = 6353;
public static final int MERKIN_WORKTEA = 6356;
public static final int MERKIN_KNUCKLEBONE = 6357;
public static final int TAFFY_BOOK = 6360;
public static final int YELLOW_TAFFY = 6361;
public static final int INDIGO_TAFFY = 6362;
public static final int GREEN_TAFFY = 6363;
public static final int MERKIN_HALLPASS = 6368;
public static final int LUMP_OF_CLAY = 6369;
public static final int TWISTED_PIECE_OF_WIRE = 6370;
public static final int FRUITY_WINE = 6372;
public static final int ANGRY_INCH = 6374;
public static final int ERASER_NUBBIN = 6378;
public static final int CHLORINE_CRYSTAL = 6379;
public static final int PH_BALANCER = 6380;
public static final int MYSTERIOUS_CHEMICAL_RESIDUE = 6381;
public static final int NUGGET_OF_SODIUM = 6382;
public static final int JIGSAW_BLADE = 6384;
public static final int WOOD_SCREW = 6385;
public static final int BALSA_PLANK = 6386;
public static final int BLOB_OF_WOOD_GLUE = 6387;
public static final int ENVYFISH_EGG = 6388;
public static final int ANEMONE_SAUCE = 6394;
public static final int INKY_SQUID_SAUCE = 6395;
public static final int MERKIN_WEAKSAUCE = 6396;
public static final int PEANUT_SAUCE = 6397;
public static final int BLACK_GLASS = 6398;
public static final int POCKET_SQUARE = 6407;
public static final int CORRUPTED_STARDUST = 6408;
public static final int SHAKING_SKULL = 6412;
public static final int TWIST_OF_LIME = 6417;
public static final int TONIC_DJINN = 6421;
public static final int TALES_OF_DREAD = 6423;
public static final int DREADSYLVANIAN_SKELETON_KEY = 6424;
public static final int BRASS_DREAD_FLASK = 6428;
public static final int SILVER_DREAD_FLASK = 6429;
public static final int KRUEGERAND = 6433;
public static final int MARK_OF_THE_BUGBEAR = 6434;
public static final int MARK_OF_THE_WEREWOLF = 6435;
public static final int MARK_OF_THE_ZOMBIE = 6436;
public static final int MARK_OF_THE_GHOST = 6437;
public static final int MARK_OF_THE_VAMPIRE = 6438;
public static final int MARK_OF_THE_SKELETON = 6439;
public static final int HELPS_YOU_SLEEP = 6443;
public static final int GREAT_WOLFS_LEFT_PAW = 6448;
public static final int GREAT_WOLFS_RIGHT_PAW = 6449;
public static final int GREAT_WOLFS_ROCKET_LAUNCHER = 6450;
public static final int HUNGER_SAUCE = 6453;
public static final int ZOMBIE_ACCORDION = 6455;
public static final int MAYOR_GHOSTS_GAVEL = 6465;
public static final int DRUNKULA_WINEGLASS = 6474;
public static final int BLOODWEISER = 6475;
public static final int ELECTRIC_KOOL_AID = 6483;
public static final int DREAD_TARRAGON = 6484;
public static final int BONE_FLOUR = 6485;
public static final int DREADFUL_ROAST = 6486;
public static final int STINKING_AGARICUS = 6487;
public static final int SHEPHERDS_PIE = 6488;
public static final int INTRICATE_MUSIC_BOX_PARTS = 6489;
public static final int WAX_BANANA = 6492;
public static final int WAX_LOCK_IMPRESSION = 6493;
public static final int REPLICA_KEY = 6494;
public static final int AUDITORS_BADGE = 6495;
public static final int BLOOD_KIWI = 6496;
public static final int EAU_DE_MORT = 6497;
public static final int BLOODY_KIWITINI = 6498;
public static final int MOON_AMBER = 6499;
public static final int MOON_AMBER_NECKLACE = 6501;
public static final int DREAD_POD = 6502;
public static final int GHOST_PENCIL = 6503;
public static final int DREADSYLVANIAN_CLOCKWORK_KEY = 6506;
public static final int COOL_IRON_INGOT = 6507;
public static final int GHOST_SHAWL = 6511;
public static final int SKULL_CAPACITOR = 6512;
public static final int WARM_FUR = 6513;
public static final int GHOST_THREAD = 6525;
public static final int HOTHAMMER = 6528;
public static final int MUDDY_SKIRT = 6531;
public static final int FRYING_BRAINPAN = 6538;
public static final int OLD_BALL_AND_CHAIN = 6539;
public static final int OLD_DRY_BONE = 6540;
public static final int WEEDY_SKIRT = 6545;
public static final int HOT_CLUSTER = 6551;
public static final int COLD_CLUSTER = 6552;
public static final int SPOOKY_CLUSTER = 6553;
public static final int STENCH_CLUSTER = 6554;
public static final int SLEAZE_CLUSTER = 6555;
public static final int PHIAL_OF_HOTNESS = 6556;
public static final int PHIAL_OF_COLDNESS = 6557;
public static final int PHIAL_OF_SPOOKINESS = 6558;
public static final int PHIAL_OF_STENCH = 6559;
public static final int PHIAL_OF_SLEAZINESS = 6560;
public static final int DREADSYLVANIAN_ALMANAC = 6579;
public static final int CLAN_HOT_DOG_STAND = 6582;
public static final int VICIOUS_SPIKED_COLLAR = 6583;
public static final int ANCIENT_HOT_DOG_WRAPPER = 6584;
public static final int DEBONAIR_DEBONER = 6585;
public static final int CHICLE_DE_SALCHICA = 6586;
public static final int JAR_OF_FROSTIGKRAUT = 6587;
public static final int GNAWED_UP_DOG_BONE = 6588;
public static final int GREY_GUANON = 6589;
public static final int ENGORGED_SAUSAGES_AND_YOU = 6590;
public static final int DREAM_OF_A_DOG = 6591;
public static final int OPTIMAL_SPREADSHEET = 6592;
public static final int DEFECTIVE_TOKEN = 6593;
public static final int HOT_DREADSYLVANIAN_COCOA = 6594;
public static final int CUCKOO_CLOCK = 6614;
public static final int SPAGHETTI_BREAKFAST = 6616;
public static final int FOLDER_HOLDER = 6617;
public static final int FOLDER_01 = 6618;
public static final int FOLDER_02 = 6619;
public static final int FOLDER_03 = 6620;
public static final int FOLDER_04 = 6621;
public static final int FOLDER_05 = 6622;
public static final int FOLDER_06 = 6623;
public static final int FOLDER_07 = 6624;
public static final int FOLDER_08 = 6625;
public static final int FOLDER_09 = 6626;
public static final int FOLDER_10 = 6627;
public static final int FOLDER_11 = 6628;
public static final int FOLDER_12 = 6629;
public static final int FOLDER_13 = 6630;
public static final int FOLDER_14 = 6631;
public static final int FOLDER_15 = 6632;
public static final int FOLDER_16 = 6633;
public static final int FOLDER_17 = 6634;
public static final int FOLDER_18 = 6635;
public static final int FOLDER_19 = 6636;
public static final int FOLDER_20 = 6637;
public static final int FOLDER_21 = 6638;
public static final int FOLDER_22 = 6639;
public static final int FOLDER_23 = 6640;
public static final int FOLDER_24 = 6641;
public static final int FOLDER_25 = 6642;
public static final int FOLDER_26 = 6643;
public static final int FOLDER_27 = 6644;
public static final int FOLDER_28 = 6645;
public static final int MOUNTAIN_STREAM_CODE_BLACK_ALERT = 6650;
public static final int SURGICAL_TAPE = 6653;
public static final int ILLEGAL_FIRECRACKER = 6656;
public static final int SCRAP_METAL = 6659;
public static final int SPIRIT_SOCKET_SET = 6660;
public static final int MINIATURE_SUSPENSION_BRIDGE = 6661;
public static final int STAFF_OF_THE_LUNCH_LADY = 6662;
public static final int UNIVERSAL_KEY = 6663;
public static final int WORLDS_MOST_DANGEROUS_BIRDHOUSE = 6664;
public static final int DEATHCHUCKS = 6665;
public static final int GIANT_ERASER = 6666;
public static final int QUASIRELGIOUS_SCULPTURE = 6667;
public static final int GIANT_FARADAY_CAGE = 6668;
public static final int MODELING_CLAYMORE = 6669;
public static final int STICKY_CLAY_HOMUNCULUS = 6670;
public static final int SODIUM_PENTASOMETHING = 6671;
public static final int GRAINS_OF_SALT = 6672;
public static final int YELLOWCAKE_BOMB = 6673;
public static final int DIRTY_STINKBOMB = 6674;
public static final int SUPERWATER = 6675;
public static final int CRUDE_SCULPTURE = 6677;
public static final int YEARBOOK_CAMERA = 6678;
public static final int ANTIQUE_MACHETE = 6679;
public static final int BOWL_OF_SCORPIONS = 6681;
public static final int BOOK_OF_MATCHES = 6683;
public static final int MCCLUSKY_FILE_PAGE5 = 6693;
public static final int BINDER_CLIP = 6694;
public static final int MCCLUSKY_FILE = 6695;
public static final int BOWLING_BALL = 6696;
public static final int MOSS_COVERED_STONE_SPHERE = 6697;
public static final int DRIPPING_STONE_SPHERE = 6698;
public static final int CRACKLING_STONE_SPHERE = 6699;
public static final int SCORCHED_STONE_SPHERE = 6700;
public static final int STONE_TRIANGLE = 6701;
public static final int BONE_ABACUS = 6712;
public static final int SHIP_TRIP_SCRIP = 6725;
public static final int UV_RESISTANT_COMPASS = 6729;
public static final int FUNKY_JUNK_KEY = 6730;
public static final int WORSE_HOMES_GARDENS = 6731;
public static final int JUNK_JUNK = 6735;
public static final int ETERNAL_CAR_BATTERY = 6741;
public static final int BEER_SEEDS = 6751;
public static final int BARLEY = 6752;
public static final int HOPS = 6753;
public static final int FANCY_BEER_BOTTLE = 6754;
public static final int FANCY_BEER_LABEL = 6755;
public static final int TIN_ROOF = 6773;
public static final int TIN_LIZZIE = 6775;
public static final int ABYSSAL_BATTLE_PLANS = 6782;
public static final int TOY_ACCORDION = 6808;
public static final int ANTIQUE_ACCORDION = 6809;
public static final int BEER_BATTERED_ACCORDION = 6810;
public static final int BARITONE_ACCORDION = 6811;
public static final int MAMAS_SQUEEZEBOX = 6812;
public static final int GUANCERTINA = 6813;
public static final int ACCORDION_FILE = 6814;
public static final int ACCORD_ION = 6815;
public static final int BONE_BANDONEON = 6816;
public static final int PENTATONIC_ACCORDION = 6817;
public static final int NON_EUCLIDEAN_NON_ACCORDION = 6818;
public static final int ACCORDION_OF_JORDION = 6819;
public static final int AUTOCALLIOPE = 6820;
public static final int ACCORDIONOID_ROCCA = 6821;
public static final int PYGMY_CONCERTINETTE = 6822;
public static final int GHOST_ACCORDION = 6823;
public static final int PEACE_ACCORDION = 6824;
public static final int ALARM_ACCORDION = 6825;
public static final int SWIZZLER = 6837;
public static final int WALKIE_TALKIE = 6846;
public static final int KILLING_JAR = 6847;
public static final int HUGE_BOWL_OF_CANDY = 6851;
public static final int ULTRA_MEGA_SOUR_BALL = 6852;
public static final int DESERT_PAMPHLET = 6854;
public static final int SUSPICIOUS_ADDRESS = 6855;
public static final int BAL_MUSETTE_ACCORDION = 6856;
public static final int CAJUN_ACCORDION = 6857;
public static final int QUIRKY_ACCORDION = 6858;
public static final int SKIPPERS_ACCORDION = 6859;
public static final int PANTSGIVING = 6860;
public static final int BLUE_LINT = 6877;
public static final int GREEN_LINT = 6878;
public static final int WHITE_LINT = 6879;
public static final int ORANGE_LINT = 6880;
public static final int SPIRIT_PILLOW = 6886;
public static final int SPIRIT_SHEET = 6887;
public static final int SPIRIT_MATTRESS = 6888;
public static final int SPIRIT_BLANKET = 6889;
public static final int SPIRIT_BED = 6890;
public static final int CHEF_BOY_BUSINESS_CARD = 6898;
public static final int PASTA_ADDITIVE = 6900;
public static final int WARBEAR_WHOSIT = 6913;
public static final int WARBEAR_BATTERY = 6916;
public static final int WARBEAR_BADGE = 6917;
public static final int WARBEAR_FEASTING_MEAD = 6924;
public static final int WARBEAR_BEARSERKER_MEAD = 6925;
public static final int WARBEAR_BLIZZARD_MEAD = 6926;
public static final int WARBEAR_OIL_PAN = 6961;
public static final int JACKHAMMER_DRILL_PRESS = 6964;
public static final int AUTO_ANVIL = 6965;
public static final int INDUCTION_OVEN = 6966;
public static final int CHEMISTRY_LAB = 6967;
public static final int WARBEAR_EMPATHY_CHIP = 6969;
public static final int SMITH_BOOK = 7003;
public static final int HANDFUL_OF_SMITHEREENS = 7006;
public static final int GOLDEN_LIGHT = 7013;
public static final int LOUDER_THAN_BOMB = 7014;
public static final int OUIJA_BOARD = 7025;
public static final int SAUCEPANIC = 7027;
public static final int SHAKESPEARES_SISTERS_ACCORDION = 7029;
public static final int WARBEAR_BLACK_BOX = 7035;
public static final int HIGH_EFFICIENCY_STILL = 7036;
public static final int LP_ROM_BURNER = 7037;
public static final int WARBEAR_GYROCOPTER = 7038;
public static final int WARBEAR_METALWORKING_PRIMER = 7042;
public static final int WARBEAR_GYROCOPTER_BROKEN = 7049;
public static final int WARBEAR_METALWORKING_PRIMER_USED = 7052;
public static final int WARBEAR_EMPATHY_CHIP_USED = 7053;
public static final int WARBEAR_BREAKFAST_MACHINE = 7056;
public static final int WARBEAR_SODA_MACHINE = 7059;
public static final int WARBEAR_BANK = 7060;
public static final int GRIMSTONE_MASK = 7061;
public static final int GRIM_FAIRY_TALE = 7065;
public static final int WINTER_SEEDS = 7070;
public static final int SNOW_BERRIES = 7071;
public static final int ICE_HARVEST = 7072;
public static final int FROST_FLOWER = 7073;
public static final int SNOW_BOARDS = 7076;
public static final int UNFINISHED_ICE_SCULPTURE = 7079;
public static final int ICE_SCULPTURE = 7080;
public static final int ICE_HOUSE = 7081;
public static final int SNOW_MACHINE = 7082;
public static final int SNOW_FORT = 7089;
public static final int JERKS_HEALTH_MAGAZINE = 7100;
public static final int MULLED_BERRY_WINE = 7119;
public static final int MAGNUM_OF_FANCY_CHAMPAGNE = 7130;
public static final int LUPINE_APPETITE_HORMONES = 7133;
public static final int WOLF_WHISTLE = 7134;
public static final int MID_LEVEL_MEDIEVAL_MEAD = 7138;
public static final int SPINNING_WHEEL = 7140;
public static final int ODD_SILVER_COIN = 7144;
public static final int EXPENSIVE_CHAMPAGNE = 7146;
public static final int FANCY_OIL_PAINTING = 7148;
public static final int SOLID_GOLD_ROSARY = 7149;
public static final int DOWSING_ROD = 7150;
public static final int STRAW = 7151;
public static final int LEATHER = 7152;
public static final int CLAY = 7153;
public static final int FILLING = 7154;
public static final int PARCHMENT = 7155;
public static final int GLASS = 7156;
public static final int CRAPPY_CAMERA = 7173;
public static final int SHAKING_CRAPPY_CAMERA = 7176;
public static final int COPPERHEAD_CHARM = 7178;
public static final int FIRST_PIZZA = 7179;
public static final int LACROSSE_STICK = 7180;
public static final int EYE_OF_THE_STARS = 7181;
public static final int STANKARA_STONE = 7182;
public static final int MURPHYS_FLAG = 7183;
public static final int SHIELD_OF_BROOK = 7184;
public static final int ZEPPELIN_TICKET = 7185;
public static final int COPPERHEAD_CHARM_RAMPANT = 7186;
public static final int UNNAMED_COCKTAIL = 7187;
public static final int TOMMY_GUN = 7190;
public static final int TOMMY_AMMO = 7191;
public static final int BUDDY_BJORN = 7200;
public static final int LYNYRD_SNARE = 7204;
public static final int FLEETWOOD_MAC_N_CHEESE = 7215;
public static final int PRICELESS_DIAMOND = 7221;
public static final int FLAMIN_WHATSHISNAME = 7222;
public static final int RED_RED_WINE = 7229;
public static final int RED_BUTTON = 7243;
public static final int GLARK_CABLE = 7246;
public static final int PETE_JACKET = 7250;
public static final int SNEAKY_PETE_SHOT = 7252;
public static final int MINI_MARTINI = 7255;
public static final int SMOKE_GRENADE = 7256;
public static final int PALINDROME_BOOK_1 = 7262;
public static final int PHOTOGRAPH_OF_DOG = 7263;
public static final int PHOTOGRAPH_OF_RED_NUGGET = 7264;
public static final int PHOTOGRAPH_OF_OSTRICH_EGG = 7265;
public static final int DISPOSABLE_CAMERA = 7266;
public static final int PETE_JACKET_COLLAR = 7267;
public static final int LETTER_FROM_MELVIGN = 7268;
public static final int PROFESSOR_WHAT_GARMENT = 7269;
public static final int PALINDROME_BOOK_2 = 7270;
public static final int THINKNERD_PACKAGE = 7278;
public static final int ELEVENT = 7295;
public static final int PROFESSOR_WHAT_TSHIRT = 7297;
public static final int SEWING_KIT = 7300;
public static final int BILLIARDS_KEY = 7301;
public static final int LIBRARY_KEY = 7302;
public static final int SPOOKYRAVEN_NECKLACE = 7303;
public static final int SPOOKYRAVEN_TELEGRAM = 7304;
public static final int POWDER_PUFF = 7305;
public static final int FINEST_GOWN = 7306;
public static final int DANCING_SHOES = 7307;
public static final int DUSTY_POPPET = 7314;
public static final int RICKETY_ROCKING_HORSE = 7315;
public static final int ANTIQUE_JACK_IN_THE_BOX = 7316;
public static final int BABY_GHOSTS = 7317;
public static final int GHOST_NECKLACE = 7318;
public static final int ELIZABETH_DOLLIE = 7319;
public static final int STEPHEN_LAB_COAT = 7321;
public static final int HAUNTED_BATTERY = 7324;
public static final int SYNTHETIC_MARROW = 7327;
public static final int FUNK = 7330;
public static final int CREEPY_VOICE_BOX = 7334;
public static final int TINY_DANCER = 7338;
public static final int SPOOKY_MUSIC_BOX_MECHANISM = 7339;
public static final int PICTURE_OF_YOU = 7350;
public static final int COAL_SHOVEL = 7355;
public static final int HOT_COAL = 7356;
public static final int LAUNDRY_SHERRY = 7366;
public static final int PSYCHOTIC_TRAIN_WINE = 7370;
public static final int DNA_LAB = 7382;
public static final int DNA_SYRINGE = 7383;
public static final int STEAM_FIST_1 = 7406;
public static final int STEAM_FIST_2 = 7407;
public static final int STEAM_FIST_3 = 7408;
public static final int STEAM_TRIP_1 = 7409;
public static final int STEAM_TRIP_2 = 7410;
public static final int STEAM_TRIP_3 = 7411;
public static final int STEAM_METEOID_1 = 7412;
public static final int STEAM_METEOID_2 = 7413;
public static final int STEAM_METEOID_3 = 7414;
public static final int STEAM_DEMON_1 = 7415;
public static final int STEAM_DEMON_2 = 7416;
public static final int STEAM_DEMON_3 = 7417;
public static final int STEAM_PLUMBER_1 = 7418;
public static final int STEAM_PLUMBER_2 = 7419;
public static final int STEAM_PLUMBER_3 = 7420;
public static final int PENCIL_THIN_MUSHROOM = 7421;
public static final int CHEESEBURGER_RECIPE = 7422;
public static final int SAILOR_SALT = 7423;
public static final int BROUPON = 7424;
public static final int TACO_DAN_SAUCE_BOTTLE = 7425;
public static final int SPRINKLE_SHAKER = 7426;
public static final int TACO_DAN_RECEIPT = 7428;
public static final int BEACH_BUCK = 7429;
public static final int OVERPOWERING_MUSHROOM_WINE = 7444;
public static final int COMPLEX_MUSHROOM_WINE = 7445;
public static final int SMOOTH_MUSHROOM_WINE = 7446;
public static final int BLOOD_RED_MUSHROOM_WINE = 7447;
public static final int BUZZING_MUSHROOM_WINE = 7448;
public static final int SWIRLING_MUSHROOM_WINE = 7449;
public static final int OFFENSIVE_JOKE_BOOK = 7458;
public static final int COOKING_WITH_GREASE_BOOK = 7459;
public static final int DINER_HANDBOOK = 7460;
public static final int SPRING_BEACH_TATTOO_COUPON = 7465;
public static final int SPRING_BEACH_CHARTER = 7466;
public static final int SPRING_BEACH_TICKET = 7467;
public static final int MOIST_BEADS = 7475;
public static final int MIND_DESTROYER = 7476;
public static final int SWEET_TOOTH = 7481;
public static final int LOOSENING_POWDER = 7485;
public static final int POWDERED_CASTOREUM = 7486;
public static final int DRAIN_DISSOLVER = 7487;
public static final int TRIPLE_DISTILLED_TURPENTINE = 7488;
public static final int DETARTRATED_ANHYDROUS_SUBLICALC = 7489;
public static final int TRIATOMACEOUS_DUST = 7490;
public static final int BOTTLE_OF_CHATEAU_DE_VINEGAR = 7491;
public static final int UNSTABLE_FULMINATE = 7493;
public static final int WINE_BOMB = 7494;
public static final int MORTAR_DISSOLVING_RECIPE = 7495;
public static final int GHOST_FORMULA = 7497;
public static final int BLACK_MAP = 7500;
public static final int BLACK_LABEL = 7508;
public static final int CRUMBLING_WHEEL = 7511;
public static final int ALIEN_SOURCE_CODE = 7533;
public static final int ALIEN_SOURCE_CODE_USED = 7534;
public static final int SPACE_BEAST_FUR = 7536;
public static final int SPACE_HEATER = 7543;
public static final int SPACE_PORT = 7545;
public static final int HOT_ASHES = 7548;
public static final int DRY_RUB = 7553;
public static final int WHITE_PAGE = 7555;
public static final int WHITE_WINE = 7558;
public static final int TIME_TWITCHING_TOOLBELT = 7566;
public static final int CHRONER = 7567;
public static final int CLAN_SPEAKEASY = 7588;
public static final int GLASS_OF_MILK = 7589;
public static final int CUP_OF_TEA = 7590;
public static final int THERMOS_OF_WHISKEY = 7591;
public static final int LUCKY_LINDY = 7592;
public static final int BEES_KNEES = 7593;
public static final int SOCKDOLLAGER = 7594;
public static final int ISH_KABIBBLE = 7595;
public static final int HOT_SOCKS = 7596;
public static final int PHONUS_BALONUS = 7597;
public static final int FLIVVER = 7598;
public static final int SLOPPY_JALOPY = 7599;
public static final int HEAVY_DUTY_UMBRELLA = 7643;
public static final int POOL_SKIMMER = 7644;
public static final int MINI_LIFE_PRESERVER = 7645;
public static final int LIGHTNING_MILK = 7646;
public static final int AQUA_BRAIN = 7647;
public static final int THUNDER_THIGH = 7648;
public static final int FRESHWATER_FISHBONE = 7651;
public static final int NEOPRENE_SKULLCAP = 7659;
public static final int GOBLIN_WATER = 7660;
public static final int LIQUID_ICE = 7665;
public static final int CAP_GUN = 7695;
public static final int CONFISCATOR_BOOK = 7706;
public static final int THORS_PLIERS = 7709;
public static final int WATER_WINGS_FOR_BABIES = 7711;
public static final int BEAUTIFUL_RAINBOW = 7712;
public static final int CHRONER_CROSS = 7723;
public static final int MERCURY_BLESSING = 7728;
public static final int CHRONER_TRIGGER = 7729;
public static final int BLACK_BARTS_BOOTY = 7732;
public static final int XIBLAXIAN_CIRCUITRY = 7733;
public static final int XIBLAXIAN_POLYMER = 7734;
public static final int XIBLAXIAN_ALLOY = 7735;
public static final int XIBLAXIAN_CRYSTAL = 7736;
public static final int XIBLAXIAN_HOLOTRAINING_SIMCODE = 7739;
public static final int XIBLAXIAN_POLITICAL_PRISONER = 7742;
public static final int XIBLAXIAN_SCHEMATIC_COWL = 7743;
public static final int XIBLAXIAN_SCHEMATIC_TROUSERS = 7744;
public static final int XIBLAXIAN_SCHEMATIC_VEST = 7745;
public static final int XIBLAXIAN_SCHEMATIC_BURRITO = 7746;
public static final int XIBLAXIAN_SCHEMATIC_WHISKEY = 7747;
public static final int XIBLAXIAN_SCHEMATIC_RESIDENCE = 7748;
public static final int XIBLAXIAN_SCHEMATIC_GOGGLES = 7749;
public static final int FIVE_D_PRINTER = 7750;
public static final int RESIDENCE_CUBE = 7758;
public static final int XIBLAXIAN_HOLOWRIST_PUTER = 7765;
public static final int CONSPIRACY_ISLAND_CHARTER = 7767;
public static final int CONSPIRACY_ISLAND_TICKET = 7768;
public static final int COINSPIRACY = 7769;
public static final int VENTILATION_UNIT = 7770;
public static final int CUDDLY_TEDDY_BEAR = 7787;
public static final int FIRST_AID_POUCH = 7789;
public static final int SHAWARMA_KEYCARD = 7792;
public static final int BOTTLE_OPENER_KEYCARD = 7793;
public static final int ARMORY_KEYCARD = 7794;
public static final int HYPERSANE_BOOK = 7803;
public static final int INTIMIDATING_MIEN_BOOK = 7804;
public static final int EXPERIMENTAL_SERUM_P00 = 7830;
public static final int FINGERNAIL_CLIPPERS = 7831;
public static final int MINI_CASSETTE_RECORDER = 7832;
public static final int GORE_BUCKET = 7833;
public static final int PACK_OF_SMOKES = 7834;
public static final int ESP_COLLAR = 7835;
public static final int GPS_WATCH = 7836;
public static final int PROJECT_TLB = 7837;
public static final int MINING_OIL = 7856;
public static final int CRIMBONIUM_FUEL_ROD = 7863;
public static final int CRIMBOT_TORSO_2 = 7865;
public static final int CRIMBOT_TORSO_3 = 7866;
public static final int CRIMBOT_TORSO_4 = 7867;
public static final int CRIMBOT_TORSO_5 = 7868;
public static final int CRIMBOT_TORSO_6 = 7869;
public static final int CRIMBOT_TORSO_7 = 7870;
public static final int CRIMBOT_TORSO_8 = 7871;
public static final int CRIMBOT_TORSO_9 = 7872;
public static final int CRIMBOT_TORSO_10 = 7873;
public static final int CRIMBOT_TORSO_11 = 7874;
public static final int CRIMBOT_LEFTARM_2 = 7875;
public static final int CRIMBOT_LEFTARM_3 = 7876;
public static final int CRIMBOT_LEFTARM_4 = 7877;
public static final int CRIMBOT_LEFTARM_5 = 7878;
public static final int CRIMBOT_LEFTARM_6 = 7879;
public static final int CRIMBOT_LEFTARM_7 = 7880;
public static final int CRIMBOT_LEFTARM_8 = 7881;
public static final int CRIMBOT_LEFTARM_9 = 7882;
public static final int CRIMBOT_LEFTARM_10 = 7883;
public static final int CRIMBOT_LEFTARM_11 = 7884;
public static final int CRIMBOT_RIGHTARM_2 = 7885;
public static final int CRIMBOT_RIGHTARM_3 = 7886;
public static final int CRIMBOT_RIGHTARM_4 = 7887;
public static final int CRIMBOT_RIGHTARM_5 = 7888;
public static final int CRIMBOT_RIGHTARM_6 = 7889;
public static final int CRIMBOT_RIGHTARM_7 = 7890;
public static final int CRIMBOT_RIGHTARM_8 = 7891;
public static final int CRIMBOT_RIGHTARM_9 = 7892;
public static final int CRIMBOT_RIGHTARM_10 = 7893;
public static final int CRIMBOT_RIGHTARM_11 = 7894;
public static final int CRIMBOT_PROPULSION_2 = 7895;
public static final int CRIMBOT_PROPULSION_3 = 7896;
public static final int CRIMBOT_PROPULSION_4 = 7897;
public static final int CRIMBOT_PROPULSION_5 = 7898;
public static final int CRIMBOT_PROPULSION_6 = 7899;
public static final int CRIMBOT_PROPULSION_7 = 7900;
public static final int CRIMBOT_PROPULSION_8 = 7901;
public static final int CRIMBOT_PROPULSION_9 = 7902;
public static final int CRIMBOT_PROPULSION_10 = 7903;
public static final int CRIMBOT_PROPULSION_11 = 7904;
public static final int FRIENDLY_TURKEY = 7922;
public static final int AGITATED_TURKEY = 7923;
public static final int AMBITIOUS_TURKEY = 7924;
public static final int SNEAKY_WRAPPING_PAPER = 7934;
public static final int PICKY_TWEEZERS = 7936;
public static final int CRIMBO_CREDIT = 7937;
public static final int SLEEVE_DEUCE = 7941;
public static final int POCKET_ACE = 7942;
public static final int MININ_DYNAMITE = 7950;
public static final int BIG_BAG_OF_MONEY = 7955;
public static final int ED_DIARY = 7960;
public static final int ED_STAFF = 7961;
public static final int ED_EYE = 7962;
public static final int ED_AMULET = 7963;
public static final int ED_FATS_STAFF = 7964;
public static final int ED_HOLY_MACGUFFIN = 7965;
public static final int KA_COIN = 7966;
public static final int TOPIARY_NUGGLET = 7968;
public static final int BEEHIVE = 7969;
public static final int ELECTRIC_BONING_KNIFE = 7970;
public static final int ANCIENT_CURE_ALL = 7982;
public static final int CHOCO_CRIMBOT = 7999;
public static final int TOY_CRIMBOT_FACE = 8002;
public static final int TOY_CRIMBOT_GLOVE = 8003;
public static final int TOY_CRIMBOT_FIST = 8004;
public static final int TOY_CRIMBOT_LEGS = 8005;
public static final int ROM_RAPID_PROTOTYPING = 8007;
public static final int ROM_MATHMATICAL_PRECISION = 8008;
public static final int ROM_RUTHLESS_EFFICIENCY = 8009;
public static final int ROM_RAPID_PROTOTYPING_DIRTY = 8013;
public static final int ROM_MATHMATICAL_PRECISION_DIRTY = 8014;
public static final int ROM_RUTHLESS_EFFICIENCY_DIRTY = 8015;
public static final int TAINTED_MINING_OIL = 8017;
public static final int RED_GREEN_RAIN_STICK = 8018;
public static final int CHATEAU_ROOM_KEY = 8019;
public static final int CHATEAU_MUSCLE = 8023;
public static final int CHATEAU_MYST = 8024;
public static final int CHATEAU_MOXIE = 8025;
public static final int CHATEAU_FAN = 8026;
public static final int CHATEAU_CHANDELIER = 8027;
public static final int CHATEAU_SKYLIGHT = 8028;
public static final int CHATEAU_BANK = 8029;
public static final int CHATEAU_JUICE_BAR = 8030;
public static final int CHATEAU_PENS = 8031;
public static final int CHATEAU_WATERCOLOR = 8033;
public static final int SPELUNKY_WHIP = 8040;
public static final int SPELUNKY_SKULL = 8041;
public static final int SPELUNKY_ROCK = 8042;
public static final int SPELUNKY_POT = 8043;
public static final int SPELUNKY_FEDORA = 8044;
public static final int SPELUNKY_MACHETE = 8045;
public static final int SPELUNKY_SHOTGUN = 8046;
public static final int SPELUNKY_BOOMERANG = 8047;
public static final int SPELUNKY_HELMET = 8049;
public static final int SPELUNKY_GOGGLES = 8050;
public static final int SPELUNKY_CAPE = 8051;
public static final int SPELUNKY_JETPACK = 8052;
public static final int SPELUNKY_SPRING_BOOTS = 8053;
public static final int SPELUNKY_SPIKED_BOOTS = 8054;
public static final int SPELUNKY_PICKAXE = 8055;
public static final int SPELUNKY_TORCH = 8056;
public static final int SPELUNKY_RIFLE = 8058;
public static final int SPELUNKY_STAFF = 8059;
public static final int SPELUNKY_JOKE_BOOK = 8060;
public static final int SPELUNKY_CROWN = 8061;
public static final int SPELUNKY_COFFEE_CUP = 8062;
public static final int TALES_OF_SPELUNKING = 8063;
public static final int POWDERED_GOLD = 8066;
public static final int WAREHOUSE_MAP_PAGE = 8070;
public static final int WAREHOUSE_INVENTORY_PAGE = 8071;
public static final int SPELUNKER_FORTUNE = 8073;
public static final int SPELUNKER_FORTUNE_USED = 8085;
public static final int STILL_BEATING_SPLEEN = 8086;
public static final int SCARAB_BEETLE_STATUETTE = 8087;
public static final int WICKERBITS = 8098;
public static final int BAKELITE_BITS = 8105;
public static final int AEROGEL_ACCORDION = 8111;
public static final int AEROSOLIZED_AEROGEL = 8112;
public static final int WROUGHT_IRON_FLAKES = 8119;
public static final int GABARDINE_GIRDLE = 8124;
public static final int GABARDEEN_SMITHEREENS = 8126;
public static final int FIBERGLASS_FIBERS = 8133;
public static final int LOVEBUG_PHEROMONES = 8134;
public static final int WINGED_YETI_FUR = 8135;
public static final int SESHAT_TALISMAN = 8144;
public static final int MEATSMITH_CHECK = 8156;
public static final int MAGICAL_BAGUETTE = 8167;
public static final int ENCHANTED_ICING = 8168;
public static final int CARTON_OF_SNAKE_MILK = 8172;
public static final int RING_OF_TELLING_SKELETONS_WHAT_TO_DO = 8179;
public static final int MAP_TO_KOKOMO = 8182;
public static final int CROWN_OF_ED = 8185;
public static final int BOOZE_MAP = 8187;
public static final int POPULAR_TART = 8200;
public static final int NO_HANDED_PIE = 8201;
public static final int DOC_VITALITY_SERUM = 8202;
public static final int DINSEY_CHARTER = 8203;
public static final int DINSEY_TICKET = 8204;
public static final int FUNFUNDS = 8205;
public static final int FILTHY_CHILD_LEASH = 8209;
public static final int GARBAGE_BAG = 8211;
public static final int SEWAGE_CLOGGED_PISTOL = 8215;
public static final int TOXIC_GLOBULE = 8218;
public static final int JAR_OF_SWAMP_HONEY = 8226;
public static final int BRAIN_PRESERVATION_FLUID = 8238;
public static final int DINSEY_REFRESHMENTS = 8243;
public static final int LUBE_SHOES = 8244;
public static final int TRASH_NET = 8245;
public static final int MASCOT_MASK = 8246;
public static final int DINSEY_GUIDE_BOOK = 8253;
public static final int TRASH_MEMOIR_BOOK = 8254;
public static final int DINSEY_MAINTENANCE_MANUAL = 8255;
public static final int DINSEY_AN_AFTERLIFE = 8258;
public static final int LOTS_ENGAGEMENT_RING = 8259;
public static final int MAYO_CLINIC = 8260;
public static final int MAYONEX = 8261;
public static final int MAYODIOL = 8262;
public static final int MAYOSTAT = 8263;
public static final int MAYOZAPINE = 8264;
public static final int MAYOFLEX = 8265;
public static final int MIRACLE_WHIP = 8266;
public static final int SPHYGMAYOMANOMETER = 8267;
public static final int REFLEX_HAMMER = 8268;
public static final int MAYO_LANCE = 8269;
public static final int ESSENCE_OF_BEAR = 8277;
public static final int RESORT_CHIP = 8279;
public static final int GOLDEN_RESORT_CHIP = 8280;
public static final int COCKTAIL_SHAKER = 8283;
public static final int MAYO_MINDER = 8285;
public static final int YELLOW_PIXEL = 8298;
public static final int POWER_PILL = 8300;
public static final int YELLOW_SUBMARINE = 8376;
public static final int DECK_OF_EVERY_CARD = 8382;
public static final int POPULAR_PART = 8383;
public static final int WHITE_MANA = 8387;
public static final int BLACK_MANA = 8388;
public static final int RED_MANA = 8389;
public static final int GREEN_MANA = 8390;
public static final int BLUE_MANA = 8391;
public static final int GIFT_CARD = 8392;
public static final int LINGUINI_IMMONDIZIA_BIANCO = 8419;
public static final int SHELLS_A_LA_SHELLFISH = 8420;
public static final int GOLD_1970 = 8424;
public static final int NEW_AGE_HEALING_CRYSTAL = 8425;
public static final int VOLCOINO = 8426;
public static final int FIZZING_SPORE_POD = 8427;
public static final int INSULATED_GOLD_WIRE = 8439;
public static final int EMPTY_LAVA_BOTTLE = 8440;
public static final int VISCOUS_LAVA_GLOBS = 8442;
public static final int HEAT_RESISTANT_SHEET_METAL = 8453;
public static final int GLOWING_NEW_AGE_CRYSTAL = 8455;
public static final int CRYSTALLINE_LIGHT_BULB = 8456;
public static final int GOOEY_LAVA_GLOBS = 8470;
public static final int LAVA_MINERS_DAUGHTER = 8482;
public static final int PSYCHO_FROM_THE_HEAT = 8483;
public static final int THE_FIREGATE_TAPES = 8484;
public static final int VOLCANO_TICKET = 8486;
public static final int VOLCANO_CHARTER = 8487;
public static final int MANUAL_OF_NUMBEROLOGY = 8488;
public static final int SMOOCH_BRACERS = 8517;
public static final int SUPERDUPERHEATED_METAL = 8522;
public static final int SUPERHEATED_METAL = 8524;
public static final int FETTRIS = 8542;
public static final int FUSILLOCYBIN = 8543;
public static final int PRESCRIPTION_NOODLES = 8544;
public static final int SHRINE_BARREL_GOD = 8564;
public static final int BARREL_LID = 8565;
public static final int BARREL_HOOP_EARRING = 8566;
public static final int BANKRUPTCY_BARREL = 8567;
public static final int LITTLE_FIRKIN = 8568;
public static final int NORMAL_BARREL = 8569;
public static final int BIG_TUN = 8570;
public static final int WEATHERED_BARREL = 8571;
public static final int DUSTY_BARREL = 8572;
public static final int DISINTEGRATING_BARREL = 8573;
public static final int MOIST_BARREL = 8574;
public static final int ROTTING_BARREL = 8575;
public static final int MOULDERING_BARREL = 8576;
public static final int BARNACLED_BARREL = 8577;
public static final int BARREL_MAP = 8599;
public static final int POTTED_TEA_TREE = 8600;
public static final int FLAMIBILI_TEA = 8601;
public static final int YET_TEA = 8602;
public static final int BOO_TEA = 8603;
public static final int NAS_TEA = 8604;
public static final int IMPROPRIE_TEA = 8605;
public static final int FROST_TEA = 8606;
public static final int TOAST_TEA = 8607;
public static final int NET_TEA = 8608;
public static final int PROPRIE_TEA = 8609;
public static final int MORBIDI_TEA = 8610;
public static final int CHARI_TEA = 8611;
public static final int SERENDIPI_TEA = 8612;
public static final int FEROCI_TEA = 8613;
public static final int PHYSICALI_TEA = 8614;
public static final int WIT_TEA = 8615;
public static final int NEUROPLASTICI_TEA = 8616;
public static final int DEXTERI_TEA = 8617;
public static final int FLEXIBILI_TEA = 8618;
public static final int IMPREGNABILI_TEA = 8619;
public static final int OBSCURI_TEA = 8620;
public static final int IRRITABILI_TEA = 8621;
public static final int MEDIOCRI_TEA = 8622;
public static final int LOYAL_TEA = 8623;
public static final int ACTIVI_TEA = 8624;
public static final int CRUEL_TEA = 8625;
public static final int ALACRI_TEA = 8626;
public static final int VITALI_TEA = 8627;
public static final int MANA_TEA = 8628;
public static final int MONSTROSI_TEA = 8629;
public static final int TWEN_TEA = 8630;
public static final int GILL_TEA = 8631;
public static final int UNCERTAIN_TEA = 8632;
public static final int VORACI_TEA = 8633;
public static final int SOBRIE_TEA = 8634;
public static final int ROYAL_TEA = 8635;
public static final int CRAFT_TEA = 8636;
public static final int INSANI_TEA = 8637;
public static final int HAUNTED_DOGHOUSE = 8639;
public static final int GHOST_DOG_CHOW = 8640;
public static final int TENNIS_BALL = 8650;
public static final int TWELVE_NIGHT_ENERGY = 8666;
public static final int ROSE = 8668;
public static final int WHITE_TULIP = 8669;
public static final int RED_TULIP = 8670;
public static final int BLUE_TULIP = 8671;
public static final int WALFORDS_BUCKET = 8672;
public static final int WALMART_GIFT_CERTIFICATE = 8673;
public static final int GLACIEST_CHARTER = 8674;
public static final int GLACIEST_TICKET = 8675;
public static final int TO_BUILD_AN_IGLOO = 8682;
public static final int CHILL_OF_THE_WILD = 8683;
public static final int COLD_FANG = 8684;
public static final int COLD_WEATHER_BARTENDER_GUIDE = 8687;
public static final int ICE_HOTEL_BELL = 8694;
public static final int ANCIENT_MEDICINAL_HERBS = 8696;
public static final int ICE_RICE = 8697;
public static final int ICED_PLUM_WINE = 8698;
public static final int TRAINING_BELT = 8699;
public static final int TRAINING_LEGWARMERS = 8700;
public static final int TRAINING_HELMET = 8701;
public static final int SCROLL_SHATTERING_PUNCH = 8702;
public static final int SCROLL_SNOKEBOMB = 8703;
public static final int SCROLL_SHIVERING_MONKEY = 8704;
public static final int SNOWMAN_CRATE = 8705;
public static final int ABSTRACTION_ACTION = 8708;
public static final int ABSTRACTION_THOUGHT = 8709;
public static final int ABSTRACTION_SENSATION = 8710;
public static final int ABSTRACTION_PURPOSE = 8711;
public static final int ABSTRACTION_CATEGORY = 8712;
public static final int ABSTRACTION_PERCEPTION = 8713;
public static final int VYKEA_FRENZY_RUNE = 8722;
public static final int VYKEA_BLOOD_RUNE = 8723;
public static final int VYKEA_LIGHTNING_RUNE = 8724;
public static final int VYKEA_PLANK = 8725;
public static final int VYKEA_RAIL = 8726;
public static final int VYKEA_BRACKET = 8727;
public static final int VYKEA_DOWEL = 8728;
public static final int VYKEA_HEX_KEY = 8729;
public static final int VYKEA_INSTRUCTIONS = 8730;
public static final int MACHINE_SNOWGLOBE = 8749;
public static final int BACON = 8763;
public static final int BUNDLE_OF_FRAGRANT_HERBS = 8777;
public static final int NUCLEAR_STOCKPILE = 8778;
public static final int CIRCLE_DRUM = 8784;
public static final int COMMUNISM_BOOK = 8785;
public static final int COMMUNISM_BOOK_USED = 8794;
public static final int BAT_OOMERANG = 8797;
public static final int BAT_JUTE = 8798;
public static final int BAT_O_MITE = 8799;
public static final int ROM_OF_OPTIMALITY = 8800;
public static final int INCRIMINATING_EVIDENCE = 8801;
public static final int DANGEROUS_CHEMICALS = 8802;
public static final int KIDNAPPED_ORPHAN = 8803;
public static final int HIGH_GRADE_METAL = 8804;
public static final int HIGH_TENSILE_STRENGTH_FIBERS = 8805;
public static final int HIGH_GRADE_EXPLOSIVES = 8806;
public static final int EXPERIMENTAL_GENE_THERAPY = 8807;
public static final int ULTRACOAGULATOR = 8808;
public static final int SELF_DEFENSE_TRAINING = 8809;
public static final int FINGERPRINT_DUSTING_KIT = 8810;
public static final int CONFIDENCE_BUILDING_HUG = 8811;
public static final int EXPLODING_KICKBALL = 8812;
public static final int GLOB_OF_BAT_GLUE = 8813;
public static final int BAT_AID_BANDAGE = 8814;
public static final int BAT_BEARING = 8815;
public static final int KUDZU_SALAD = 8816;
public static final int MANSQUITO_SERUM = 8817;
public static final int MISS_GRAVES_VERMOUTH = 8818;
public static final int PLUMBERS_MUSHROOM_STEW = 8819;
public static final int AUTHORS_INK = 8820;
public static final int MAD_LIQUOR = 8821;
public static final int DOC_CLOCKS_THYME_COCKTAIL = 8822;
public static final int MR_BURNSGER = 8823;
public static final int INQUISITORS_UNIDENTIFIABLE_OBJECT = 8824;
public static final int REPLICA_BAT_OOMERANG = 8829;
public static final int ROBIN_EGG = 8833;
public static final int TELEGRAPH_OFFICE_DEED = 8836;
public static final int PLAINTIVE_TELEGRAM = 8837;
public static final int COWBOY_BOOTS = 8850;
public static final int HEIMZ_BEANS = 8866;
public static final int TESLA_BEANS = 8867;
public static final int MIXED_BEANS = 8868;
public static final int HELLFIRE_BEANS = 8869;
public static final int FRIGID_BEANS = 8870;
public static final int BLACKEST_EYED_PEAS = 8871;
public static final int STINKBEANS = 8872;
public static final int PORK_N_BEANS = 8873;
public static final int PREMIUM_BEANS = 8875;
public static final int MUS_BEANS_PLATE = 8876;
public static final int MYS_BEANS_PLATE = 8877;
public static final int MOX_BEANS_PLATE = 8878;
public static final int HOT_BEANS_PLATE = 8879;
public static final int COLD_BEANS_PLATE = 8880;
public static final int SPOOKY_BEANS_PLATE = 8881;
public static final int STENCH_BEANS_PLATE = 8882;
public static final int SLEAZE_BEANS_PLATE = 8883;
public static final int PREMIUM_BEANS_PLATE = 8885;
public static final int GLENN_DICE = 8890;
public static final int CLARA_BELL = 8893;
public static final int BUFFALO_DIME = 8895;
public static final int WESTERN_BOOK_BRAGGADOCCIO = 8916;
public static final int WESTERN_BOOK_HELL = 8917;
public static final int WESTERN_BOOK_LOOK = 8918;
public static final int WESTERN_SLANG_VOL_1 = 8920;
public static final int WESTERN_SLANG_VOL_2 = 8921;
public static final int WESTERN_SLANG_VOL_3 = 8922;
public static final int STRANGE_DISC_WHITE = 8923;
public static final int STRANGE_DISC_BLACK = 8924;
public static final int STRANGE_DISC_RED = 8925;
public static final int STRANGE_DISC_GREEN = 8926;
public static final int STRANGE_DISC_BLUE = 8927;
public static final int STRANGE_DISC_YELLOW = 8928;
public static final int MOUNTAIN_SKIN = 8937;
public static final int GRIZZLED_SKIN = 8938;
public static final int DIAMONDBACK_SKIN = 8939;
public static final int COAL_SKIN = 8940;
public static final int FRONTWINDER_SKIN = 8941;
public static final int ROTTING_SKIN = 8942;
public static final int QUICKSILVER_SPURS = 8947;
public static final int THICKSILVER_SPURS = 8948;
public static final int WICKSILVER_SPURS = 8949;
public static final int SLICKSILVER_SPURS = 8950;
public static final int SICKSILVER_SPURS = 8951;
public static final int NICKSILVER_SPURS = 8952;
public static final int TICKSILVER_SPURS = 8953;
public static final int COW_PUNCHING_TALES = 8955;
public static final int BEAN_SLINGING_TALES = 8956;
public static final int SNAKE_OILING_TALES = 8957;
public static final int SNAKE_OIL = 8971;
public static final int MEMORIES_OF_COW_PUNCHING = 8986;
public static final int MEMORIES_OF_BEAN_SLINGING = 8987;
public static final int MEMORIES_OF_SNAKE_OILING = 8988;
public static final int WITCHESS_SET = 8989;
public static final int BRAIN_TRAINER_GAME = 8990;
public static final int LASER_EYE_SURGERY_KIT = 8991;
public static final int SACRAMENTO_WINE = 8994;
public static final int CLAN_FLOUNDRY = 9000;
public static final int CARPE = 9001;
public static final int CODPIECE = 9002;
public static final int TROUTSERS = 9003;
public static final int BASS_CLARINET = 9004;
public static final int FISH_HATCHET = 9005;
public static final int TUNAC = 9006;
public static final int FISHING_POLE = 9007;
public static final int WRIGGLING_WORM = 9008;
public static final int FISHING_LINE = 9010;
public static final int FISHING_HAT = 9011;
public static final int TROUT_FISHING_IN_LOATHING = 9012;
public static final int ANTIQUE_TACKLE_BOX = 9015;
public static final int VIRAL_VIDEO = 9017;
public static final int MEME_GENERATOR = 9019;
public static final int PLUS_ONE = 9020;
public static final int GALLON_OF_MILK = 9021;
public static final int PRINT_SCREEN = 9022;
public static final int SCREENCAPPED_MONSTER = 9023;
public static final int DAILY_DUNGEON_MALWARE = 9024;
public static final int BACON_MACHINE = 9025;
public static final int NO_SPOON = 9029;
public static final int SOURCE_TERMINAL = 9033;
public static final int SOURCE_ESSENCE = 9034;
public static final int BROWSER_COOKIE = 9035;
public static final int HACKED_GIBSON = 9036;
public static final int SOURCE_SHADES = 9037;
public static final int SOFTWARE_BUG = 9038;
public static final int SOURCE_TERMINAL_PRAM_CHIP = 9040;
public static final int SOURCE_TERMINAL_GRAM_CHIP = 9041;
public static final int SOURCE_TERMINAL_SPAM_CHIP = 9042;
public static final int SOURCE_TERMINAL_CRAM_CHIP = 9043;
public static final int SOURCE_TERMINAL_DRAM_CHIP = 9044;
public static final int SOURCE_TERMINAL_TRAM_CHIP = 9045;
public static final int SOURCE_TERMINAL_INGRAM_CHIP = 9046;
public static final int SOURCE_TERMINAL_DIAGRAM_CHIP = 9047;
public static final int SOURCE_TERMINAL_ASHRAM_CHIP = 9048;
public static final int SOURCE_TERMINAL_SCRAM_CHIP = 9049;
public static final int SOURCE_TERMINAL_TRIGRAM_CHIP = 9050;
public static final int SOURCE_TERMINAL_SUBSTATS_ENH = 9051;
public static final int SOURCE_TERMINAL_DAMAGE_ENH = 9052;
public static final int SOURCE_TERMINAL_CRITICAL_ENH = 9053;
public static final int SOURCE_TERMINAL_PROTECT_ENQ = 9054;
public static final int SOURCE_TERMINAL_STATS_ENQ = 9055;
public static final int SOURCE_TERMINAL_COMPRESS_EDU = 9056;
public static final int SOURCE_TERMINAL_DUPLICATE_EDU = 9057;
public static final int SOURCE_TERMINAL_PORTSCAN_EDU = 9058;
public static final int SOURCE_TERMINAL_TURBO_EDU = 9059;
public static final int SOURCE_TERMINAL_FAMILIAR_EXT = 9060;
public static final int SOURCE_TERMINAL_PRAM_EXT = 9061;
public static final int SOURCE_TERMINAL_GRAM_EXT = 9062;
public static final int SOURCE_TERMINAL_SPAM_EXT = 9063;
public static final int SOURCE_TERMINAL_CRAM_EXT = 9064;
public static final int SOURCE_TERMINAL_DRAM_EXT = 9065;
public static final int SOURCE_TERMINAL_TRAM_EXT = 9066;
public static final int COP_DOLLAR = 9072;
public static final int DETECTIVE_APPLICATION = 9073;
public static final int PROTON_ACCELERATOR = 9082;
public static final int STANDARDS_AND_PRACTICES = 9095;
public static final int RAD = 9100;
public static final int WRIST_BOY = 9102;
public static final int TIME_SPINNER = 9104;
public static final int HOLORECORD_SHRIEKING_WEASEL = 9109;
public static final int HOLORECORD_POWERGUY = 9110;
public static final int HOLORECORD_LUCKY_STRIKES = 9111;
public static final int HOLORECORD_EMD = 9112;
public static final int HOLORECORD_SUPERDRIFTER = 9113;
public static final int HOLORECORD_PIGS = 9114;
public static final int HOLORECORD_DRUNK_UNCLES = 9115;
public static final int TIME_RESIDUE = 9116;
public static final int SCHOOL_OF_HARD_KNOCKS_DIPLOMA = 9123;
public static final int KOL_COL_13_SNOWGLOBE = 9133;
public static final int TRICK_TOT_KNIGHT = 9137;
public static final int TRICK_TOT_UNICORN = 9138;
public static final int TRICK_TOT_CANDY = 9139;
public static final int TRICK_TOT_ROBOT = 9143;
public static final int TRICK_TOT_EYEBALL = 9144;
public static final int TRICK_TOT_LIBERTY = 9145;
public static final int HOARDED_CANDY_WAD = 9146;
public static final int STUFFING_FLUFFER = 9164;
public static final int TURKEY_BLASTER = 9166;
public static final int CANDIED_SWEET_POTATOES = 9171;
public static final int BREAD_ROLL = 9179;
public static final int CORNUCOPIA = 9183;
public static final int MEGACOPIA = 9184;
public static final int GIANT_PILGRIM_HAT = 9185;
public static final int THANKSGARDEN_SEEDS = 9186;
public static final int CASHEW = 9187;
public static final int BOMB_OF_UNKNOWN_ORIGIN = 9188;
public static final int GINGERBREAD_CITY = 9203;
public static final int COUNTERFEIT_CITY = 9204;
public static final int SPRINKLES = 9205;
public static final int VIGILANTE_BOOK = 9206;
public static final int BROKEN_CHOCOLATE_POCKETWATCH = 9215;
public static final int GINGERBREAD_RESTRAINING_ORDER = 9217;
public static final int GINGERBREAD_WINE = 9220;
public static final int GINGERBREAD_MUG = 9221;
public static final int GINGERSERVO = 9223;
public static final int GINGERBEARD = 9225;
public static final int CREME_BRULEE_TORCH = 9230;
public static final int GINGERBREAD_DOG_TREAT = 9233;
public static final int GINGERBREAD_CIGARETTE = 9237;
public static final int SPARE_CHOCOLATE_PARTS = 9240;
public static final int HIGH_END_GINGER_WINE = 9243;
public static final int MY_LIFE_OF_CRIME_BOOK = 9258;
public static final int POP_ART_BOOK = 9259;
public static final int NO_HATS_BOOK = 9260;
public static final int RETHINKING_CANDY_BOOK = 9261;
public static final int FRUIT_LEATHER_NEGATIVE = 9262;
public static final int GINGERBREAD_BLACKMAIL_PHOTOS = 9263;
public static final int TEETHPICK = 9265;
public static final int CHOCOLATE_SCULPTURE = 9269;
public static final int NO_HAT = 9270;
public static final int NEGATIVE_LUMP = 9272;
public static final int LUMP_STACKING_BOOK = 9285;
public static final int HOT_JELLY = 9291;
public static final int COLD_JELLY = 9292;
public static final int SPOOKY_JELLY = 9293;
public static final int SLEAZE_JELLY = 9294;
public static final int STENCH_JELLY = 9295;
public static final int WAX_HAND = 9305;
public static final int MINIATURE_CANDLE = 9306;
public static final int WAX_PANCAKE = 9307;
public static final int WAX_FACE = 9308;
public static final int WAX_BOOZE = 9309;
public static final int WAX_GLOB = 9310;
public static final int HEART_SHAPED_CRATE = 9316;
public static final int LOVE_BOOMERANG = 9323;
public static final int LOVE_CHOCOLATE = 9325;
public static final int ELDRITCH_ICHOR = 9333;
public static final int ELDRITCH_TINCTURE = 9335;
public static final int ELDRITCH_TINCTURE_DEPLETED = 9336;
public static final int CLOD_OF_DIRT = 9216;
public static final int DIRTY_BOTTLECAP = 9343;
public static final int DISCARDED_BUTTON = 9344;
public static final int GUMMY_MEMORY = 9345;
public static final int NOVELTY_HOT_SAUCE = 9349;
public static final int COCKTAIL_MUSHROOM = 9353;
public static final int GRANOLA_LIQUEUR = 9354;
public static final int GREGNADIGNE = 9357;
public static final int BABY_OIL_SHOOTER = 9359;
public static final int LIMEPATCH = 9361;
public static final int LITERAL_GRASSHOPPER = 9365;
public static final int PHIL_COLLINS = 9400;
public static final int TOGGLE_SWITCH_BARTEND = 9402;
public static final int TOGGLE_SWITCH_BOUNCE = 9403;
public static final int SPACEGATE_ACCESS_BADGE = 9404;
public static final int SPACEGATE_RESEARCH = 9410;
public static final int ALIEN_ROCK_SAMPLE = 9411;
public static final int ALIEN_GEMSTONE = 9412;
public static final int ALIEN_PLANT_FIBERS = 9416;
public static final int ALIEN_PLANT_SAMPLE = 9417;
public static final int COMPLEX_ALIEN_PLANT_SAMPLE = 9418;
public static final int FASCINATING_ALIEN_PLANT_SAMPLE = 9419;
public static final int ALIEN_PLANT_POD = 9421;
public static final int ALIEN_TOENAILS = 9424;
public static final int ALIEN_ZOOLOGICAL_SAMPLE = 9425;
public static final int COMPLEX_ALIEN_ZOOLOGICAL_SAMPLE = 9426;
public static final int FASCINATING_ALIEN_ZOOLOGICAL_SAMPLE = 9427;
public static final int ALIEN_ANIMAL_MILK = 9429;
public static final int SPANT_EGG_CASING = 9430;
public static final int MURDERBOT_DATA_CORE = 9431;
public static final int SPANT_CHITIN = 9441;
public static final int PRIMITIVE_ALIEN_TOTEM = 9439;
public static final int SPANT_TENDON = 9442;
public static final int MURDERBOT_MEMORY_CHIP = 9457;
public static final int SPACE_PIRATE_TREASURE_MAP = 9458;
public static final int SPACE_PIRATE_ASTROGATION_HANDBOOK = 9459;
public static final int NON_EUCLIDEAN_FINANCE = 9460;
public static final int PEEK_A_BOO = 9461;
public static final int PROCRASTINATOR_LOCKER_KEY = 9462;
public static final int SPACE_BABY_CHILDRENS_BOOK = 9463;
public static final int SPACE_BABY_BAWBAW = 9464;
public static final int PORTABLE_SPACEGATE = 9465;
public static final int NEW_YOU_CLUB_MEMBERSHIP_FORM = 9478;
public static final int AFFIRMATION_SUPERFICIALLY_INTERESTED = 9481;
public static final int AFFIRMATION_MIND_MASTER = 9483;
public static final int AFFIRMATION_HATE = 9485;
public static final int AFFIRMATION_COOKIE = 9486;
public static final int LICENSE_TO_KILL = 9487;
public static final int VICTOR_SPOILS = 9493;
public static final int KREMLIN_BRIEFCASE = 9493;
public static final int LICENSE_TO_CHILL = 9503;
public static final int CELSIUS_233 = 9504;
public static final int CELSIUS_233_SINGED = 9505;
public static final int LAZENBY = 9506;
public static final int ASDON_MARTIN = 9508;
public static final int METEORITE_ADE = 9513;
public static final int METAL_METEOROID = 9516;
public static final int METEORTARBOARD = 9517;
public static final int METEORITE_GUARD = 9518;
public static final int METEORB = 9519;
public static final int ASTEROID_BELT = 9520;
public static final int METEORTHOPEDIC_SHOES = 9521;
public static final int SHOOTING_MORNING_STAR = 9522;
public static final int PERFECTLY_FAIR_COIN = 9526;
public static final int CORKED_GENIE_BOTTLE = 9528;
public static final int GENIE_BOTTLE = 9529;
public static final int POCKET_WISH = 9537;
public static final int SHOVELFUL_OF_EARTH = 9539;
public static final int HUNK_OF_GRANITE = 9540;
public static final int X = 9543;
public static final int O = 9544;
public static final int MAFIA_PINKY_RING = 9546;
public static final int FLASK_OF_PORT = 9547;
public static final int BRIDGE_TRUSS = 9556;
public static final int AMORPHOUS_BLOB = 9558;
public static final int GIANT_AMORPHOUS_BLOB = 9561;
public static final int MAFIA_THUMB_RING = 9564;
public static final int PORTABLE_PANTOGRAM = 9573;
public static final int PANTOGRAM_PANTS = 9574;
public static final int MUMMING_TRUNK = 9592;
public static final int EARTHENWARE_MUFFIN_TIN = 9596;
public static final int BRAN_MUFFIN = 9597;
public static final int BLUEBERRY_MUFFIN = 9598;
public static final int CRYSTALLINE_CHEER = 9625;
public static final int WAREHOUSE_KEY = 9627;
public static final int MIME_SCIENCE_VOL_1 = 9635;
public static final int MIME_SCIENCE_VOL_1_USED = 9636;
public static final int MIME_SCIENCE_VOL_2 = 9637;
public static final int MIME_SCIENCE_VOL_2_USED = 9638;
public static final int MIME_SCIENCE_VOL_3 = 9639;
public static final int MIME_SCIENCE_VOL_3_USED = 9640;
public static final int MIME_SCIENCE_VOL_4 = 9641;
public static final int MIME_SCIENCE_VOL_4_USED = 9642;
public static final int MIME_SCIENCE_VOL_5 = 9643;
public static final int MIME_SCIENCE_VOL_5_USED = 9644;
public static final int MIME_SCIENCE_VOL_6 = 9645;
public static final int MIME_SCIENCE_VOL_6_USED = 9646;
public static final int GOD_LOBSTER = 9661;
public static final int DONATED_BOOZE = 9662;
public static final int DONATED_FOOD = 9663;
public static final int DONATED_CANDY = 9664;
public static final int MIME_ARMY_INFILTRATION_GLOVE = 9675;
public static final int MIME_SHOTGLASS = 9676;
public static final int TOASTED_HALF_SANDWICH = 9681;
public static final int MULLED_HOBO_WINE = 9682;
public static final int BURNING_NEWSPAPER = 9683;
public static final int BURNING_HAT = 9684;
public static final int BURNING_CAPE = 9685;
public static final int BURNING_SLIPPERS = 9686;
public static final int BURNING_JORTS = 9687;
public static final int BURNING_CRANE = 9688;
public static final int GARBAGE_TOTE = 9690;
public static final int DECEASED_TREE = 9691;
public static final int BROKEN_CHAMPAGNE = 9692;
public static final int TINSEL_TIGHTS = 9693;
public static final int WAD_OF_TAPE = 9694;
public static final int MAKESHIFT_GARBAGE_SHIRT = 9699;
public static final int DIETING_PILL = 9707;
public static final int CLAN_CARNIVAL_GAME = 9712;
public static final int GET_BIG_BOOK = 9713;
public static final int GALAPAGOS_BOOK = 9714;
public static final int FUTURE_BOOK = 9715;
public static final int LOVE_POTION_BOOK = 9716;
public static final int RHINESTONE_BOOK = 9717;
public static final int LOVE_SONG_BOOK = 9718;
public static final int MYSTERIOUS_RED_BOX = 9739;
public static final int MYSTERIOUS_GREEN_BOX = 9740;
public static final int MYSTERIOUS_BLUE_BOX = 9741;
public static final int MYSTERIOUS_BLACK_BOX = 9742;
public static final int LOVE_POTION_XYZ = 9745;
public static final int POKEDOLLAR_BILLS = 9747;
public static final int METANDIENONE = 9748;
public static final int RIBOFLAVIN = 9749;
public static final int BRONZE = 9750;
public static final int PIRACETAM = 9751;
public static final int ULTRACALCIUM = 9752;
public static final int GINSENG = 9753;
public static final int TALL_GRASS_SEEDS = 9760;
public static final int POKE_GROW_FERTILIZER = 9761;
public static final int LUCK_INCENSE = 9821;
public static final int SHELL_BELL = 9822;
public static final int MUSCLE_BAND = 9823;
public static final int AMULET_COIN = 9824;
public static final int RAZOR_FANG = 9825;
public static final int SMOKE_BALL = 9826;
public static final int GREEN_ROCKET = 9827;
public static final int FR_MEMBER = 9835;
public static final int FR_GUEST = 9836;
public static final int FANTASY_REALM_GEM = 9837;
public static final int RUBEE = 9838;
public static final int FR_WARRIOR_HELM = 9839;
public static final int FR_MAGE_HAT = 9840;
public static final int FR_ROGUE_MASK = 9841;
public static final int FR_KEY = 9844;
public static final int FR_PURPLE_MUSHROOM = 9845;
public static final int FR_TAINTED_MARSHMALLOW = 9846;
public static final int FR_CHESWICKS_NOTES = 9847;
public static final int MY_FIRST_ART_OF_WAR = 9850;
public static final int FR_DRAGON_ORE = 9851;
public static final int FR_POISONED_SMORE = 9853;
public static final int FR_DRUIDIC_ORB = 9854;
public static final int FR_HOLY_WATER = 9856;
public static final int CONTRACTOR_MANUAL = 9861;
public static final int FR_CHESWICKS_COMPASS = 9865;
public static final int FR_ARREST_WARRANT = 9866;
public static final int FR_MOUNTAIN_MAP = 9873;
public static final int FR_WOOD_MAP = 9874;
public static final int FR_SWAMP_MAP = 9875;
public static final int FR_VILLAGE_MAP = 9876;
public static final int FR_CEMETARY_MAP = 9877;
public static final int FR_CHARGED_ORB = 9895;
public static final int FR_NOTARIZED_WARRANT = 9897;
public static final int CLARIFIED_BUTTER = 9908;
public static final int G = 9909;
public static final int GARLAND_OF_GREATNESS = 9910;
public static final int GLUED_BOO_CLUE = 9913;
public static final int BOOMBOX = 9919;
public static final int GUIDE_TO_SAFARI = 9921;
public static final int SHIELDING_POTION = 9922;
public static final int PUNCHING_POTION = 9923;
public static final int SPECIAL_SEASONING = 9924;
public static final int NIGHTMARE_FUEL = 9925;
public static final int MEAT_CLIP = 9926;
public static final int CHEESE_WHEEL = 9937;
public static final int NEVERENDING_PARTY_INVITE = 9942;
public static final int NEVERENDING_PARTY_INVITE_DAILY = 9943;
public static final int PARTY_HARD_T_SHIRT = 9944;
public static final int ELECTRONICS_KIT = 9952;
public static final int PAINT_PALETTE = 9956;
public static final int PURPLE_BEAST_ENERGY_DRINK = 9958;
public static final int PUMP_UP_HIGH_TOPS = 9961;
public static final int VERY_SMALL_RED_DRESS = 9963;
public static final int EVERFULL_GLASS = 9966;
public static final int JAM_BAND_BOOTLEG = 9968;
public static final int INTIMIDATING_CHAINSAW = 9972;
public static final int PARTY_PLANNING_BOOK = 9978;
public static final int PARTYCRASHER = 9983;
public static final int DRINKING_TO_DRINK_BOOK = 9984;
public static final int LATTE_MUG = 9987;
public static final int VOTER_REGISTRATION_FORM = 9989;
public static final int I_VOTED_STICKER = 9990;
public static final int VOTER_BALLOT = 9991;
public static final int BLACK_SLIME_GLOB = 9996;
public static final int GREEN_SLIME_GLOB = 9997;
public static final int ORANGE_SLIME_GLOB = 9998;
public static final int GOVERNMENT_REQUISITION_FORM = 10003;
public static final int HAUNTED_HELL_RAMEN = 10018;
public static final int WALRUS_BLUBBER = 10034;
public static final int TINY_BOMB = 10036;
public static final int MOOSEFLANK = 10038;
public static final int BOXING_DAY_CARE = 10049;
public static final int BOXING_DAY_PASS = 10056;
public static final int SAUSAGE_O_MATIC = 10058;
public static final int MAGICAL_SAUSAGE_CASING = 10059;
public static final int MAGICAL_SAUSAGE = 10060;
public static final int CRIMBO_CANDLE = 10072;
public static final int CHALK_CHUNKS = 10088;
public static final int MARBLE_MOECULES = 10096;
public static final int PARAFFIN_PSEUDOACCORDION = 10103;
public static final int PARAFFIN_PIECES = 10104;
public static final int TERRA_COTTA_TIDBITS = 10112;
public static final int TRYPTOPHAN_DART = 10159;
public static final int DOCTOR_BAG = 10166;
public static final int BOOKE_OF_VAMPYRIC_KNOWLEDGE = 10180;
public static final int VAMPYRE_BLOOD = 10185;
public static final int GLITCH_ITEM = 10207;
public static final int PR_MEMBER = 10187;
public static final int PR_GUEST = 10188;
public static final int CURSED_COMPASS = 10191;
public static final int ISLAND_DRINKIN = 10211;
public static final int PIRATE_REALM_FUN_LOG = 10225;
public static final int PIRATE_FORK = 10227;
public static final int SCURVY_AND_SOBRIETY_PREVENTION = 10228;
public static final int LUCKY_GOLD_RING = 10229;
public static final int VAMPYRIC_CLOAKE = 10242;
public static final int FOURTH_SABER = 10251;
public static final int RING = 10252;
public static final int HEWN_MOON_RUNE_SPOON = 10254;
public static final int BEACH_COMB = 10258;
public static final int ETCHED_HOURGLASS = 10265;
public static final int PIECE_OF_DRIFTWOOD = 10281;
public static final int DRIFTWOOD_BEACH_COMB = 10291;
public static final int STICK_OF_FIREWOOD = 10293;
public static final int GETAWAY_BROCHURE = 10292;
public static final int RARE_MEAT_ISOTOPE = 10310;
public static final int BURNT_STICK = 10311;
public static final int BUNDLE_OF_FIREWOOD = 10312;
public static final int CAMPFIRE_SMOKE = 10313;
public static final int THE_IMPLODED_WORLD = 10322;
public static final int POCKET_PROFESSOR_MEMORY_CHIP = 10324;
public static final int LAW_OF_AVERAGES = 10325;
public static final int PILL_KEEPER = 10333;
public static final int DIABOLIC_PIZZA_CUBE = 10335;
public static final int DIABOLIC_PIZZA = 10336;
public static final int HUMAN_MUSK = 10350;
public static final int EXTRA_WARM_FUR = 10351;
public static final int INDUSTRIAL_LUBRICANT = 10352;
public static final int UNFINISHED_PLEASURE = 10353;
public static final int HUMANOID_GROWTH_HORMONE = 10354;
public static final int BUG_LYMPH = 10355;
public static final int ORGANIC_POTPOURRI = 10356;
public static final int BOOT_FLASK = 10357;
public static final int INFERNAL_SNOWBALL = 10358;
public static final int POWDERED_MADNESS = 10359;
public static final int FISH_SAUCE = 10360;
public static final int GUFFIN = 10361;
public static final int SHANTIX = 10362;
public static final int GOODBERRY = 10363;
public static final int EUCLIDEAN_ANGLE = 10364;
public static final int PEPPERMINT_SYRUP = 10365;
public static final int MERKIN_EYEDROPS = 10366;
public static final int EXTRA_STRENGTH_GOO = 10367;
public static final int ENVELOPE_MEAT = 10368;
public static final int LIVID_ENERGY = 10369;
public static final int MICRONOVA = 10370;
public static final int BEGGIN_COLOGNE = 10371;
public static final int THE_SPIRIT_OF_GIVING = 10380;
public static final int PEPPERMINT_EEL_SAUCE = 10416;
public static final int GREEN_AND_RED_BEAN = 10417;
public static final int TEMPURA_GREEN_AND_RED_BEAN = 10425;
public static final int BIRD_A_DAY_CALENDAR = 10434;
public static final int POWERFUL_GLOVE = 10438;
public static final int DRIP_HARNESS = 10441;
public static final int DRIPPY_TRUNCHEON = 10442;
public static final int DRIPLET = 10443;
public static final int DRIPPY_SNAIL_SHELL = 10444;
public static final int DRIPPY_NUGGET = 10445;
public static final int DRIPPY_WINE = 10446;
public static final int DRIPPY_CAVIAR = 10447;
public static final int DRIPPY_PLUM = 10448;
public static final int EYE_OF_THE_THING = 10450;
public static final int DRIPPY_SHIELD = 10452;
public static final int FIRST_PLUMBER_QUEST_ITEM = 10454;
public static final int COIN = 10454;
public static final int MUSHROOM = 10455;
public static final int DELUXE_MUSHROOM = 10456;
public static final int SUPER_DELUXE_MUSHROOM = 10457;
public static final int HAMMER = 10460;
public static final int HEAVY_HAMMER = 10461;
public static final int PLUMBER_FIRE_FLOWER = 10462;
public static final int BONFIRE_FLOWER = 10463;
public static final int WORK_BOOTS = 10464;
public static final int FANCY_BOOTS = 10465;
public static final int POWER_PANTS = 10469;
public static final int FROSTY_BUTTON = 10473;
public static final int LAST_PLUMBER_QUEST_ITEM = 10474;
public static final int MUSHROOM_SPORES = 10482;
public static final int FREE_RANGE_MUSHROOM = 10483;
public static final int PLUMP_FREE_RANGE_MUSHROOM = 10484;
public static final int BULKY_FREE_RANGE_MUSHROOM = 10485;
public static final int GIANT_FREE_RANGE_MUSHROOM = 10486;
public static final int IMMENSE_FREE_RANGE_MUSHROOM = 10487;
public static final int COLOSSAL_FREE_RANGE_MUSHROOM = 10488;
public static final int HOUSE_SIZED_MUSHROOM = 10497;
public static final int RED_PLUMBERS_BOOTS = 10501;
public static final int DRIPPY_STEIN = 10524;
public static final int DRIPPY_PILSNER = 10525;
public static final int DRIPPY_STAFF = 10526;
public static final int GUZZLR_TABLET = 10533;
public static final int GUZZLR_COCKTAIL_SET = 10534;
public static final int GUZZLRBUCK = 10535;
public static final int GUZZLR_SHOES = 10537;
public static final int CLOWN_CAR_KEY = 10547;
public static final int BATTING_CAGE_KEY = 10548;
public static final int AQUI = 10549;
public static final int KNOB_LABINET_KEY = 10550;
public static final int WEREMOOSE_KEY = 10551;
public static final int PEG_KEY = 10552;
public static final int KEKEKEY = 10553;
public static final int RABBITS_FOOT_KEY = 10554;
public static final int KNOB_SHAFT_SKATE_KEY = 10555;
public static final int ICE_KEY = 10556;
public static final int ANCHOVY_CAN_KEY = 10557;
public static final int CACTUS_KEY = 10558;
public static final int F_C_LE_SH_C_LE_K_Y = 10559;
public static final int TREASURE_CHEST_KEY = 10560;
public static final int DEMONIC_KEY = 10561;
public static final int KEY_SAUSAGE = 10562;
public static final int KNOB_TREASURY_KEY = 10563;
public static final int SCRAP_METAL_KEY = 10564;
public static final int BLACK_ROSE_KEY = 10565;
public static final int MUSIC_BOX_KEY = 10566;
public static final int ACTUAL_SKELETON_KEY = 10567;
public static final int DEEP_FRIED_KEY = 10568;
public static final int DISCARDED_BIKE_LOCK_KEY = 10569;
public static final int MANUAL_OF_LOCK_PICKING = 10571;
public static final int SPINMASTER = 10582;
public static final int FLIMSY_HARDWOOD_SCRAPS = 10583;
public static final int DREADSYLVANIAN_HEMLOCK = 10589;
public static final int HEMLOCK_HELM = 10590;
public static final int SWEATY_BALSAM = 10591;
public static final int BALSAM_BARREL = 10592;
public static final int ANCIENT_REDWOOD = 10593;
public static final int REDWOOD_RAIN_STICK = 10594;
public static final int PURPLEHEART_LOGS = 10595;
public static final int PURPLEHEART_PANTS = 10596;
public static final int WORMWOOD_STICK = 10597;
public static final int WORMWOOD_WEDDING_RING = 10598;
public static final int DRIPWOOD_SLAB = 10599;
public static final int DRIPPY_DIADEM = 10600;
public static final int SIZZLING_DESK_BELL = 10617;
public static final int FROST_RIMED_DESK_BELL = 10618;
public static final int UNCANNY_DESK_BELL = 10619;
public static final int NASTY_DESK_BELL = 10620;
public static final int GREASY_DESK_BELL = 10621;
public static final int FANCY_CHESS_SET = 10622;
public static final int ONYX_KING = 10623;
public static final int ONYX_QUEEN = 10624;
public static final int ONYX_ROOK = 10625;
public static final int ONYX_BISHOP = 10626;
public static final int ONYX_KNIGHT = 10627;
public static final int ONYX_PAWN = 10628;
public static final int ALABASTER_KING = 10629;
public static final int ALABASTER_QUEEN = 10630;
public static final int ALABASTER_ROOK = 10631;
public static final int ALABASTER_BISHOP = 10632;
public static final int ALABASTER_KNIGHT = 10633;
public static final int ALABASTER_PAWN = 10634;
public static final int CARGO_CULTIST_SHORTS = 10636;
public static final int UNIVERSAL_SEASONING = 10640;
public static final int CHOCOLATE_CHIP_MUFFIN = 10643;
public static final int KNOCK_OFF_RETRO_SUPERHERO_CAPE = 10647;
public static final int SUBSCRIPTION_COCOA_DISPENSER = 10652;
public static final int OVERFLOWING_GIFT_BASKET = 10670;
public static final int FOOD_DRIVE_BUTTON = 10691;
public static final int BOOZE_DRIVE_BUTTON = 10692;
public static final int CANDY_DRIVE_BUTTON = 10693;
public static final int FOOD_MAILING_LIST = 10694;
public static final int BOOZE_MAILING_LIST = 10695;
public static final int CANDY_MAILING_LIST = 10696;
public static final int GOVERNMENT_FOOD_SHIPMENT = 10685;
public static final int GOVERNMENT_BOOZE_SHIPMENT = 10686;
public static final int GOVERNMENT_CANDY_SHIPMENT = 10687;
public static final int MINIATURE_CRYSTAL_BALL = 10730;
public static final int COAT_OF_PAINT = 10732;
public static final int BATTERY_9V = 10742;
public static final int BATTERY_LANTERN = 10743;
public static final int BATTERY_CAR = 10744;
public static final int GREEN_MARSHMALLOW = 10746;
public static final int MARSHMALLOW_BOMB = 10747;
public static final int BACKUP_CAMERA = 10749;
public static final int BLUE_PLATE = 10751;
public static final int FAMILIAR_SCRAPBOOK = 10759;
public static final int CLAN_UNDERGROUND_FIREWORKS_SHOP = 10761;
public static final int FEDORA_MOUNTED_FOUNTAIN = 10762;
public static final int PORKPIE_MOUNTED_POPPER = 10763;
public static final int SOMBRERO_MOUNTED_SPARKLER = 10764;
public static final int CATHERINE_WHEEL = 10770;
public static final int ROCKET_BOOTS = 10771;
public static final int OVERSIZED_SPARKLER = 10772;
public static final int BLART = 10790;
public static final int RAINPROOF_BARREL_CAULK = 10794;
public static final int PUMP_GREASE = 10795;
public static final int INDUSTRIAL_FIRE_EXTINGUISHER = 10797;
public static final int VAMPIRE_VINTNER_WINE = 10800;
public static final int COLD_MEDICINE_CABINET = 10815;
public static final int HOMEBODYL = 10828;
public static final int EXTROVERMECTIN = 10829;
public static final int BREATHITIN = 10830;
public static final AdventureResult get(String itemName, int count) {
int itemId = ItemDatabase.getItemId(itemName, 1, false);
if (itemId != -1) {
return ItemPool.get(itemId, count);
}
return AdventureResult.tallyItem(itemName, count, false);
}
public static final AdventureResult get(int itemId, int count) {
return new AdventureResult(itemId, count, false);
}
public static final AdventureResult get(int itemId) {
return new AdventureResult(itemId, 1, false);
}
// Support for various classes of items:
// El Vibrato helmet
public static final String[] EV_HELMET_CONDUITS =
new String[] {
"ATTACK", "BUILD", "BUFF", "MODIFY", "REPAIR", "TARGET", "SELF", "DRONE", "WALL"
};
public static final List<String> EV_HELMET_LEVELS =
Arrays.asList(
"PA",
"ZERO",
"NOKGAGA",
"NEGLIGIBLE",
"GABUHO NO",
"EXTREMELY LOW",
"GA NO",
"VERY LOW",
"NO",
"LOW",
"FUZEVENI",
"MODERATE",
"PAPACHA",
"ELEVATED",
"FU",
"HIGH",
"GA FU",
"VERY HIGH",
"GABUHO FU",
"EXTREMELY HIGH",
"CHOSOM",
"MAXIMAL");
// BANG POTIONS and SLIME VIALS
public static final String[][] bangPotionStrings = {
// name, combat use mssage, inventory use message
{"inebriety", "wino", "liquid fire"},
{"healing", "better", "You gain"},
{"confusion", "confused", "Confused"},
{"blessing", "stylish", "Izchak's Blessing"},
{"detection", "blink", "Object Detection"},
{"sleepiness", "yawn", "Sleepy"},
{"mental acuity", "smarter", "Strange Mental Acuity"},
{"ettin strength", "stronger", "Strength of Ten Ettins"},
{"teleportitis", "disappearing", "Teleportitis"},
};
public static final String[][][] slimeVialStrings = {
// name, inventory use mssage
{ // primary
{"strong", "Slimily Strong"},
{"sagacious", "Slimily Sagacious"},
{"speedy", "Slimily Speedy"},
},
{ // secondary
{"brawn", "Bilious Brawn"},
{"brains", "Bilious Brains"},
{"briskness", "Bilious Briskness"},
},
{ // tertiary
{"slimeform", "Slimeform"},
{"eyesight", "Ichorous Eyesight"},
{"intensity", "Ichorous Intensity"},
{"muscle", "Mucilaginous Muscle"},
{"mentalism", "Mucilaginous Mentalism"},
{"moxiousness", "Mucilaginous Moxiousness"},
},
};
public static final boolean eliminationProcessor(
final String[][] strings,
final int index,
final int id,
final int minId,
final int maxId,
final String baseName,
final String joiner) {
String effect = strings[index][0];
Preferences.setString(baseName + id, effect);
String name = ItemDatabase.getItemName(id);
String testName = name + joiner + effect;
String testPlural = ItemDatabase.getPluralName(id) + joiner + effect;
ItemDatabase.registerItemAlias(id, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
HashSet<String> possibilities = new HashSet<>();
for (int i = 0; i < strings.length; ++i) {
possibilities.add(strings[i][0]);
}
int missing = 0;
for (int i = minId; i <= maxId; ++i) {
effect = Preferences.getString(baseName + i);
if (effect.equals("")) {
if (missing != 0) {
// more than one missing item in set
return false;
}
missing = i;
} else {
possibilities.remove(effect);
}
}
if (missing == 0) {
// no missing items
return false;
}
if (possibilities.size() != 1) {
// something's screwed up if this happens
return false;
}
effect = possibilities.iterator().next();
Preferences.setString(baseName + missing, effect);
name = ItemDatabase.getItemName(missing);
testName = name + joiner + effect;
testPlural = ItemDatabase.getPluralName(missing) + joiner + effect;
ItemDatabase.registerItemAlias(missing, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
return true;
}
// Suggest one or two items from a permutation group that need to be identified.
// Strategy: identify the items the player has the most of first,
// to maximize the usefulness of having identified them.
// If two items remain unidentified, only identify one, since
// eliminationProcessor will handle the other.
public static final void suggestIdentify(
final List<Integer> items, final int minId, final int maxId, final String baseName) {
// Can't autoidentify in G-Lover
if (KoLCharacter.inGLover()) {
return;
}
ArrayList<Integer> possible = new ArrayList<>();
int unknown = 0;
for (int i = minId; i <= maxId; ++i) {
if (!Preferences.getString(baseName + i).equals("")) {
continue; // already identified;
}
++unknown;
AdventureResult item = new AdventureResult(i, 1, false);
int count = item.getCount(KoLConstants.inventory);
if (count <= 0) {
continue; // can't identify yet
}
possible.add(IntegerPool.get(i | Math.min(count, 127) << 24));
}
int count = possible.size();
// Nothing to do if we have no items that qualify
if (count == 0) {
return;
}
if (count > 1) {
Collections.sort(possible, Collections.reverseOrder());
}
// Identify the item we have the most of
items.add(possible.get(0) & 0x00FFFFFF);
// If only two items are unknown, that's enough, since the
// other will be identified by eliminationProcessor
if (unknown == 2) {
return;
}
// If we have three or more unknowns, try for a second
if (count > 1) {
items.add(possible.get(1) & 0x00FFFFFF);
}
}
}
| libraryaddict/kolmafia | src/net/sourceforge/kolmafia/objectpool/ItemPool.java |
729 | package net.sourceforge.kolmafia.objectpool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import net.sourceforge.kolmafia.AdventureResult;
import net.sourceforge.kolmafia.KoLCharacter;
import net.sourceforge.kolmafia.KoLConstants;
import net.sourceforge.kolmafia.persistence.ItemDatabase;
import net.sourceforge.kolmafia.preferences.Preferences;
public class ItemPool {
public static final int SEAL_CLUB = 1;
public static final int SEAL_TOOTH = 2;
public static final int HELMET_TURTLE = 3;
public static final int TURTLE_TOTEM = 4;
public static final int PASTA_SPOON = 5;
public static final int RAVIOLI_HAT = 6;
public static final int SAUCEPAN = 7;
public static final int SPICES = 8;
public static final int DISCO_MASK = 9;
public static final int DISCO_BALL = 10;
public static final int STOLEN_ACCORDION = 11;
public static final int MARIACHI_PANTS = 12;
public static final int WORTHLESS_ITEM = 13; // Pseudo item
public static final int MOXIE_WEED = 14;
public static final int ASPARAGUS_KNIFE = 19;
public static final int CHEWING_GUM = 23;
public static final int TEN_LEAF_CLOVER = 24;
public static final int MEAT_PASTE = 25;
public static final int DOLPHIN_KING_MAP = 26;
public static final int SPIDER_WEB = 27;
public static final int BIG_ROCK = 30;
public static final int BJORNS_HAMMER = 32;
public static final int CASINO_PASS = 40;
public static final int SCHLITZ = 41;
public static final int HERMIT_PERMIT = 42;
public static final int WORTHLESS_TRINKET = 43;
public static final int WORTHLESS_GEWGAW = 44;
public static final int WORTHLESS_KNICK_KNACK = 45;
public static final int WOODEN_FIGURINE = 46;
public static final int BUTTERED_ROLL = 47;
public static final int ROCK_N_ROLL_LEGEND = 50;
public static final int BANJO_STRINGS = 52;
public static final int STONE_BANJO = 53;
public static final int DISCO_BANJO = 54;
public static final int JABANERO_PEPPER = 55;
public static final int FIVE_ALARM_SAUCEPAN = 57;
public static final int MACE_OF_THE_TORTOISE = 60;
public static final int FORTUNE_COOKIE = 61;
public static final int GOLDEN_TWIG = 66;
public static final int PASTA_SPOON_OF_PERIL = 68;
public static final int NEWBIESPORT_TENT = 69;
public static final int BAR_SKIN = 70;
public static final int WOODEN_STAKES = 71;
public static final int BARSKIN_TENT = 73;
public static final int SPOOKY_MAP = 74;
public static final int SPOOKY_SAPLING = 75;
public static final int SPOOKY_FERTILIZER = 76;
public static final int PRETTY_BOUQUET = 78;
public static final int GRAVY_BOAT = 80;
public static final int WILLER = 81;
public static final int LOCKED_LOCKER = 84;
public static final int TBONE_KEY = 86;
public static final int MEAT_FROM_YESTERDAY = 87;
public static final int MEAT_STACK = 88;
public static final int MEAT_GOLEM = 101;
public static final int SCARECROW = 104;
public static final int KETCHUP = 106;
public static final int CATSUP = 107;
public static final int SPRING = 118;
public static final int SPROCKET = 119;
public static final int COG = 120;
public static final int GNOLLISH_AUTOPLUNGER = 127;
public static final int FRILLY_SKIRT = 131;
public static final int BITCHIN_MEATCAR = 134;
public static final int SWEET_RIMS = 135;
public static final int ICE_COLD_SIX_PACK = 138;
public static final int VALUABLE_TRINKET = 139;
public static final int DINGY_PLANKS = 140;
public static final int DINGY_DINGHY = 141;
public static final int ANTICHEESE = 142;
public static final int COTTAGE = 143;
public static final int BARBED_FENCE = 145;
public static final int DINGHY_PLANS = 146;
public static final int SCALP_OF_GORGOLOK = 150;
public static final int ELDER_TURTLE_SHELL = 151;
public static final int COLANDER_OF_EMERIL = 152;
public static final int ANCIENT_SAUCEHELM = 153;
public static final int DISCO_FRO_PICK = 154;
public static final int EL_SOMBRERO_DE_LOPEZ = 155;
public static final int RANGE = 157;
public static final int DOUGH = 159;
public static final int SKELETON_BONE = 163;
public static final int BONE_RATTLE = 168;
public static final int TACO_SHELL = 173;
public static final int BRIEFCASE = 184;
public static final int FAT_STACKS_OF_CASH = 185;
public static final int ENCHANTED_BEAN = 186;
public static final int LOOSE_TEETH = 187;
public static final int BAT_GUANO = 188;
public static final int BATSKIN_BELT = 191;
public static final int MR_ACCESSORY = 194;
public static final int DISASSEMBLED_CLOVER = 196;
public static final int RAT_WHISKER = 197;
public static final int FENG_SHUI = 210;
public static final int FOUNTAIN = 211;
public static final int WINDCHIMES = 212;
public static final int DREADSACK = 214;
public static final int HEMP_STRING = 218;
public static final int EYEPATCH = 224;
public static final int PUNGENT_UNGUENT = 231;
public static final int COCKTAIL_KIT = 236;
public static final int GRAPEFRUIT = 243;
public static final int TOMATO = 246;
public static final int FERMENTING_POWDER = 247;
public static final int MARTINI = 251;
public static final int DENSE_STACK = 258;
public static final int MULLET_WIG = 267;
public static final int PICKET_FENCE = 270;
public static final int MOSQUITO_LARVA = 275;
public static final int PICKOMATIC_LOCKPICKS = 280;
public static final int BORIS_KEY = 282;
public static final int JARLSBERG_KEY = 283;
public static final int SNEAKY_PETE_KEY = 284;
public static final int RUBBER_AXE = 292;
public static final int FLAT_DOUGH = 301;
public static final int DRY_NOODLES = 304;
public static final int KNOB_GOBLIN_PERFUME = 307;
public static final int KNOB_GOBLIN_HELM = 308;
public static final int KNOB_GOBLIN_PANTS = 309;
public static final int KNOB_GOBLIN_POLEARM = 310;
public static final int KNOB_GOBLIN_CROWN = 313;
public static final int GOAT_CHEESE = 322;
public static final int PLAIN_PIZZA = 323;
public static final int SAUSAGE_PIZZA = 324;
public static final int GOAT_CHEESE_PIZZA = 325;
public static final int MUSHROOM_PIZZA = 326;
public static final int TENDER_HAMMER = 338;
public static final int LAB_KEY = 339;
public static final int SELTZER = 344;
public static final int REAGENT = 346;
public static final int DYSPEPSI_COLA = 347;
public static final int MINERS_HELMET = 360;
public static final int MINERS_PANTS = 361;
public static final int MATTOCK = 362;
public static final int LINOLEUM_ORE = 363;
public static final int ASBESTOS_ORE = 364;
public static final int CHROME_ORE = 365;
public static final int YETI_FUR = 388;
public static final int PENGUIN_SKIN = 393;
public static final int YAK_SKIN = 394;
public static final int HIPPOPOTAMUS_SKIN = 395;
public static final int ACOUSTIC_GUITAR = 404;
public static final int PIRATE_CHEST = 405;
public static final int PIRATE_PELVIS = 406;
public static final int PIRATE_SKULL = 407;
public static final int JOLLY_CHARRRM = 411;
public static final int JOLLY_BRACELET = 413;
public static final int BEANBAG_CHAIR = 429;
public static final int LONG_SKINNY_BALLOON = 433;
public static final int BALLOON_MONKEY = 436;
public static final int CHEF = 438;
public static final int BARTENDER = 440;
public static final int BEER_LENS = 443;
public static final int PRETENTIOUS_PAINTBRUSH = 450;
public static final int PRETENTIOUS_PALETTE = 451;
public static final int RUSTY_SCREWDRIVER = 454;
public static final int DRY_MARTINI = 456;
public static final int TRANSFUNCTIONER = 458;
public static final int WHITE_PIXEL = 459;
public static final int BLACK_PIXEL = 460;
public static final int RED_PIXEL = 461;
public static final int GREEN_PIXEL = 462;
public static final int BLUE_PIXEL = 463;
public static final int RED_PIXEL_POTION = 464;
public static final int RUBY_W = 468;
public static final int HOT_WING = 471;
public static final int DODECAGRAM = 479;
public static final int CANDLES = 480;
public static final int BUTTERKNIFE = 481;
public static final int MR_CONTAINER = 482;
public static final int NEWBIESPORT_BACKPACK = 483;
public static final int HEMP_BACKPACK = 484;
public static final int SNAKEHEAD_CHARM = 485;
public static final int TALISMAN = 486;
public static final int KETCHUP_HOUND = 493;
public static final int PAPAYA = 498;
public static final int ELF_FARM_RAFFLE_TICKET = 500;
public static final int PAGODA_PLANS = 502;
public static final int HEAVY_METAL_GUITAR = 507;
public static final int HEY_DEZE_NUTS = 509;
public static final int BORIS_PIE = 513;
public static final int JARLSBERG_PIE = 514;
public static final int SNEAKY_PETE_PIE = 515;
public static final int HEY_DEZE_MAP = 516;
public static final int MMJ = 518;
public static final int MOXIE_MAGNET = 519;
public static final int STRANGE_LEAFLET = 520;
public static final int HOUSE = 526;
public static final int VOLLEYBALL = 527;
public static final int SPECIAL_SAUCE_GLOVE = 531;
public static final int ABRIDGED = 534;
public static final int BRIDGE = 535;
public static final int DICTIONARY = 536;
public static final int LOWERCASE_N = 539;
public static final int ELITE_TROUSERS = 542;
public static final int SCROLL_334 = 547;
public static final int SCROLL_668 = 548;
public static final int SCROLL_30669 = 549;
public static final int SCROLL_33398 = 550;
public static final int SCROLL_64067 = 551;
public static final int GATES_SCROLL = 552;
public static final int ELITE_SCROLL = 553;
public static final int CAN_LID = 559;
public static final int SONAR = 563;
public static final int HERMIT_SCRIPT = 567;
public static final int LUCIFER = 571;
public static final int HELL_RAMEN = 578;
public static final int FETTUCINI_INCONNU = 583;
public static final int SPAGHETTI_WITH_SKULLHEADS = 584;
public static final int GNOCCHETTI_DI_NIETZSCHE = 585;
public static final int REMEDY = 588;
public static final int TINY_HOUSE = 592;
public static final int PHONICS_DOWN = 593;
public static final int EXTREME_AMULET = 594;
public static final int DRASTIC_HEALING = 595;
public static final int TITANIUM_UMBRELLA = 596;
public static final int MOHAWK_WIG = 597;
public static final int SLUG_LORD_MAP = 598;
public static final int DR_HOBO_MAP = 601;
public static final int SHOPPING_LIST = 602;
public static final int TISSUE_PAPER_IMMATERIA = 605;
public static final int TIN_FOIL_IMMATERIA = 606;
public static final int GAUZE_IMMATERIA = 607;
public static final int PLASTIC_WRAP_IMMATERIA = 608;
public static final int SOCK = 609;
public static final int HEAVY_D = 611;
public static final int CHAOS_BUTTERFLY = 615;
public static final int FURRY_FUR = 616;
public static final int GIANT_NEEDLE = 619;
public static final int BLACK_CANDLE = 620;
public static final int WARM_SUBJECT = 621;
public static final int AWFUL_POETRY_JOURNAL = 622;
public static final int WA = 623;
public static final int NG = 624;
public static final int WAND_OF_NAGAMAR = 626;
public static final int ND = 627;
public static final int METALLIC_A = 628;
public static final int MEAT_GLOBE = 636;
public static final int TOASTER = 637;
public static final int TOAST = 641;
public static final int SKELETON_KEY = 642;
public static final int SKELETON_KEY_RING = 643;
public static final int ROWBOAT = 653;
public static final int STAR = 654;
public static final int LINE = 655;
public static final int STAR_CHART = 656;
public static final int STAR_SWORD = 657;
public static final int STAR_CROSSBOW = 658;
public static final int STAR_STAFF = 659;
public static final int STAR_HAT = 661;
public static final int STAR_STARFISH = 664;
public static final int STAR_KEY = 665;
public static final int STEAMING_EVIL = 666;
public static final int GIANT_CASTLE_MAP = 667;
public static final int CRANBERRIES = 672;
public static final int BONERDAGON_SKULL = 675;
public static final int DRAGONBONE_BELT_BUCKLE = 676;
public static final int BADASS_BELT = 677;
public static final int BONERDAGON_CHEST = 678;
public static final int SUMP_M_SUMP_M = 682;
public static final int DIGITAL_KEY = 691;
public static final int HAMETHYST = 704;
public static final int BACONSTONE = 705;
public static final int PORQUOISE = 706;
public static final int JEWELRY_PLIERS = 709;
public static final int BACONSTONE_EARRING = 715;
public static final int BACONSTONE_BRACELET = 717;
public static final int MIRROR_SHARD = 726;
public static final int PUZZLE_PIECE = 727;
public static final int HEDGE_KEY = 728;
public static final int FISHBOWL = 729;
public static final int FISHTANK = 730;
public static final int FISH_HOSE = 731;
public static final int HOSED_TANK = 732;
public static final int HOSED_FISHBOWL = 733;
public static final int SCUBA_GEAR = 734;
public static final int SINISTER_STRUMMING = 736;
public static final int SQUEEZINGS_OF_WOE = 737;
public static final int REALLY_EVIL_RHYTHM = 738;
public static final int TAMBOURINE = 740;
public static final int BROKEN_SKULL = 741;
public static final int KNOB_FIRECRACKER = 747;
public static final int FLAMING_MUSHROOM = 755;
public static final int FROZEN_MUSHROOM = 756;
public static final int STINKY_MUSHROOM = 757;
public static final int CUMMERBUND = 778;
public static final int MAFIA_ARIA = 781;
public static final int RAFFLE_TICKET = 785;
public static final int STRAWBERRY = 786;
public static final int GOLDEN_MR_ACCESSORY = 792;
public static final int ROCKIN_WAGON = 797;
public static final int PLUS_SIGN = 818;
public static final int FIRST_BANG_POTION = 819;
public static final int MILKY_POTION = 819;
public static final int SWIRLY_POTION = 820;
public static final int BUBBLY_POTION = 821;
public static final int SMOKY_POTION = 822;
public static final int CLOUDY_POTION = 823;
public static final int EFFERVESCENT_POTION = 824;
public static final int FIZZY_POTION = 825;
public static final int DARK_POTION = 826;
public static final int LAST_BANG_POTION = 827;
public static final int MURKY_POTION = 827;
public static final int ANTIDOTE = 829;
public static final int ROYAL_JELLY = 830;
public static final int SHOCK_COLLAR = 856;
public static final int MOONGLASSES = 857;
public static final int LEAD_NECKLACE = 865;
public static final int TEARS = 869;
public static final int ROLLING_PIN = 873;
public static final int UNROLLING_PIN = 874;
public static final int GOOFBALLS = 879;
public static final int YUMMY_TUMMY_BEAN = 905;
public static final int DWARF_BREAD = 910;
public static final int PLASTIC_SWORD = 938;
public static final int DIRTY_MARTINI = 948;
public static final int GROGTINI = 949;
public static final int CHERRY_BOMB = 950;
public static final int WHITE_CHOCOLATE_AND_TOMATO_PIZZA = 958;
public static final int MAID = 1000;
public static final int TEQUILA = 1004;
public static final int BOXED_WINE = 1005;
public static final int VODKA_MARTINI = 1009;
public static final int DRY_VODKA_MARTINI = 1019;
public static final int VESPER = 1023;
public static final int BODYSLAM = 1024;
public static final int SANGRIA_DEL_DIABLO = 1025;
public static final int VALENTINE = 1026;
public static final int TAM_O_SHANTER = 1040;
public static final int GREEN_BEER = 1041;
public static final int RED_STRIPED_EGG = 1048;
public static final int RED_POLKA_EGG = 1049;
public static final int RED_PAISLEY_EGG = 1050;
public static final int BLUE_STRIPED_EGG = 1052;
public static final int BLUE_POLKA_EGG = 1053;
public static final int BLUE_PAISLEY_EGG = 1054;
public static final int OYSTER_BASKET = 1080;
public static final int TARGETING_CHIP = 1102;
public static final int CLOCKWORK_BARTENDER = 1111;
public static final int CLOCKWORK_CHEF = 1112;
public static final int CLOCKWORK_MAID = 1113;
public static final int ANNOYING_PITCHFORK = 1116;
public static final int PREGNANT_FLAMING_MUSHROOM = 1118;
public static final int PREGNANT_FROZEN_MUSHROOM = 1119;
public static final int PREGNANT_STINKY_MUSHROOM = 1120;
public static final int INEXPLICABLY_GLOWING_ROCK = 1121;
public static final int SPOOKY_GLOVE = 1125;
public static final int SPOOKY_BICYCLE_CHAIN = 1137;
public static final int FLAMING_MUSHROOM_WINE = 1139;
public static final int ICY_MUSHROOM_WINE = 1140;
public static final int STINKY_MUSHROOM_WINE = 1141;
public static final int POINTY_MUSHROOM_WINE = 1142;
public static final int FLAT_MUSHROOM_WINE = 1143;
public static final int COOL_MUSHROOM_WINE = 1144;
public static final int KNOB_MUSHROOM_WINE = 1145;
public static final int KNOLL_MUSHROOM_WINE = 1146;
public static final int SPOOKY_MUSHROOM_WINE = 1147;
public static final int GRAVY_MAYPOLE = 1152;
public static final int GIFT1 = 1167;
public static final int GIFT2 = 1168;
public static final int GIFT3 = 1169;
public static final int GIFT4 = 1170;
public static final int GIFT5 = 1171;
public static final int GIFT6 = 1172;
public static final int GIFT7 = 1173;
public static final int GIFT8 = 1174;
public static final int GIFT9 = 1175;
public static final int GIFT10 = 1176;
public static final int GIFT11 = 1177;
public static final int POTTED_FERN = 1180;
public static final int TULIP = 1181;
public static final int VENUS_FLYTRAP = 1182;
public static final int ALL_PURPOSE_FLOWER = 1183;
public static final int EXOTIC_ORCHID = 1184;
public static final int LONG_STEMMED_ROSE = 1185;
public static final int GILDED_LILY = 1186;
public static final int DEADLY_NIGHTSHADE = 1187;
public static final int BLACK_LOTUS = 1188;
public static final int STUFFED_GHUOL_WHELP = 1191;
public static final int STUFFED_ZMOBIE = 1192;
public static final int RAGGEDY_HIPPY_DOLL = 1193;
public static final int STUFFED_STAB_BAT = 1194;
public static final int APATHETIC_LIZARDMAN_DOLL = 1195;
public static final int STUFFED_YETI = 1196;
public static final int STUFFED_MOB_PENGUIN = 1197;
public static final int STUFFED_SABRE_TOOTHED_LIME = 1198;
public static final int GIANT_STUFFED_BUGBEAR = 1199;
public static final int HAPPY_BIRTHDAY_CLAUDE_CAKE = 1202;
public static final int PERSONALIZED_BIRTHDAY_CAKE = 1203;
public static final int THREE_TIERED_WEDDING_CAKE = 1204;
public static final int BABYCAKES = 1205;
public static final int BLUE_VELVET_CAKE = 1206;
public static final int CONGRATULATORY_CAKE = 1207;
public static final int ANGEL_FOOD_CAKE = 1208;
public static final int DEVILS_FOOD_CAKE = 1209;
public static final int BIRTHDAY_PARTY_JELLYBEAN_CHEESECAKE = 1210;
public static final int HEART_SHAPED_BALLOON = 1213;
public static final int ANNIVERSARY_BALLOON = 1214;
public static final int MYLAR_BALLOON = 1215;
public static final int KEVLAR_BALLOON = 1216;
public static final int THOUGHT_BALLOON = 1217;
public static final int RAT_BALLOON = 1218;
public static final int MINI_ZEPPELIN = 1219;
public static final int MR_BALLOON = 1220;
public static final int RED_BALLOON = 1221;
public static final int STAINLESS_STEEL_SOLITAIRE = 1226;
public static final int PLEXIGLASS_PITH_HELMET = 1231;
public static final int PLEXIGLASS_POCKETWATCH = 1232;
public static final int PLEXIGLASS_PENDANT = 1235;
public static final int TOY_HOVERCRAFT = 1243;
public static final int KNOB_GOBLIN_BALLS = 1244;
public static final int KNOB_GOBLIN_CODPIECE = 1245;
public static final int BONERDAGON_VERTEBRA = 1247;
public static final int BONERDAGON_NECKLACE = 1248;
public static final int PRETENTIOUS_PAIL = 1258;
public static final int WAX_LIPS = 1260;
public static final int NOSE_BONE_FETISH = 1264;
public static final int GLOOMY_BLACK_MUSHROOM = 1266;
public static final int DEAD_MIMIC = 1267;
public static final int PINE_WAND = 1268;
public static final int EBONY_WAND = 1269;
public static final int HEXAGONAL_WAND = 1270;
public static final int ALUMINUM_WAND = 1271;
public static final int MARBLE_WAND = 1272;
public static final int MEDICINAL_HERBS = 1274;
public static final int MAKEUP_KIT = 1305;
public static final int COMFY_BLANKET = 1311;
public static final int FACSIMILE_DICTIONARY = 1316;
public static final int TIME_HELMET = 1323;
public static final int CLOACA_COLA = 1334;
public static final int FANCY_CHOCOLATE = 1382;
public static final int TOY_SOLDIER = 1397;
public static final int SNOWCONE_BOOK = 1411;
public static final int PURPLE_SNOWCONE = 1412;
public static final int GREEN_SNOWCONE = 1413;
public static final int ORANGE_SNOWCONE = 1414;
public static final int RED_SNOWCONE = 1415;
public static final int BLUE_SNOWCONE = 1416;
public static final int BLACK_SNOWCONE = 1417;
public static final int TEDDY_SEWING_KIT = 1419;
public static final int ICEBERGLET = 1423;
public static final int ICE_SICKLE = 1424;
public static final int ICE_BABY = 1425;
public static final int ICE_PICK = 1426;
public static final int ICE_SKATES = 1427;
public static final int OILY_GOLDEN_MUSHROOM = 1432;
public static final int USELESS_POWDER = 1437;
public static final int TWINKLY_WAD = 1450;
public static final int HOT_WAD = 1451;
public static final int COLD_WAD = 1452;
public static final int SPOOKY_WAD = 1453;
public static final int STENCH_WAD = 1454;
public static final int SLEAZE_WAD = 1455;
public static final int GIFTV = 1460;
public static final int LUCKY_RABBIT_FOOT = 1485;
public static final int MINIATURE_DORMOUSE = 1489;
public static final int GLOOMY_MUSHROOM_WINE = 1496;
public static final int OILY_MUSHROOM_WINE = 1497;
public static final int HILARIOUS_BOOK = 1498;
public static final int RUBBER_EMO_ROE = 1503;
public static final int FAKE_HAND = 1511;
public static final int PET_BUFFING_SPRAY = 1512;
public static final int VAMPIRE_HEART = 1518;
public static final int BAKULA = 1519;
public static final int RADIO_KOL_COFFEE_MUG = 1520;
public static final int JOYBUZZER = 1525;
public static final int SNOOTY_DISGUISE = 1526;
public static final int GIFTR = 1534;
public static final int WEEGEE_SQOUIJA = 1537;
public static final int TAM_O_SHATNER = 1539;
public static final int GRIMACITE_GOGGLES = 1540;
public static final int GRIMACITE_GLAIVE = 1541;
public static final int GRIMACITE_GREAVES = 1542;
public static final int GRIMACITE_GARTER = 1543;
public static final int GRIMACITE_GALOSHES = 1544;
public static final int GRIMACITE_GORGET = 1545;
public static final int GRIMACITE_GUAYABERA = 1546;
public static final int MSG = 1549;
public static final int BOXED_CHAMPAGNE = 1556;
public static final int COCKTAIL_ONION = 1560;
public static final int VODKA_GIBSON = 1569;
public static final int GIBSON = 1570;
public static final int HOT_HI_MEIN = 1592;
public static final int COLD_HI_MEIN = 1593;
public static final int SPOOKY_HI_MEIN = 1594;
public static final int STINKY_HI_MEIN = 1595;
public static final int SLEAZY_HI_MEIN = 1596;
public static final int CATALYST = 1605;
public static final int ULTIMATE_WAD = 1606;
public static final int C_CLOCHE = 1615;
public static final int C_CULOTTES = 1616;
public static final int C_CROSSBOW = 1617;
public static final int ICE_STEIN = 1618;
public static final int MUNCHIES_PILL = 1619;
public static final int HOMEOPATHIC = 1620;
public static final int ASTRAL_MUSHROOM = 1622;
public static final int BADGER_BADGE = 1623;
public static final int BLUE_CUPCAKE = 1624;
public static final int GREEN_CUPCAKE = 1625;
public static final int ORANGE_CUPCAKE = 1626;
public static final int PURPLE_CUPCAKE = 1627;
public static final int PINK_CUPCAKE = 1628;
public static final int SPANISH_FLY = 1633;
public static final int BRICK = 1649;
public static final int MILK_OF_MAGNESIUM = 1650;
public static final int JEWEL_EYED_WIZARD_HAT = 1653;
public static final int CITADEL_SATCHEL = 1656;
public static final int CHERRY_CLOACA_COLA = 1658;
public static final int FRAUDWORT = 1670;
public static final int SHYSTERWEED = 1671;
public static final int SWINDLEBLOSSOM = 1672;
public static final int CARDBOARD_ORE = 1675;
public static final int STYROFOAM_ORE = 1676;
public static final int BUBBLEWRAP_ORE = 1677;
public static final int GROUCHO_DISGUISE = 1678;
public static final int EXPRESS_CARD = 1687;
public static final int MUCULENT_MACHETE = 1721;
public static final int SWORD_PREPOSITIONS = 1734;
public static final int GALLERY_KEY = 1765;
public static final int BALLROOM_KEY = 1766;
public static final int PACK_OF_CHEWING_GUM = 1767;
public static final int TRAVOLTAN_TROUSERS = 1792;
public static final int POOL_CUE = 1793;
public static final int HAND_CHALK = 1794;
public static final int DUSTY_ANIMAL_SKULL = 1799;
public static final int ONE_BALL = 1900;
public static final int TWO_BALL = 1901;
public static final int FIVE_BALL = 1904;
public static final int SIX_BALL = 1905;
public static final int EIGHT_BALL = 1907;
public static final int SPOOKYRAVEN_SPECTACLES = 1916;
public static final int ENGLISH_TO_A_F_U_E_DICTIONARY = 1919;
public static final int BIZARRE_ILLEGIBLE_SHEET_MUSIC = 1920;
public static final int TOILET_PAPER = 1923;
public static final int TATTERED_WOLF_STANDARD = 1924;
public static final int TATTERED_SNAKE_STANDARD = 1925;
public static final int TUNING_FORK = 1928;
public static final int ANTIQUE_GREAVES = 1929;
public static final int ANTIQUE_HELMET = 1930;
public static final int ANTIQUE_SPEAR = 1931;
public static final int ANTIQUE_SHIELD = 1932;
public static final int CHINTZY_SEAL_PENDANT = 1941;
public static final int CHINTZY_TURTLE_BROOCH = 1942;
public static final int CHINTZY_NOODLE_RING = 1943;
public static final int CHINTZY_SAUCEPAN_EARRING = 1944;
public static final int CHINTZY_DISCO_BALL_PENDANT = 1945;
public static final int CHINTZY_ACCORDION_PIN = 1946;
public static final int MANETWICH = 1949;
public static final int VANGOGHBITUSSIN = 1950;
public static final int PINOT_RENOIR = 1951;
public static final int FLAT_CHAMPAGNE = 1953;
public static final int QUILL_PEN = 1957;
public static final int INKWELL = 1958;
public static final int SCRAP_OF_PAPER = 1959;
public static final int EVIL_SCROLL = 1960;
public static final int DANCE_CARD = 1963;
public static final int OPERA_MASK = 1964;
public static final int PUMPKIN_BUCKET = 1971;
public static final int SILVER_SHRIMP_FORK = 1972;
public static final int STUFFED_COCOABO = 1974;
public static final int RUBBER_WWTNSD_BRACELET = 1994;
public static final int SPADE_NECKLACE = 2017;
public static final int PATCHOULI_OIL_BOMB = 2040;
public static final int EXPLODING_HACKY_SACK = 2042;
public static final int MACGUFFIN_DIARY = 2044;
public static final int BROKEN_WINGS = 2050;
public static final int SUNKEN_EYES = 2051;
public static final int REASSEMBLED_BLACKBIRD = 2052;
public static final int BLACKBERRY = 2063;
public static final int FORGED_ID_DOCUMENTS = 2064;
public static final int PADL_PHONE = 2065;
public static final int TEQUILA_GRENADE = 2068;
public static final int BEER_HELMET = 2069;
public static final int DISTRESSED_DENIM_PANTS = 2070;
public static final int NOVELTY_BUTTON = 2072;
public static final int MAKESHIFT_TURBAN = 2079;
public static final int MAKESHIFT_CAPE = 2080;
public static final int MAKESHIFT_SKIRT = 2081;
public static final int MAKESHIFT_CRANE = 2083;
public static final int CAN_OF_STARCH = 2084;
public static final int ANTIQUE_HAND_MIRROR = 2092;
public static final int TOWEL = 2095;
public static final int GMOB_POLLEN = 2096;
public static final int LUCRE = 2098;
public static final int ASCII_SHIRT = 2121;
public static final int TOY_MERCENARY = 2139;
public static final int EVIL_TEDDY_SEWING_KIT = 2147;
public static final int TRIANGULAR_STONE = 2173;
public static final int ANCIENT_AMULET = 2180;
public static final int HAROLDS_HAMMER_HEAD = 2182;
public static final int HAROLDS_HAMMER = 2184;
public static final int UNLIT_BIRTHDAY_CAKE = 2186;
public static final int LIT_BIRTHDAY_CAKE = 2187;
public static final int ANCIENT_CAROLS = 2191;
public static final int SHEET_MUSIC = 2192;
public static final int FANCY_EVIL_CHOCOLATE = 2197;
public static final int CRIMBO_UKELELE = 2209;
public static final int LIARS_PANTS = 2222;
public static final int JUGGLERS_BALLS = 2223;
public static final int PINK_SHIRT = 2224;
public static final int FAMILIAR_DOPPELGANGER = 2225;
public static final int EYEBALL_PENDANT = 2226;
public static final int CALAVERA_CONCERTINA = 2234;
public static final int TURTLE_PHEROMONES = 2236;
public static final int PHOTOGRAPH_OF_GOD = 2259;
public static final int WET_STUNT_NUT_STEW = 2266;
public static final int MEGA_GEM = 2267;
public static final int STAFF_OF_FATS = 2268;
public static final int DUSTY_BOTTLE_OF_MERLOT = 2271;
public static final int DUSTY_BOTTLE_OF_PORT = 2272;
public static final int DUSTY_BOTTLE_OF_PINOT_NOIR = 2273;
public static final int DUSTY_BOTTLE_OF_ZINFANDEL = 2274;
public static final int DUSTY_BOTTLE_OF_MARSALA = 2275;
public static final int DUSTY_BOTTLE_OF_MUSCAT = 2276;
public static final int FERNSWARTHYS_KEY = 2277;
public static final int DUSTY_BOOK = 2279;
public static final int MUS_MANUAL = 2280;
public static final int MYS_MANUAL = 2281;
public static final int MOX_MANUAL = 2282;
public static final int SEAL_HELMET = 2283;
public static final int PETRIFIED_NOODLES = 2284;
public static final int CHISEL = 2285;
public static final int EYE_OF_ED = 2286;
public static final int RED_PAPER_CLIP = 2289;
public static final int REALLY_BIG_TINY_HOUSE = 2290;
public static final int NONESSENTIAL_AMULET = 2291;
public static final int WHITE_WINE_VINAIGRETTE = 2292;
public static final int CUP_OF_STRONG_TEA = 2293;
public static final int CURIOUSLY_SHINY_AX = 2294;
public static final int MARINATED_STAKES = 2295;
public static final int KNOB_BUTTER = 2296;
public static final int VIAL_OF_ECTOPLASM = 2297;
public static final int BOOCK_OF_MAGIKS = 2298;
public static final int EZ_PLAY_HARMONICA_BOOK = 2299;
public static final int FINGERLESS_HOBO_GLOVES = 2300;
public static final int CHOMSKYS_COMICS = 2301;
public static final int WORM_RIDING_HOOKS = 2302;
public static final int CANDY_BOOK = 2303;
public static final int GREEN_CANDY = 2309;
public static final int ANCIENT_BRONZE_TOKEN = 2317;
public static final int ANCIENT_BOMB = 2318;
public static final int CARVED_WOODEN_WHEEL = 2319;
public static final int WORM_RIDING_MANUAL_PAGE = 2320;
public static final int HEADPIECE_OF_ED = 2323;
public static final int STAFF_OF_ED = 2325;
public static final int STONE_ROSE = 2326;
public static final int BLACK_PAINT = 2327;
public static final int DRUM_MACHINE = 2328;
public static final int CONFETTI = 2329;
public static final int CHOCOLATE_COVERED_DIAMOND_STUDDED_ROSES = 2330;
public static final int BOUQUET_OF_CIRCULAR_SAW_BLADES = 2331;
public static final int BETTER_THAN_CUDDLING_CAKE = 2332;
public static final int STUFFED_NINJA_SNOWMAN = 2333;
public static final int HOLY_MACGUFFIN = 2334;
public static final int BLACK_PUDDING = 2338;
public static final int BLACKFLY_CHARDONNAY = 2339;
public static final int FILTHWORM_QUEEN_HEART = 2347;
public static final int BEJEWELED_PLEDGE_PIN = 2353;
public static final int COMMUNICATIONS_WINDCHIMES = 2354;
public static final int ZIM_MERMANS_GUITAR = 2364;
public static final int FILTHY_POULTICE = 2369;
public static final int MOLOTOV_COCKTAIL_COCKTAIL = 2400;
public static final int GAUZE_GARTER = 2402;
public static final int GUNPOWDER = 2403;
public static final int JAM_BAND_FLYERS = 2404;
public static final int ROCK_BAND_FLYERS = 2405;
public static final int RHINO_HORMONES = 2419;
public static final int MAGIC_SCROLL = 2420;
public static final int PIRATE_JUICE = 2421;
public static final int PET_SNACKS = 2422;
public static final int INHALER = 2423;
public static final int CYCLOPS_EYEDROPS = 2424;
public static final int SPINACH = 2425;
public static final int FIRE_FLOWER = 2426;
public static final int ICE_CUBE = 2427;
public static final int FAKE_BLOOD = 2428;
public static final int GUANEAU = 2429;
public static final int LARD = 2430;
public static final int MYSTIC_SHELL = 2431;
public static final int LIP_BALM = 2432;
public static final int ANTIFREEZE = 2433;
public static final int BLACK_EYEDROPS = 2434;
public static final int DOGSGOTNONOZ = 2435;
public static final int FLIPBOOK = 2436;
public static final int NEW_CLOACA_COLA = 2437;
public static final int MASSAGE_OIL = 2438;
public static final int POLTERGEIST = 2439;
public static final int ENCRYPTION_KEY = 2441;
public static final int COBBS_KNOB_MAP = 2442;
public static final int SUPERNOVA_CHAMPAGNE = 2444;
public static final int GOATSKIN_UMBRELLA = 2451;
public static final int BAR_WHIP = 2455;
public static final int ODOR_EXTRACTOR = 2462;
public static final int OLFACTION_BOOK = 2463;
public static final int TUXEDO_SHIRT = 2489;
public static final int SHIRT_KIT = 2491;
public static final int TROPICAL_ORCHID = 2492;
public static final int MOLYBDENUM_MAGNET = 2497;
public static final int MOLYBDENUM_HAMMER = 2498;
public static final int MOLYBDENUM_SCREWDRIVER = 2499;
public static final int MOLYBDENUM_PLIERS = 2500;
public static final int MOLYBDENUM_WRENCH = 2501;
public static final int JEWELRY_BOOK = 2502;
public static final int WOVEN_BALING_WIRE_BRACELETS = 2514;
public static final int CRUELTY_FREE_WINE = 2521;
public static final int THISTLE_WINE = 2522;
public static final int FISHY_FISH_LASAGNA = 2527;
public static final int GNAT_LASAGNA = 2531;
public static final int LONG_PORK_LASAGNA = 2535;
public static final int TOMB_RATCHET = 2540;
public static final int MAYFLOWER_BOUQUET = 2541;
public static final int LESSER_GRODULATED_VIOLET = 2542;
public static final int TIN_MAGNOLIA = 2543;
public static final int BEGPWNIA = 2544;
public static final int UPSY_DAISY = 2545;
public static final int HALF_ORCHID = 2546;
public static final int OUTRAGEOUS_SOMBRERO = 2548;
public static final int SHAGADELIC_DISCO_BANJO = 2556;
public static final int SQUEEZEBOX_OF_THE_AGES = 2557;
public static final int CHELONIAN_MORNINGSTAR = 2558;
public static final int HAMMER_OF_SMITING = 2559;
public static final int SEVENTEEN_ALARM_SAUCEPAN = 2560;
public static final int GREEK_PASTA_OF_PERIL = 2561;
public static final int AZAZELS_UNICORN = 2566;
public static final int AZAZELS_LOLLIPOP = 2567;
public static final int AZAZELS_TUTU = 2568;
public static final int ANT_HOE = 2570;
public static final int ANT_RAKE = 2571;
public static final int ANT_PITCHFORK = 2572;
public static final int ANT_SICKLE = 2573;
public static final int ANT_PICK = 2574;
public static final int HANDFUL_OF_SAND = 2581;
public static final int SAND_BRICK = 2582;
public static final int TASTY_TART = 2591;
public static final int LUNCHBOX = 2592;
public static final int KNOB_PASTY = 2593;
public static final int KNOB_COFFEE = 2594;
public static final int TELESCOPE = 2599;
public static final int TUESDAYS_RUBY = 2604;
public static final int PALM_FROND = 2605;
public static final int MOJO_FILTER = 2614;
public static final int WEAVING_MANUAL = 2630;
public static final int PAT_A_CAKE_PENDANT = 2633;
public static final int MUMMY_WRAP = 2634;
public static final int GAUZE_HAMMOCK = 2638;
public static final int MAXWELL_HAMMER = 2642;
public static final int ABSINTHE = 2655;
public static final int BOTTLE_OF_REALPAGNE = 2658;
public static final int SPIKY_COLLAR = 2667;
public static final int LIBRARY_CARD = 2672;
public static final int SPECTRE_SCEPTER = 2678;
public static final int SPARKLER = 2679;
public static final int SNAKE = 2680;
public static final int M282 = 2681;
public static final int DETUNED_RADIO = 2682;
public static final int GIFTW = 2683;
public static final int MASSIVE_SITAR = 2693;
public static final int DUCT_TAPE = 2697;
public static final int SHRINKING_POWDER = 2704;
public static final int PARROT_CRACKER = 2710;
public static final int SPARE_KIDNEY = 2718;
public static final int HAND_CARVED_BOKKEN = 2719;
public static final int HAND_CARVED_BOW = 2720;
public static final int HAND_CARVED_STAFF = 2721;
public static final int PLUM_WINE = 2730;
public static final int BUNCH_OF_SQUARE_GRAPES = 2733;
public static final int STEEL_STOMACH = 2742;
public static final int STEEL_LIVER = 2743;
public static final int STEEL_SPLEEN = 2744;
public static final int HAROLDS_BELL = 2765;
public static final int GOLD_BOWLING_BALL = 2766;
public static final int SOLID_BACONSTONE_EARRING = 2780;
public static final int BRIMSTONE_BERET = 2813;
public static final int BRIMSTONE_BUNKER = 2815;
public static final int BRIMSTONE_BRACELET = 2818;
public static final int GRIMACITE_GASMASK = 2819;
public static final int GRIMACITE_GAT = 2820;
public static final int GRIMACITE_GAITERS = 2821;
public static final int GRIMACITE_GAUNTLETS = 2822;
public static final int GRIMACITE_GO_GO_BOOTS = 2823;
public static final int GRIMACITE_GIRDLE = 2824;
public static final int GRIMACITE_GOWN = 2825;
public static final int REALLY_DENSE_MEAT_STACK = 2829;
public static final int BOTTLE_ROCKET = 2834;
public static final int COOKING_SHERRY = 2840;
public static final int NAVEL_RING = 2844;
public static final int PLASTIC_BIB = 2846;
public static final int GNOME_DEMODULIZER = 2848;
public static final int GREAT_TREE_BRANCH = 2852;
public static final int PHIL_BUNION_AXE = 2853;
public static final int SWAMP_ROSE_BOUQUET = 2854;
public static final int PARTY_HAT = 2945;
public static final int V_MASK = 2946;
public static final int PIRATE_INSULT_BOOK = 2947;
public static final int CARONCH_MAP = 2950;
public static final int FRATHOUSE_BLUEPRINTS = 2951;
public static final int CHARRRM_BRACELET = 2953;
public static final int COCKTAIL_NAPKIN = 2956;
public static final int RUM_CHARRRM = 2957;
public static final int RUM_BRACELET = 2959;
public static final int RIGGING_SHAMPOO = 2963;
public static final int BALL_POLISH = 2964;
public static final int MIZZENMAST_MOP = 2965;
public static final int GRUMPY_CHARRRM = 2972;
public static final int GRUMPY_BRACELET = 2973;
public static final int TARRRNISH_CHARRRM = 2974;
public static final int TARRRNISH_BRACELET = 2975;
public static final int BILGE_WINE = 2976;
public static final int BOOTY_CHARRRM = 2980;
public static final int BOOTY_BRACELET = 2981;
public static final int CANNONBALL_CHARRRM = 2982;
public static final int CANNONBALL_BRACELET = 2983;
public static final int COPPER_CHARRRM = 2984;
public static final int COPPER_BRACELET = 2985;
public static final int TONGUE_CHARRRM = 2986;
public static final int TONGUE_BRACELET = 2987;
public static final int CLINGFILM = 2988;
public static final int CARONCH_NASTY_BOOTY = 2999;
public static final int CARONCH_DENTURES = 3000;
public static final int IDOL_AKGYXOTH = 3009;
public static final int EMBLEM_AKGYXOTH = 3010;
public static final int SIMPLE_CURSED_KEY = 3013;
public static final int ORNATE_CURSED_KEY = 3014;
public static final int GILDED_CURSED_KEY = 3015;
public static final int ANCIENT_CURSED_FOOTLOCKER = 3016;
public static final int ORNATE_CURSED_CHEST = 3017;
public static final int GILDED_CURSED_CHEST = 3018;
public static final int PIRATE_FLEDGES = 3033;
public static final int CURSED_PIECE_OF_THIRTEEN = 3034;
public static final int FOIL_BOW = 3043;
public static final int FOIL_RADAR = 3044;
public static final int POWER_SPHERE = 3049;
public static final int FOIL_CAT_EARS = 3056;
public static final int LASER_CANON = 3069;
public static final int CHIN_STRAP = 3070;
public static final int GLUTEAL_SHIELD = 3071;
public static final int CARBONITE_VISOR = 3072;
public static final int UNOBTAINIUM_STRAPS = 3073;
public static final int FASTENING_APPARATUS = 3074;
public static final int GENERAL_ASSEMBLY_MODULE = 3075;
public static final int LASER_TARGETING_CHIP = 3076;
public static final int LEG_ARMOR = 3077;
public static final int KEVLATEFLOCITE_HELMET = 3078;
public static final int TEDDY_BORG_SEWING_KIT = 3087;
public static final int VITACHOC_CAPSULE = 3091;
public static final int HOBBY_HORSE = 3092;
public static final int BALL_IN_A_CUP = 3093;
public static final int SET_OF_JACKS = 3094;
public static final int FISH_SCALER = 3097;
public static final int MINIBORG_STOMPER = 3109;
public static final int MINIBORG_STRANGLER = 3110;
public static final int MINIBORG_LASER = 3111;
public static final int MINIBORG_BEEPER = 3112;
public static final int MINIBORG_HIVEMINDER = 3113;
public static final int MINIBORG_DESTROYOBOT = 3114;
public static final int DIVINE_BOOK = 3117;
public static final int DIVINE_NOISEMAKER = 3118;
public static final int DIVINE_SILLY_STRING = 3119;
public static final int DIVINE_BLOWOUT = 3120;
public static final int DIVINE_CHAMPAGNE_POPPER = 3121;
public static final int DIVINE_CRACKER = 3122;
public static final int DIVINE_FLUTE = 3123;
public static final int HOBO_NICKEL = 3126;
public static final int SANDCASTLE = 3127;
public static final int MARSHMALLOW = 3128;
public static final int ROASTED_MARSHMALLOW = 3129;
public static final int TORN_PAPER_STRIP = 3144;
public static final int PUNCHCARD_ATTACK = 3146;
public static final int PUNCHCARD_REPAIR = 3147;
public static final int PUNCHCARD_BUFF = 3148;
public static final int PUNCHCARD_MODIFY = 3149;
public static final int PUNCHCARD_BUILD = 3150;
public static final int PUNCHCARD_TARGET = 3151;
public static final int PUNCHCARD_SELF = 3152;
public static final int PUNCHCARD_FLOOR = 3153;
public static final int PUNCHCARD_DRONE = 3154;
public static final int PUNCHCARD_WALL = 3155;
public static final int PUNCHCARD_SPHERE = 3156;
public static final int DRONE = 3157;
public static final int EL_VIBRATO_HELMET = 3162;
public static final int EL_VIBRATO_SPEAR = 3163;
public static final int EL_VIBRATO_PANTS = 3164;
public static final int BROKEN_DRONE = 3165;
public static final int REPAIRED_DRONE = 3166;
public static final int AUGMENTED_DRONE = 3167;
public static final int FORTUNE_TELLER = 3193;
public static final int ORIGAMI_MAGAZINE = 3194;
public static final int PAPER_SHURIKEN = 3195;
public static final int ORIGAMI_PASTIES = 3196;
public static final int RIDING_CROP = 3197;
public static final int TRAPEZOID = 3198;
public static final int LUMP_OF_COAL = 3199;
public static final int THICK_PADDED_ENVELOPE = 3201;
public static final int DWARVISH_PUNCHCARD = 3207;
public static final int SMALL_LAMINATED_CARD = 3208;
public static final int LITTLE_LAMINATED_CARD = 3209;
public static final int NOTBIG_LAMINATED_CARD = 3210;
public static final int UNLARGE_LAMINATED_CARD = 3211;
public static final int DWARVISH_DOCUMENT = 3212;
public static final int DWARVISH_PAPER = 3213;
public static final int DWARVISH_PARCHMENT = 3214;
public static final int OVERCHARGED_POWER_SPHERE = 3215;
public static final int HOBO_CODE_BINDER = 3220;
public static final int GATORSKIN_UMBRELLA = 3222;
public static final int SEWER_WAD = 3224;
public static final int OOZE_O = 3226;
public static final int DUMPLINGS = 3228;
public static final int OIL_OF_OILINESS = 3230;
public static final int TATTERED_PAPER_CROWN = 3231;
public static final int INFLATABLE_DUCK = 3233;
public static final int WATER_WINGS = 3234;
public static final int FOAM_NOODLE = 3235;
public static final int KISSIN_COUSINS = 3236;
public static final int TALES_FROM_THE_FIRESIDE = 3237;
public static final int BLIZZARDS_I_HAVE_DIED_IN = 3238;
public static final int MAXING_RELAXING = 3239;
public static final int BIDDY_CRACKERS_COOKBOOK = 3240;
public static final int TRAVELS_WITH_JERRY = 3241;
public static final int LET_ME_BE = 3242;
public static final int ASLEEP_IN_THE_CEMETERY = 3243;
public static final int SUMMER_NIGHTS = 3244;
public static final int SENSUAL_MASSAGE_FOR_CREEPS = 3245;
public static final int BAG_OF_CANDY = 3261;
public static final int TASTEFUL_BOOK = 3263;
public static final int CROTCHETY_PANTS = 3271;
public static final int SACCHARINE_MAPLE_PENDANT = 3272;
public static final int WILLOWY_BONNET = 3273;
public static final int BLACK_BLUE_LIGHT = 3276;
public static final int LOUDMOUTH_LARRY = 3277;
public static final int CHEAP_STUDDED_BELT = 3278;
public static final int PERSONAL_MASSAGER = 3279;
public static final int PLASMA_BALL = 3281;
public static final int STICK_ON_EYEBROW_PIERCING = 3282;
public static final int MACARONI_FRAGMENTS = 3287;
public static final int SHIMMERING_TENDRILS = 3288;
public static final int SCINTILLATING_POWDER = 3289;
public static final int VOLCANO_MAP = 3291;
public static final int PRETTY_PINK_BOW = 3298;
public static final int SMILEY_FACE_STICKER = 3299;
public static final int FARFALLE_BOW_TIE = 3300;
public static final int JALAPENO_SLICES = 3301;
public static final int SOLAR_PANELS = 3302;
public static final int TINY_SOMBRERO = 3303;
public static final int EPIC_WAD = 3316;
public static final int MAYFLY_BAIT_NECKLACE = 3322;
public static final int SCRATCHS_FORK = 3323;
public static final int FROSTYS_MUG = 3324;
public static final int FERMENTED_PICKLE_JUICE = 3325;
public static final int EXTRA_GREASY_SLIDER = 3327;
public static final int CRUMPLED_FELT_FEDORA = 3328;
public static final int DOUBLE_SIDED_TAPE = 3336;
public static final int HOT_BEDDING = 3344; // bed of coals
public static final int COLD_BEDDING = 3345; // frigid air mattress
public static final int STENCH_BEDDING = 3346; // filth-encrusted futon
public static final int SPOOKY_BEDDING = 3347; // comfy coffin
public static final int SLEAZE_BEDDING = 3348; // stained mattress
public static final int ZEN_MOTORCYCLE = 3352;
public static final int GONG = 3353;
public static final int GRUB = 3356;
public static final int MOTH = 3357;
public static final int FIRE_ANT = 3358;
public static final int ICE_ANT = 3359;
public static final int STINKBUG = 3360;
public static final int DEATH_WATCH_BEETLE = 3361;
public static final int LOUSE = 3362;
public static final int INTERESTING_TWIG = 3367;
public static final int TWIG_HOUSE = 3374;
public static final int RICHIE_THINGFINDER = 3375;
public static final int MEDLEY_OF_DIVERSITY = 3376;
public static final int EXPLOSIVE_ETUDE = 3377;
public static final int CHORALE_OF_COMPANIONSHIP = 3378;
public static final int PRELUDE_OF_PRECISION = 3379;
public static final int CHESTER_GLASSES = 3383;
public static final int EMPTY_EYE = 3388;
public static final int ICEBALL = 3391;
public static final int NEVERENDING_SODA = 3393;
public static final int HODGMANS_PORKPIE_HAT = 3395;
public static final int HODGMANS_LOBSTERSKIN_PANTS = 3396;
public static final int HODGMANS_BOW_TIE = 3397;
public static final int SQUEEZE = 3399;
public static final int FISHYSOISSE = 3400;
public static final int LAMP_SHADE = 3401;
public static final int GARBAGE_JUICE = 3402;
public static final int LEWD_CARD = 3403;
public static final int HODGMAN_JOURNAL_1 = 3412;
public static final int HODGMAN_JOURNAL_2 = 3413;
public static final int HODGMAN_JOURNAL_3 = 3414;
public static final int HODGMAN_JOURNAL_4 = 3415;
public static final int HOBO_FORTRESS = 3416;
public static final int FIREWORKS = 3421;
public static final int GIFTH = 3430;
public static final int SPICE_MELANGE = 3433;
public static final int RAINBOWS_GRAVITY = 3439;
public static final int COTTON_CANDY_CONDE = 3449;
public static final int COTTON_CANDY_PINCH = 3450;
public static final int COTTON_CANDY_SMIDGEN = 3451;
public static final int COTTON_CANDY_SKOSHE = 3452;
public static final int COTTON_CANDY_PLUG = 3453;
public static final int COTTON_CANDY_PILLOW = 3454;
public static final int COTTON_CANDY_BALE = 3455;
public static final int STYX_SPRAY = 3458;
public static final int HAIKU_KATANA = 3466;
public static final int BATHYSPHERE = 3470;
public static final int DAMP_OLD_BOOT = 3471;
public static final int BOXTOP = 3473;
public static final int DULL_FISH_SCALE = 3486;
public static final int ROUGH_FISH_SCALE = 3487;
public static final int PRISTINE_FISH_SCALE = 3488;
public static final int FISH_SCIMITAR = 3492;
public static final int FISH_STICK = 3493;
public static final int FISH_BAZOOKA = 3494;
public static final int SEA_SALT_CRYSTAL = 3495;
public static final int LARP_MEMBERSHIP_CARD = 3506;
public static final int STICKER_BOOK = 3507;
public static final int STICKER_SWORD = 3508;
public static final int STICKER_CROSSBOW = 3526;
public static final int GRIMACITE_HAMMER = 3542;
public static final int GRIMACITE_GRAVY_BOAT = 3543;
public static final int GRIMACITE_WEIGHTLIFTING_BELT = 3544;
public static final int GRIMACITE_GRAPPLING_HOOK = 3545;
public static final int GRIMACITE_NINJA_MASK = 3546;
public static final int GRIMACITE_SHINGUARDS = 3547;
public static final int GRIMACITE_ASTROLABE = 3548;
public static final int SEED_PACKET = 3553;
public static final int GREEN_SLIME = 3554;
public static final int SEA_CARROT = 3555;
public static final int SEA_CUCUMBER = 3556;
public static final int SEA_AVOCADO = 3557;
public static final int POTION_OF_PUISSANCE = 3561;
public static final int POTION_OF_PERSPICACITY = 3562;
public static final int POTION_OF_PULCHRITUDE = 3563;
public static final int SAND_DOLLAR = 3575;
public static final int BEZOAR_RING = 3577;
public static final int WRIGGLING_FLYTRAP_PELLET = 3580;
public static final int SUSHI_ROLLING_MAT = 3581;
public static final int WHITE_RICE = 3582;
public static final int RUSTY_BROKEN_DIVING_HELMET = 3602;
public static final int BUBBLIN_STONE = 3605;
public static final int AERATED_DIVING_HELMET = 3607;
public static final int DAS_BOOT = 3609;
public static final int IMITATION_WHETSTONE = 3610;
public static final int PARASITIC_CLAW = 3624;
public static final int PARASITIC_TENTACLES = 3625;
public static final int PARASITIC_HEADGNAWER = 3626;
public static final int PARASITIC_STRANGLEWORM = 3627;
public static final int BURROWGRUB_HIVE = 3629;
public static final int JAMFISH_JAM = 3641;
public static final int DRAGONFISH_CAVIAR = 3642;
public static final int GRIMACITE_KNEECAPPING_STICK = 3644;
public static final int CANTEEN_OF_WINE = 3645;
public static final int MADNESS_REEF_MAP = 3649;
public static final int MINIATURE_ANTLERS = 3651;
public static final int SPOOKY_PUTTY_MITRE = 3662;
public static final int SPOOKY_PUTTY_LEOTARD = 3663;
public static final int SPOOKY_PUTTY_BALL = 3664;
public static final int SPOOKY_PUTTY_SHEET = 3665;
public static final int SPOOKY_PUTTY_SNAKE = 3666;
public static final int SPOOKY_PUTTY_MONSTER = 3667;
public static final int RAGE_GLAND = 3674;
public static final int MERKIN_PRESSUREGLOBE = 3675;
public static final int GLOWING_ESCA = 3680;
public static final int MARINARA_TRENCH_MAP = 3683;
public static final int TEMPURA_CARROT = 3684;
public static final int TEMPURA_CUCUMBER = 3685;
public static final int TEMPURA_AVOCADO = 3686;
public static final int TEMPURA_BROCCOLI = 3689;
public static final int TEMPURA_CAULIFLOWER = 3690;
public static final int POTION_OF_PERCEPTION = 3693;
public static final int POTION_OF_PROFICIENCY = 3694;
public static final int VELCRO_ORE = 3698;
public static final int TEFLON_ORE = 3699;
public static final int VINYL_ORE = 3700;
public static final int ANEMONE_MINE_MAP = 3701;
public static final int VINYL_BOOTS = 3716;
public static final int GNOLL_EYE = 3731;
public static final int BOOZEHOUND_TOKEN = 3739;
public static final int UNSTABLE_QUARK = 3743;
public static final int LOVE_BOOK = 3753;
public static final int VAGUE_AMBIGUITY = 3754;
public static final int SMOLDERING_PASSION = 3755;
public static final int ICY_REVENGE = 3756;
public static final int SUGARY_CUTENESS = 3757;
public static final int DISTURBING_OBSESSION = 3758;
public static final int NAUGHTY_INNUENDO = 3759;
public static final int DIVE_BAR_MAP = 3774;
public static final int MERKIN_PINKSLIP = 3775;
public static final int PARANORMAL_RICOTTA = 3784;
public static final int SMOKING_TALON = 3785;
public static final int VAMPIRE_GLITTER = 3786;
public static final int WINE_SOAKED_BONE_CHIPS = 3787;
public static final int CRUMBLING_RAT_SKULL = 3788;
public static final int TWITCHING_TRIGGER_FINGER = 3789;
public static final int AQUAVIOLET_JUBJUB_BIRD = 3800;
public static final int CRIMSILION_JUBJUB_BIRD = 3801;
public static final int CHARPUCE_JUBJUB_BIRD = 3802;
public static final int MERKIN_LOCKKEY = 3810;
public static final int MERKIN_STASHBOX = 3811;
public static final int SEA_RADISH = 3817;
public static final int EEL_SAUCE = 3819;
public static final int FISHY_WAND = 3822;
public static final int GRANDMAS_NOTE = 3824;
public static final int FUCHSIA_YARN = 3825;
public static final int CHARTREUSE_YARN = 3826;
public static final int GRANDMAS_MAP = 3828;
public static final int TEMPURA_RADISH = 3829;
public static final int TINY_COSTUME_WARDROBE = 3835;
public static final int ELVISH_SUNGLASSES = 3836;
public static final int OOT_BIWA = 3842;
public static final int JUNGLE_DRUM = 3846;
public static final int HIPPY_BONGO = 3847;
public static final int GUITAR_4D = 3849;
public static final int HALF_GUITAR = 3852;
public static final int BASS_DRUM = 3853;
public static final int SMALLEST_VIOLIN = 3855;
public static final int PLASTIC_GUITAR = 3863;
public static final int FINGER_CYMBALS = 3864;
public static final int KETTLE_DRUM = 3865;
public static final int HELLSEAL_HIDE = 3874;
public static final int HELLSEAL_BRAIN = 3876;
public static final int HELLSEAL_SINEW = 3878;
public static final int HELLSEAL_DISGUISE = 3880;
public static final int FOUET_DE_TORTUE_DRESSAGE = 3881;
public static final int CULT_MEMO = 3883;
public static final int DECODED_CULT_DOCUMENTS = 3884;
public static final int FIRST_SLIME_VIAL = 3885;
public static final int VIAL_OF_RED_SLIME = 3885;
public static final int VIAL_OF_YELLOW_SLIME = 3886;
public static final int VIAL_OF_BLUE_SLIME = 3887;
public static final int VIAL_OF_ORANGE_SLIME = 3888;
public static final int VIAL_OF_GREEN_SLIME = 3889;
public static final int VIAL_OF_VIOLET_SLIME = 3890;
public static final int VIAL_OF_VERMILION_SLIME = 3891;
public static final int VIAL_OF_AMBER_SLIME = 3892;
public static final int VIAL_OF_CHARTREUSE_SLIME = 3893;
public static final int VIAL_OF_TEAL_SLIME = 3894;
public static final int VIAL_OF_INDIGO_SLIME = 3895;
public static final int VIAL_OF_PURPLE_SLIME = 3896;
public static final int LAST_SLIME_VIAL = 3897;
public static final int VIAL_OF_BROWN_SLIME = 3897;
public static final int BOTTLE_OF_GU_GONE = 3898;
public static final int SEAL_BLUBBER_CANDLE = 3901;
public static final int WRETCHED_SEAL = 3902;
public static final int CUTE_BABY_SEAL = 3903;
public static final int ARMORED_SEAL = 3904;
public static final int ANCIENT_SEAL = 3905;
public static final int SLEEK_SEAL = 3906;
public static final int SHADOWY_SEAL = 3907;
public static final int STINKING_SEAL = 3908;
public static final int CHARRED_SEAL = 3909;
public static final int COLD_SEAL = 3910;
public static final int SLIPPERY_SEAL = 3911;
public static final int IMBUED_SEAL_BLUBBER_CANDLE = 3912;
public static final int TURTLE_WAX = 3914;
public static final int TURTLEMAIL_BITS = 3919;
public static final int TURTLING_ROD = 3927;
public static final int SEAL_IRON_INGOT = 3932;
public static final int HYPERINFLATED_SEAL_LUNG = 3935;
public static final int VIP_LOUNGE_KEY = 3947;
public static final int STUFFED_CHEST = 3949;
public static final int STUFFED_KEY = 3950;
public static final int STUFFED_BARON = 3951;
public static final int CLAN_POOL_TABLE = 3963;
public static final int TINY_CELL_PHONE = 3964;
public static final int DUELING_BANJO = 3984;
public static final int SAMURAI_TURTLE = 3986;
public static final int SLIME_SOAKED_HYPOPHYSIS = 3991;
public static final int SLIME_SOAKED_BRAIN = 3992;
public static final int SLIME_SOAKED_SWEAT_GLAND = 3993;
public static final int DOLPHIN_WHISTLE = 3997;
public static final int AGUA_DE_VIDA = 4001;
public static final int MOONTAN_LOTION = 4003;
public static final int BALLAST_TURTLE = 4005;
public static final int AMINO_ACIDS = 4006;
public static final int CA_BASE_PAIR = 4011;
public static final int CG_BASE_PAIR = 4012;
public static final int CT_BASE_PAIR = 4013;
public static final int AG_BASE_PAIR = 4014;
public static final int AT_BASE_PAIR = 4015;
public static final int GT_BASE_PAIR = 4016;
public static final int CONTACT_LENSES = 4019;
public static final int GRAPPLING_HOOK = 4029;
public static final int SMALL_STONE_BLOCK = 4030;
public static final int LITTLE_STONE_BLOCK = 4031;
public static final int HALF_STONE_CIRCLE = 4032;
public static final int STONE_HALF_CIRCLE = 4033;
public static final int IRON_KEY = 4034;
public static final int CULTIST_ROBE = 4040;
public static final int WUMPUS_HAIR = 4044;
public static final int RING_OF_TELEPORTATION = 4051;
public static final int INDIGO_PARTY_INVITATION = 4060;
public static final int VIOLET_HUNT_INVITATION = 4061;
public static final int BLUE_MILK_CLUB_CARD = 4062;
public static final int MECHA_MAYHEM_CLUB_CARD = 4063;
public static final int SMUGGLER_SHOT_FIRST_BUTTON = 4064;
public static final int SPACEFLEET_COMMUNICATOR_BADGE = 4065;
public static final int RUBY_ROD = 4066;
public static final int ESSENCE_OF_HEAT = 4067;
public static final int ESSENCE_OF_KINK = 4068;
public static final int ESSENCE_OF_COLD = 4069;
public static final int ESSENCE_OF_STENCH = 4070;
public static final int ESSENCE_OF_FRIGHT = 4071;
public static final int ESSENCE_OF_CUTE = 4072;
public static final int SUPREME_BEING_GLOSSARY = 4073;
public static final int GRISLY_SHIELD = 4080;
public static final int CYBER_MATTOCK = 4086;
public static final int GREEN_PEAWEE_MARBLE = 4095;
public static final int BROWN_CROCK_MARBLE = 4096;
public static final int RED_CHINA_MARBLE = 4097;
public static final int LEMONADE_MARBLE = 4098;
public static final int BUMBLEBEE_MARBLE = 4099;
public static final int JET_BENNIE_MARBLE = 4100;
public static final int BEIGE_CLAMBROTH_MARBLE = 4101;
public static final int STEELY_MARBLE = 4102;
public static final int BEACH_BALL_MARBLE = 4103;
public static final int BLACK_CATSEYE_MARBLE = 4104;
public static final int BIG_BUMBOOZER_MARBLE = 4105;
public static final int MONSTROUS_MONOCLE = 4108;
public static final int MUSTY_MOCCASINS = 4109;
public static final int MOLTEN_MEDALLION = 4110;
public static final int BRAZEN_BRACELET = 4111;
public static final int BITTER_BOWTIE = 4112;
public static final int BEWITCHING_BOOTS = 4113;
public static final int SECRET_FROM_THE_FUTURE = 4114;
public static final int EMPTY_AGUA_DE_VIDA_BOTTLE = 4130;
public static final int TEMPURA_AIR = 4133;
public static final int PRESSURIZED_PNEUMATICITY = 4134;
public static final int MOVEABLE_FEAST = 4135;
public static final int BAG_O_TRICKS = 4136;
public static final int SLIME_STACK = 4137;
public static final int RUMPLED_PAPER_STRIP = 4138;
public static final int CREASED_PAPER_STRIP = 4139;
public static final int FOLDED_PAPER_STRIP = 4140;
public static final int CRINKLED_PAPER_STRIP = 4141;
public static final int CRUMPLED_PAPER_STRIP = 4142;
public static final int RAGGED_PAPER_STRIP = 4143;
public static final int RIPPED_PAPER_STRIP = 4144;
public static final int QUADROCULARS = 4149;
public static final int CAMERA = 4169;
public static final int SHAKING_CAMERA = 4170;
public static final int SPAGHETTI_CULT_ROBE = 4175;
public static final int SUGAR_SHEET = 4176;
public static final int SUGAR_BOOK = 4177;
public static final int SUGAR_SHOTGUN = 4178;
public static final int SUGAR_SHILLELAGH = 4179;
public static final int SUGAR_SHANK = 4180;
public static final int SUGAR_CHAPEAU = 4181;
public static final int SUGAR_SHORTS = 4182;
public static final int SUGAR_SHIELD = 4183;
public static final int SUGAR_SHIRT = 4191;
public static final int SUGAR_SHARD = 4192;
public static final int RAVE_VISOR = 4193;
public static final int BAGGY_RAVE_PANTS = 4194;
public static final int PACIFIER_NECKLACE = 4195;
public static final int MERKIN_CHEATSHEET = 4204;
public static final int MERKIN_WORDQUIZ = 4205;
public static final int SKATE_PARK_MAP = 4222;
public static final int AMPHIBIOUS_TOPHAT = 4229;
public static final int HACIENDA_KEY = 4233;
public static final int SILVER_PATE_KNIFE = 4234;
public static final int SILVER_CHEESE_SLICER = 4237;
public static final int SLEEP_MASK = 4241;
public static final int FISHERMANS_SACK = 4250;
public static final int FISH_OIL_SMOKE_BOMB = 4251;
public static final int VIAL_OF_SQUID_INK = 4252;
public static final int POTION_OF_FISHY_SPEED = 4253;
public static final int WOLFMAN_MASK = 4260;
public static final int PUMPKINHEAD_MASK = 4261;
public static final int MUMMY_COSTUME = 4262;
public static final int KRAKROXS_LOINCLOTH = 4267;
public static final int GALAPAGOSIAN_CUISSES = 4268;
public static final int ANGELHAIR_CULOTTES = 4269;
public static final int NEWMANS_OWN_TROUSERS = 4270;
public static final int VOLARTTAS_BELLBOTTOMS = 4271;
public static final int LEDERHOSEN_OF_THE_NIGHT = 4272;
public static final int UNDERWORLD_ACORN = 4274;
public static final int CRAPPY_MASK = 4282;
public static final int GLADIATOR_MASK = 4284;
public static final int SCHOLAR_MASK = 4285;
public static final int MERKIN_DODGEBALL = 4292;
public static final int MERKIN_DRAGNET = 4293;
public static final int MERKIN_SWITCHBLADE = 4294;
public static final int CRYSTAL_ORB = 4295;
public static final int DEPLETED_URANIUM_SEAL = 4296;
public static final int VIOLENCE_STOMPERS = 4297;
public static final int VIOLENCE_BRAND = 4298;
public static final int VIOLENCE_LENS = 4300;
public static final int VIOLENCE_PANTS = 4302;
public static final int HATRED_STONE = 4303;
public static final int HATRED_GIRDLE = 4304;
public static final int HATRED_STAFF = 4305;
public static final int HATRED_PANTS = 4306;
public static final int HATRED_SLIPPERS = 4307;
public static final int HATRED_LENS = 4308;
public static final int SLEDGEHAMMER_OF_THE_VAELKYR = 4316;
public static final int FLAIL_OF_THE_SEVEN_ASPECTS = 4317;
public static final int WRATH_OF_THE_PASTALORDS = 4318;
public static final int WINDSOR_PAN_OF_THE_SOURCE = 4319;
public static final int SEEGERS_BANJO = 4320;
public static final int TRICKSTER_TRIKITIXA = 4321;
public static final int INFERNAL_SEAL_CLAW = 4322;
public static final int TURTLE_POACHER_GARTER = 4323;
public static final int SPAGHETTI_BANDOLIER = 4324;
public static final int SAUCEBLOB_BELT = 4325;
public static final int NEW_WAVE_BLING = 4326;
public static final int BELT_BUCKLE_OF_LOPEZ = 4327;
public static final int BAG_OF_MANY_CONFECTIONS = 4329;
public static final int FANCY_CHOCOLATE_CAR = 4334;
public static final int CRIMBUCK = 4343;
public static final int GINGERBREAD_HOUSE = 4347;
public static final int CRIMBOUGH = 4353;
public static final int CRIMBO_CAROL_V1 = 4354;
public static final int CRIMBO_CAROL_V2 = 4355;
public static final int CRIMBO_CAROL_V3 = 4356;
public static final int CRIMBO_CAROL_V4 = 4357;
public static final int CRIMBO_CAROL_V5 = 4358;
public static final int CRIMBO_CAROL_V6 = 4359;
public static final int ELF_RESISTANCE_BUTTON = 4363;
public static final int WRENCH_HANDLE = 4368;
public static final int HEADLESS_BOLTS = 4369;
public static final int AGITPROP_INK = 4370;
public static final int HANDFUL_OF_WIRES = 4371;
public static final int CHUNK_OF_CEMENT = 4372;
public static final int PENGUIN_GRAPPLING_HOOK = 4373;
public static final int CARDBOARD_ELF_EAR = 4374;
public static final int SPIRALING_SHAPE = 4375;
public static final int CRIMBOMINATION_CONTRAPTION = 4376;
public static final int RED_AND_GREEN_SWEATER = 4391;
public static final int CRIMBO_CANDY_COOKBOOK = 4392;
public static final int STINKY_CHEESE_BALL = 4398;
public static final int STINKY_CHEESE_SWORD = 4399;
public static final int STINKY_CHEESE_DIAPER = 4400;
public static final int STINKY_CHEESE_WHEEL = 4401;
public static final int STINKY_CHEESE_EYE = 4402;
public static final int STINKY_CHEESE_STAFF = 4403;
public static final int SLAPFIGHTING_BOOK = 4406;
public static final int UNCLE_ROMULUS = 4407;
public static final int SNAKE_CHARMING_BOOK = 4408;
public static final int ZU_MANNKASE_DIENEN = 4409;
public static final int DYNAMITE_SUPERMAN_JONES = 4410;
public static final int INIGO_BOOK = 4411;
public static final int QUANTUM_TACO = 4412;
public static final int SCHRODINGERS_THERMOS = 4413;
public static final int BLACK_HYMNAL = 4426;
public static final int GLOWSTICK_ON_A_STRING = 4428;
public static final int CANDY_NECKLACE = 4429;
public static final int TEDDYBEAR_BACKPACK = 4430;
public static final int STRANGE_CUBE = 4436;
public static final int INSTANT_KARMA = 4448;
public static final int MACHETITO = 4452;
public static final int LEAFBLOWER = 4455;
public static final int SNAILMAIL_BITS = 4457;
public static final int CHOCOLATE_SEAL_CLUBBING_CLUB = 4462;
public static final int CHOCOLATE_TURTLE_TOTEM = 4463;
public static final int CHOCOLATE_PASTA_SPOON = 4464;
public static final int CHOCOLATE_SAUCEPAN = 4465;
public static final int CHOCOLATE_DISCO_BALL = 4466;
public static final int CHOCOLATE_STOLEN_ACCORDION = 4467;
public static final int BRICKO_BOOK = 4468;
public static final int BRICKO_EYE = 4470;
public static final int BRICKO_HAT = 4471;
public static final int BRICKO_PANTS = 4472;
public static final int BRICKO_SWORD = 4473;
public static final int BRICKO_OOZE = 4474;
public static final int BRICKO_BAT = 4475;
public static final int BRICKO_OYSTER = 4476;
public static final int BRICKO_TURTLE = 4477;
public static final int BRICKO_ELEPHANT = 4478;
public static final int BRICKO_OCTOPUS = 4479;
public static final int BRICKO_PYTHON = 4480;
public static final int BRICKO_VACUUM_CLEANER = 4481;
public static final int BRICKO_AIRSHIP = 4482;
public static final int BRICKO_CATHEDRAL = 4483;
public static final int BRICKO_CHICKEN = 4484;
public static final int BRICKO_PYRAMID = 4485;
public static final int RECORDING_BALLAD = 4497;
public static final int RECORDING_BENETTON = 4498;
public static final int RECORDING_ELRON = 4499;
public static final int RECORDING_CHORALE = 4500;
public static final int RECORDING_PRELUDE = 4501;
public static final int RECORDING_DONHO = 4502;
public static final int RECORDING_INIGO = 4503;
public static final int CLAN_LOOKING_GLASS = 4507;
public static final int DRINK_ME_POTION = 4508;
public static final int REFLECTION_OF_MAP = 4509;
public static final int WALRUS_ICE_CREAM = 4510;
public static final int BEAUTIFUL_SOUP = 4511;
public static final int HUMPTY_DUMPLINGS = 4514;
public static final int LOBSTER_QUA_GRILL = 4515;
public static final int MISSING_WINE = 4516;
public static final int ITTAH_BITTAH_HOOKAH = 4519;
public static final int STUFFED_POCKETWATCH = 4545;
public static final int JACKING_MAP = 4560;
public static final int TINY_FLY_GLASSES = 4566;
public static final int LEGENDARY_BEAT = 4573;
public static final int BUGGED_BEANIE = 4575;
public static final int BUGGED_POTION = 4579;
public static final int BUGGED_BAIO = 4581;
public static final int PIXEL_WHIP = 4589;
public static final int PIXEL_CHAIN_WHIP = 4590;
public static final int PIXEL_MORNING_STAR = 4591;
public static final int PIXEL_ORB = 4592;
public static final int KEGGER_MAP = 4600;
public static final int ORQUETTES_PHONE_NUMBER = 4602;
public static final int BOTTLE_OF_GOLDENSCHNOCKERED = 4605;
public static final int ESSENTIAL_TOFU = 4609;
public static final int HATSEAT = 4614;
public static final int GG_TOKEN = 4621;
public static final int GG_TICKET = 4622;
public static final int COFFEE_PIXIE_STICK = 4625;
public static final int SPIDER_RING = 4629;
public static final int SINISTER_DEMON_MASK = 4637;
public static final int CHAMPION_BELT = 4638;
public static final int SPACE_TRIP_HEADPHONES = 4639;
public static final int KOL_CON_SIX_PACK = 4641;
public static final int JUJU_MOJO_MASK = 4644;
public static final int METEOID_ICE_BEAM = 4646;
public static final int DUNGEON_FIST_GAUNTLET = 4647;
public static final int IRONIC_MOUSTACHE = 4651;
public static final int BLACKBERRY_GALOSHES = 4659;
public static final int ELLSBURY_BOOK = 4663;
public static final int INSULT_PUPPET = 4667;
public static final int OBSERVATIONAL_GLASSES = 4668;
public static final int COMEDY_PROP = 4669;
public static final int BEER_SCENTED_TEDDY_BEAR = 4670;
public static final int BOOZE_SOAKED_CHERRY = 4671;
public static final int COMFY_PILLOW = 4672;
public static final int GIANT_MARSHMALLOW = 4673;
public static final int SPONGE_CAKE = 4674;
public static final int GIN_SOAKED_BLOTTER_PAPER = 4675;
public static final int TREE_HOLED_COIN = 4676;
public static final int UNEARTHED_METEOROID = 4677;
public static final int VOLCANIC_ASH = 4679;
public static final int FOSSILIZED_BAT_SKULL = 4687;
public static final int FOSSILIZED_SERPENT_SKULL = 4688;
public static final int FOSSILIZED_BABOON_SKULL = 4689;
public static final int FOSSILIZED_WYRM_SKULL = 4690;
public static final int FOSSILIZED_WING = 4691;
public static final int FOSSILIZED_LIMB = 4692;
public static final int FOSSILIZED_TORSO = 4693;
public static final int FOSSILIZED_SPINE = 4694;
public static final int GREAT_PANTS = 4696;
public static final int IMP_AIR = 4698;
public static final int BUS_PASS = 4699;
public static final int FOSSILIZED_SPIKE = 4700;
public static final int ARCHAEOLOGING_SHOVEL = 4702;
public static final int FOSSILIZED_DEMON_SKULL = 4704;
public static final int FOSSILIZED_SPIDER_SKULL = 4705;
public static final int SINISTER_ANCIENT_TABLET = 4706;
public static final int OVEN = 4707;
public static final int SHAKER = 4708;
public static final int OLD_SWEATPANTS = 4711;
public static final int MARIACHI_HAT = 4718;
public static final int HOLLANDAISE_HELMET = 4719;
public static final int MICROWAVE_STOGIE = 4721;
public static final int LIVER_PIE = 4722;
public static final int BADASS_PIE = 4723;
public static final int FISH_PIE = 4724;
public static final int PIPING_PIE = 4725;
public static final int IGLOO_PIE = 4726;
public static final int TURNOVER = 4727;
public static final int DEAD_PIE = 4728;
public static final int THROBBING_PIE = 4729;
public static final int BONE_CHIPS = 4743;
public static final int STABONIC_SCROLL = 4757;
public static final int PUMPKIN_SEEDS = 4760;
public static final int PUMPKIN = 4761;
public static final int HUGE_PUMPKIN = 4762;
public static final int PUMPKIN_BOMB = 4766;
public static final int PUMPKIN_CARRIAGE = 4769;
public static final int DESERT_BUS_PASS = 4770;
public static final int GINORMOUS_PUMPKIN = 4771;
public static final int ESSENCE_OF_ANNOYANCE = 4804;
public static final int HOLIDAY_FUN_BOOK = 4810;
public static final int ANTAGONISTIC_SNOWMAN_KIT = 4812;
public static final int SLEEPING_STOCKING = 4842;
public static final int KANSAS_TOYMAKER = 4843;
public static final int WASSAILING_BOOK = 4844;
public static final int UNCLE_HOBO_BEARD = 4846;
public static final int CHOCOLATE_CIGAR = 4851;
public static final int CRIMBCO_SCRIP = 4854;
public static final int BLANK_OUT_BOTTLE = 4857;
public static final int CRIMBCO_MANUAL_1 = 4859;
public static final int CRIMBCO_MANUAL_2 = 4860;
public static final int CRIMBCO_MANUAL_3 = 4861;
public static final int CRIMBCO_MANUAL_4 = 4862;
public static final int CRIMBCO_MANUAL_5 = 4863;
public static final int PHOTOCOPIER = 4864;
public static final int CLAN_FAX_MACHINE = 4865;
public static final int WORKYTIME_TEA = 4866;
public static final int GLOB_OF_BLANK_OUT = 4872;
public static final int PHOTOCOPIED_MONSTER = 4873;
public static final int GAUDY_KEY = 4874;
public static final int CRIMBCO_MUG = 4880;
public static final int CRIMBCO_WINE = 4881;
public static final int BGE_SHOTGLASS = 4893;
public static final int BGE_TATTOO = 4900;
public static final int COAL_PAPERWEIGHT = 4905;
public static final int JINGLE_BELL = 4906;
public static final int LOATHING_LEGION_KNIFE = 4908;
public static final int LOATHING_LEGION_MANY_PURPOSE_HOOK = 4909;
public static final int LOATHING_LEGION_MOONDIAL = 4910;
public static final int LOATHING_LEGION_NECKTIE = 4911;
public static final int LOATHING_LEGION_ELECTRIC_KNIFE = 4912;
public static final int LOATHING_LEGION_CORKSCREW = 4913;
public static final int LOATHING_LEGION_CAN_OPENER = 4914;
public static final int LOATHING_LEGION_CHAINSAW = 4915;
public static final int LOATHING_LEGION_ROLLERBLADES = 4916;
public static final int LOATHING_LEGION_FLAMETHROWER = 4917;
public static final int LOATHING_LEGION_TATTOO_NEEDLE = 4918;
public static final int LOATHING_LEGION_DEFIBRILLATOR = 4919;
public static final int LOATHING_LEGION_DOUBLE_PRISM = 4920;
public static final int LOATHING_LEGION_TAPE_MEASURE = 4921;
public static final int LOATHING_LEGION_KITCHEN_SINK = 4922;
public static final int LOATHING_LEGION_ABACUS = 4923;
public static final int LOATHING_LEGION_HELICOPTER = 4924;
public static final int LOATHING_LEGION_PIZZA_STONE = 4925;
public static final int LOATHING_LEGION_UNIVERSAL_SCREWDRIVER = 4926;
public static final int LOATHING_LEGION_JACKHAMMER = 4927;
public static final int LOATHING_LEGION_HAMMER = 4928;
public static final int QUAKE_OF_ARROWS = 4938;
public static final int KNOB_CAKE = 4942;
public static final int MENAGERIE_KEY = 4947;
public static final int GOTO = 4948;
public static final int WEREMOOSE_SPIT = 4949;
public static final int ABOMINABLE_BLUBBER = 4950;
public static final int SUBJECT_37_FILE = 4961;
public static final int EVILOMETER = 4964;
public static final int CARD_GAME_BOOK = 4965;
public static final int CARD_SLEEVE = 5009;
public static final int EVIL_EYE = 5010;
public static final int SNACK_VOUCHER = 5012;
public static final int WASABI_FOOD = 5013;
public static final int TOBIKO_FOOD = 5014;
public static final int NATTO_FOOD = 5015;
public static final int WASABI_BOOZE = 5016;
public static final int TOBIKO_BOOZE = 5017;
public static final int NATTO_BOOZE = 5018;
public static final int WASABI_POTION = 5019;
public static final int TOBIKO_POTION = 5020;
public static final int NATTO_POTION = 5021;
public static final int PET_SWEATER = 5040;
public static final int ASTRAL_HOT_DOG = 5043;
public static final int ASTRAL_PILSNER = 5044;
public static final int CLAN_SHOWER = 5047;
public static final int LARS_THE_CYBERIAN = 5053;
public static final int CREEPY_VOODOO_DOLL = 5062;
public static final int SPAGHETTI_CON_CALAVERAS = 5065;
public static final int SMORE_GUN = 5066;
public static final int TINY_BLACK_HOLE = 5069;
public static final int SMORE = 5071;
public static final int RUSSIAN_ICE = 5073;
public static final int STRESS_BALL = 5109;
public static final int PEN_PAL_KIT = 5112;
public static final int RUSTY_HEDGE_TRIMMERS = 5115;
public static final int AWOL_COMMENDATION = 5116;
public static final int RECONSTITUTED_CROW = 5117;
public static final int BIRD_BRAIN = 5118;
public static final int BUSTED_WINGS = 5119;
public static final int MARAUDER_MOCKERY_MANUAL = 5120;
public static final int SKELETON_BOOK = 5124;
public static final int LUNAR_ISOTOPE = 5134;
public static final int EMU_JOYSTICK = 5135;
public static final int EMU_ROCKET = 5136;
public static final int EMU_HELMET = 5137;
public static final int EMU_HARNESS = 5138;
public static final int ASTRAL_ENERGY_DRINK = 5140;
public static final int EMU_UNIT = 5143;
public static final int HONEYPOT = 5145;
public static final int SPOOKY_LITTLE_GIRL = 5165;
public static final int SYNTHETIC_DOG_HAIR_PILL = 5167;
public static final int DISTENTION_PILL = 5168;
public static final int TRANSPORTER_TRANSPONDER = 5170;
public static final int RONALD_SHELTER_MAP = 5171;
public static final int GRIMACE_SHELTER_MAP = 5172;
public static final int MOON_BOOZE_1 = 5174;
public static final int MOON_BOOZE_2 = 5175;
public static final int MOON_BOOZE_3 = 5176;
public static final int MOON_FOOD_1 = 5177;
public static final int MOON_FOOD_2 = 5178;
public static final int MOON_FOOD_3 = 5179;
public static final int MOON_POTION_1 = 5180;
public static final int MOON_POTION_2 = 5181;
public static final int MOON_POTION_3 = 5182;
public static final int DOUBLE_ICE_GUM = 5189;
public static final int PATRIOT_SHIELD = 5190;
public static final int BIG_KNOB_SAUSAGE = 5193;
public static final int EXORCISED_SANDWICH = 5194;
public static final int GOOEY_PASTE = 5198;
public static final int BEASTLY_PASTE = 5199;
public static final int OILY_PASTE = 5200;
public static final int ECTOPLASMIC = 5201;
public static final int GREASY_PASTE = 5202;
public static final int BUG_PASTE = 5203;
public static final int HIPPY_PASTE = 5204;
public static final int ORC_PASTE = 5205;
public static final int DEMONIC_PASTE = 5206;
public static final int INDESCRIBABLY_HORRIBLE_PASTE = 5207;
public static final int FISHY_PASTE = 5208;
public static final int GOBLIN_PASTE = 5209;
public static final int PIRATE_PASTE = 5210;
public static final int CHLOROPHYLL_PASTE = 5211;
public static final int STRANGE_PASTE = 5212;
public static final int MER_KIN_PASTE = 5213;
public static final int SLIMY_PASTE = 5214;
public static final int PENGUIN_PASTE = 5215;
public static final int ELEMENTAL_PASTE = 5216;
public static final int COSMIC_PASTE = 5217;
public static final int HOBO_PASTE = 5218;
public static final int CRIMBO_PASTE = 5219;
public static final int TEACHINGS_OF_THE_FIST = 5220;
public static final int FAT_LOOT_TOKEN = 5221;
public static final int CLIP_ART_BOOK = 5223;
public static final int BUCKET_OF_WINE = 5227;
public static final int CRYSTAL_SKULL = 5231;
public static final int BORROWED_TIME = 5232;
public static final int BOX_OF_HAMMERS = 5233;
public static final int LUMINEUX_LIMNIO = 5238;
public static final int MORTO_MORETO = 5239;
public static final int TEMPS_TEMPRANILLO = 5240;
public static final int BORDEAUX_MARTEAUX = 5241;
public static final int FROMAGE_PINOTAGE = 5242;
public static final int BEIGNET_MILGRANET = 5243;
public static final int MUSCHAT = 5244;
public static final int FIELD_GAR_POTION = 5257;
public static final int DICE_BOOK = 5284;
public static final int D4 = 5285;
public static final int D6 = 5286;
public static final int D8 = 5287;
public static final int D10 = 5288;
public static final int D12 = 5289;
public static final int D20 = 5290;
public static final int PLASTIC_VAMPIRE_FANGS = 5299;
public static final int STAFF_GUIDE = 5307;
public static final int CHAINSAW_CHAIN = 5309;
public static final int SILVER_SHOTGUN_SHELL = 5310;
public static final int FUNHOUSE_MIRROR = 5311;
public static final int GHOSTLY_BODY_PAINT = 5312;
public static final int NECROTIZING_BODY_SPRAY = 5313;
public static final int BITE_LIPSTICK = 5314;
public static final int WHISKER_PENCIL = 5315;
public static final int PRESS_ON_RIBS = 5316;
public static final int BB_WINE_COOLER = 5323;
public static final int NECBRONOMICON = 5341;
public static final int NECBRONOMICON_USED = 5343;
public static final int CRIMBO_CAROL_V1_USED = 5347;
public static final int CRIMBO_CAROL_V2_USED = 5348;
public static final int CRIMBO_CAROL_V3_USED = 5349;
public static final int CRIMBO_CAROL_V4_USED = 5350;
public static final int CRIMBO_CAROL_V5_USED = 5351;
public static final int CRIMBO_CAROL_V6_USED = 5352;
public static final int JAR_OF_OIL = 5353;
public static final int SLAPFIGHTING_BOOK_USED = 5354;
public static final int UNCLE_ROMULUS_USED = 5355;
public static final int SNAKE_CHARMING_BOOK_USED = 5356;
public static final int ZU_MANNKASE_DIENEN_USED = 5357;
public static final int DYNAMITE_SUPERMAN_JONES_USED = 5358;
public static final int INIGO_BOOK_USED = 5359;
public static final int KANSAS_TOYMAKER_USED = 5360;
public static final int WASSAILING_BOOK_USED = 5361;
public static final int CRIMBCO_MANUAL_1_USED = 5362;
public static final int CRIMBCO_MANUAL_2_USED = 5363;
public static final int CRIMBCO_MANUAL_3_USED = 5364;
public static final int CRIMBCO_MANUAL_4_USED = 5365;
public static final int CRIMBCO_MANUAL_5_USED = 5366;
public static final int SKELETON_BOOK_USED = 5367;
public static final int ELLSBURY_BOOK_USED = 5368;
public static final int GROOSE_GREASE = 5379;
public static final int LOLLIPOP_STICK = 5380;
public static final int PEPPERMINT_SPROUT = 5395;
public static final int PEPPERMINT_PARASOL = 5401;
public static final int GIANT_CANDY_CANE = 5402;
public static final int PEPPERMINT_PACKET = 5404;
public static final int FUDGECULE = 5435;
public static final int FUDGE_WAND = 5441;
public static final int DEVILISH_FOLIO = 5444;
public static final int FURIOUS_STONE = 5448;
public static final int VANITY_STONE = 5449;
public static final int LECHEROUS_STONE = 5450;
public static final int JEALOUSY_STONE = 5451;
public static final int AVARICE_STONE = 5452;
public static final int GLUTTONOUS_STONE = 5453;
public static final int FUDGIE_ROLL = 5457;
public static final int FUDGE_BUNNY = 5458;
public static final int FUDGE_SPORK = 5459;
public static final int FUDGECYCLE = 5460;
public static final int FUDGE_CUBE = 5461;
public static final int RESOLUTION_BOOK = 5463;
public static final int RESOLUTION_KINDER = 5470;
public static final int RESOLUTION_ADVENTUROUS = 5471;
public static final int RESOLUTION_LUCKIER = 5472;
public static final int RED_DRUNKI_BEAR = 5482;
public static final int GREEN_DRUNKI_BEAR = 5483;
public static final int YELLOW_DRUNKI_BEAR = 5484;
public static final int ALL_YEAR_SUCKER = 5497;
public static final int DARK_CHOCOLATE_HEART = 5498;
public static final int JACKASS_PLUMBER_GAME = 5501;
public static final int TRIVIAL_AVOCATIONS_GAME = 5502;
public static final int PACK_OF_POGS = 5505;
public static final int WHAT_CARD = 5511;
public static final int WHEN_CARD = 5512;
public static final int WHO_CARD = 5513;
public static final int WHERE_CARD = 5514;
public static final int PLANT_BOOK = 5546;
public static final int CLANCY_SACKBUT = 5547;
public static final int GHOST_BOOK = 5548;
public static final int CLANCY_CRUMHORN = 5549;
public static final int TATTLE_BOOK = 5550;
public static final int CLANCY_LUTE = 5551;
public static final int TRUSTY = 5552;
public static final int RAIN_DOH_BOX = 5563;
public static final int RAIN_DOH_MONSTER = 5564;
public static final int GROARS_FUR = 5571;
public static final int GLOWING_FUNGUS = 5641;
public static final int STONE_WOOL = 5643;
public static final int NOSTRIL_OF_THE_SERPENT = 5645;
public static final int BORIS_HELM = 5648;
public static final int BORIS_HELM_ASKEW = 5650;
public static final int MIME_SOUL_FRAGMENT = 5651;
public static final int KEYOTRON = 5653;
public static final int CLAN_SWIMMING_POOL = 5662;
public static final int CURSED_MICROWAVE = 5663;
public static final int CURSED_KEG = 5664;
public static final int JERK_BOOK = 5665;
public static final int GRUDGE_BOOK = 5666;
public static final int LOST_KEY = 5680;
public static final int NOTE_FROM_CLANCY = 5682;
public static final int BURT = 5683;
public static final int AUTOPSY_TWEEZERS = 5687;
public static final int ONE_MEAT = 5697;
public static final int LOST_GLASSES = 5698;
public static final int LITTLE_MANNEQUIN = 5702;
public static final int CRAYON_SHAVINGS = 5703;
public static final int WAX_BUGBEAR = 5704;
public static final int FDKOL_COMMENDATION = 5707;
public static final int HJODOR_GUIDE = 5715;
public static final int HJODOR_GUIDE_USED = 5716;
public static final int LORD_FLAMEFACES_CLOAK = 5735;
public static final int CSA_FIRE_STARTING_KIT = 5739;
public static final int CRAPPY_BRAIN = 5752;
public static final int DECENT_BRAIN = 5753;
public static final int GOOD_BRAIN = 5754;
public static final int BOSS_BRAIN = 5755;
public static final int HUNTER_BRAIN = 5756;
public static final int FUZZY_BUSBY = 5764;
public static final int FUZZY_EARMUFFS = 5765;
public static final int FUZZY_MONTERA = 5766;
public static final int GNOMISH_EAR = 5768;
public static final int GNOMISH_LUNG = 5769;
public static final int GNOMISH_ELBOW = 5770;
public static final int GNOMISH_KNEE = 5771;
public static final int GNOMISH_FOOT = 5772;
public static final int SOFT_GREEN_ECHO_ANTIDOTE_MARTINI = 5781;
public static final int MORNINGWOOD_PLANK = 5782;
public static final int HARDWOOD_PLANK = 5783;
public static final int WEIRDWOOD_PLANK = 5784;
public static final int THICK_CAULK = 5785;
public static final int LONG_SCREW = 5786;
public static final int BUTT_JOINT = 5787;
public static final int BUBBLIN_CRUDE = 5789;
public static final int BOX_OF_BEAR_ARM = 5790;
public static final int RIGHT_BEAR_ARM = 5791;
public static final int LEFT_BEAR_ARM = 5792;
public static final int RAD_LIB_BOOK = 5862;
public static final int PAPIER_MACHETE = 5868;
public static final int PAPIER_MACHINE_GUN = 5869;
public static final int PAPIER_MASK = 5870;
public static final int PAPIER_MITRE = 5871;
public static final int PAPIER_MACHURIDARS = 5872;
public static final int DRAGON_TEETH = 5880;
public static final int SKELETON = 5881;
public static final int SKIFF = 5885;
public static final int LAZYBONES_RECLINER = 5888;
public static final int UNCONSCIOUS_COLLECTIVE_DREAM_JAR = 5897;
public static final int SUSPICIOUS_JAR = 5898;
public static final int GOURD_JAR = 5899;
public static final int MYSTIC_JAR = 5900;
public static final int OLD_MAN_JAR = 5901;
public static final int ARTIST_JAR = 5902;
public static final int MEATSMITH_JAR = 5903;
public static final int JICK_JAR = 5905;
public static final int CHIBIBUDDY_ON = 5908;
public static final int NANORHINO_CREDIT_CARD = 5911;
public static final int BEET_MEDIOCREBAR = 5915;
public static final int CORN_MEDIOCREBAR = 5916;
public static final int CABBAGE_MEDIOCREBAR = 5917;
public static final int CHIBIBUDDY_OFF = 5925;
public static final int BITTYCAR_MEATCAR = 5926;
public static final int BITTYCAR_HOTCAR = 5927;
public static final int ELECTRONIC_DULCIMER_PANTS = 5963;
public static final int BOO_CLUE = 5964;
public static final int INFURIATING_SILENCE_RECORD = 5971;
public static final int INFURIATING_SILENCE_RECORD_USED = 5972;
public static final int TRANQUIL_SILENCE_RECORD = 5973;
public static final int TRANQUIL_SILENCE_RECORD_USED = 5974;
public static final int MENACING_SILENCE_RECORD = 5975;
public static final int MENACING_SILENCE_RECORD_USED = 5976;
public static final int SLICE_OF_PIZZA = 5978;
public static final int BOTTLE_OF_WINE = 5990;
public static final int BOSS_HELM = 6002;
public static final int BOSS_CLOAK = 6003;
public static final int BOSS_SWORD = 6004;
public static final int BOSS_SHIELD = 6005;
public static final int BOSS_PANTS = 6006;
public static final int BOSS_GAUNTLETS = 6007;
public static final int BOSS_BOOTS = 6008;
public static final int BOSS_BELT = 6009;
public static final int TRIPPLES = 6027;
public static final int DRESS_PANTS = 6030;
public static final int INCREDIBLE_PIZZA = 6038;
public static final int OIL_PAN = 6042;
public static final int BITTYCAR_SOULCAR = 6046;
public static final int MISTY_CLOAK = 6047;
public static final int MISTY_ROBE = 6048;
public static final int MISTY_CAPE = 6049;
public static final int TACO_FLIER = 6051;
public static final int PSYCHOANALYTIC_JAR = 6055;
public static final int CRIMBO_CREEPY_HEAD = 6058;
public static final int CRIMBO_STOGIE_ODORIZER = 6059;
public static final int CRIMBO_HOT_MUG = 6060;
public static final int CRIMBO_TREE_FLOCKER = 6061;
public static final int CRIMBO_RUDOLPH_DOLL = 6062;
public static final int GEEKY_BOOK = 6071;
public static final int LED_CLOCK = 6072;
public static final int HAGGIS_SOCKS = 6080;
public static final int CLASSY_MONKEY = 6097;
public static final int CEO_OFFICE_CARD = 6116;
public static final int STRANGE_GOGGLES = 6118;
public static final int BONSAI_TREE = 6120;
public static final int LUCKY_CAT_STATUE = 6122;
public static final int GOLD_PIECE = 6130;
public static final int JICK_SWORD = 6146;
public static final int SNOW_SUIT = 6150;
public static final int CARROT_NOSE = 6151;
public static final int CARROT_CLARET = 6153;
public static final int PIXEL_POWER_CELL = 6155;
public static final int ANGER_BLASTER = 6158;
public static final int DOUBT_CANNON = 6159;
public static final int FEAR_CONDENSER = 6160;
public static final int REGRET_HOSE = 6161;
public static final int GAMEPRO_MAGAZINE = 6174;
public static final int GAMEPRO_WALKTHRU = 6175;
public static final int COSMIC_EGG = 6176;
public static final int COSMIC_VEGETABLE = 6178;
public static final int COSMIC_POTATO = 6181;
public static final int COSMIC_CREAM = 6182;
public static final int MEDIOCRE_LAGER = 6215;
public static final int COSMIC_SIX_PACK = 6237;
public static final int WALBERG_BOOK = 6253;
public static final int OCELOT_BOOK = 6254;
public static final int DRESCHER_BOOK = 6255;
public static final int STAFF_OF_BREAKFAST = 6258;
public static final int STAFF_OF_LIFE = 6259;
public static final int STAFF_OF_CHEESE = 6261;
public static final int STAFF_OF_STEAK = 6263;
public static final int STAFF_OF_CREAM = 6265;
public static final int YE_OLDE_MEAD = 6276;
public static final int MARK_V_STEAM_HAT = 6289;
public static final int ROCKETSHIP = 6290;
public static final int DRUM_N_BASS_RECORD = 6295;
public static final int JARLSBERG_SOUL_FRAGMENT = 6297;
public static final int MODEL_AIRSHIP = 6299;
public static final int RING_OF_DETECT_BORING_DOORS = 6303;
public static final int JARLS_COSMIC_PAN = 6304;
public static final int JARLS_PAN = 6305;
public static final int UNCLE_BUCK = 6311;
public static final int FISH_MEAT_CRATE = 6312;
public static final int DAMP_WALLET = 6313;
public static final int FISHY_PIPE = 6314;
public static final int OLD_SCUBA_TANK = 6315;
public static final int SUSHI_DOILY = 6328;
public static final int COZY_SCIMITAR = 6332;
public static final int COZY_STAFF = 6333;
public static final int COZY_BAZOOKA = 6334;
public static final int SALTWATERBED = 6338;
public static final int DREADSCROLL = 6353;
public static final int MERKIN_WORKTEA = 6356;
public static final int MERKIN_KNUCKLEBONE = 6357;
public static final int TAFFY_BOOK = 6360;
public static final int YELLOW_TAFFY = 6361;
public static final int INDIGO_TAFFY = 6362;
public static final int GREEN_TAFFY = 6363;
public static final int MERKIN_HALLPASS = 6368;
public static final int LUMP_OF_CLAY = 6369;
public static final int TWISTED_PIECE_OF_WIRE = 6370;
public static final int FRUITY_WINE = 6372;
public static final int ANGRY_INCH = 6374;
public static final int ERASER_NUBBIN = 6378;
public static final int CHLORINE_CRYSTAL = 6379;
public static final int PH_BALANCER = 6380;
public static final int MYSTERIOUS_CHEMICAL_RESIDUE = 6381;
public static final int NUGGET_OF_SODIUM = 6382;
public static final int JIGSAW_BLADE = 6384;
public static final int WOOD_SCREW = 6385;
public static final int BALSA_PLANK = 6386;
public static final int BLOB_OF_WOOD_GLUE = 6387;
public static final int ENVYFISH_EGG = 6388;
public static final int ANEMONE_SAUCE = 6394;
public static final int INKY_SQUID_SAUCE = 6395;
public static final int MERKIN_WEAKSAUCE = 6396;
public static final int PEANUT_SAUCE = 6397;
public static final int BLACK_GLASS = 6398;
public static final int POCKET_SQUARE = 6407;
public static final int CORRUPTED_STARDUST = 6408;
public static final int SHAKING_SKULL = 6412;
public static final int TWIST_OF_LIME = 6417;
public static final int TONIC_DJINN = 6421;
public static final int TALES_OF_DREAD = 6423;
public static final int DREADSYLVANIAN_SKELETON_KEY = 6424;
public static final int BRASS_DREAD_FLASK = 6428;
public static final int SILVER_DREAD_FLASK = 6429;
public static final int KRUEGERAND = 6433;
public static final int MARK_OF_THE_BUGBEAR = 6434;
public static final int MARK_OF_THE_WEREWOLF = 6435;
public static final int MARK_OF_THE_ZOMBIE = 6436;
public static final int MARK_OF_THE_GHOST = 6437;
public static final int MARK_OF_THE_VAMPIRE = 6438;
public static final int MARK_OF_THE_SKELETON = 6439;
public static final int HELPS_YOU_SLEEP = 6443;
public static final int GREAT_WOLFS_LEFT_PAW = 6448;
public static final int GREAT_WOLFS_RIGHT_PAW = 6449;
public static final int GREAT_WOLFS_ROCKET_LAUNCHER = 6450;
public static final int HUNGER_SAUCE = 6453;
public static final int ZOMBIE_ACCORDION = 6455;
public static final int MAYOR_GHOSTS_GAVEL = 6465;
public static final int DRUNKULA_WINEGLASS = 6474;
public static final int BLOODWEISER = 6475;
public static final int ELECTRIC_KOOL_AID = 6483;
public static final int DREAD_TARRAGON = 6484;
public static final int BONE_FLOUR = 6485;
public static final int DREADFUL_ROAST = 6486;
public static final int STINKING_AGARICUS = 6487;
public static final int SHEPHERDS_PIE = 6488;
public static final int INTRICATE_MUSIC_BOX_PARTS = 6489;
public static final int WAX_BANANA = 6492;
public static final int WAX_LOCK_IMPRESSION = 6493;
public static final int REPLICA_KEY = 6494;
public static final int AUDITORS_BADGE = 6495;
public static final int BLOOD_KIWI = 6496;
public static final int EAU_DE_MORT = 6497;
public static final int BLOODY_KIWITINI = 6498;
public static final int MOON_AMBER = 6499;
public static final int MOON_AMBER_NECKLACE = 6501;
public static final int DREAD_POD = 6502;
public static final int GHOST_PENCIL = 6503;
public static final int DREADSYLVANIAN_CLOCKWORK_KEY = 6506;
public static final int COOL_IRON_INGOT = 6507;
public static final int GHOST_SHAWL = 6511;
public static final int SKULL_CAPACITOR = 6512;
public static final int WARM_FUR = 6513;
public static final int GHOST_THREAD = 6525;
public static final int HOTHAMMER = 6528;
public static final int MUDDY_SKIRT = 6531;
public static final int FRYING_BRAINPAN = 6538;
public static final int OLD_BALL_AND_CHAIN = 6539;
public static final int OLD_DRY_BONE = 6540;
public static final int WEEDY_SKIRT = 6545;
public static final int HOT_CLUSTER = 6551;
public static final int COLD_CLUSTER = 6552;
public static final int SPOOKY_CLUSTER = 6553;
public static final int STENCH_CLUSTER = 6554;
public static final int SLEAZE_CLUSTER = 6555;
public static final int PHIAL_OF_HOTNESS = 6556;
public static final int PHIAL_OF_COLDNESS = 6557;
public static final int PHIAL_OF_SPOOKINESS = 6558;
public static final int PHIAL_OF_STENCH = 6559;
public static final int PHIAL_OF_SLEAZINESS = 6560;
public static final int DREADSYLVANIAN_ALMANAC = 6579;
public static final int CLAN_HOT_DOG_STAND = 6582;
public static final int VICIOUS_SPIKED_COLLAR = 6583;
public static final int ANCIENT_HOT_DOG_WRAPPER = 6584;
public static final int DEBONAIR_DEBONER = 6585;
public static final int CHICLE_DE_SALCHICA = 6586;
public static final int JAR_OF_FROSTIGKRAUT = 6587;
public static final int GNAWED_UP_DOG_BONE = 6588;
public static final int GREY_GUANON = 6589;
public static final int ENGORGED_SAUSAGES_AND_YOU = 6590;
public static final int DREAM_OF_A_DOG = 6591;
public static final int OPTIMAL_SPREADSHEET = 6592;
public static final int DEFECTIVE_TOKEN = 6593;
public static final int HOT_DREADSYLVANIAN_COCOA = 6594;
public static final int CUCKOO_CLOCK = 6614;
public static final int SPAGHETTI_BREAKFAST = 6616;
public static final int FOLDER_HOLDER = 6617;
public static final int FOLDER_01 = 6618;
public static final int FOLDER_02 = 6619;
public static final int FOLDER_03 = 6620;
public static final int FOLDER_04 = 6621;
public static final int FOLDER_05 = 6622;
public static final int FOLDER_06 = 6623;
public static final int FOLDER_07 = 6624;
public static final int FOLDER_08 = 6625;
public static final int FOLDER_09 = 6626;
public static final int FOLDER_10 = 6627;
public static final int FOLDER_11 = 6628;
public static final int FOLDER_12 = 6629;
public static final int FOLDER_13 = 6630;
public static final int FOLDER_14 = 6631;
public static final int FOLDER_15 = 6632;
public static final int FOLDER_16 = 6633;
public static final int FOLDER_17 = 6634;
public static final int FOLDER_18 = 6635;
public static final int FOLDER_19 = 6636;
public static final int FOLDER_20 = 6637;
public static final int FOLDER_21 = 6638;
public static final int FOLDER_22 = 6639;
public static final int FOLDER_23 = 6640;
public static final int FOLDER_24 = 6641;
public static final int FOLDER_25 = 6642;
public static final int FOLDER_26 = 6643;
public static final int FOLDER_27 = 6644;
public static final int FOLDER_28 = 6645;
public static final int MOUNTAIN_STREAM_CODE_BLACK_ALERT = 6650;
public static final int SURGICAL_TAPE = 6653;
public static final int ILLEGAL_FIRECRACKER = 6656;
public static final int SCRAP_METAL = 6659;
public static final int SPIRIT_SOCKET_SET = 6660;
public static final int MINIATURE_SUSPENSION_BRIDGE = 6661;
public static final int STAFF_OF_THE_LUNCH_LADY = 6662;
public static final int UNIVERSAL_KEY = 6663;
public static final int WORLDS_MOST_DANGEROUS_BIRDHOUSE = 6664;
public static final int DEATHCHUCKS = 6665;
public static final int GIANT_ERASER = 6666;
public static final int QUASIRELGIOUS_SCULPTURE = 6667;
public static final int GIANT_FARADAY_CAGE = 6668;
public static final int MODELING_CLAYMORE = 6669;
public static final int STICKY_CLAY_HOMUNCULUS = 6670;
public static final int SODIUM_PENTASOMETHING = 6671;
public static final int GRAINS_OF_SALT = 6672;
public static final int YELLOWCAKE_BOMB = 6673;
public static final int DIRTY_STINKBOMB = 6674;
public static final int SUPERWATER = 6675;
public static final int CRUDE_SCULPTURE = 6677;
public static final int YEARBOOK_CAMERA = 6678;
public static final int ANTIQUE_MACHETE = 6679;
public static final int BOWL_OF_SCORPIONS = 6681;
public static final int BOOK_OF_MATCHES = 6683;
public static final int MCCLUSKY_FILE_PAGE5 = 6693;
public static final int BINDER_CLIP = 6694;
public static final int MCCLUSKY_FILE = 6695;
public static final int BOWLING_BALL = 6696;
public static final int MOSS_COVERED_STONE_SPHERE = 6697;
public static final int DRIPPING_STONE_SPHERE = 6698;
public static final int CRACKLING_STONE_SPHERE = 6699;
public static final int SCORCHED_STONE_SPHERE = 6700;
public static final int STONE_TRIANGLE = 6701;
public static final int BONE_ABACUS = 6712;
public static final int SHIP_TRIP_SCRIP = 6725;
public static final int UV_RESISTANT_COMPASS = 6729;
public static final int FUNKY_JUNK_KEY = 6730;
public static final int WORSE_HOMES_GARDENS = 6731;
public static final int JUNK_JUNK = 6735;
public static final int ETERNAL_CAR_BATTERY = 6741;
public static final int BEER_SEEDS = 6751;
public static final int BARLEY = 6752;
public static final int HOPS = 6753;
public static final int FANCY_BEER_BOTTLE = 6754;
public static final int FANCY_BEER_LABEL = 6755;
public static final int TIN_ROOF = 6773;
public static final int TIN_LIZZIE = 6775;
public static final int ABYSSAL_BATTLE_PLANS = 6782;
public static final int TOY_ACCORDION = 6808;
public static final int ANTIQUE_ACCORDION = 6809;
public static final int BEER_BATTERED_ACCORDION = 6810;
public static final int BARITONE_ACCORDION = 6811;
public static final int MAMAS_SQUEEZEBOX = 6812;
public static final int GUANCERTINA = 6813;
public static final int ACCORDION_FILE = 6814;
public static final int ACCORD_ION = 6815;
public static final int BONE_BANDONEON = 6816;
public static final int PENTATONIC_ACCORDION = 6817;
public static final int NON_EUCLIDEAN_NON_ACCORDION = 6818;
public static final int ACCORDION_OF_JORDION = 6819;
public static final int AUTOCALLIOPE = 6820;
public static final int ACCORDIONOID_ROCCA = 6821;
public static final int PYGMY_CONCERTINETTE = 6822;
public static final int GHOST_ACCORDION = 6823;
public static final int PEACE_ACCORDION = 6824;
public static final int ALARM_ACCORDION = 6825;
public static final int SWIZZLER = 6837;
public static final int WALKIE_TALKIE = 6846;
public static final int KILLING_JAR = 6847;
public static final int HUGE_BOWL_OF_CANDY = 6851;
public static final int ULTRA_MEGA_SOUR_BALL = 6852;
public static final int DESERT_PAMPHLET = 6854;
public static final int SUSPICIOUS_ADDRESS = 6855;
public static final int BAL_MUSETTE_ACCORDION = 6856;
public static final int CAJUN_ACCORDION = 6857;
public static final int QUIRKY_ACCORDION = 6858;
public static final int SKIPPERS_ACCORDION = 6859;
public static final int PANTSGIVING = 6860;
public static final int BLUE_LINT = 6877;
public static final int GREEN_LINT = 6878;
public static final int WHITE_LINT = 6879;
public static final int ORANGE_LINT = 6880;
public static final int SPIRIT_PILLOW = 6886;
public static final int SPIRIT_SHEET = 6887;
public static final int SPIRIT_MATTRESS = 6888;
public static final int SPIRIT_BLANKET = 6889;
public static final int SPIRIT_BED = 6890;
public static final int CHEF_BOY_BUSINESS_CARD = 6898;
public static final int PASTA_ADDITIVE = 6900;
public static final int WARBEAR_WHOSIT = 6913;
public static final int WARBEAR_BATTERY = 6916;
public static final int WARBEAR_BADGE = 6917;
public static final int WARBEAR_FEASTING_MEAD = 6924;
public static final int WARBEAR_BEARSERKER_MEAD = 6925;
public static final int WARBEAR_BLIZZARD_MEAD = 6926;
public static final int WARBEAR_OIL_PAN = 6961;
public static final int JACKHAMMER_DRILL_PRESS = 6964;
public static final int AUTO_ANVIL = 6965;
public static final int INDUCTION_OVEN = 6966;
public static final int CHEMISTRY_LAB = 6967;
public static final int WARBEAR_EMPATHY_CHIP = 6969;
public static final int SMITH_BOOK = 7003;
public static final int HANDFUL_OF_SMITHEREENS = 7006;
public static final int GOLDEN_LIGHT = 7013;
public static final int LOUDER_THAN_BOMB = 7014;
public static final int OUIJA_BOARD = 7025;
public static final int SAUCEPANIC = 7027;
public static final int SHAKESPEARES_SISTERS_ACCORDION = 7029;
public static final int WARBEAR_BLACK_BOX = 7035;
public static final int HIGH_EFFICIENCY_STILL = 7036;
public static final int LP_ROM_BURNER = 7037;
public static final int WARBEAR_GYROCOPTER = 7038;
public static final int WARBEAR_METALWORKING_PRIMER = 7042;
public static final int WARBEAR_GYROCOPTER_BROKEN = 7049;
public static final int WARBEAR_METALWORKING_PRIMER_USED = 7052;
public static final int WARBEAR_EMPATHY_CHIP_USED = 7053;
public static final int WARBEAR_BREAKFAST_MACHINE = 7056;
public static final int WARBEAR_SODA_MACHINE = 7059;
public static final int WARBEAR_BANK = 7060;
public static final int GRIMSTONE_MASK = 7061;
public static final int GRIM_FAIRY_TALE = 7065;
public static final int WINTER_SEEDS = 7070;
public static final int SNOW_BERRIES = 7071;
public static final int ICE_HARVEST = 7072;
public static final int FROST_FLOWER = 7073;
public static final int SNOW_BOARDS = 7076;
public static final int UNFINISHED_ICE_SCULPTURE = 7079;
public static final int ICE_SCULPTURE = 7080;
public static final int ICE_HOUSE = 7081;
public static final int SNOW_MACHINE = 7082;
public static final int SNOW_FORT = 7089;
public static final int JERKS_HEALTH_MAGAZINE = 7100;
public static final int MULLED_BERRY_WINE = 7119;
public static final int MAGNUM_OF_FANCY_CHAMPAGNE = 7130;
public static final int LUPINE_APPETITE_HORMONES = 7133;
public static final int WOLF_WHISTLE = 7134;
public static final int MID_LEVEL_MEDIEVAL_MEAD = 7138;
public static final int SPINNING_WHEEL = 7140;
public static final int ODD_SILVER_COIN = 7144;
public static final int EXPENSIVE_CHAMPAGNE = 7146;
public static final int FANCY_OIL_PAINTING = 7148;
public static final int SOLID_GOLD_ROSARY = 7149;
public static final int DOWSING_ROD = 7150;
public static final int STRAW = 7151;
public static final int LEATHER = 7152;
public static final int CLAY = 7153;
public static final int FILLING = 7154;
public static final int PARCHMENT = 7155;
public static final int GLASS = 7156;
public static final int CRAPPY_CAMERA = 7173;
public static final int SHAKING_CRAPPY_CAMERA = 7176;
public static final int COPPERHEAD_CHARM = 7178;
public static final int FIRST_PIZZA = 7179;
public static final int LACROSSE_STICK = 7180;
public static final int EYE_OF_THE_STARS = 7181;
public static final int STANKARA_STONE = 7182;
public static final int MURPHYS_FLAG = 7183;
public static final int SHIELD_OF_BROOK = 7184;
public static final int ZEPPELIN_TICKET = 7185;
public static final int COPPERHEAD_CHARM_RAMPANT = 7186;
public static final int UNNAMED_COCKTAIL = 7187;
public static final int TOMMY_GUN = 7190;
public static final int TOMMY_AMMO = 7191;
public static final int BUDDY_BJORN = 7200;
public static final int LYNYRD_SNARE = 7204;
public static final int FLEETWOOD_MAC_N_CHEESE = 7215;
public static final int PRICELESS_DIAMOND = 7221;
public static final int FLAMIN_WHATSHISNAME = 7222;
public static final int RED_RED_WINE = 7229;
public static final int RED_BUTTON = 7243;
public static final int GLARK_CABLE = 7246;
public static final int PETE_JACKET = 7250;
public static final int SNEAKY_PETE_SHOT = 7252;
public static final int MINI_MARTINI = 7255;
public static final int SMOKE_GRENADE = 7256;
public static final int PALINDROME_BOOK_1 = 7262;
public static final int PHOTOGRAPH_OF_DOG = 7263;
public static final int PHOTOGRAPH_OF_RED_NUGGET = 7264;
public static final int PHOTOGRAPH_OF_OSTRICH_EGG = 7265;
public static final int DISPOSABLE_CAMERA = 7266;
public static final int PETE_JACKET_COLLAR = 7267;
public static final int LETTER_FROM_MELVIGN = 7268;
public static final int PROFESSOR_WHAT_GARMENT = 7269;
public static final int PALINDROME_BOOK_2 = 7270;
public static final int THINKNERD_PACKAGE = 7278;
public static final int ELEVENT = 7295;
public static final int PROFESSOR_WHAT_TSHIRT = 7297;
public static final int SEWING_KIT = 7300;
public static final int BILLIARDS_KEY = 7301;
public static final int LIBRARY_KEY = 7302;
public static final int SPOOKYRAVEN_NECKLACE = 7303;
public static final int SPOOKYRAVEN_TELEGRAM = 7304;
public static final int POWDER_PUFF = 7305;
public static final int FINEST_GOWN = 7306;
public static final int DANCING_SHOES = 7307;
public static final int DUSTY_POPPET = 7314;
public static final int RICKETY_ROCKING_HORSE = 7315;
public static final int ANTIQUE_JACK_IN_THE_BOX = 7316;
public static final int BABY_GHOSTS = 7317;
public static final int GHOST_NECKLACE = 7318;
public static final int ELIZABETH_DOLLIE = 7319;
public static final int STEPHEN_LAB_COAT = 7321;
public static final int HAUNTED_BATTERY = 7324;
public static final int SYNTHETIC_MARROW = 7327;
public static final int FUNK = 7330;
public static final int CREEPY_VOICE_BOX = 7334;
public static final int TINY_DANCER = 7338;
public static final int SPOOKY_MUSIC_BOX_MECHANISM = 7339;
public static final int PICTURE_OF_YOU = 7350;
public static final int COAL_SHOVEL = 7355;
public static final int HOT_COAL = 7356;
public static final int LAUNDRY_SHERRY = 7366;
public static final int PSYCHOTIC_TRAIN_WINE = 7370;
public static final int DNA_LAB = 7382;
public static final int DNA_SYRINGE = 7383;
public static final int STEAM_FIST_1 = 7406;
public static final int STEAM_FIST_2 = 7407;
public static final int STEAM_FIST_3 = 7408;
public static final int STEAM_TRIP_1 = 7409;
public static final int STEAM_TRIP_2 = 7410;
public static final int STEAM_TRIP_3 = 7411;
public static final int STEAM_METEOID_1 = 7412;
public static final int STEAM_METEOID_2 = 7413;
public static final int STEAM_METEOID_3 = 7414;
public static final int STEAM_DEMON_1 = 7415;
public static final int STEAM_DEMON_2 = 7416;
public static final int STEAM_DEMON_3 = 7417;
public static final int STEAM_PLUMBER_1 = 7418;
public static final int STEAM_PLUMBER_2 = 7419;
public static final int STEAM_PLUMBER_3 = 7420;
public static final int PENCIL_THIN_MUSHROOM = 7421;
public static final int CHEESEBURGER_RECIPE = 7422;
public static final int SAILOR_SALT = 7423;
public static final int BROUPON = 7424;
public static final int TACO_DAN_SAUCE_BOTTLE = 7425;
public static final int SPRINKLE_SHAKER = 7426;
public static final int TACO_DAN_RECEIPT = 7428;
public static final int BEACH_BUCK = 7429;
public static final int OVERPOWERING_MUSHROOM_WINE = 7444;
public static final int COMPLEX_MUSHROOM_WINE = 7445;
public static final int SMOOTH_MUSHROOM_WINE = 7446;
public static final int BLOOD_RED_MUSHROOM_WINE = 7447;
public static final int BUZZING_MUSHROOM_WINE = 7448;
public static final int SWIRLING_MUSHROOM_WINE = 7449;
public static final int OFFENSIVE_JOKE_BOOK = 7458;
public static final int COOKING_WITH_GREASE_BOOK = 7459;
public static final int DINER_HANDBOOK = 7460;
public static final int SPRING_BEACH_TATTOO_COUPON = 7465;
public static final int SPRING_BEACH_CHARTER = 7466;
public static final int SPRING_BEACH_TICKET = 7467;
public static final int MOIST_BEADS = 7475;
public static final int MIND_DESTROYER = 7476;
public static final int SWEET_TOOTH = 7481;
public static final int LOOSENING_POWDER = 7485;
public static final int POWDERED_CASTOREUM = 7486;
public static final int DRAIN_DISSOLVER = 7487;
public static final int TRIPLE_DISTILLED_TURPENTINE = 7488;
public static final int DETARTRATED_ANHYDROUS_SUBLICALC = 7489;
public static final int TRIATOMACEOUS_DUST = 7490;
public static final int BOTTLE_OF_CHATEAU_DE_VINEGAR = 7491;
public static final int UNSTABLE_FULMINATE = 7493;
public static final int WINE_BOMB = 7494;
public static final int MORTAR_DISSOLVING_RECIPE = 7495;
public static final int GHOST_FORMULA = 7497;
public static final int BLACK_MAP = 7500;
public static final int BLACK_LABEL = 7508;
public static final int CRUMBLING_WHEEL = 7511;
public static final int ALIEN_SOURCE_CODE = 7533;
public static final int ALIEN_SOURCE_CODE_USED = 7534;
public static final int SPACE_BEAST_FUR = 7536;
public static final int SPACE_HEATER = 7543;
public static final int SPACE_PORT = 7545;
public static final int HOT_ASHES = 7548;
public static final int DRY_RUB = 7553;
public static final int WHITE_PAGE = 7555;
public static final int WHITE_WINE = 7558;
public static final int TIME_TWITCHING_TOOLBELT = 7566;
public static final int CHRONER = 7567;
public static final int CLAN_SPEAKEASY = 7588;
public static final int GLASS_OF_MILK = 7589;
public static final int CUP_OF_TEA = 7590;
public static final int THERMOS_OF_WHISKEY = 7591;
public static final int LUCKY_LINDY = 7592;
public static final int BEES_KNEES = 7593;
public static final int SOCKDOLLAGER = 7594;
public static final int ISH_KABIBBLE = 7595;
public static final int HOT_SOCKS = 7596;
public static final int PHONUS_BALONUS = 7597;
public static final int FLIVVER = 7598;
public static final int SLOPPY_JALOPY = 7599;
public static final int HEAVY_DUTY_UMBRELLA = 7643;
public static final int POOL_SKIMMER = 7644;
public static final int MINI_LIFE_PRESERVER = 7645;
public static final int LIGHTNING_MILK = 7646;
public static final int AQUA_BRAIN = 7647;
public static final int THUNDER_THIGH = 7648;
public static final int FRESHWATER_FISHBONE = 7651;
public static final int NEOPRENE_SKULLCAP = 7659;
public static final int GOBLIN_WATER = 7660;
public static final int LIQUID_ICE = 7665;
public static final int CAP_GUN = 7695;
public static final int CONFISCATOR_BOOK = 7706;
public static final int THORS_PLIERS = 7709;
public static final int WATER_WINGS_FOR_BABIES = 7711;
public static final int BEAUTIFUL_RAINBOW = 7712;
public static final int CHRONER_CROSS = 7723;
public static final int MERCURY_BLESSING = 7728;
public static final int CHRONER_TRIGGER = 7729;
public static final int BLACK_BARTS_BOOTY = 7732;
public static final int XIBLAXIAN_CIRCUITRY = 7733;
public static final int XIBLAXIAN_POLYMER = 7734;
public static final int XIBLAXIAN_ALLOY = 7735;
public static final int XIBLAXIAN_CRYSTAL = 7736;
public static final int XIBLAXIAN_HOLOTRAINING_SIMCODE = 7739;
public static final int XIBLAXIAN_POLITICAL_PRISONER = 7742;
public static final int XIBLAXIAN_SCHEMATIC_COWL = 7743;
public static final int XIBLAXIAN_SCHEMATIC_TROUSERS = 7744;
public static final int XIBLAXIAN_SCHEMATIC_VEST = 7745;
public static final int XIBLAXIAN_SCHEMATIC_BURRITO = 7746;
public static final int XIBLAXIAN_SCHEMATIC_WHISKEY = 7747;
public static final int XIBLAXIAN_SCHEMATIC_RESIDENCE = 7748;
public static final int XIBLAXIAN_SCHEMATIC_GOGGLES = 7749;
public static final int FIVE_D_PRINTER = 7750;
public static final int RESIDENCE_CUBE = 7758;
public static final int XIBLAXIAN_HOLOWRIST_PUTER = 7765;
public static final int CONSPIRACY_ISLAND_CHARTER = 7767;
public static final int CONSPIRACY_ISLAND_TICKET = 7768;
public static final int COINSPIRACY = 7769;
public static final int VENTILATION_UNIT = 7770;
public static final int CUDDLY_TEDDY_BEAR = 7787;
public static final int FIRST_AID_POUCH = 7789;
public static final int SHAWARMA_KEYCARD = 7792;
public static final int BOTTLE_OPENER_KEYCARD = 7793;
public static final int ARMORY_KEYCARD = 7794;
public static final int HYPERSANE_BOOK = 7803;
public static final int INTIMIDATING_MIEN_BOOK = 7804;
public static final int EXPERIMENTAL_SERUM_P00 = 7830;
public static final int FINGERNAIL_CLIPPERS = 7831;
public static final int MINI_CASSETTE_RECORDER = 7832;
public static final int GORE_BUCKET = 7833;
public static final int PACK_OF_SMOKES = 7834;
public static final int ESP_COLLAR = 7835;
public static final int GPS_WATCH = 7836;
public static final int PROJECT_TLB = 7837;
public static final int MINING_OIL = 7856;
public static final int CRIMBONIUM_FUEL_ROD = 7863;
public static final int CRIMBOT_TORSO_2 = 7865;
public static final int CRIMBOT_TORSO_3 = 7866;
public static final int CRIMBOT_TORSO_4 = 7867;
public static final int CRIMBOT_TORSO_5 = 7868;
public static final int CRIMBOT_TORSO_6 = 7869;
public static final int CRIMBOT_TORSO_7 = 7870;
public static final int CRIMBOT_TORSO_8 = 7871;
public static final int CRIMBOT_TORSO_9 = 7872;
public static final int CRIMBOT_TORSO_10 = 7873;
public static final int CRIMBOT_TORSO_11 = 7874;
public static final int CRIMBOT_LEFTARM_2 = 7875;
public static final int CRIMBOT_LEFTARM_3 = 7876;
public static final int CRIMBOT_LEFTARM_4 = 7877;
public static final int CRIMBOT_LEFTARM_5 = 7878;
public static final int CRIMBOT_LEFTARM_6 = 7879;
public static final int CRIMBOT_LEFTARM_7 = 7880;
public static final int CRIMBOT_LEFTARM_8 = 7881;
public static final int CRIMBOT_LEFTARM_9 = 7882;
public static final int CRIMBOT_LEFTARM_10 = 7883;
public static final int CRIMBOT_LEFTARM_11 = 7884;
public static final int CRIMBOT_RIGHTARM_2 = 7885;
public static final int CRIMBOT_RIGHTARM_3 = 7886;
public static final int CRIMBOT_RIGHTARM_4 = 7887;
public static final int CRIMBOT_RIGHTARM_5 = 7888;
public static final int CRIMBOT_RIGHTARM_6 = 7889;
public static final int CRIMBOT_RIGHTARM_7 = 7890;
public static final int CRIMBOT_RIGHTARM_8 = 7891;
public static final int CRIMBOT_RIGHTARM_9 = 7892;
public static final int CRIMBOT_RIGHTARM_10 = 7893;
public static final int CRIMBOT_RIGHTARM_11 = 7894;
public static final int CRIMBOT_PROPULSION_2 = 7895;
public static final int CRIMBOT_PROPULSION_3 = 7896;
public static final int CRIMBOT_PROPULSION_4 = 7897;
public static final int CRIMBOT_PROPULSION_5 = 7898;
public static final int CRIMBOT_PROPULSION_6 = 7899;
public static final int CRIMBOT_PROPULSION_7 = 7900;
public static final int CRIMBOT_PROPULSION_8 = 7901;
public static final int CRIMBOT_PROPULSION_9 = 7902;
public static final int CRIMBOT_PROPULSION_10 = 7903;
public static final int CRIMBOT_PROPULSION_11 = 7904;
public static final int FRIENDLY_TURKEY = 7922;
public static final int AGITATED_TURKEY = 7923;
public static final int AMBITIOUS_TURKEY = 7924;
public static final int SNEAKY_WRAPPING_PAPER = 7934;
public static final int PICKY_TWEEZERS = 7936;
public static final int CRIMBO_CREDIT = 7937;
public static final int SLEEVE_DEUCE = 7941;
public static final int POCKET_ACE = 7942;
public static final int MININ_DYNAMITE = 7950;
public static final int BIG_BAG_OF_MONEY = 7955;
public static final int ED_DIARY = 7960;
public static final int ED_STAFF = 7961;
public static final int ED_EYE = 7962;
public static final int ED_AMULET = 7963;
public static final int ED_FATS_STAFF = 7964;
public static final int ED_HOLY_MACGUFFIN = 7965;
public static final int KA_COIN = 7966;
public static final int TOPIARY_NUGGLET = 7968;
public static final int BEEHIVE = 7969;
public static final int ELECTRIC_BONING_KNIFE = 7970;
public static final int ANCIENT_CURE_ALL = 7982;
public static final int CHOCO_CRIMBOT = 7999;
public static final int TOY_CRIMBOT_FACE = 8002;
public static final int TOY_CRIMBOT_GLOVE = 8003;
public static final int TOY_CRIMBOT_FIST = 8004;
public static final int TOY_CRIMBOT_LEGS = 8005;
public static final int ROM_RAPID_PROTOTYPING = 8007;
public static final int ROM_MATHMATICAL_PRECISION = 8008;
public static final int ROM_RUTHLESS_EFFICIENCY = 8009;
public static final int ROM_RAPID_PROTOTYPING_DIRTY = 8013;
public static final int ROM_MATHMATICAL_PRECISION_DIRTY = 8014;
public static final int ROM_RUTHLESS_EFFICIENCY_DIRTY = 8015;
public static final int TAINTED_MINING_OIL = 8017;
public static final int RED_GREEN_RAIN_STICK = 8018;
public static final int CHATEAU_ROOM_KEY = 8019;
public static final int CHATEAU_MUSCLE = 8023;
public static final int CHATEAU_MYST = 8024;
public static final int CHATEAU_MOXIE = 8025;
public static final int CHATEAU_FAN = 8026;
public static final int CHATEAU_CHANDELIER = 8027;
public static final int CHATEAU_SKYLIGHT = 8028;
public static final int CHATEAU_BANK = 8029;
public static final int CHATEAU_JUICE_BAR = 8030;
public static final int CHATEAU_PENS = 8031;
public static final int CHATEAU_WATERCOLOR = 8033;
public static final int SPELUNKY_WHIP = 8040;
public static final int SPELUNKY_SKULL = 8041;
public static final int SPELUNKY_ROCK = 8042;
public static final int SPELUNKY_POT = 8043;
public static final int SPELUNKY_FEDORA = 8044;
public static final int SPELUNKY_MACHETE = 8045;
public static final int SPELUNKY_SHOTGUN = 8046;
public static final int SPELUNKY_BOOMERANG = 8047;
public static final int SPELUNKY_HELMET = 8049;
public static final int SPELUNKY_GOGGLES = 8050;
public static final int SPELUNKY_CAPE = 8051;
public static final int SPELUNKY_JETPACK = 8052;
public static final int SPELUNKY_SPRING_BOOTS = 8053;
public static final int SPELUNKY_SPIKED_BOOTS = 8054;
public static final int SPELUNKY_PICKAXE = 8055;
public static final int SPELUNKY_TORCH = 8056;
public static final int SPELUNKY_RIFLE = 8058;
public static final int SPELUNKY_STAFF = 8059;
public static final int SPELUNKY_JOKE_BOOK = 8060;
public static final int SPELUNKY_CROWN = 8061;
public static final int SPELUNKY_COFFEE_CUP = 8062;
public static final int TALES_OF_SPELUNKING = 8063;
public static final int POWDERED_GOLD = 8066;
public static final int WAREHOUSE_MAP_PAGE = 8070;
public static final int WAREHOUSE_INVENTORY_PAGE = 8071;
public static final int SPELUNKER_FORTUNE = 8073;
public static final int SPELUNKER_FORTUNE_USED = 8085;
public static final int STILL_BEATING_SPLEEN = 8086;
public static final int SCARAB_BEETLE_STATUETTE = 8087;
public static final int WICKERBITS = 8098;
public static final int BAKELITE_BITS = 8105;
public static final int AEROGEL_ACCORDION = 8111;
public static final int AEROSOLIZED_AEROGEL = 8112;
public static final int WROUGHT_IRON_FLAKES = 8119;
public static final int GABARDINE_GIRDLE = 8124;
public static final int GABARDEEN_SMITHEREENS = 8126;
public static final int FIBERGLASS_FIBERS = 8133;
public static final int LOVEBUG_PHEROMONES = 8134;
public static final int WINGED_YETI_FUR = 8135;
public static final int SESHAT_TALISMAN = 8144;
public static final int MEATSMITH_CHECK = 8156;
public static final int MAGICAL_BAGUETTE = 8167;
public static final int ENCHANTED_ICING = 8168;
public static final int CARTON_OF_SNAKE_MILK = 8172;
public static final int RING_OF_TELLING_SKELETONS_WHAT_TO_DO = 8179;
public static final int MAP_TO_KOKOMO = 8182;
public static final int CROWN_OF_ED = 8185;
public static final int BOOZE_MAP = 8187;
public static final int POPULAR_TART = 8200;
public static final int NO_HANDED_PIE = 8201;
public static final int DOC_VITALITY_SERUM = 8202;
public static final int DINSEY_CHARTER = 8203;
public static final int DINSEY_TICKET = 8204;
public static final int FUNFUNDS = 8205;
public static final int FILTHY_CHILD_LEASH = 8209;
public static final int GARBAGE_BAG = 8211;
public static final int SEWAGE_CLOGGED_PISTOL = 8215;
public static final int TOXIC_GLOBULE = 8218;
public static final int JAR_OF_SWAMP_HONEY = 8226;
public static final int BRAIN_PRESERVATION_FLUID = 8238;
public static final int DINSEY_REFRESHMENTS = 8243;
public static final int LUBE_SHOES = 8244;
public static final int TRASH_NET = 8245;
public static final int MASCOT_MASK = 8246;
public static final int DINSEY_GUIDE_BOOK = 8253;
public static final int TRASH_MEMOIR_BOOK = 8254;
public static final int DINSEY_MAINTENANCE_MANUAL = 8255;
public static final int DINSEY_AN_AFTERLIFE = 8258;
public static final int LOTS_ENGAGEMENT_RING = 8259;
public static final int MAYO_CLINIC = 8260;
public static final int MAYONEX = 8261;
public static final int MAYODIOL = 8262;
public static final int MAYOSTAT = 8263;
public static final int MAYOZAPINE = 8264;
public static final int MAYOFLEX = 8265;
public static final int MIRACLE_WHIP = 8266;
public static final int SPHYGMAYOMANOMETER = 8267;
public static final int REFLEX_HAMMER = 8268;
public static final int MAYO_LANCE = 8269;
public static final int ESSENCE_OF_BEAR = 8277;
public static final int RESORT_CHIP = 8279;
public static final int GOLDEN_RESORT_CHIP = 8280;
public static final int COCKTAIL_SHAKER = 8283;
public static final int MAYO_MINDER = 8285;
public static final int YELLOW_PIXEL = 8298;
public static final int POWER_PILL = 8300;
public static final int YELLOW_SUBMARINE = 8376;
public static final int DECK_OF_EVERY_CARD = 8382;
public static final int POPULAR_PART = 8383;
public static final int WHITE_MANA = 8387;
public static final int BLACK_MANA = 8388;
public static final int RED_MANA = 8389;
public static final int GREEN_MANA = 8390;
public static final int BLUE_MANA = 8391;
public static final int GIFT_CARD = 8392;
public static final int LINGUINI_IMMONDIZIA_BIANCO = 8419;
public static final int SHELLS_A_LA_SHELLFISH = 8420;
public static final int GOLD_1970 = 8424;
public static final int NEW_AGE_HEALING_CRYSTAL = 8425;
public static final int VOLCOINO = 8426;
public static final int FIZZING_SPORE_POD = 8427;
public static final int INSULATED_GOLD_WIRE = 8439;
public static final int EMPTY_LAVA_BOTTLE = 8440;
public static final int VISCOUS_LAVA_GLOBS = 8442;
public static final int HEAT_RESISTANT_SHEET_METAL = 8453;
public static final int GLOWING_NEW_AGE_CRYSTAL = 8455;
public static final int CRYSTALLINE_LIGHT_BULB = 8456;
public static final int GOOEY_LAVA_GLOBS = 8470;
public static final int LAVA_MINERS_DAUGHTER = 8482;
public static final int PSYCHO_FROM_THE_HEAT = 8483;
public static final int THE_FIREGATE_TAPES = 8484;
public static final int VOLCANO_TICKET = 8486;
public static final int VOLCANO_CHARTER = 8487;
public static final int MANUAL_OF_NUMBEROLOGY = 8488;
public static final int SMOOCH_BRACERS = 8517;
public static final int SUPERDUPERHEATED_METAL = 8522;
public static final int SUPERHEATED_METAL = 8524;
public static final int FETTRIS = 8542;
public static final int FUSILLOCYBIN = 8543;
public static final int PRESCRIPTION_NOODLES = 8544;
public static final int SHRINE_BARREL_GOD = 8564;
public static final int BARREL_LID = 8565;
public static final int BARREL_HOOP_EARRING = 8566;
public static final int BANKRUPTCY_BARREL = 8567;
public static final int LITTLE_FIRKIN = 8568;
public static final int NORMAL_BARREL = 8569;
public static final int BIG_TUN = 8570;
public static final int WEATHERED_BARREL = 8571;
public static final int DUSTY_BARREL = 8572;
public static final int DISINTEGRATING_BARREL = 8573;
public static final int MOIST_BARREL = 8574;
public static final int ROTTING_BARREL = 8575;
public static final int MOULDERING_BARREL = 8576;
public static final int BARNACLED_BARREL = 8577;
public static final int BARREL_MAP = 8599;
public static final int POTTED_TEA_TREE = 8600;
public static final int FLAMIBILI_TEA = 8601;
public static final int YET_TEA = 8602;
public static final int BOO_TEA = 8603;
public static final int NAS_TEA = 8604;
public static final int IMPROPRIE_TEA = 8605;
public static final int FROST_TEA = 8606;
public static final int TOAST_TEA = 8607;
public static final int NET_TEA = 8608;
public static final int PROPRIE_TEA = 8609;
public static final int MORBIDI_TEA = 8610;
public static final int CHARI_TEA = 8611;
public static final int SERENDIPI_TEA = 8612;
public static final int FEROCI_TEA = 8613;
public static final int PHYSICALI_TEA = 8614;
public static final int WIT_TEA = 8615;
public static final int NEUROPLASTICI_TEA = 8616;
public static final int DEXTERI_TEA = 8617;
public static final int FLEXIBILI_TEA = 8618;
public static final int IMPREGNABILI_TEA = 8619;
public static final int OBSCURI_TEA = 8620;
public static final int IRRITABILI_TEA = 8621;
public static final int MEDIOCRI_TEA = 8622;
public static final int LOYAL_TEA = 8623;
public static final int ACTIVI_TEA = 8624;
public static final int CRUEL_TEA = 8625;
public static final int ALACRI_TEA = 8626;
public static final int VITALI_TEA = 8627;
public static final int MANA_TEA = 8628;
public static final int MONSTROSI_TEA = 8629;
public static final int TWEN_TEA = 8630;
public static final int GILL_TEA = 8631;
public static final int UNCERTAIN_TEA = 8632;
public static final int VORACI_TEA = 8633;
public static final int SOBRIE_TEA = 8634;
public static final int ROYAL_TEA = 8635;
public static final int CRAFT_TEA = 8636;
public static final int INSANI_TEA = 8637;
public static final int HAUNTED_DOGHOUSE = 8639;
public static final int GHOST_DOG_CHOW = 8640;
public static final int TENNIS_BALL = 8650;
public static final int TWELVE_NIGHT_ENERGY = 8666;
public static final int ROSE = 8668;
public static final int WHITE_TULIP = 8669;
public static final int RED_TULIP = 8670;
public static final int BLUE_TULIP = 8671;
public static final int WALFORDS_BUCKET = 8672;
public static final int WALMART_GIFT_CERTIFICATE = 8673;
public static final int GLACIEST_CHARTER = 8674;
public static final int GLACIEST_TICKET = 8675;
public static final int TO_BUILD_AN_IGLOO = 8682;
public static final int CHILL_OF_THE_WILD = 8683;
public static final int COLD_FANG = 8684;
public static final int COLD_WEATHER_BARTENDER_GUIDE = 8687;
public static final int ICE_HOTEL_BELL = 8694;
public static final int ANCIENT_MEDICINAL_HERBS = 8696;
public static final int ICE_RICE = 8697;
public static final int ICED_PLUM_WINE = 8698;
public static final int TRAINING_BELT = 8699;
public static final int TRAINING_LEGWARMERS = 8700;
public static final int TRAINING_HELMET = 8701;
public static final int SCROLL_SHATTERING_PUNCH = 8702;
public static final int SCROLL_SNOKEBOMB = 8703;
public static final int SCROLL_SHIVERING_MONKEY = 8704;
public static final int SNOWMAN_CRATE = 8705;
public static final int ABSTRACTION_ACTION = 8708;
public static final int ABSTRACTION_THOUGHT = 8709;
public static final int ABSTRACTION_SENSATION = 8710;
public static final int ABSTRACTION_PURPOSE = 8711;
public static final int ABSTRACTION_CATEGORY = 8712;
public static final int ABSTRACTION_PERCEPTION = 8713;
public static final int VYKEA_FRENZY_RUNE = 8722;
public static final int VYKEA_BLOOD_RUNE = 8723;
public static final int VYKEA_LIGHTNING_RUNE = 8724;
public static final int VYKEA_PLANK = 8725;
public static final int VYKEA_RAIL = 8726;
public static final int VYKEA_BRACKET = 8727;
public static final int VYKEA_DOWEL = 8728;
public static final int VYKEA_HEX_KEY = 8729;
public static final int VYKEA_INSTRUCTIONS = 8730;
public static final int MACHINE_SNOWGLOBE = 8749;
public static final int BACON = 8763;
public static final int BUNDLE_OF_FRAGRANT_HERBS = 8777;
public static final int NUCLEAR_STOCKPILE = 8778;
public static final int CIRCLE_DRUM = 8784;
public static final int COMMUNISM_BOOK = 8785;
public static final int COMMUNISM_BOOK_USED = 8794;
public static final int BAT_OOMERANG = 8797;
public static final int BAT_JUTE = 8798;
public static final int BAT_O_MITE = 8799;
public static final int ROM_OF_OPTIMALITY = 8800;
public static final int INCRIMINATING_EVIDENCE = 8801;
public static final int DANGEROUS_CHEMICALS = 8802;
public static final int KIDNAPPED_ORPHAN = 8803;
public static final int HIGH_GRADE_METAL = 8804;
public static final int HIGH_TENSILE_STRENGTH_FIBERS = 8805;
public static final int HIGH_GRADE_EXPLOSIVES = 8806;
public static final int EXPERIMENTAL_GENE_THERAPY = 8807;
public static final int ULTRACOAGULATOR = 8808;
public static final int SELF_DEFENSE_TRAINING = 8809;
public static final int FINGERPRINT_DUSTING_KIT = 8810;
public static final int CONFIDENCE_BUILDING_HUG = 8811;
public static final int EXPLODING_KICKBALL = 8812;
public static final int GLOB_OF_BAT_GLUE = 8813;
public static final int BAT_AID_BANDAGE = 8814;
public static final int BAT_BEARING = 8815;
public static final int KUDZU_SALAD = 8816;
public static final int MANSQUITO_SERUM = 8817;
public static final int MISS_GRAVES_VERMOUTH = 8818;
public static final int PLUMBERS_MUSHROOM_STEW = 8819;
public static final int AUTHORS_INK = 8820;
public static final int MAD_LIQUOR = 8821;
public static final int DOC_CLOCKS_THYME_COCKTAIL = 8822;
public static final int MR_BURNSGER = 8823;
public static final int INQUISITORS_UNIDENTIFIABLE_OBJECT = 8824;
public static final int REPLICA_BAT_OOMERANG = 8829;
public static final int ROBIN_EGG = 8833;
public static final int TELEGRAPH_OFFICE_DEED = 8836;
public static final int PLAINTIVE_TELEGRAM = 8837;
public static final int COWBOY_BOOTS = 8850;
public static final int HEIMZ_BEANS = 8866;
public static final int TESLA_BEANS = 8867;
public static final int MIXED_BEANS = 8868;
public static final int HELLFIRE_BEANS = 8869;
public static final int FRIGID_BEANS = 8870;
public static final int BLACKEST_EYED_PEAS = 8871;
public static final int STINKBEANS = 8872;
public static final int PORK_N_BEANS = 8873;
public static final int PREMIUM_BEANS = 8875;
public static final int MUS_BEANS_PLATE = 8876;
public static final int MYS_BEANS_PLATE = 8877;
public static final int MOX_BEANS_PLATE = 8878;
public static final int HOT_BEANS_PLATE = 8879;
public static final int COLD_BEANS_PLATE = 8880;
public static final int SPOOKY_BEANS_PLATE = 8881;
public static final int STENCH_BEANS_PLATE = 8882;
public static final int SLEAZE_BEANS_PLATE = 8883;
public static final int PREMIUM_BEANS_PLATE = 8885;
public static final int GLENN_DICE = 8890;
public static final int CLARA_BELL = 8893;
public static final int BUFFALO_DIME = 8895;
public static final int WESTERN_BOOK_BRAGGADOCCIO = 8916;
public static final int WESTERN_BOOK_HELL = 8917;
public static final int WESTERN_BOOK_LOOK = 8918;
public static final int WESTERN_SLANG_VOL_1 = 8920;
public static final int WESTERN_SLANG_VOL_2 = 8921;
public static final int WESTERN_SLANG_VOL_3 = 8922;
public static final int STRANGE_DISC_WHITE = 8923;
public static final int STRANGE_DISC_BLACK = 8924;
public static final int STRANGE_DISC_RED = 8925;
public static final int STRANGE_DISC_GREEN = 8926;
public static final int STRANGE_DISC_BLUE = 8927;
public static final int STRANGE_DISC_YELLOW = 8928;
public static final int MOUNTAIN_SKIN = 8937;
public static final int GRIZZLED_SKIN = 8938;
public static final int DIAMONDBACK_SKIN = 8939;
public static final int COAL_SKIN = 8940;
public static final int FRONTWINDER_SKIN = 8941;
public static final int ROTTING_SKIN = 8942;
public static final int QUICKSILVER_SPURS = 8947;
public static final int THICKSILVER_SPURS = 8948;
public static final int WICKSILVER_SPURS = 8949;
public static final int SLICKSILVER_SPURS = 8950;
public static final int SICKSILVER_SPURS = 8951;
public static final int NICKSILVER_SPURS = 8952;
public static final int TICKSILVER_SPURS = 8953;
public static final int COW_PUNCHING_TALES = 8955;
public static final int BEAN_SLINGING_TALES = 8956;
public static final int SNAKE_OILING_TALES = 8957;
public static final int SNAKE_OIL = 8971;
public static final int MEMORIES_OF_COW_PUNCHING = 8986;
public static final int MEMORIES_OF_BEAN_SLINGING = 8987;
public static final int MEMORIES_OF_SNAKE_OILING = 8988;
public static final int WITCHESS_SET = 8989;
public static final int BRAIN_TRAINER_GAME = 8990;
public static final int LASER_EYE_SURGERY_KIT = 8991;
public static final int SACRAMENTO_WINE = 8994;
public static final int CLAN_FLOUNDRY = 9000;
public static final int CARPE = 9001;
public static final int CODPIECE = 9002;
public static final int TROUTSERS = 9003;
public static final int BASS_CLARINET = 9004;
public static final int FISH_HATCHET = 9005;
public static final int TUNAC = 9006;
public static final int FISHING_POLE = 9007;
public static final int WRIGGLING_WORM = 9008;
public static final int FISHING_LINE = 9010;
public static final int FISHING_HAT = 9011;
public static final int TROUT_FISHING_IN_LOATHING = 9012;
public static final int ANTIQUE_TACKLE_BOX = 9015;
public static final int VIRAL_VIDEO = 9017;
public static final int MEME_GENERATOR = 9019;
public static final int PLUS_ONE = 9020;
public static final int GALLON_OF_MILK = 9021;
public static final int PRINT_SCREEN = 9022;
public static final int SCREENCAPPED_MONSTER = 9023;
public static final int DAILY_DUNGEON_MALWARE = 9024;
public static final int BACON_MACHINE = 9025;
public static final int NO_SPOON = 9029;
public static final int SOURCE_TERMINAL = 9033;
public static final int SOURCE_ESSENCE = 9034;
public static final int BROWSER_COOKIE = 9035;
public static final int HACKED_GIBSON = 9036;
public static final int SOURCE_SHADES = 9037;
public static final int SOFTWARE_BUG = 9038;
public static final int SOURCE_TERMINAL_PRAM_CHIP = 9040;
public static final int SOURCE_TERMINAL_GRAM_CHIP = 9041;
public static final int SOURCE_TERMINAL_SPAM_CHIP = 9042;
public static final int SOURCE_TERMINAL_CRAM_CHIP = 9043;
public static final int SOURCE_TERMINAL_DRAM_CHIP = 9044;
public static final int SOURCE_TERMINAL_TRAM_CHIP = 9045;
public static final int SOURCE_TERMINAL_INGRAM_CHIP = 9046;
public static final int SOURCE_TERMINAL_DIAGRAM_CHIP = 9047;
public static final int SOURCE_TERMINAL_ASHRAM_CHIP = 9048;
public static final int SOURCE_TERMINAL_SCRAM_CHIP = 9049;
public static final int SOURCE_TERMINAL_TRIGRAM_CHIP = 9050;
public static final int SOURCE_TERMINAL_SUBSTATS_ENH = 9051;
public static final int SOURCE_TERMINAL_DAMAGE_ENH = 9052;
public static final int SOURCE_TERMINAL_CRITICAL_ENH = 9053;
public static final int SOURCE_TERMINAL_PROTECT_ENQ = 9054;
public static final int SOURCE_TERMINAL_STATS_ENQ = 9055;
public static final int SOURCE_TERMINAL_COMPRESS_EDU = 9056;
public static final int SOURCE_TERMINAL_DUPLICATE_EDU = 9057;
public static final int SOURCE_TERMINAL_PORTSCAN_EDU = 9058;
public static final int SOURCE_TERMINAL_TURBO_EDU = 9059;
public static final int SOURCE_TERMINAL_FAMILIAR_EXT = 9060;
public static final int SOURCE_TERMINAL_PRAM_EXT = 9061;
public static final int SOURCE_TERMINAL_GRAM_EXT = 9062;
public static final int SOURCE_TERMINAL_SPAM_EXT = 9063;
public static final int SOURCE_TERMINAL_CRAM_EXT = 9064;
public static final int SOURCE_TERMINAL_DRAM_EXT = 9065;
public static final int SOURCE_TERMINAL_TRAM_EXT = 9066;
public static final int COP_DOLLAR = 9072;
public static final int DETECTIVE_APPLICATION = 9073;
public static final int PROTON_ACCELERATOR = 9082;
public static final int STANDARDS_AND_PRACTICES = 9095;
public static final int RAD = 9100;
public static final int WRIST_BOY = 9102;
public static final int TIME_SPINNER = 9104;
public static final int HOLORECORD_SHRIEKING_WEASEL = 9109;
public static final int HOLORECORD_POWERGUY = 9110;
public static final int HOLORECORD_LUCKY_STRIKES = 9111;
public static final int HOLORECORD_EMD = 9112;
public static final int HOLORECORD_SUPERDRIFTER = 9113;
public static final int HOLORECORD_PIGS = 9114;
public static final int HOLORECORD_DRUNK_UNCLES = 9115;
public static final int TIME_RESIDUE = 9116;
public static final int EARL_GREY = 9122;
public static final int SCHOOL_OF_HARD_KNOCKS_DIPLOMA = 9123;
public static final int KOL_COL_13_SNOWGLOBE = 9133;
public static final int TRICK_TOT_KNIGHT = 9137;
public static final int TRICK_TOT_UNICORN = 9138;
public static final int TRICK_TOT_CANDY = 9139;
public static final int TRICK_TOT_ROBOT = 9143;
public static final int TRICK_TOT_EYEBALL = 9144;
public static final int TRICK_TOT_LIBERTY = 9145;
public static final int HOARDED_CANDY_WAD = 9146;
public static final int STUFFING_FLUFFER = 9164;
public static final int TURKEY_BLASTER = 9166;
public static final int CANDIED_SWEET_POTATOES = 9171;
public static final int BREAD_ROLL = 9179;
public static final int CORNUCOPIA = 9183;
public static final int MEGACOPIA = 9184;
public static final int GIANT_PILGRIM_HAT = 9185;
public static final int THANKSGARDEN_SEEDS = 9186;
public static final int CASHEW = 9187;
public static final int BOMB_OF_UNKNOWN_ORIGIN = 9188;
public static final int GINGERBREAD_CITY = 9203;
public static final int COUNTERFEIT_CITY = 9204;
public static final int SPRINKLES = 9205;
public static final int VIGILANTE_BOOK = 9206;
public static final int BROKEN_CHOCOLATE_POCKETWATCH = 9215;
public static final int GINGERBREAD_RESTRAINING_ORDER = 9217;
public static final int GINGERBREAD_WINE = 9220;
public static final int GINGERBREAD_MUG = 9221;
public static final int GINGERSERVO = 9223;
public static final int GINGERBEARD = 9225;
public static final int CREME_BRULEE_TORCH = 9230;
public static final int GINGERBREAD_DOG_TREAT = 9233;
public static final int GINGERBREAD_CIGARETTE = 9237;
public static final int SPARE_CHOCOLATE_PARTS = 9240;
public static final int HIGH_END_GINGER_WINE = 9243;
public static final int MY_LIFE_OF_CRIME_BOOK = 9258;
public static final int POP_ART_BOOK = 9259;
public static final int NO_HATS_BOOK = 9260;
public static final int RETHINKING_CANDY_BOOK = 9261;
public static final int FRUIT_LEATHER_NEGATIVE = 9262;
public static final int GINGERBREAD_BLACKMAIL_PHOTOS = 9263;
public static final int TEETHPICK = 9265;
public static final int CHOCOLATE_SCULPTURE = 9269;
public static final int NO_HAT = 9270;
public static final int NEGATIVE_LUMP = 9272;
public static final int LUMP_STACKING_BOOK = 9285;
public static final int HOT_JELLY = 9291;
public static final int COLD_JELLY = 9292;
public static final int SPOOKY_JELLY = 9293;
public static final int SLEAZE_JELLY = 9294;
public static final int STENCH_JELLY = 9295;
public static final int WAX_HAND = 9305;
public static final int MINIATURE_CANDLE = 9306;
public static final int WAX_PANCAKE = 9307;
public static final int WAX_FACE = 9308;
public static final int WAX_BOOZE = 9309;
public static final int WAX_GLOB = 9310;
public static final int HEART_SHAPED_CRATE = 9316;
public static final int LOVE_BOOMERANG = 9323;
public static final int LOVE_CHOCOLATE = 9325;
public static final int ELDRITCH_ICHOR = 9333;
public static final int ELDRITCH_TINCTURE = 9335;
public static final int ELDRITCH_TINCTURE_DEPLETED = 9336;
public static final int CLOD_OF_DIRT = 9216;
public static final int DIRTY_BOTTLECAP = 9343;
public static final int DISCARDED_BUTTON = 9344;
public static final int GUMMY_MEMORY = 9345;
public static final int NOVELTY_HOT_SAUCE = 9349;
public static final int COCKTAIL_MUSHROOM = 9353;
public static final int GRANOLA_LIQUEUR = 9354;
public static final int GREGNADIGNE = 9357;
public static final int FISH_HEAD = 9360;
public static final int BABY_OIL_SHOOTER = 9359;
public static final int LIMEPATCH = 9361;
public static final int LITERAL_GRASSHOPPER = 9365;
public static final int PISCATINI = 9378;
public static final int DRIVE_BY_SHOOTING = 9396;
public static final int PHIL_COLLINS = 9400;
public static final int TOGGLE_SWITCH_BARTEND = 9402;
public static final int TOGGLE_SWITCH_BOUNCE = 9403;
public static final int SPACEGATE_ACCESS_BADGE = 9404;
public static final int SPACEGATE_RESEARCH = 9410;
public static final int ALIEN_ROCK_SAMPLE = 9411;
public static final int ALIEN_GEMSTONE = 9412;
public static final int ALIEN_PLANT_FIBERS = 9416;
public static final int ALIEN_PLANT_SAMPLE = 9417;
public static final int COMPLEX_ALIEN_PLANT_SAMPLE = 9418;
public static final int FASCINATING_ALIEN_PLANT_SAMPLE = 9419;
public static final int ALIEN_PLANT_POD = 9421;
public static final int ALIEN_TOENAILS = 9424;
public static final int ALIEN_ZOOLOGICAL_SAMPLE = 9425;
public static final int COMPLEX_ALIEN_ZOOLOGICAL_SAMPLE = 9426;
public static final int FASCINATING_ALIEN_ZOOLOGICAL_SAMPLE = 9427;
public static final int ALIEN_ANIMAL_MILK = 9429;
public static final int SPANT_EGG_CASING = 9430;
public static final int MURDERBOT_DATA_CORE = 9431;
public static final int SPANT_CHITIN = 9441;
public static final int PRIMITIVE_ALIEN_TOTEM = 9439;
public static final int SPANT_TENDON = 9442;
public static final int MURDERBOT_MEMORY_CHIP = 9457;
public static final int SPACE_PIRATE_TREASURE_MAP = 9458;
public static final int SPACE_PIRATE_ASTROGATION_HANDBOOK = 9459;
public static final int NON_EUCLIDEAN_FINANCE = 9460;
public static final int PEEK_A_BOO = 9461;
public static final int PROCRASTINATOR_LOCKER_KEY = 9462;
public static final int SPACE_BABY_CHILDRENS_BOOK = 9463;
public static final int SPACE_BABY_BAWBAW = 9464;
public static final int PORTABLE_SPACEGATE = 9465;
public static final int NEW_YOU_CLUB_MEMBERSHIP_FORM = 9478;
public static final int AFFIRMATION_SUPERFICIALLY_INTERESTED = 9481;
public static final int AFFIRMATION_MIND_MASTER = 9483;
public static final int AFFIRMATION_HATE = 9485;
public static final int AFFIRMATION_COOKIE = 9486;
public static final int LICENSE_TO_KILL = 9487;
public static final int VICTOR_SPOILS = 9493;
public static final int KREMLIN_BRIEFCASE = 9493;
public static final int LICENSE_TO_CHILL = 9503;
public static final int CELSIUS_233 = 9504;
public static final int CELSIUS_233_SINGED = 9505;
public static final int LAZENBY = 9506;
public static final int ASDON_MARTIN = 9508;
public static final int METEORITE_ADE = 9513;
public static final int METAL_METEOROID = 9516;
public static final int METEORTARBOARD = 9517;
public static final int METEORITE_GUARD = 9518;
public static final int METEORB = 9519;
public static final int ASTEROID_BELT = 9520;
public static final int METEORTHOPEDIC_SHOES = 9521;
public static final int SHOOTING_MORNING_STAR = 9522;
public static final int PERFECTLY_FAIR_COIN = 9526;
public static final int CORKED_GENIE_BOTTLE = 9528;
public static final int GENIE_BOTTLE = 9529;
public static final int POCKET_WISH = 9537;
public static final int SHOVELFUL_OF_EARTH = 9539;
public static final int HUNK_OF_GRANITE = 9540;
public static final int X = 9543;
public static final int O = 9544;
public static final int MAFIA_PINKY_RING = 9546;
public static final int FLASK_OF_PORT = 9547;
public static final int BRIDGE_TRUSS = 9556;
public static final int AMORPHOUS_BLOB = 9558;
public static final int GIANT_AMORPHOUS_BLOB = 9561;
public static final int MAFIA_THUMB_RING = 9564;
public static final int PORTABLE_PANTOGRAM = 9573;
public static final int PANTOGRAM_PANTS = 9574;
public static final int MUMMING_TRUNK = 9592;
public static final int EARTHENWARE_MUFFIN_TIN = 9596;
public static final int BRAN_MUFFIN = 9597;
public static final int BLUEBERRY_MUFFIN = 9598;
public static final int CRYSTALLINE_CHEER = 9625;
public static final int WAREHOUSE_KEY = 9627;
public static final int MIME_SCIENCE_VOL_1 = 9635;
public static final int MIME_SCIENCE_VOL_1_USED = 9636;
public static final int MIME_SCIENCE_VOL_2 = 9637;
public static final int MIME_SCIENCE_VOL_2_USED = 9638;
public static final int MIME_SCIENCE_VOL_3 = 9639;
public static final int MIME_SCIENCE_VOL_3_USED = 9640;
public static final int MIME_SCIENCE_VOL_4 = 9641;
public static final int MIME_SCIENCE_VOL_4_USED = 9642;
public static final int MIME_SCIENCE_VOL_5 = 9643;
public static final int MIME_SCIENCE_VOL_5_USED = 9644;
public static final int MIME_SCIENCE_VOL_6 = 9645;
public static final int MIME_SCIENCE_VOL_6_USED = 9646;
public static final int GOD_LOBSTER = 9661;
public static final int DONATED_BOOZE = 9662;
public static final int DONATED_FOOD = 9663;
public static final int DONATED_CANDY = 9664;
public static final int MIME_ARMY_INFILTRATION_GLOVE = 9675;
public static final int MIME_SHOTGLASS = 9676;
public static final int TOASTED_HALF_SANDWICH = 9681;
public static final int MULLED_HOBO_WINE = 9682;
public static final int BURNING_NEWSPAPER = 9683;
public static final int BURNING_HAT = 9684;
public static final int BURNING_CAPE = 9685;
public static final int BURNING_SLIPPERS = 9686;
public static final int BURNING_JORTS = 9687;
public static final int BURNING_CRANE = 9688;
public static final int GARBAGE_TOTE = 9690;
public static final int DECEASED_TREE = 9691;
public static final int BROKEN_CHAMPAGNE = 9692;
public static final int TINSEL_TIGHTS = 9693;
public static final int WAD_OF_TAPE = 9694;
public static final int MAKESHIFT_GARBAGE_SHIRT = 9699;
public static final int DIETING_PILL = 9707;
public static final int CLAN_CARNIVAL_GAME = 9712;
public static final int GET_BIG_BOOK = 9713;
public static final int GALAPAGOS_BOOK = 9714;
public static final int FUTURE_BOOK = 9715;
public static final int LOVE_POTION_BOOK = 9716;
public static final int RHINESTONE_BOOK = 9717;
public static final int LOVE_SONG_BOOK = 9718;
public static final int MYSTERIOUS_RED_BOX = 9739;
public static final int MYSTERIOUS_GREEN_BOX = 9740;
public static final int MYSTERIOUS_BLUE_BOX = 9741;
public static final int MYSTERIOUS_BLACK_BOX = 9742;
public static final int LOVE_POTION_XYZ = 9745;
public static final int POKEDOLLAR_BILLS = 9747;
public static final int METANDIENONE = 9748;
public static final int RIBOFLAVIN = 9749;
public static final int BRONZE = 9750;
public static final int PIRACETAM = 9751;
public static final int ULTRACALCIUM = 9752;
public static final int GINSENG = 9753;
public static final int TALL_GRASS_SEEDS = 9760;
public static final int POKE_GROW_FERTILIZER = 9761;
public static final int LUCK_INCENSE = 9821;
public static final int SHELL_BELL = 9822;
public static final int MUSCLE_BAND = 9823;
public static final int AMULET_COIN = 9824;
public static final int RAZOR_FANG = 9825;
public static final int SMOKE_BALL = 9826;
public static final int GREEN_ROCKET = 9827;
public static final int MAGNIFICENT_OYSTER_EGG = 9828;
public static final int BRILLIANT_OYSTER_EGG = 9829;
public static final int GLISTENING_OYSTER_EGG = 9830;
public static final int SCINTILATING_OYSTER_EGG = 9831;
public static final int PEARLESCENT_OYSTER_EGG = 9832;
public static final int LUSTROUS_OYSTER_EGG = 9833;
public static final int GLEAMING_OYSTER_EGG = 9834;
public static final int FR_MEMBER = 9835;
public static final int FR_GUEST = 9836;
public static final int FANTASY_REALM_GEM = 9837;
public static final int RUBEE = 9838;
public static final int FR_WARRIOR_HELM = 9839;
public static final int FR_MAGE_HAT = 9840;
public static final int FR_ROGUE_MASK = 9841;
public static final int FR_KEY = 9844;
public static final int FR_PURPLE_MUSHROOM = 9845;
public static final int FR_TAINTED_MARSHMALLOW = 9846;
public static final int FR_CHESWICKS_NOTES = 9847;
public static final int MY_FIRST_ART_OF_WAR = 9850;
public static final int FR_DRAGON_ORE = 9851;
public static final int FR_POISONED_SMORE = 9853;
public static final int FR_DRUIDIC_ORB = 9854;
public static final int FR_HOLY_WATER = 9856;
public static final int CONTRACTOR_MANUAL = 9861;
public static final int FR_CHESWICKS_COMPASS = 9865;
public static final int FR_ARREST_WARRANT = 9866;
public static final int FR_MOUNTAIN_MAP = 9873;
public static final int FR_WOOD_MAP = 9874;
public static final int FR_SWAMP_MAP = 9875;
public static final int FR_VILLAGE_MAP = 9876;
public static final int FR_CEMETARY_MAP = 9877;
public static final int FR_CHARGED_ORB = 9895;
public static final int FR_NOTARIZED_WARRANT = 9897;
public static final int CLARIFIED_BUTTER = 9908;
public static final int G = 9909;
public static final int GARLAND_OF_GREATNESS = 9910;
public static final int GLUED_BOO_CLUE = 9913;
public static final int BOOMBOX = 9919;
public static final int GUIDE_TO_SAFARI = 9921;
public static final int SHIELDING_POTION = 9922;
public static final int PUNCHING_POTION = 9923;
public static final int SPECIAL_SEASONING = 9924;
public static final int NIGHTMARE_FUEL = 9925;
public static final int MEAT_CLIP = 9926;
public static final int CHEESE_WHEEL = 9937;
public static final int NEVERENDING_PARTY_INVITE = 9942;
public static final int NEVERENDING_PARTY_INVITE_DAILY = 9943;
public static final int PARTY_HARD_T_SHIRT = 9944;
public static final int ELECTRONICS_KIT = 9952;
public static final int PAINT_PALETTE = 9956;
public static final int PURPLE_BEAST_ENERGY_DRINK = 9958;
public static final int PUMP_UP_HIGH_TOPS = 9961;
public static final int VERY_SMALL_RED_DRESS = 9963;
public static final int EVERFULL_GLASS = 9966;
public static final int JAM_BAND_BOOTLEG = 9968;
public static final int INTIMIDATING_CHAINSAW = 9972;
public static final int PARTY_PLANNING_BOOK = 9978;
public static final int PARTYCRASHER = 9983;
public static final int DRINKING_TO_DRINK_BOOK = 9984;
public static final int LATTE_MUG = 9987;
public static final int VOTER_REGISTRATION_FORM = 9989;
public static final int I_VOTED_STICKER = 9990;
public static final int VOTER_BALLOT = 9991;
public static final int BLACK_SLIME_GLOB = 9996;
public static final int GREEN_SLIME_GLOB = 9997;
public static final int ORANGE_SLIME_GLOB = 9998;
public static final int GOVERNMENT_REQUISITION_FORM = 10003;
public static final int HAUNTED_HELL_RAMEN = 10018;
public static final int WALRUS_BLUBBER = 10034;
public static final int TINY_BOMB = 10036;
public static final int MOOSEFLANK = 10038;
public static final int BOXING_DAY_CARE = 10049;
public static final int BOXING_DAY_PASS = 10056;
public static final int SAUSAGE_O_MATIC = 10058;
public static final int MAGICAL_SAUSAGE_CASING = 10059;
public static final int MAGICAL_SAUSAGE = 10060;
public static final int CRIMBO_CANDLE = 10072;
public static final int CHALK_CHUNKS = 10088;
public static final int MARBLE_MOECULES = 10096;
public static final int PARAFFIN_PSEUDOACCORDION = 10103;
public static final int PARAFFIN_PIECES = 10104;
public static final int TERRA_COTTA_TIDBITS = 10112;
public static final int TRYPTOPHAN_DART = 10159;
public static final int DOCTOR_BAG = 10166;
public static final int BOOKE_OF_VAMPYRIC_KNOWLEDGE = 10180;
public static final int VAMPYRE_BLOOD = 10185;
public static final int GLITCH_ITEM = 10207;
public static final int PR_MEMBER = 10187;
public static final int PR_GUEST = 10188;
public static final int CURSED_COMPASS = 10191;
public static final int ISLAND_DRINKIN = 10211;
public static final int PIRATE_REALM_FUN_LOG = 10225;
public static final int PIRATE_FORK = 10227;
public static final int SCURVY_AND_SOBRIETY_PREVENTION = 10228;
public static final int LUCKY_GOLD_RING = 10229;
public static final int VAMPYRIC_CLOAKE = 10242;
public static final int FOURTH_SABER = 10251;
public static final int RING = 10252;
public static final int HEWN_MOON_RUNE_SPOON = 10254;
public static final int BEACH_COMB = 10258;
public static final int ETCHED_HOURGLASS = 10265;
public static final int PIECE_OF_DRIFTWOOD = 10281;
public static final int DRIFTWOOD_BEACH_COMB = 10291;
public static final int STICK_OF_FIREWOOD = 10293;
public static final int GETAWAY_BROCHURE = 10292;
public static final int RARE_MEAT_ISOTOPE = 10310;
public static final int BURNT_STICK = 10311;
public static final int BUNDLE_OF_FIREWOOD = 10312;
public static final int CAMPFIRE_SMOKE = 10313;
public static final int THE_IMPLODED_WORLD = 10322;
public static final int POCKET_PROFESSOR_MEMORY_CHIP = 10324;
public static final int LAW_OF_AVERAGES = 10325;
public static final int PILL_KEEPER = 10333;
public static final int DIABOLIC_PIZZA_CUBE = 10335;
public static final int DIABOLIC_PIZZA = 10336;
public static final int HUMAN_MUSK = 10350;
public static final int EXTRA_WARM_FUR = 10351;
public static final int INDUSTRIAL_LUBRICANT = 10352;
public static final int UNFINISHED_PLEASURE = 10353;
public static final int HUMANOID_GROWTH_HORMONE = 10354;
public static final int BUG_LYMPH = 10355;
public static final int ORGANIC_POTPOURRI = 10356;
public static final int BOOT_FLASK = 10357;
public static final int INFERNAL_SNOWBALL = 10358;
public static final int POWDERED_MADNESS = 10359;
public static final int FISH_SAUCE = 10360;
public static final int GUFFIN = 10361;
public static final int SHANTIX = 10362;
public static final int GOODBERRY = 10363;
public static final int EUCLIDEAN_ANGLE = 10364;
public static final int PEPPERMINT_SYRUP = 10365;
public static final int MERKIN_EYEDROPS = 10366;
public static final int EXTRA_STRENGTH_GOO = 10367;
public static final int ENVELOPE_MEAT = 10368;
public static final int LIVID_ENERGY = 10369;
public static final int MICRONOVA = 10370;
public static final int BEGGIN_COLOGNE = 10371;
public static final int THE_SPIRIT_OF_GIVING = 10380;
public static final int PEPPERMINT_EEL_SAUCE = 10416;
public static final int GREEN_AND_RED_BEAN = 10417;
public static final int TEMPURA_GREEN_AND_RED_BEAN = 10425;
public static final int BIRD_A_DAY_CALENDAR = 10434;
public static final int POWERFUL_GLOVE = 10438;
public static final int DRIP_HARNESS = 10441;
public static final int DRIPPY_TRUNCHEON = 10442;
public static final int DRIPLET = 10443;
public static final int DRIPPY_SNAIL_SHELL = 10444;
public static final int DRIPPY_NUGGET = 10445;
public static final int DRIPPY_WINE = 10446;
public static final int DRIPPY_CAVIAR = 10447;
public static final int DRIPPY_PLUM = 10448;
public static final int EYE_OF_THE_THING = 10450;
public static final int DRIPPY_SHIELD = 10452;
public static final int FIRST_PLUMBER_QUEST_ITEM = 10454;
public static final int COIN = 10454;
public static final int MUSHROOM = 10455;
public static final int DELUXE_MUSHROOM = 10456;
public static final int SUPER_DELUXE_MUSHROOM = 10457;
public static final int HAMMER = 10460;
public static final int HEAVY_HAMMER = 10461;
public static final int PLUMBER_FIRE_FLOWER = 10462;
public static final int BONFIRE_FLOWER = 10463;
public static final int WORK_BOOTS = 10464;
public static final int FANCY_BOOTS = 10465;
public static final int POWER_PANTS = 10469;
public static final int FROSTY_BUTTON = 10473;
public static final int LAST_PLUMBER_QUEST_ITEM = 10474;
public static final int MUSHROOM_SPORES = 10482;
public static final int FREE_RANGE_MUSHROOM = 10483;
public static final int PLUMP_FREE_RANGE_MUSHROOM = 10484;
public static final int BULKY_FREE_RANGE_MUSHROOM = 10485;
public static final int GIANT_FREE_RANGE_MUSHROOM = 10486;
public static final int IMMENSE_FREE_RANGE_MUSHROOM = 10487;
public static final int COLOSSAL_FREE_RANGE_MUSHROOM = 10488;
public static final int HOUSE_SIZED_MUSHROOM = 10497;
public static final int RED_PLUMBERS_BOOTS = 10501;
public static final int DRIPPY_STEIN = 10524;
public static final int DRIPPY_PILSNER = 10525;
public static final int DRIPPY_STAFF = 10526;
public static final int GUZZLR_TABLET = 10533;
public static final int GUZZLR_COCKTAIL_SET = 10534;
public static final int GUZZLRBUCK = 10535;
public static final int GUZZLR_SHOES = 10537;
public static final int CLOWN_CAR_KEY = 10547;
public static final int BATTING_CAGE_KEY = 10548;
public static final int AQUI = 10549;
public static final int KNOB_LABINET_KEY = 10550;
public static final int WEREMOOSE_KEY = 10551;
public static final int PEG_KEY = 10552;
public static final int KEKEKEY = 10553;
public static final int RABBITS_FOOT_KEY = 10554;
public static final int KNOB_SHAFT_SKATE_KEY = 10555;
public static final int ICE_KEY = 10556;
public static final int ANCHOVY_CAN_KEY = 10557;
public static final int CACTUS_KEY = 10558;
public static final int F_C_LE_SH_C_LE_K_Y = 10559;
public static final int TREASURE_CHEST_KEY = 10560;
public static final int DEMONIC_KEY = 10561;
public static final int KEY_SAUSAGE = 10562;
public static final int KNOB_TREASURY_KEY = 10563;
public static final int SCRAP_METAL_KEY = 10564;
public static final int BLACK_ROSE_KEY = 10565;
public static final int MUSIC_BOX_KEY = 10566;
public static final int ACTUAL_SKELETON_KEY = 10567;
public static final int DEEP_FRIED_KEY = 10568;
public static final int DISCARDED_BIKE_LOCK_KEY = 10569;
public static final int MANUAL_OF_LOCK_PICKING = 10571;
public static final int DROMEDARY_DRINKING_HELMENT = 10580;
public static final int SPINMASTER = 10582;
public static final int FLIMSY_HARDWOOD_SCRAPS = 10583;
public static final int DREADSYLVANIAN_HEMLOCK = 10589;
public static final int HEMLOCK_HELM = 10590;
public static final int SWEATY_BALSAM = 10591;
public static final int BALSAM_BARREL = 10592;
public static final int ANCIENT_REDWOOD = 10593;
public static final int REDWOOD_RAIN_STICK = 10594;
public static final int PURPLEHEART_LOGS = 10595;
public static final int PURPLEHEART_PANTS = 10596;
public static final int WORMWOOD_STICK = 10597;
public static final int WORMWOOD_WEDDING_RING = 10598;
public static final int DRIPWOOD_SLAB = 10599;
public static final int DRIPPY_DIADEM = 10600;
public static final int GREY_GOO_RING = 10602;
public static final int SIZZLING_DESK_BELL = 10617;
public static final int FROST_RIMED_DESK_BELL = 10618;
public static final int UNCANNY_DESK_BELL = 10619;
public static final int NASTY_DESK_BELL = 10620;
public static final int GREASY_DESK_BELL = 10621;
public static final int FANCY_CHESS_SET = 10622;
public static final int ONYX_KING = 10623;
public static final int ONYX_QUEEN = 10624;
public static final int ONYX_ROOK = 10625;
public static final int ONYX_BISHOP = 10626;
public static final int ONYX_KNIGHT = 10627;
public static final int ONYX_PAWN = 10628;
public static final int ALABASTER_KING = 10629;
public static final int ALABASTER_QUEEN = 10630;
public static final int ALABASTER_ROOK = 10631;
public static final int ALABASTER_BISHOP = 10632;
public static final int ALABASTER_KNIGHT = 10633;
public static final int ALABASTER_PAWN = 10634;
public static final int CARGO_CULTIST_SHORTS = 10636;
public static final int UNIVERSAL_SEASONING = 10640;
public static final int CHOCOLATE_CHIP_MUFFIN = 10643;
public static final int KNOCK_OFF_RETRO_SUPERHERO_CAPE = 10647;
public static final int SUBSCRIPTION_COCOA_DISPENSER = 10652;
public static final int OVERFLOWING_GIFT_BASKET = 10670;
public static final int FOOD_DRIVE_BUTTON = 10691;
public static final int BOOZE_DRIVE_BUTTON = 10692;
public static final int CANDY_DRIVE_BUTTON = 10693;
public static final int FOOD_MAILING_LIST = 10694;
public static final int BOOZE_MAILING_LIST = 10695;
public static final int CANDY_MAILING_LIST = 10696;
public static final int GOVERNMENT_FOOD_SHIPMENT = 10685;
public static final int GOVERNMENT_BOOZE_SHIPMENT = 10686;
public static final int GOVERNMENT_CANDY_SHIPMENT = 10687;
public static final int MINIATURE_CRYSTAL_BALL = 10730;
public static final int COAT_OF_PAINT = 10732;
public static final int SPINAL_FLUID_COVERED_EMOTION_CHIP = 10734;
public static final int BATTERY_9V = 10742;
public static final int BATTERY_LANTERN = 10743;
public static final int BATTERY_CAR = 10744;
public static final int GREEN_MARSHMALLOW = 10746;
public static final int MARSHMALLOW_BOMB = 10747;
public static final int BACKUP_CAMERA = 10749;
public static final int BLUE_PLATE = 10751;
public static final int FAMILIAR_SCRAPBOOK = 10759;
public static final int CLAN_UNDERGROUND_FIREWORKS_SHOP = 10761;
public static final int FEDORA_MOUNTED_FOUNTAIN = 10762;
public static final int PORKPIE_MOUNTED_POPPER = 10763;
public static final int SOMBRERO_MOUNTED_SPARKLER = 10764;
public static final int CATHERINE_WHEEL = 10770;
public static final int ROCKET_BOOTS = 10771;
public static final int OVERSIZED_SPARKLER = 10772;
public static final int BLART = 10790;
public static final int RAINPROOF_BARREL_CAULK = 10794;
public static final int PUMP_GREASE = 10795;
public static final int INDUSTRIAL_FIRE_EXTINGUISHER = 10797;
public static final int VAMPIRE_VINTNER_WINE = 10800;
public static final int DAYLIGHT_SHAVINGS_HELMET = 10804;
public static final int COLD_MEDICINE_CABINET = 10815;
public static final int HOMEBODYL = 10828;
public static final int EXTROVERMECTIN = 10829;
public static final int BREATHITIN = 10830;
public static final int GOOIFIED_ANIMAL_MATTER = 10844;
public static final int GOOIFIED_VEGETABLE_MATTER = 10845;
public static final int GOOIFIED_MINERAL_MATTER = 10846;
public static final int MEATBALL_MACHINE = 10878;
public static final int REFURBISHED_AIR_FRYER = 10879;
public static final int ELEVEN_LEAF_CLOVER = 10881;
public static final int CURSED_MAGNIFYING_GLASS = 10885;
public static final int COSMIC_BOWLING_BALL = 10891;
public static final int COMBAT_LOVERS_LOCKET = 10893;
public static final int UNBREAKABLE_UMBRELLA = 10899;
private ItemPool() {}
public static final AdventureResult get(String itemName, int count) {
int itemId = ItemDatabase.getItemId(itemName, 1, false);
if (itemId != -1) {
return ItemPool.get(itemId, count);
}
return AdventureResult.tallyItem(itemName, count, false);
}
public static final AdventureResult get(int itemId, int count) {
return new AdventureResult(itemId, count, false);
}
public static final AdventureResult get(int itemId) {
return new AdventureResult(itemId, 1, false);
}
// Support for various classes of items:
// El Vibrato helmet
public static final String[] EV_HELMET_CONDUITS =
new String[] {
"ATTACK", "BUILD", "BUFF", "MODIFY", "REPAIR", "TARGET", "SELF", "DRONE", "WALL"
};
public static final List<String> EV_HELMET_LEVELS =
Arrays.asList(
"PA",
"ZERO",
"NOKGAGA",
"NEGLIGIBLE",
"GABUHO NO",
"EXTREMELY LOW",
"GA NO",
"VERY LOW",
"NO",
"LOW",
"FUZEVENI",
"MODERATE",
"PAPACHA",
"ELEVATED",
"FU",
"HIGH",
"GA FU",
"VERY HIGH",
"GABUHO FU",
"EXTREMELY HIGH",
"CHOSOM",
"MAXIMAL");
// BANG POTIONS and SLIME VIALS
public static final String[][] bangPotionStrings = {
// name, combat use mssage, inventory use message
{"inebriety", "wino", "liquid fire"},
{"healing", "better", "You gain"},
{"confusion", "confused", "Confused"},
{"blessing", "stylish", "Izchak's Blessing"},
{"detection", "blink", "Object Detection"},
{"sleepiness", "yawn", "Sleepy"},
{"mental acuity", "smarter", "Strange Mental Acuity"},
{"ettin strength", "stronger", "Strength of Ten Ettins"},
{"teleportitis", "disappearing", "Teleportitis"},
};
public static final String[][][] slimeVialStrings = {
// name, inventory use mssage
{ // primary
{"strong", "Slimily Strong"},
{"sagacious", "Slimily Sagacious"},
{"speedy", "Slimily Speedy"},
},
{ // secondary
{"brawn", "Bilious Brawn"},
{"brains", "Bilious Brains"},
{"briskness", "Bilious Briskness"},
},
{ // tertiary
{"slimeform", "Slimeform"},
{"eyesight", "Ichorous Eyesight"},
{"intensity", "Ichorous Intensity"},
{"muscle", "Mucilaginous Muscle"},
{"mentalism", "Mucilaginous Mentalism"},
{"moxiousness", "Mucilaginous Moxiousness"},
},
};
public static final boolean eliminationProcessor(
final String[][] strings,
final int index,
final int id,
final int minId,
final int maxId,
final String baseName,
final String joiner) {
String effect = strings[index][0];
Preferences.setString(baseName + id, effect);
String name = ItemDatabase.getItemName(id);
String testName = name + joiner + effect;
String testPlural = ItemDatabase.getPluralName(id) + joiner + effect;
ItemDatabase.registerItemAlias(id, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
HashSet<String> possibilities = new HashSet<>();
for (int i = 0; i < strings.length; ++i) {
possibilities.add(strings[i][0]);
}
int missing = 0;
for (int i = minId; i <= maxId; ++i) {
effect = Preferences.getString(baseName + i);
if (effect.equals("")) {
if (missing != 0) {
// more than one missing item in set
return false;
}
missing = i;
} else {
possibilities.remove(effect);
}
}
if (missing == 0) {
// no missing items
return false;
}
if (possibilities.size() != 1) {
// something's screwed up if this happens
return false;
}
effect = possibilities.iterator().next();
Preferences.setString(baseName + missing, effect);
name = ItemDatabase.getItemName(missing);
testName = name + joiner + effect;
testPlural = ItemDatabase.getPluralName(missing) + joiner + effect;
ItemDatabase.registerItemAlias(missing, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
return true;
}
// Suggest one or two items from a permutation group that need to be identified.
// Strategy: identify the items the player has the most of first,
// to maximize the usefulness of having identified them.
// If two items remain unidentified, only identify one, since
// eliminationProcessor will handle the other.
public static final void suggestIdentify(
final List<Integer> items, final int minId, final int maxId, final String baseName) {
// Can't autoidentify in G-Lover
if (KoLCharacter.inGLover()) {
return;
}
ArrayList<Integer> possible = new ArrayList<>();
int unknown = 0;
for (int i = minId; i <= maxId; ++i) {
if (!Preferences.getString(baseName + i).equals("")) {
continue; // already identified;
}
++unknown;
AdventureResult item = new AdventureResult(i, 1, false);
int count = item.getCount(KoLConstants.inventory);
if (count <= 0) {
continue; // can't identify yet
}
possible.add(IntegerPool.get(i | Math.min(count, 127) << 24));
}
int count = possible.size();
// Nothing to do if we have no items that qualify
if (count == 0) {
return;
}
if (count > 1) {
possible.sort(Collections.reverseOrder());
}
// Identify the item we have the most of
items.add(possible.get(0) & 0x00FFFFFF);
// If only two items are unknown, that's enough, since the
// other will be identified by eliminationProcessor
if (unknown == 2) {
return;
}
// If we have three or more unknowns, try for a second
if (count > 1) {
items.add(possible.get(1) & 0x00FFFFFF);
}
}
}
| ajoshi/kolmafia | src/net/sourceforge/kolmafia/objectpool/ItemPool.java |
730 | package entity;
public class Game extends Media{
private String uitgever;
public Game(String titel, String beschrijving, double rating, String uitgever) {
super(titel, beschrijving, rating);
this.uitgever = uitgever;
}
public Game(int id, String titel, String beschrijving, double rating, String uitgever) {
super(id, titel, beschrijving, rating);
this.uitgever = uitgever;
}
@Override
public void verplaatsNaarArchief() {
//doet er niet toe
}
public String getUitgever() {
return uitgever;
}
}
| EHB-TI/Programming-Essentials-2 | Werkcollege10/src/entity/Game.java |
731 | package net.sourceforge.kolmafia.objectpool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import net.sourceforge.kolmafia.AdventureResult;
import net.sourceforge.kolmafia.KoLCharacter;
import net.sourceforge.kolmafia.KoLConstants;
import net.sourceforge.kolmafia.persistence.ItemDatabase;
import net.sourceforge.kolmafia.preferences.Preferences;
public class ItemPool {
public static final int SEAL_CLUB = 1;
public static final int SEAL_TOOTH = 2;
public static final int HELMET_TURTLE = 3;
public static final int TURTLE_TOTEM = 4;
public static final int PASTA_SPOON = 5;
public static final int RAVIOLI_HAT = 6;
public static final int SAUCEPAN = 7;
public static final int SPICES = 8;
public static final int DISCO_MASK = 9;
public static final int DISCO_BALL = 10;
public static final int STOLEN_ACCORDION = 11;
public static final int MARIACHI_PANTS = 12;
public static final int WORTHLESS_ITEM = 13; // Pseudo item
public static final int MOXIE_WEED = 14;
public static final int ASPARAGUS_KNIFE = 19;
public static final int CHEWING_GUM = 23;
public static final int TEN_LEAF_CLOVER = 24;
public static final int MEAT_PASTE = 25;
public static final int DOLPHIN_KING_MAP = 26;
public static final int SPIDER_WEB = 27;
public static final int BIG_ROCK = 30;
public static final int BJORNS_HAMMER = 32;
public static final int VIKING_HELMET = 37;
public static final int CASINO_PASS = 40;
public static final int SCHLITZ = 41;
public static final int HERMIT_PERMIT = 42;
public static final int WORTHLESS_TRINKET = 43;
public static final int WORTHLESS_GEWGAW = 44;
public static final int WORTHLESS_KNICK_KNACK = 45;
public static final int WOODEN_FIGURINE = 46;
public static final int BUTTERED_ROLL = 47;
public static final int ROCK_N_ROLL_LEGEND = 50;
public static final int BANJO_STRINGS = 52;
public static final int STONE_BANJO = 53;
public static final int DISCO_BANJO = 54;
public static final int JABANERO_PEPPER = 55;
public static final int FIVE_ALARM_SAUCEPAN = 57;
public static final int MACE_OF_THE_TORTOISE = 60;
public static final int FORTUNE_COOKIE = 61;
public static final int GOLDEN_TWIG = 66;
public static final int PASTA_SPOON_OF_PERIL = 68;
public static final int NEWBIESPORT_TENT = 69;
public static final int BAR_SKIN = 70;
public static final int WOODEN_STAKES = 71;
public static final int BARSKIN_TENT = 73;
public static final int SPOOKY_MAP = 74;
public static final int SPOOKY_SAPLING = 75;
public static final int SPOOKY_FERTILIZER = 76;
public static final int PRETTY_BOUQUET = 78;
public static final int GRAVY_BOAT = 80;
public static final int WILLER = 81;
public static final int LOCKED_LOCKER = 84;
public static final int TBONE_KEY = 86;
public static final int MEAT_FROM_YESTERDAY = 87;
public static final int MEAT_STACK = 88;
public static final int MEAT_GOLEM = 101;
public static final int SCARECROW = 104;
public static final int KETCHUP = 106;
public static final int CATSUP = 107;
public static final int SPRING = 118;
public static final int SPROCKET = 119;
public static final int COG = 120;
public static final int GNOLLISH_AUTOPLUNGER = 127;
public static final int FRILLY_SKIRT = 131;
public static final int BITCHIN_MEATCAR = 134;
public static final int SWEET_RIMS = 135;
public static final int ICE_COLD_SIX_PACK = 138;
public static final int VALUABLE_TRINKET = 139;
public static final int DINGY_PLANKS = 140;
public static final int DINGY_DINGHY = 141;
public static final int ANTICHEESE = 142;
public static final int COTTAGE = 143;
public static final int BARBED_FENCE = 145;
public static final int DINGHY_PLANS = 146;
public static final int SCALP_OF_GORGOLOK = 150;
public static final int ELDER_TURTLE_SHELL = 151;
public static final int COLANDER_OF_EMERIL = 152;
public static final int ANCIENT_SAUCEHELM = 153;
public static final int DISCO_FRO_PICK = 154;
public static final int EL_SOMBRERO_DE_LOPEZ = 155;
public static final int RANGE = 157;
public static final int DOUGH = 159;
public static final int SKELETON_BONE = 163;
public static final int SMART_SKULL = 164;
public static final int BONE_RATTLE = 168;
public static final int TACO_SHELL = 173;
public static final int BRIEFCASE = 184;
public static final int FAT_STACKS_OF_CASH = 185;
public static final int ENCHANTED_BEAN = 186;
public static final int LOOSE_TEETH = 187;
public static final int BAT_GUANO = 188;
public static final int BATSKIN_BELT = 191;
public static final int MR_ACCESSORY = 194;
public static final int DISASSEMBLED_CLOVER = 196;
public static final int RAT_WHISKER = 197;
public static final int SHINY_RING = 199;
public static final int FENG_SHUI = 210;
public static final int FOUNTAIN = 211;
public static final int WINDCHIMES = 212;
public static final int DREADSACK = 214;
public static final int HEMP_STRING = 218;
public static final int EYEPATCH = 224;
public static final int PUNGENT_UNGUENT = 231;
public static final int COCKTAIL_KIT = 236;
public static final int BOTTLE_OF_GIN = 237;
public static final int GRAPEFRUIT = 243;
public static final int TOMATO = 246;
public static final int FERMENTING_POWDER = 247;
public static final int MARTINI = 251;
public static final int DENSE_STACK = 258;
public static final int MULLET_WIG = 267;
public static final int PICKET_FENCE = 270;
public static final int MOSQUITO_LARVA = 275;
public static final int PICKOMATIC_LOCKPICKS = 280;
public static final int BORIS_KEY = 282;
public static final int JARLSBERG_KEY = 283;
public static final int SNEAKY_PETE_KEY = 284;
public static final int RUBBER_AXE = 292;
public static final int FLAT_DOUGH = 301;
public static final int DRY_NOODLES = 304;
public static final int KNOB_GOBLIN_PERFUME = 307;
public static final int KNOB_GOBLIN_HELM = 308;
public static final int KNOB_GOBLIN_PANTS = 309;
public static final int KNOB_GOBLIN_POLEARM = 310;
public static final int KNOB_GOBLIN_CROWN = 313;
public static final int GOAT_CHEESE = 322;
public static final int PLAIN_PIZZA = 323;
public static final int SAUSAGE_PIZZA = 324;
public static final int GOAT_CHEESE_PIZZA = 325;
public static final int MUSHROOM_PIZZA = 326;
public static final int TENDER_HAMMER = 338;
public static final int LAB_KEY = 339;
public static final int SELTZER = 344;
public static final int REAGENT = 346;
public static final int DYSPEPSI_COLA = 347;
public static final int ICY_KATANA_HILT = 349;
public static final int HOT_KATANA_BLADE = 350;
public static final int ICY_HOT_KATANA = 351;
public static final int MINERS_HELMET = 360;
public static final int MINERS_PANTS = 361;
public static final int MATTOCK = 362;
public static final int LINOLEUM_ORE = 363;
public static final int ASBESTOS_ORE = 364;
public static final int CHROME_ORE = 365;
public static final int YETI_FUR = 388;
public static final int PENGUIN_SKIN = 393;
public static final int YAK_SKIN = 394;
public static final int HIPPOPOTAMUS_SKIN = 395;
public static final int ACOUSTIC_GUITAR = 404;
public static final int PIRATE_CHEST = 405;
public static final int PIRATE_PELVIS = 406;
public static final int PIRATE_SKULL = 407;
public static final int JOLLY_CHARRRM = 411;
public static final int JOLLY_BRACELET = 413;
public static final int BEANBAG_CHAIR = 429;
public static final int LONG_SKINNY_BALLOON = 433;
public static final int BALLOON_MONKEY = 436;
public static final int CHEF = 438;
public static final int BARTENDER = 440;
public static final int BEER_LENS = 443;
public static final int PRETENTIOUS_PAINTBRUSH = 450;
public static final int PRETENTIOUS_PALETTE = 451;
public static final int RUSTY_SCREWDRIVER = 454;
public static final int DRY_MARTINI = 456;
public static final int TRANSFUNCTIONER = 458;
public static final int WHITE_PIXEL = 459;
public static final int BLACK_PIXEL = 460;
public static final int RED_PIXEL = 461;
public static final int GREEN_PIXEL = 462;
public static final int BLUE_PIXEL = 463;
public static final int RED_PIXEL_POTION = 464;
public static final int RUBY_W = 468;
public static final int HOT_WING = 471;
public static final int DODECAGRAM = 479;
public static final int CANDLES = 480;
public static final int BUTTERKNIFE = 481;
public static final int MR_CONTAINER = 482;
public static final int NEWBIESPORT_BACKPACK = 483;
public static final int HEMP_BACKPACK = 484;
public static final int SNAKEHEAD_CHARM = 485;
public static final int TALISMAN = 486;
public static final int KETCHUP_HOUND = 493;
public static final int PAPAYA = 498;
public static final int ELF_FARM_RAFFLE_TICKET = 500;
public static final int PAGODA_PLANS = 502;
public static final int HEAVY_METAL_GUITAR = 507;
public static final int HEY_DEZE_NUTS = 509;
public static final int BORIS_PIE = 513;
public static final int JARLSBERG_PIE = 514;
public static final int SNEAKY_PETE_PIE = 515;
public static final int HEY_DEZE_MAP = 516;
public static final int MMJ = 518;
public static final int MOXIE_MAGNET = 519;
public static final int STRANGE_LEAFLET = 520;
public static final int HOUSE = 526;
public static final int VOLLEYBALL = 527;
public static final int SPECIAL_SAUCE_GLOVE = 531;
public static final int ABRIDGED = 534;
public static final int BRIDGE = 535;
public static final int DICTIONARY = 536;
public static final int LOWERCASE_N = 539;
public static final int ELITE_TROUSERS = 542;
public static final int SCROLL_334 = 547;
public static final int SCROLL_668 = 548;
public static final int SCROLL_30669 = 549;
public static final int SCROLL_33398 = 550;
public static final int SCROLL_64067 = 551;
public static final int GATES_SCROLL = 552;
public static final int ELITE_SCROLL = 553;
public static final int CAN_LID = 559;
public static final int SONAR = 563;
public static final int HERMIT_SCRIPT = 567;
public static final int LUCIFER = 571;
public static final int HELL_RAMEN = 578;
public static final int FETTUCINI_INCONNU = 583;
public static final int SPAGHETTI_WITH_SKULLHEADS = 584;
public static final int GNOCCHETTI_DI_NIETZSCHE = 585;
public static final int REMEDY = 588;
public static final int TINY_HOUSE = 592;
public static final int PHONICS_DOWN = 593;
public static final int EXTREME_AMULET = 594;
public static final int DRASTIC_HEALING = 595;
public static final int TITANIUM_UMBRELLA = 596;
public static final int MOHAWK_WIG = 597;
public static final int SLUG_LORD_MAP = 598;
public static final int DR_HOBO_MAP = 601;
public static final int SHOPPING_LIST = 602;
public static final int TISSUE_PAPER_IMMATERIA = 605;
public static final int TIN_FOIL_IMMATERIA = 606;
public static final int GAUZE_IMMATERIA = 607;
public static final int PLASTIC_WRAP_IMMATERIA = 608;
public static final int SOCK = 609;
public static final int HEAVY_D = 611;
public static final int CHAOS_BUTTERFLY = 615;
public static final int FURRY_FUR = 616;
public static final int GIANT_NEEDLE = 619;
public static final int BLACK_CANDLE = 620;
public static final int WARM_SUBJECT = 621;
public static final int AWFUL_POETRY_JOURNAL = 622;
public static final int WA = 623;
public static final int NG = 624;
public static final int WAND_OF_NAGAMAR = 626;
public static final int ND = 627;
public static final int METALLIC_A = 628;
public static final int MEAT_GLOBE = 636;
public static final int TOASTER = 637;
public static final int TOAST = 641;
public static final int SKELETON_KEY = 642;
public static final int SKELETON_KEY_RING = 643;
public static final int ROWBOAT = 653;
public static final int STAR = 654;
public static final int LINE = 655;
public static final int STAR_CHART = 656;
public static final int STAR_SWORD = 657;
public static final int STAR_CROSSBOW = 658;
public static final int STAR_STAFF = 659;
public static final int STAR_HAT = 661;
public static final int STAR_STARFISH = 664;
public static final int STAR_KEY = 665;
public static final int STEAMING_EVIL = 666;
public static final int GIANT_CASTLE_MAP = 667;
public static final int CRANBERRIES = 672;
public static final int BONERDAGON_SKULL = 675;
public static final int DRAGONBONE_BELT_BUCKLE = 676;
public static final int BADASS_BELT = 677;
public static final int BONERDAGON_CHEST = 678;
public static final int SUMP_M_SUMP_M = 682;
public static final int DIGITAL_KEY = 691;
public static final int HAMETHYST = 704;
public static final int BACONSTONE = 705;
public static final int PORQUOISE = 706;
public static final int JEWELRY_PLIERS = 709;
public static final int BACONSTONE_EARRING = 715;
public static final int BACONSTONE_BRACELET = 717;
public static final int MIRROR_SHARD = 726;
public static final int PUZZLE_PIECE = 727;
public static final int HEDGE_KEY = 728;
public static final int FISHBOWL = 729;
public static final int FISHTANK = 730;
public static final int FISH_HOSE = 731;
public static final int HOSED_TANK = 732;
public static final int HOSED_FISHBOWL = 733;
public static final int SCUBA_GEAR = 734;
public static final int SINISTER_STRUMMING = 736;
public static final int SQUEEZINGS_OF_WOE = 737;
public static final int REALLY_EVIL_RHYTHM = 738;
public static final int TAMBOURINE = 740;
public static final int BROKEN_SKULL = 741;
public static final int SERRATED_PROBOSCIS_EXTENSION = 745;
public static final int KNOB_FIRECRACKER = 747;
public static final int FLAMING_MUSHROOM = 755;
public static final int FROZEN_MUSHROOM = 756;
public static final int STINKY_MUSHROOM = 757;
public static final int CUMMERBUND = 778;
public static final int MAFIA_ARIA = 781;
public static final int RAFFLE_TICKET = 785;
public static final int STRAWBERRY = 786;
public static final int GOLDEN_MR_ACCESSORY = 792;
public static final int ROCKIN_WAGON = 797;
public static final int PLUS_SIGN = 818;
public static final int FIRST_BANG_POTION = 819;
public static final int MILKY_POTION = 819;
public static final int SWIRLY_POTION = 820;
public static final int BUBBLY_POTION = 821;
public static final int SMOKY_POTION = 822;
public static final int CLOUDY_POTION = 823;
public static final int EFFERVESCENT_POTION = 824;
public static final int FIZZY_POTION = 825;
public static final int DARK_POTION = 826;
public static final int LAST_BANG_POTION = 827;
public static final int MURKY_POTION = 827;
public static final int ANTIDOTE = 829;
public static final int ROYAL_JELLY = 830;
public static final int SHOCK_COLLAR = 856;
public static final int MOONGLASSES = 857;
public static final int LEAD_NECKLACE = 865;
public static final int TEARS = 869;
public static final int ROLLING_PIN = 873;
public static final int UNROLLING_PIN = 874;
public static final int GOOFBALLS = 879;
public static final int ONE_HUNDRED_WATT_BULB = 902;
public static final int YUMMY_TUMMY_BEAN = 905;
public static final int DWARF_BREAD = 910;
public static final int PLASTIC_SWORD = 938;
public static final int DIRTY_MARTINI = 948;
public static final int GROGTINI = 949;
public static final int CHERRY_BOMB = 950;
public static final int WHITE_CHOCOLATE_AND_TOMATO_PIZZA = 958;
public static final int MAID = 1000;
public static final int TEQUILA = 1004;
public static final int BOXED_WINE = 1005;
public static final int VODKA_MARTINI = 1009;
public static final int DRY_VODKA_MARTINI = 1019;
public static final int VESPER = 1023;
public static final int BODYSLAM = 1024;
public static final int SANGRIA_DEL_DIABLO = 1025;
public static final int VALENTINE = 1026;
public static final int TAM_O_SHANTER = 1040;
public static final int GREEN_BEER = 1041;
public static final int RED_STRIPED_EGG = 1048;
public static final int RED_POLKA_EGG = 1049;
public static final int RED_PAISLEY_EGG = 1050;
public static final int BLUE_STRIPED_EGG = 1052;
public static final int BLUE_POLKA_EGG = 1053;
public static final int BLUE_PAISLEY_EGG = 1054;
public static final int OYSTER_BASKET = 1080;
public static final int TARGETING_CHIP = 1102;
public static final int CLOCKWORK_BARTENDER = 1111;
public static final int CLOCKWORK_CHEF = 1112;
public static final int CLOCKWORK_MAID = 1113;
public static final int ANNOYING_PITCHFORK = 1116;
public static final int PREGNANT_FLAMING_MUSHROOM = 1118;
public static final int PREGNANT_FROZEN_MUSHROOM = 1119;
public static final int PREGNANT_STINKY_MUSHROOM = 1120;
public static final int INEXPLICABLY_GLOWING_ROCK = 1121;
public static final int SPOOKY_GLOVE = 1125;
public static final int SPOOKY_BICYCLE_CHAIN = 1137;
public static final int FLAMING_MUSHROOM_WINE = 1139;
public static final int ICY_MUSHROOM_WINE = 1140;
public static final int STINKY_MUSHROOM_WINE = 1141;
public static final int POINTY_MUSHROOM_WINE = 1142;
public static final int FLAT_MUSHROOM_WINE = 1143;
public static final int COOL_MUSHROOM_WINE = 1144;
public static final int KNOB_MUSHROOM_WINE = 1145;
public static final int KNOLL_MUSHROOM_WINE = 1146;
public static final int SPOOKY_MUSHROOM_WINE = 1147;
public static final int GRAVY_MAYPOLE = 1152;
public static final int GIFT1 = 1167;
public static final int GIFT2 = 1168;
public static final int GIFT3 = 1169;
public static final int GIFT4 = 1170;
public static final int GIFT5 = 1171;
public static final int GIFT6 = 1172;
public static final int GIFT7 = 1173;
public static final int GIFT8 = 1174;
public static final int GIFT9 = 1175;
public static final int GIFT10 = 1176;
public static final int GIFT11 = 1177;
public static final int POTTED_FERN = 1180;
public static final int TULIP = 1181;
public static final int VENUS_FLYTRAP = 1182;
public static final int ALL_PURPOSE_FLOWER = 1183;
public static final int EXOTIC_ORCHID = 1184;
public static final int LONG_STEMMED_ROSE = 1185;
public static final int GILDED_LILY = 1186;
public static final int DEADLY_NIGHTSHADE = 1187;
public static final int BLACK_LOTUS = 1188;
public static final int STUFFED_GHUOL_WHELP = 1191;
public static final int STUFFED_ZMOBIE = 1192;
public static final int RAGGEDY_HIPPY_DOLL = 1193;
public static final int STUFFED_STAB_BAT = 1194;
public static final int APATHETIC_LIZARDMAN_DOLL = 1195;
public static final int STUFFED_YETI = 1196;
public static final int STUFFED_MOB_PENGUIN = 1197;
public static final int STUFFED_SABRE_TOOTHED_LIME = 1198;
public static final int GIANT_STUFFED_BUGBEAR = 1199;
public static final int HAPPY_BIRTHDAY_CLAUDE_CAKE = 1202;
public static final int PERSONALIZED_BIRTHDAY_CAKE = 1203;
public static final int THREE_TIERED_WEDDING_CAKE = 1204;
public static final int BABYCAKES = 1205;
public static final int BLUE_VELVET_CAKE = 1206;
public static final int CONGRATULATORY_CAKE = 1207;
public static final int ANGEL_FOOD_CAKE = 1208;
public static final int DEVILS_FOOD_CAKE = 1209;
public static final int BIRTHDAY_PARTY_JELLYBEAN_CHEESECAKE = 1210;
public static final int HEART_SHAPED_BALLOON = 1213;
public static final int ANNIVERSARY_BALLOON = 1214;
public static final int MYLAR_BALLOON = 1215;
public static final int KEVLAR_BALLOON = 1216;
public static final int THOUGHT_BALLOON = 1217;
public static final int RAT_BALLOON = 1218;
public static final int MINI_ZEPPELIN = 1219;
public static final int MR_BALLOON = 1220;
public static final int RED_BALLOON = 1221;
public static final int STAINLESS_STEEL_SOLITAIRE = 1226;
public static final int PLEXIGLASS_PITH_HELMET = 1231;
public static final int PLEXIGLASS_POCKETWATCH = 1232;
public static final int PLEXIGLASS_PENDANT = 1235;
public static final int TOY_HOVERCRAFT = 1243;
public static final int KNOB_GOBLIN_BALLS = 1244;
public static final int KNOB_GOBLIN_CODPIECE = 1245;
public static final int BONERDAGON_VERTEBRA = 1247;
public static final int BONERDAGON_NECKLACE = 1248;
public static final int PRETENTIOUS_PAIL = 1258;
public static final int WAX_LIPS = 1260;
public static final int NOSE_BONE_FETISH = 1264;
public static final int GLOOMY_BLACK_MUSHROOM = 1266;
public static final int DEAD_MIMIC = 1267;
public static final int PINE_WAND = 1268;
public static final int EBONY_WAND = 1269;
public static final int HEXAGONAL_WAND = 1270;
public static final int ALUMINUM_WAND = 1271;
public static final int MARBLE_WAND = 1272;
public static final int MEDICINAL_HERBS = 1274;
public static final int MAKEUP_KIT = 1305;
public static final int COMFY_BLANKET = 1311;
public static final int FACSIMILE_DICTIONARY = 1316;
public static final int TIME_HELMET = 1323;
public static final int TIME_SWORD = 1325;
public static final int DYSPEPSI_HELMET = 1326;
public static final int CLOACA_SHIELD = 1327;
public static final int CLOACA_FATIGUES = 1328;
public static final int DYSPEPSI_SHIELD = 1329;
public static final int DYSPEPSI_FATIGUES = 1330;
public static final int CLOACA_HELMET = 1331;
public static final int CLOACA_COLA = 1334;
public static final int FANCY_CHOCOLATE = 1382;
public static final int TOY_SOLDIER = 1397;
public static final int SNOWCONE_BOOK = 1411;
public static final int PURPLE_SNOWCONE = 1412;
public static final int GREEN_SNOWCONE = 1413;
public static final int ORANGE_SNOWCONE = 1414;
public static final int RED_SNOWCONE = 1415;
public static final int BLUE_SNOWCONE = 1416;
public static final int BLACK_SNOWCONE = 1417;
public static final int TEDDY_SEWING_KIT = 1419;
public static final int ICEBERGLET = 1423;
public static final int ICE_SICKLE = 1424;
public static final int ICE_BABY = 1425;
public static final int ICE_PICK = 1426;
public static final int ICE_SKATES = 1427;
public static final int OILY_GOLDEN_MUSHROOM = 1432;
public static final int USELESS_POWDER = 1437;
public static final int TWINKLY_WAD = 1450;
public static final int HOT_WAD = 1451;
public static final int COLD_WAD = 1452;
public static final int SPOOKY_WAD = 1453;
public static final int STENCH_WAD = 1454;
public static final int SLEAZE_WAD = 1455;
public static final int GIFTV = 1460;
public static final int LUCKY_RABBIT_FOOT = 1485;
public static final int MINIATURE_DORMOUSE = 1489;
public static final int GLOOMY_MUSHROOM_WINE = 1496;
public static final int OILY_MUSHROOM_WINE = 1497;
public static final int HILARIOUS_BOOK = 1498;
public static final int RUBBER_EMO_ROE = 1503;
public static final int FAKE_HAND = 1511;
public static final int PET_BUFFING_SPRAY = 1512;
public static final int VAMPIRE_HEART = 1518;
public static final int BAKULA = 1519;
public static final int RADIO_KOL_COFFEE_MUG = 1520;
public static final int JOYBUZZER = 1525;
public static final int SNOOTY_DISGUISE = 1526;
public static final int GIFTR = 1534;
public static final int WEEGEE_SQOUIJA = 1537;
public static final int TAM_O_SHATNER = 1539;
public static final int GRIMACITE_GOGGLES = 1540;
public static final int GRIMACITE_GLAIVE = 1541;
public static final int GRIMACITE_GREAVES = 1542;
public static final int GRIMACITE_GARTER = 1543;
public static final int GRIMACITE_GALOSHES = 1544;
public static final int GRIMACITE_GORGET = 1545;
public static final int GRIMACITE_GUAYABERA = 1546;
public static final int MSG = 1549;
public static final int BOXED_CHAMPAGNE = 1556;
public static final int COCKTAIL_ONION = 1560;
public static final int VODKA_GIBSON = 1569;
public static final int GIBSON = 1570;
public static final int HOT_HI_MEIN = 1592;
public static final int COLD_HI_MEIN = 1593;
public static final int SPOOKY_HI_MEIN = 1594;
public static final int STINKY_HI_MEIN = 1595;
public static final int SLEAZY_HI_MEIN = 1596;
public static final int CATALYST = 1605;
public static final int ULTIMATE_WAD = 1606;
public static final int C_CLOCHE = 1615;
public static final int C_CULOTTES = 1616;
public static final int C_CROSSBOW = 1617;
public static final int ICE_STEIN = 1618;
public static final int MUNCHIES_PILL = 1619;
public static final int HOMEOPATHIC = 1620;
public static final int ASTRAL_MUSHROOM = 1622;
public static final int BADGER_BADGE = 1623;
public static final int BLUE_CUPCAKE = 1624;
public static final int GREEN_CUPCAKE = 1625;
public static final int ORANGE_CUPCAKE = 1626;
public static final int PURPLE_CUPCAKE = 1627;
public static final int PINK_CUPCAKE = 1628;
public static final int SPANISH_FLY = 1633;
public static final int BRICK = 1649;
public static final int MILK_OF_MAGNESIUM = 1650;
public static final int JEWEL_EYED_WIZARD_HAT = 1653;
public static final int CITADEL_SATCHEL = 1656;
public static final int CHERRY_CLOACA_COLA = 1658;
public static final int FRAUDWORT = 1670;
public static final int SHYSTERWEED = 1671;
public static final int SWINDLEBLOSSOM = 1672;
public static final int CARDBOARD_ORE = 1675;
public static final int STYROFOAM_ORE = 1676;
public static final int BUBBLEWRAP_ORE = 1677;
public static final int GROUCHO_DISGUISE = 1678;
public static final int EXPRESS_CARD = 1687;
public static final int MUCULENT_MACHETE = 1721;
public static final int SWORD_PREPOSITIONS = 1734;
public static final int GOULAUNCHER = 1748;
public static final int GALLERY_KEY = 1765;
public static final int BALLROOM_KEY = 1766;
public static final int PACK_OF_CHEWING_GUM = 1767;
public static final int TRAVOLTAN_TROUSERS = 1792;
public static final int POOL_CUE = 1793;
public static final int HAND_CHALK = 1794;
public static final int DUSTY_ANIMAL_SKULL = 1799;
public static final int ONE_BALL = 1900;
public static final int TWO_BALL = 1901;
public static final int FIVE_BALL = 1904;
public static final int SIX_BALL = 1905;
public static final int SEVEN_BALL = 1906;
public static final int EIGHT_BALL = 1907;
public static final int SPOOKYRAVEN_SPECTACLES = 1916;
public static final int ENGLISH_TO_A_F_U_E_DICTIONARY = 1919;
public static final int BIZARRE_ILLEGIBLE_SHEET_MUSIC = 1920;
public static final int TOILET_PAPER = 1923;
public static final int TATTERED_WOLF_STANDARD = 1924;
public static final int TATTERED_SNAKE_STANDARD = 1925;
public static final int TUNING_FORK = 1928;
public static final int ANTIQUE_GREAVES = 1929;
public static final int ANTIQUE_HELMET = 1930;
public static final int ANTIQUE_SPEAR = 1931;
public static final int ANTIQUE_SHIELD = 1932;
public static final int CHINTZY_SEAL_PENDANT = 1941;
public static final int CHINTZY_TURTLE_BROOCH = 1942;
public static final int CHINTZY_NOODLE_RING = 1943;
public static final int CHINTZY_SAUCEPAN_EARRING = 1944;
public static final int CHINTZY_DISCO_BALL_PENDANT = 1945;
public static final int CHINTZY_ACCORDION_PIN = 1946;
public static final int MANETWICH = 1949;
public static final int VANGOGHBITUSSIN = 1950;
public static final int PINOT_RENOIR = 1951;
public static final int FLAT_CHAMPAGNE = 1953;
public static final int QUILL_PEN = 1957;
public static final int INKWELL = 1958;
public static final int SCRAP_OF_PAPER = 1959;
public static final int EVIL_SCROLL = 1960;
public static final int DANCE_CARD = 1963;
public static final int OPERA_MASK = 1964;
public static final int PUMPKIN_BUCKET = 1971;
public static final int SILVER_SHRIMP_FORK = 1972;
public static final int STUFFED_COCOABO = 1974;
public static final int RUBBER_WWTNSD_BRACELET = 1994;
public static final int SPADE_NECKLACE = 2017;
public static final int HIPPY_PROTEST_BUTTON = 2029;
public static final int WICKER_SHIELD = 2034;
public static final int PATCHOULI_OIL_BOMB = 2040;
public static final int EXPLODING_HACKY_SACK = 2042;
public static final int MACGUFFIN_DIARY = 2044;
public static final int BROKEN_WINGS = 2050;
public static final int SUNKEN_EYES = 2051;
public static final int REASSEMBLED_BLACKBIRD = 2052;
public static final int BLACKBERRY = 2063;
public static final int FORGED_ID_DOCUMENTS = 2064;
public static final int PADL_PHONE = 2065;
public static final int TEQUILA_GRENADE = 2068;
public static final int BEER_HELMET = 2069;
public static final int DISTRESSED_DENIM_PANTS = 2070;
public static final int NOVELTY_BUTTON = 2072;
public static final int MAKESHIFT_TURBAN = 2079;
public static final int MAKESHIFT_CAPE = 2080;
public static final int MAKESHIFT_SKIRT = 2081;
public static final int MAKESHIFT_CRANE = 2083;
public static final int CAN_OF_STARCH = 2084;
public static final int ANTIQUE_HAND_MIRROR = 2092;
public static final int TOWEL = 2095;
public static final int GMOB_POLLEN = 2096;
public static final int SEVENTEEN_BALL = 2097;
public static final int LUCRE = 2098;
public static final int ASCII_SHIRT = 2121;
public static final int TOY_MERCENARY = 2139;
public static final int EVIL_TEDDY_SEWING_KIT = 2147;
public static final int TRIANGULAR_STONE = 2173;
public static final int ANCIENT_AMULET = 2180;
public static final int HAROLDS_HAMMER_HEAD = 2182;
public static final int HAROLDS_HAMMER = 2184;
public static final int UNLIT_BIRTHDAY_CAKE = 2186;
public static final int LIT_BIRTHDAY_CAKE = 2187;
public static final int ANCIENT_CAROLS = 2191;
public static final int SHEET_MUSIC = 2192;
public static final int FANCY_EVIL_CHOCOLATE = 2197;
public static final int CRIMBO_UKELELE = 2209;
public static final int LIARS_PANTS = 2222;
public static final int JUGGLERS_BALLS = 2223;
public static final int PINK_SHIRT = 2224;
public static final int FAMILIAR_DOPPELGANGER = 2225;
public static final int EYEBALL_PENDANT = 2226;
public static final int CALAVERA_CONCERTINA = 2234;
public static final int TURTLE_PHEROMONES = 2236;
public static final int PHOTOGRAPH_OF_GOD = 2259;
public static final int WET_STUNT_NUT_STEW = 2266;
public static final int MEGA_GEM = 2267;
public static final int STAFF_OF_FATS = 2268;
public static final int DUSTY_BOTTLE_OF_MERLOT = 2271;
public static final int DUSTY_BOTTLE_OF_PORT = 2272;
public static final int DUSTY_BOTTLE_OF_PINOT_NOIR = 2273;
public static final int DUSTY_BOTTLE_OF_ZINFANDEL = 2274;
public static final int DUSTY_BOTTLE_OF_MARSALA = 2275;
public static final int DUSTY_BOTTLE_OF_MUSCAT = 2276;
public static final int FERNSWARTHYS_KEY = 2277;
public static final int DUSTY_BOOK = 2279;
public static final int MUS_MANUAL = 2280;
public static final int MYS_MANUAL = 2281;
public static final int MOX_MANUAL = 2282;
public static final int SEAL_HELMET = 2283;
public static final int PETRIFIED_NOODLES = 2284;
public static final int CHISEL = 2285;
public static final int EYE_OF_ED = 2286;
public static final int RED_PAPER_CLIP = 2289;
public static final int REALLY_BIG_TINY_HOUSE = 2290;
public static final int NONESSENTIAL_AMULET = 2291;
public static final int WHITE_WINE_VINAIGRETTE = 2292;
public static final int CUP_OF_STRONG_TEA = 2293;
public static final int CURIOUSLY_SHINY_AX = 2294;
public static final int MARINATED_STAKES = 2295;
public static final int KNOB_BUTTER = 2296;
public static final int VIAL_OF_ECTOPLASM = 2297;
public static final int BOOCK_OF_MAGIKS = 2298;
public static final int EZ_PLAY_HARMONICA_BOOK = 2299;
public static final int FINGERLESS_HOBO_GLOVES = 2300;
public static final int CHOMSKYS_COMICS = 2301;
public static final int WORM_RIDING_HOOKS = 2302;
public static final int CANDY_BOOK = 2303;
public static final int GREEN_CANDY = 2309;
public static final int ANCIENT_BRONZE_TOKEN = 2317;
public static final int ANCIENT_BOMB = 2318;
public static final int CARVED_WOODEN_WHEEL = 2319;
public static final int WORM_RIDING_MANUAL_PAGE = 2320;
public static final int HEADPIECE_OF_ED = 2323;
public static final int STAFF_OF_ED = 2325;
public static final int STONE_ROSE = 2326;
public static final int BLACK_PAINT = 2327;
public static final int DRUM_MACHINE = 2328;
public static final int CONFETTI = 2329;
public static final int CHOCOLATE_COVERED_DIAMOND_STUDDED_ROSES = 2330;
public static final int BOUQUET_OF_CIRCULAR_SAW_BLADES = 2331;
public static final int BETTER_THAN_CUDDLING_CAKE = 2332;
public static final int STUFFED_NINJA_SNOWMAN = 2333;
public static final int HOLY_MACGUFFIN = 2334;
public static final int REINFORCED_BEADED_HEADBAND = 2337;
public static final int BLACK_PUDDING = 2338;
public static final int BLACKFLY_CHARDONNAY = 2339;
public static final int BLACK_TAN = 2340;
public static final int FILTHWORM_HATCHLING_GLAND = 2344;
public static final int FILTHWORM_DRONE_GLAND = 2345;
public static final int FILTHWORM_GUARD_GLAND = 2346;
public static final int FILTHWORM_QUEEN_HEART = 2347;
public static final int BEJEWELED_PLEDGE_PIN = 2353;
public static final int COMMUNICATIONS_WINDCHIMES = 2354;
public static final int ZIM_MERMANS_GUITAR = 2364;
public static final int FILTHY_POULTICE = 2369;
public static final int BOTTLE_OPENER_BELT_BUCKLE = 2385;
public static final int MOLOTOV_COCKTAIL_COCKTAIL = 2400;
public static final int GAUZE_GARTER = 2402;
public static final int GUNPOWDER = 2403;
public static final int JAM_BAND_FLYERS = 2404;
public static final int ROCK_BAND_FLYERS = 2405;
public static final int RHINO_HORMONES = 2419;
public static final int MAGIC_SCROLL = 2420;
public static final int PIRATE_JUICE = 2421;
public static final int PET_SNACKS = 2422;
public static final int INHALER = 2423;
public static final int CYCLOPS_EYEDROPS = 2424;
public static final int SPINACH = 2425;
public static final int FIRE_FLOWER = 2426;
public static final int ICE_CUBE = 2427;
public static final int FAKE_BLOOD = 2428;
public static final int GUANEAU = 2429;
public static final int LARD = 2430;
public static final int MYSTIC_SHELL = 2431;
public static final int LIP_BALM = 2432;
public static final int ANTIFREEZE = 2433;
public static final int BLACK_EYEDROPS = 2434;
public static final int DOGSGOTNONOZ = 2435;
public static final int FLIPBOOK = 2436;
public static final int NEW_CLOACA_COLA = 2437;
public static final int MASSAGE_OIL = 2438;
public static final int POLTERGEIST = 2439;
public static final int ENCRYPTION_KEY = 2441;
public static final int COBBS_KNOB_MAP = 2442;
public static final int SUPERNOVA_CHAMPAGNE = 2444;
public static final int GOATSKIN_UMBRELLA = 2451;
public static final int BAR_WHIP = 2455;
public static final int ODOR_EXTRACTOR = 2462;
public static final int OLFACTION_BOOK = 2463;
public static final int OREILLE_DIVISEE_BRANDY = 2465;
public static final int TUXEDO_SHIRT = 2489;
public static final int SHIRT_KIT = 2491;
public static final int TROPICAL_ORCHID = 2492;
public static final int MOLYBDENUM_MAGNET = 2497;
public static final int MOLYBDENUM_HAMMER = 2498;
public static final int MOLYBDENUM_SCREWDRIVER = 2499;
public static final int MOLYBDENUM_PLIERS = 2500;
public static final int MOLYBDENUM_WRENCH = 2501;
public static final int JEWELRY_BOOK = 2502;
public static final int WOVEN_BALING_WIRE_BRACELETS = 2514;
public static final int CRUELTY_FREE_WINE = 2521;
public static final int THISTLE_WINE = 2522;
public static final int FISHY_FISH_LASAGNA = 2527;
public static final int GNAT_LASAGNA = 2531;
public static final int LONG_PORK_LASAGNA = 2535;
public static final int TOMB_RATCHET = 2540;
public static final int MAYFLOWER_BOUQUET = 2541;
public static final int LESSER_GRODULATED_VIOLET = 2542;
public static final int TIN_MAGNOLIA = 2543;
public static final int BEGPWNIA = 2544;
public static final int UPSY_DAISY = 2545;
public static final int HALF_ORCHID = 2546;
public static final int OUTRAGEOUS_SOMBRERO = 2548;
public static final int PEPPERCORNS_OF_POWER = 2550;
public static final int VIAL_OF_MOJO = 2551;
public static final int GOLDEN_REEDS = 2552;
public static final int TURTLE_CHAIN = 2553;
public static final int DISTILLED_SEAL_BLOOD = 2554;
public static final int HIGH_OCTANE_OLIVE_OIL = 2555;
public static final int SHAGADELIC_DISCO_BANJO = 2556;
public static final int SQUEEZEBOX_OF_THE_AGES = 2557;
public static final int CHELONIAN_MORNINGSTAR = 2558;
public static final int HAMMER_OF_SMITING = 2559;
public static final int SEVENTEEN_ALARM_SAUCEPAN = 2560;
public static final int GREEK_PASTA_OF_PERIL = 2561;
public static final int AZAZELS_UNICORN = 2566;
public static final int AZAZELS_LOLLIPOP = 2567;
public static final int AZAZELS_TUTU = 2568;
public static final int ANT_HOE = 2570;
public static final int ANT_RAKE = 2571;
public static final int ANT_PITCHFORK = 2572;
public static final int ANT_SICKLE = 2573;
public static final int ANT_PICK = 2574;
public static final int HANDFUL_OF_SAND = 2581;
public static final int SAND_BRICK = 2582;
public static final int TASTY_TART = 2591;
public static final int LUNCHBOX = 2592;
public static final int KNOB_PASTY = 2593;
public static final int KNOB_COFFEE = 2594;
public static final int TELESCOPE = 2599;
public static final int TUESDAYS_RUBY = 2604;
public static final int PALM_FROND = 2605;
public static final int PALM_FROND_FAN = 2606;
public static final int MOJO_FILTER = 2614;
public static final int WEAVING_MANUAL = 2630;
public static final int PAT_A_CAKE_PENDANT = 2633;
public static final int MUMMY_WRAP = 2634;
public static final int GAUZE_HAMMOCK = 2638;
public static final int MAXWELL_HAMMER = 2642;
public static final int ABSINTHE = 2655;
public static final int BOTTLE_OF_REALPAGNE = 2658;
public static final int SPIKY_COLLAR = 2667;
public static final int LIBRARY_CARD = 2672;
public static final int SPECTRE_SCEPTER = 2678;
public static final int SPARKLER = 2679;
public static final int SNAKE = 2680;
public static final int M282 = 2681;
public static final int DETUNED_RADIO = 2682;
public static final int GIFTW = 2683;
public static final int MASSIVE_SITAR = 2693;
public static final int DUCT_TAPE = 2697;
public static final int SHRINKING_POWDER = 2704;
public static final int PARROT_CRACKER = 2710;
public static final int SPARE_KIDNEY = 2718;
public static final int HAND_CARVED_BOKKEN = 2719;
public static final int HAND_CARVED_BOW = 2720;
public static final int HAND_CARVED_STAFF = 2721;
public static final int JUNIPER_BERRIES = 2726;
public static final int PLUM_WINE = 2730;
public static final int BUNCH_OF_SQUARE_GRAPES = 2733;
public static final int STEEL_STOMACH = 2742;
public static final int STEEL_LIVER = 2743;
public static final int STEEL_SPLEEN = 2744;
public static final int HAROLDS_BELL = 2765;
public static final int GOLD_BOWLING_BALL = 2766;
public static final int SOLID_BACONSTONE_EARRING = 2780;
public static final int BRIMSTONE_BERET = 2813;
public static final int BRIMSTONE_BUNKER = 2815;
public static final int BRIMSTONE_BRACELET = 2818;
public static final int GRIMACITE_GASMASK = 2819;
public static final int GRIMACITE_GAT = 2820;
public static final int GRIMACITE_GAITERS = 2821;
public static final int GRIMACITE_GAUNTLETS = 2822;
public static final int GRIMACITE_GO_GO_BOOTS = 2823;
public static final int GRIMACITE_GIRDLE = 2824;
public static final int GRIMACITE_GOWN = 2825;
public static final int REALLY_DENSE_MEAT_STACK = 2829;
public static final int BOTTLE_ROCKET = 2834;
public static final int COOKING_SHERRY = 2840;
public static final int NAVEL_RING = 2844;
public static final int PLASTIC_BIB = 2846;
public static final int GNOME_DEMODULIZER = 2848;
public static final int GREAT_TREE_BRANCH = 2852;
public static final int PHIL_BUNION_AXE = 2853;
public static final int SWAMP_ROSE_BOUQUET = 2854;
public static final int PARTY_HAT = 2945;
public static final int V_MASK = 2946;
public static final int PIRATE_INSULT_BOOK = 2947;
public static final int CARONCH_MAP = 2950;
public static final int FRATHOUSE_BLUEPRINTS = 2951;
public static final int CHARRRM_BRACELET = 2953;
public static final int COCKTAIL_NAPKIN = 2956;
public static final int RUM_CHARRRM = 2957;
public static final int RUM_BRACELET = 2959;
public static final int RIGGING_SHAMPOO = 2963;
public static final int BALL_POLISH = 2964;
public static final int MIZZENMAST_MOP = 2965;
public static final int GRUMPY_CHARRRM = 2972;
public static final int GRUMPY_BRACELET = 2973;
public static final int TARRRNISH_CHARRRM = 2974;
public static final int TARRRNISH_BRACELET = 2975;
public static final int BILGE_WINE = 2976;
public static final int BOOTY_CHARRRM = 2980;
public static final int BOOTY_BRACELET = 2981;
public static final int CANNONBALL_CHARRRM = 2982;
public static final int CANNONBALL_BRACELET = 2983;
public static final int COPPER_CHARRRM = 2984;
public static final int COPPER_BRACELET = 2985;
public static final int TONGUE_CHARRRM = 2986;
public static final int TONGUE_BRACELET = 2987;
public static final int CLINGFILM = 2988;
public static final int CARONCH_NASTY_BOOTY = 2999;
public static final int CARONCH_DENTURES = 3000;
public static final int IDOL_AKGYXOTH = 3009;
public static final int EMBLEM_AKGYXOTH = 3010;
public static final int SIMPLE_CURSED_KEY = 3013;
public static final int ORNATE_CURSED_KEY = 3014;
public static final int GILDED_CURSED_KEY = 3015;
public static final int ANCIENT_CURSED_FOOTLOCKER = 3016;
public static final int ORNATE_CURSED_CHEST = 3017;
public static final int GILDED_CURSED_CHEST = 3018;
public static final int PIRATE_FLEDGES = 3033;
public static final int CURSED_PIECE_OF_THIRTEEN = 3034;
public static final int FOIL_BOW = 3043;
public static final int FOIL_RADAR = 3044;
public static final int POWER_SPHERE = 3049;
public static final int FOIL_CAT_EARS = 3056;
public static final int LASER_CANON = 3069;
public static final int CHIN_STRAP = 3070;
public static final int GLUTEAL_SHIELD = 3071;
public static final int CARBONITE_VISOR = 3072;
public static final int UNOBTAINIUM_STRAPS = 3073;
public static final int FASTENING_APPARATUS = 3074;
public static final int GENERAL_ASSEMBLY_MODULE = 3075;
public static final int LASER_TARGETING_CHIP = 3076;
public static final int LEG_ARMOR = 3077;
public static final int KEVLATEFLOCITE_HELMET = 3078;
public static final int TEDDY_BORG_SEWING_KIT = 3087;
public static final int VITACHOC_CAPSULE = 3091;
public static final int HOBBY_HORSE = 3092;
public static final int BALL_IN_A_CUP = 3093;
public static final int SET_OF_JACKS = 3094;
public static final int FISH_SCALER = 3097;
public static final int MINIBORG_STOMPER = 3109;
public static final int MINIBORG_STRANGLER = 3110;
public static final int MINIBORG_LASER = 3111;
public static final int MINIBORG_BEEPER = 3112;
public static final int MINIBORG_HIVEMINDER = 3113;
public static final int MINIBORG_DESTROYOBOT = 3114;
public static final int DIVINE_BOOK = 3117;
public static final int DIVINE_NOISEMAKER = 3118;
public static final int DIVINE_SILLY_STRING = 3119;
public static final int DIVINE_BLOWOUT = 3120;
public static final int DIVINE_CHAMPAGNE_POPPER = 3121;
public static final int DIVINE_CRACKER = 3122;
public static final int DIVINE_FLUTE = 3123;
public static final int HOBO_NICKEL = 3126;
public static final int SANDCASTLE = 3127;
public static final int MARSHMALLOW = 3128;
public static final int ROASTED_MARSHMALLOW = 3129;
public static final int TORN_PAPER_STRIP = 3144;
public static final int PUNCHCARD_ATTACK = 3146;
public static final int PUNCHCARD_REPAIR = 3147;
public static final int PUNCHCARD_BUFF = 3148;
public static final int PUNCHCARD_MODIFY = 3149;
public static final int PUNCHCARD_BUILD = 3150;
public static final int PUNCHCARD_TARGET = 3151;
public static final int PUNCHCARD_SELF = 3152;
public static final int PUNCHCARD_FLOOR = 3153;
public static final int PUNCHCARD_DRONE = 3154;
public static final int PUNCHCARD_WALL = 3155;
public static final int PUNCHCARD_SPHERE = 3156;
public static final int DRONE = 3157;
public static final int EL_VIBRATO_HELMET = 3162;
public static final int EL_VIBRATO_SPEAR = 3163;
public static final int EL_VIBRATO_PANTS = 3164;
public static final int BROKEN_DRONE = 3165;
public static final int REPAIRED_DRONE = 3166;
public static final int AUGMENTED_DRONE = 3167;
public static final int FORTUNE_TELLER = 3193;
public static final int ORIGAMI_MAGAZINE = 3194;
public static final int PAPER_SHURIKEN = 3195;
public static final int ORIGAMI_PASTIES = 3196;
public static final int RIDING_CROP = 3197;
public static final int TRAPEZOID = 3198;
public static final int LUMP_OF_COAL = 3199;
public static final int THICK_PADDED_ENVELOPE = 3201;
public static final int DWARVISH_WAR_HELMET = 3204;
public static final int DWARVISH_WAR_MATTOCK = 3205;
public static final int DWARVISH_WAR_KILT = 3206;
public static final int DWARVISH_PUNCHCARD = 3207;
public static final int SMALL_LAMINATED_CARD = 3208;
public static final int LITTLE_LAMINATED_CARD = 3209;
public static final int NOTBIG_LAMINATED_CARD = 3210;
public static final int UNLARGE_LAMINATED_CARD = 3211;
public static final int DWARVISH_DOCUMENT = 3212;
public static final int DWARVISH_PAPER = 3213;
public static final int DWARVISH_PARCHMENT = 3214;
public static final int OVERCHARGED_POWER_SPHERE = 3215;
public static final int HOBO_CODE_BINDER = 3220;
public static final int GATORSKIN_UMBRELLA = 3222;
public static final int SEWER_WAD = 3224;
public static final int OOZE_O = 3226;
public static final int DUMPLINGS = 3228;
public static final int OIL_OF_OILINESS = 3230;
public static final int TATTERED_PAPER_CROWN = 3231;
public static final int INFLATABLE_DUCK = 3233;
public static final int WATER_WINGS = 3234;
public static final int FOAM_NOODLE = 3235;
public static final int KISSIN_COUSINS = 3236;
public static final int TALES_FROM_THE_FIRESIDE = 3237;
public static final int BLIZZARDS_I_HAVE_DIED_IN = 3238;
public static final int MAXING_RELAXING = 3239;
public static final int BIDDY_CRACKERS_COOKBOOK = 3240;
public static final int TRAVELS_WITH_JERRY = 3241;
public static final int LET_ME_BE = 3242;
public static final int ASLEEP_IN_THE_CEMETERY = 3243;
public static final int SUMMER_NIGHTS = 3244;
public static final int SENSUAL_MASSAGE_FOR_CREEPS = 3245;
public static final int BAG_OF_CANDY = 3261;
public static final int TASTEFUL_BOOK = 3263;
public static final int LITTLE_ROUND_PEBBLE = 3464;
public static final int CROTCHETY_PANTS = 3271;
public static final int SACCHARINE_MAPLE_PENDANT = 3272;
public static final int WILLOWY_BONNET = 3273;
public static final int BLACK_BLUE_LIGHT = 3276;
public static final int LOUDMOUTH_LARRY = 3277;
public static final int CHEAP_STUDDED_BELT = 3278;
public static final int PERSONAL_MASSAGER = 3279;
public static final int PLASMA_BALL = 3281;
public static final int STICK_ON_EYEBROW_PIERCING = 3282;
public static final int MACARONI_FRAGMENTS = 3287;
public static final int SHIMMERING_TENDRILS = 3288;
public static final int SCINTILLATING_POWDER = 3289;
public static final int VOLCANO_MAP = 3291;
public static final int PRETTY_PINK_BOW = 3298;
public static final int SMILEY_FACE_STICKER = 3299;
public static final int FARFALLE_BOW_TIE = 3300;
public static final int JALAPENO_SLICES = 3301;
public static final int SOLAR_PANELS = 3302;
public static final int TINY_SOMBRERO = 3303;
public static final int EPIC_WAD = 3316;
public static final int MAYFLY_BAIT_NECKLACE = 3322;
public static final int SCRATCHS_FORK = 3323;
public static final int FROSTYS_MUG = 3324;
public static final int FERMENTED_PICKLE_JUICE = 3325;
public static final int EXTRA_GREASY_SLIDER = 3327;
public static final int CRUMPLED_FELT_FEDORA = 3328;
public static final int DOUBLE_SIDED_TAPE = 3336;
public static final int HOT_BEDDING = 3344; // bed of coals
public static final int COLD_BEDDING = 3345; // frigid air mattress
public static final int STENCH_BEDDING = 3346; // filth-encrusted futon
public static final int SPOOKY_BEDDING = 3347; // comfy coffin
public static final int SLEAZE_BEDDING = 3348; // stained mattress
public static final int ZEN_MOTORCYCLE = 3352;
public static final int GONG = 3353;
public static final int GRUB = 3356;
public static final int MOTH = 3357;
public static final int FIRE_ANT = 3358;
public static final int ICE_ANT = 3359;
public static final int STINKBUG = 3360;
public static final int DEATH_WATCH_BEETLE = 3361;
public static final int LOUSE = 3362;
public static final int INTERESTING_TWIG = 3367;
public static final int TWIG_HOUSE = 3374;
public static final int RICHIE_THINGFINDER = 3375;
public static final int MEDLEY_OF_DIVERSITY = 3376;
public static final int EXPLOSIVE_ETUDE = 3377;
public static final int CHORALE_OF_COMPANIONSHIP = 3378;
public static final int PRELUDE_OF_PRECISION = 3379;
public static final int CHESTER_GLASSES = 3383;
public static final int EMPTY_EYE = 3388;
public static final int ICEBALL = 3391;
public static final int NEVERENDING_SODA = 3393;
public static final int HODGMANS_PORKPIE_HAT = 3395;
public static final int HODGMANS_LOBSTERSKIN_PANTS = 3396;
public static final int HODGMANS_BOW_TIE = 3397;
public static final int SQUEEZE = 3399;
public static final int FISHYSOISSE = 3400;
public static final int LAMP_SHADE = 3401;
public static final int GARBAGE_JUICE = 3402;
public static final int LEWD_CARD = 3403;
public static final int HODGMAN_JOURNAL_1 = 3412;
public static final int HODGMAN_JOURNAL_2 = 3413;
public static final int HODGMAN_JOURNAL_3 = 3414;
public static final int HODGMAN_JOURNAL_4 = 3415;
public static final int HOBO_FORTRESS = 3416;
public static final int FIREWORKS = 3421;
public static final int GIFTH = 3430;
public static final int SPICE_MELANGE = 3433;
public static final int RAINBOWS_GRAVITY = 3439;
public static final int COTTON_CANDY_CONDE = 3449;
public static final int COTTON_CANDY_PINCH = 3450;
public static final int COTTON_CANDY_SMIDGEN = 3451;
public static final int COTTON_CANDY_SKOSHE = 3452;
public static final int COTTON_CANDY_PLUG = 3453;
public static final int COTTON_CANDY_PILLOW = 3454;
public static final int COTTON_CANDY_BALE = 3455;
public static final int STYX_SPRAY = 3458;
public static final int BASH_OS_CEREAL = 3465;
public static final int HAIKU_KATANA = 3466;
public static final int BATHYSPHERE = 3470;
public static final int DAMP_OLD_BOOT = 3471;
public static final int BOXTOP = 3473;
public static final int DULL_FISH_SCALE = 3486;
public static final int ROUGH_FISH_SCALE = 3487;
public static final int PRISTINE_FISH_SCALE = 3488;
public static final int FISH_SCIMITAR = 3492;
public static final int FISH_STICK = 3493;
public static final int FISH_BAZOOKA = 3494;
public static final int SEA_SALT_CRYSTAL = 3495;
public static final int LARP_MEMBERSHIP_CARD = 3506;
public static final int STICKER_BOOK = 3507;
public static final int STICKER_SWORD = 3508;
public static final int UNICORN_STICKER = 3509;
public static final int APPLE_STICKER = 3510;
public static final int UPC_STICKER = 3511;
public static final int WRESTLER_STICKER = 3512;
public static final int DRAGON_STICKER = 3513;
public static final int ROCK_BAND_STICKER = 3514;
public static final int EELSKIN_HAT = 3517;
public static final int EELSKIN_PANTS = 3518;
public static final int EELSKIN_SHIELD = 3519;
public static final int STICKER_CROSSBOW = 3526;
public static final int PLANS_FOR_GRIMACITE_HAMMER = 3535;
public static final int PLANS_FOR_GRIMACITE_GRAVY_BOAT = 3536;
public static final int PLANS_FOR_GRIMACITE_WEIGHTLIFTING_BELT = 3537;
public static final int PLANS_FOR_GRIMACITE_GRAPPLING_HOOK = 3538;
public static final int PLANS_FOR_GRIMACITE_NINJA_MASK = 3539;
public static final int PLANS_FOR_GRIMACITE_SHINGUARDS = 3540;
public static final int PLANS_FOR_GRIMACITE_ASTROLABE = 3541;
public static final int GRIMACITE_HAMMER = 3542;
public static final int GRIMACITE_GRAVY_BOAT = 3543;
public static final int GRIMACITE_WEIGHTLIFTING_BELT = 3544;
public static final int GRIMACITE_GRAPPLING_HOOK = 3545;
public static final int GRIMACITE_NINJA_MASK = 3546;
public static final int GRIMACITE_SHINGUARDS = 3547;
public static final int GRIMACITE_ASTROLABE = 3548;
public static final int SEED_PACKET = 3553;
public static final int GREEN_SLIME = 3554;
public static final int SEA_CARROT = 3555;
public static final int SEA_CUCUMBER = 3556;
public static final int SEA_AVOCADO = 3557;
public static final int POTION_OF_PUISSANCE = 3561;
public static final int POTION_OF_PERSPICACITY = 3562;
public static final int POTION_OF_PULCHRITUDE = 3563;
public static final int SPONGE_HELMET = 3568;
public static final int SAND_DOLLAR = 3575;
public static final int BEZOAR_RING = 3577;
public static final int WRIGGLING_FLYTRAP_PELLET = 3580;
public static final int SUSHI_ROLLING_MAT = 3581;
public static final int WHITE_RICE = 3582;
public static final int RUSTY_BROKEN_DIVING_HELMET = 3602;
public static final int BUBBLIN_STONE = 3605;
public static final int AERATED_DIVING_HELMET = 3607;
public static final int DAS_BOOT = 3609;
public static final int IMITATION_WHETSTONE = 3610;
public static final int PARASITIC_CLAW = 3624;
public static final int PARASITIC_TENTACLES = 3625;
public static final int PARASITIC_HEADGNAWER = 3626;
public static final int PARASITIC_STRANGLEWORM = 3627;
public static final int BURROWGRUB_HIVE = 3629;
public static final int JAMFISH_JAM = 3641;
public static final int DRAGONFISH_CAVIAR = 3642;
public static final int GRIMACITE_KNEECAPPING_STICK = 3644;
public static final int CANTEEN_OF_WINE = 3645;
public static final int MADNESS_REEF_MAP = 3649;
public static final int MINIATURE_ANTLERS = 3651;
public static final int SPOOKY_PUTTY_MITRE = 3662;
public static final int SPOOKY_PUTTY_LEOTARD = 3663;
public static final int SPOOKY_PUTTY_BALL = 3664;
public static final int SPOOKY_PUTTY_SHEET = 3665;
public static final int SPOOKY_PUTTY_SNAKE = 3666;
public static final int SPOOKY_PUTTY_MONSTER = 3667;
public static final int RAGE_GLAND = 3674;
public static final int MERKIN_PRESSUREGLOBE = 3675;
public static final int GLOWING_ESCA = 3680;
public static final int MARINARA_TRENCH_MAP = 3683;
public static final int TEMPURA_CARROT = 3684;
public static final int TEMPURA_CUCUMBER = 3685;
public static final int TEMPURA_AVOCADO = 3686;
public static final int TEMPURA_BROCCOLI = 3689;
public static final int TEMPURA_CAULIFLOWER = 3690;
public static final int POTION_OF_PERCEPTION = 3693;
public static final int POTION_OF_PROFICIENCY = 3694;
public static final int VELCRO_ORE = 3698;
public static final int TEFLON_ORE = 3699;
public static final int VINYL_ORE = 3700;
public static final int ANEMONE_MINE_MAP = 3701;
public static final int VINYL_BOOTS = 3716;
public static final int GNOLL_EYE = 3731;
public static final int CHEAP_CIGAR_BUTT = 3732;
public static final int BOOZEHOUND_TOKEN = 3739;
public static final int UNSTABLE_QUARK = 3743;
public static final int FUMBLE_FORMULA = 3745;
public static final int MOTHERS_SECRET_RECIPE = 3747;
public static final int LOVE_BOOK = 3753;
public static final int VAGUE_AMBIGUITY = 3754;
public static final int SMOLDERING_PASSION = 3755;
public static final int ICY_REVENGE = 3756;
public static final int SUGARY_CUTENESS = 3757;
public static final int DISTURBING_OBSESSION = 3758;
public static final int NAUGHTY_INNUENDO = 3759;
public static final int DIVE_BAR_MAP = 3774;
public static final int MERKIN_PINKSLIP = 3775;
public static final int PARANORMAL_RICOTTA = 3784;
public static final int SMOKING_TALON = 3785;
public static final int VAMPIRE_GLITTER = 3786;
public static final int WINE_SOAKED_BONE_CHIPS = 3787;
public static final int CRUMBLING_RAT_SKULL = 3788;
public static final int TWITCHING_TRIGGER_FINGER = 3789;
public static final int AQUAVIOLET_JUBJUB_BIRD = 3800;
public static final int CRIMSILION_JUBJUB_BIRD = 3801;
public static final int CHARPUCE_JUBJUB_BIRD = 3802;
public static final int MERKIN_TRAILMAP = 3808;
public static final int MERKIN_LOCKKEY = 3810;
public static final int MERKIN_STASHBOX = 3811;
public static final int SEA_RADISH = 3817;
public static final int EEL_SAUCE = 3819;
public static final int FISHY_WAND = 3822;
public static final int GRANDMAS_NOTE = 3824;
public static final int FUCHSIA_YARN = 3825;
public static final int CHARTREUSE_YARN = 3826;
public static final int GRANDMAS_MAP = 3828;
public static final int TEMPURA_RADISH = 3829;
public static final int TINY_COSTUME_WARDROBE = 3835;
public static final int ELVISH_SUNGLASSES = 3836;
public static final int OOT_BIWA = 3842;
public static final int JUNGLE_DRUM = 3846;
public static final int HIPPY_BONGO = 3847;
public static final int GUITAR_4D = 3849;
public static final int HALF_GUITAR = 3852;
public static final int BASS_DRUM = 3853;
public static final int SMALLEST_VIOLIN = 3855;
public static final int BONE_FLUTE = 3858;
public static final int PLASTIC_GUITAR = 3863;
public static final int FINGER_CYMBALS = 3864;
public static final int KETTLE_DRUM = 3865;
public static final int HELLSEAL_HIDE = 3874;
public static final int HELLSEAL_BRAIN = 3876;
public static final int HELLSEAL_SINEW = 3878;
public static final int HELLSEAL_DISGUISE = 3880;
public static final int FOUET_DE_TORTUE_DRESSAGE = 3881;
public static final int CULT_MEMO = 3883;
public static final int DECODED_CULT_DOCUMENTS = 3884;
public static final int FIRST_SLIME_VIAL = 3885;
public static final int VIAL_OF_RED_SLIME = 3885;
public static final int VIAL_OF_YELLOW_SLIME = 3886;
public static final int VIAL_OF_BLUE_SLIME = 3887;
public static final int VIAL_OF_ORANGE_SLIME = 3888;
public static final int VIAL_OF_GREEN_SLIME = 3889;
public static final int VIAL_OF_VIOLET_SLIME = 3890;
public static final int VIAL_OF_VERMILION_SLIME = 3891;
public static final int VIAL_OF_AMBER_SLIME = 3892;
public static final int VIAL_OF_CHARTREUSE_SLIME = 3893;
public static final int VIAL_OF_TEAL_SLIME = 3894;
public static final int VIAL_OF_INDIGO_SLIME = 3895;
public static final int VIAL_OF_PURPLE_SLIME = 3896;
public static final int LAST_SLIME_VIAL = 3897;
public static final int VIAL_OF_BROWN_SLIME = 3897;
public static final int BOTTLE_OF_GU_GONE = 3898;
public static final int SEAL_BLUBBER_CANDLE = 3901;
public static final int WRETCHED_SEAL = 3902;
public static final int CUTE_BABY_SEAL = 3903;
public static final int ARMORED_SEAL = 3904;
public static final int ANCIENT_SEAL = 3905;
public static final int SLEEK_SEAL = 3906;
public static final int SHADOWY_SEAL = 3907;
public static final int STINKING_SEAL = 3908;
public static final int CHARRED_SEAL = 3909;
public static final int COLD_SEAL = 3910;
public static final int SLIPPERY_SEAL = 3911;
public static final int IMBUED_SEAL_BLUBBER_CANDLE = 3912;
public static final int TURTLE_WAX = 3914;
public static final int TURTLEMAIL_BITS = 3919;
public static final int TURTLING_ROD = 3927;
public static final int SEAL_IRON_INGOT = 3932;
public static final int HYPERINFLATED_SEAL_LUNG = 3935;
public static final int VIP_LOUNGE_KEY = 3947;
public static final int STUFFED_CHEST = 3949;
public static final int STUFFED_KEY = 3950;
public static final int STUFFED_BARON = 3951;
public static final int CLAN_POOL_TABLE = 3963;
public static final int TINY_CELL_PHONE = 3964;
public static final int DUELING_BANJO = 3984;
public static final int SAMURAI_TURTLE = 3986;
public static final int SLIME_SOAKED_HYPOPHYSIS = 3991;
public static final int SLIME_SOAKED_BRAIN = 3992;
public static final int SLIME_SOAKED_SWEAT_GLAND = 3993;
public static final int DOLPHIN_WHISTLE = 3997;
public static final int AGUA_DE_VIDA = 4001;
public static final int MOONTAN_LOTION = 4003;
public static final int BALLAST_TURTLE = 4005;
public static final int AMINO_ACIDS = 4006;
public static final int CA_BASE_PAIR = 4011;
public static final int CG_BASE_PAIR = 4012;
public static final int CT_BASE_PAIR = 4013;
public static final int AG_BASE_PAIR = 4014;
public static final int AT_BASE_PAIR = 4015;
public static final int GT_BASE_PAIR = 4016;
public static final int CONTACT_LENSES = 4019;
public static final int GRAPPLING_HOOK = 4029;
public static final int SMALL_STONE_BLOCK = 4030;
public static final int LITTLE_STONE_BLOCK = 4031;
public static final int HALF_STONE_CIRCLE = 4032;
public static final int STONE_HALF_CIRCLE = 4033;
public static final int IRON_KEY = 4034;
public static final int CULTIST_ROBE = 4040;
public static final int WUMPUS_HAIR = 4044;
public static final int RING_OF_TELEPORTATION = 4051;
public static final int INDIGO_PARTY_INVITATION = 4060;
public static final int VIOLET_HUNT_INVITATION = 4061;
public static final int BLUE_MILK_CLUB_CARD = 4062;
public static final int MECHA_MAYHEM_CLUB_CARD = 4063;
public static final int SMUGGLER_SHOT_FIRST_BUTTON = 4064;
public static final int SPACEFLEET_COMMUNICATOR_BADGE = 4065;
public static final int RUBY_ROD = 4066;
public static final int ESSENCE_OF_HEAT = 4067;
public static final int ESSENCE_OF_KINK = 4068;
public static final int ESSENCE_OF_COLD = 4069;
public static final int ESSENCE_OF_STENCH = 4070;
public static final int ESSENCE_OF_FRIGHT = 4071;
public static final int ESSENCE_OF_CUTE = 4072;
public static final int SUPREME_BEING_GLOSSARY = 4073;
public static final int MULTI_PASS = 4074;
public static final int GRISLY_SHIELD = 4080;
public static final int CYBER_MATTOCK = 4086;
public static final int GREEN_PEAWEE_MARBLE = 4095;
public static final int BROWN_CROCK_MARBLE = 4096;
public static final int RED_CHINA_MARBLE = 4097;
public static final int LEMONADE_MARBLE = 4098;
public static final int BUMBLEBEE_MARBLE = 4099;
public static final int JET_BENNIE_MARBLE = 4100;
public static final int BEIGE_CLAMBROTH_MARBLE = 4101;
public static final int STEELY_MARBLE = 4102;
public static final int BEACH_BALL_MARBLE = 4103;
public static final int BLACK_CATSEYE_MARBLE = 4104;
public static final int BIG_BUMBOOZER_MARBLE = 4105;
public static final int MONSTROUS_MONOCLE = 4108;
public static final int MUSTY_MOCCASINS = 4109;
public static final int MOLTEN_MEDALLION = 4110;
public static final int BRAZEN_BRACELET = 4111;
public static final int BITTER_BOWTIE = 4112;
public static final int BEWITCHING_BOOTS = 4113;
public static final int SECRET_FROM_THE_FUTURE = 4114;
public static final int EMPTY_AGUA_DE_VIDA_BOTTLE = 4130;
public static final int TEMPURA_AIR = 4133;
public static final int PRESSURIZED_PNEUMATICITY = 4134;
public static final int MOVEABLE_FEAST = 4135;
public static final int BAG_O_TRICKS = 4136;
public static final int SLIME_STACK = 4137;
public static final int RUMPLED_PAPER_STRIP = 4138;
public static final int CREASED_PAPER_STRIP = 4139;
public static final int FOLDED_PAPER_STRIP = 4140;
public static final int CRINKLED_PAPER_STRIP = 4141;
public static final int CRUMPLED_PAPER_STRIP = 4142;
public static final int RAGGED_PAPER_STRIP = 4143;
public static final int RIPPED_PAPER_STRIP = 4144;
public static final int QUADROCULARS = 4149;
public static final int CAMERA = 4169;
public static final int SHAKING_CAMERA = 4170;
public static final int SPAGHETTI_CULT_ROBE = 4175;
public static final int SUGAR_SHEET = 4176;
public static final int SUGAR_BOOK = 4177;
public static final int SUGAR_SHOTGUN = 4178;
public static final int SUGAR_SHILLELAGH = 4179;
public static final int SUGAR_SHANK = 4180;
public static final int SUGAR_CHAPEAU = 4181;
public static final int SUGAR_SHORTS = 4182;
public static final int SUGAR_SHIELD = 4183;
public static final int SUGAR_SHIRT = 4191;
public static final int SUGAR_SHARD = 4192;
public static final int RAVE_VISOR = 4193;
public static final int BAGGY_RAVE_PANTS = 4194;
public static final int PACIFIER_NECKLACE = 4195;
public static final int SEA_COWBELL = 4196;
public static final int SEA_LASSO = 4198;
public static final int MERKIN_CHEATSHEET = 4204;
public static final int MERKIN_WORDQUIZ = 4205;
public static final int SKATE_PARK_MAP = 4222;
public static final int AMPHIBIOUS_TOPHAT = 4229;
public static final int HACIENDA_KEY = 4233;
public static final int SILVER_PATE_KNIFE = 4234;
public static final int SILVER_CHEESE_SLICER = 4237;
public static final int SLEEP_MASK = 4241;
public static final int FISHERMANS_SACK = 4250;
public static final int FISH_OIL_SMOKE_BOMB = 4251;
public static final int VIAL_OF_SQUID_INK = 4252;
public static final int POTION_OF_FISHY_SPEED = 4253;
public static final int WOLFMAN_MASK = 4260;
public static final int PUMPKINHEAD_MASK = 4261;
public static final int MUMMY_COSTUME = 4262;
public static final int KRAKROXS_LOINCLOTH = 4267;
public static final int GALAPAGOSIAN_CUISSES = 4268;
public static final int ANGELHAIR_CULOTTES = 4269;
public static final int NEWMANS_OWN_TROUSERS = 4270;
public static final int VOLARTTAS_BELLBOTTOMS = 4271;
public static final int LEDERHOSEN_OF_THE_NIGHT = 4272;
public static final int UNDERWORLD_ACORN = 4274;
public static final int CRAPPY_MASK = 4282;
public static final int GLADIATOR_MASK = 4284;
public static final int SCHOLAR_MASK = 4285;
public static final int MERKIN_DODGEBALL = 4292;
public static final int MERKIN_DRAGNET = 4293;
public static final int MERKIN_SWITCHBLADE = 4294;
public static final int CRYSTAL_ORB = 4295;
public static final int DEPLETED_URANIUM_SEAL = 4296;
public static final int VIOLENCE_STOMPERS = 4297;
public static final int VIOLENCE_BRAND = 4298;
public static final int VIOLENCE_LENS = 4300;
public static final int VIOLENCE_PANTS = 4302;
public static final int HATRED_STONE = 4303;
public static final int HATRED_GIRDLE = 4304;
public static final int HATRED_STAFF = 4305;
public static final int HATRED_PANTS = 4306;
public static final int HATRED_SLIPPERS = 4307;
public static final int HATRED_LENS = 4308;
public static final int SLEDGEHAMMER_OF_THE_VAELKYR = 4316;
public static final int FLAIL_OF_THE_SEVEN_ASPECTS = 4317;
public static final int WRATH_OF_THE_PASTALORDS = 4318;
public static final int WINDSOR_PAN_OF_THE_SOURCE = 4319;
public static final int SEEGERS_BANJO = 4320;
public static final int TRICKSTER_TRIKITIXA = 4321;
public static final int INFERNAL_SEAL_CLAW = 4322;
public static final int TURTLE_POACHER_GARTER = 4323;
public static final int SPAGHETTI_BANDOLIER = 4324;
public static final int SAUCEBLOB_BELT = 4325;
public static final int NEW_WAVE_BLING = 4326;
public static final int BELT_BUCKLE_OF_LOPEZ = 4327;
public static final int BAG_OF_MANY_CONFECTIONS = 4329;
public static final int FANCY_CHOCOLATE_CAR = 4334;
public static final int CRIMBUCK = 4343;
public static final int GINGERBREAD_HOUSE = 4347;
public static final int CRIMBOUGH = 4353;
public static final int CRIMBO_CAROL_V1 = 4354;
public static final int CRIMBO_CAROL_V2 = 4355;
public static final int CRIMBO_CAROL_V3 = 4356;
public static final int CRIMBO_CAROL_V4 = 4357;
public static final int CRIMBO_CAROL_V5 = 4358;
public static final int CRIMBO_CAROL_V6 = 4359;
public static final int ELF_RESISTANCE_BUTTON = 4363;
public static final int WRENCH_HANDLE = 4368;
public static final int HEADLESS_BOLTS = 4369;
public static final int AGITPROP_INK = 4370;
public static final int HANDFUL_OF_WIRES = 4371;
public static final int CHUNK_OF_CEMENT = 4372;
public static final int PENGUIN_GRAPPLING_HOOK = 4373;
public static final int CARDBOARD_ELF_EAR = 4374;
public static final int SPIRALING_SHAPE = 4375;
public static final int CRIMBOMINATION_CONTRAPTION = 4376;
public static final int RED_AND_GREEN_SWEATER = 4391;
public static final int CRIMBO_CANDY_COOKBOOK = 4392;
public static final int STINKY_CHEESE_BALL = 4398;
public static final int STINKY_CHEESE_SWORD = 4399;
public static final int STINKY_CHEESE_DIAPER = 4400;
public static final int STINKY_CHEESE_WHEEL = 4401;
public static final int STINKY_CHEESE_EYE = 4402;
public static final int STINKY_CHEESE_STAFF = 4403;
public static final int SLAPFIGHTING_BOOK = 4406;
public static final int UNCLE_ROMULUS = 4407;
public static final int SNAKE_CHARMING_BOOK = 4408;
public static final int ZU_MANNKASE_DIENEN = 4409;
public static final int DYNAMITE_SUPERMAN_JONES = 4410;
public static final int INIGO_BOOK = 4411;
public static final int QUANTUM_TACO = 4412;
public static final int SCHRODINGERS_THERMOS = 4413;
public static final int BLACK_HYMNAL = 4426;
public static final int GLOWSTICK_ON_A_STRING = 4428;
public static final int CANDY_NECKLACE = 4429;
public static final int TEDDYBEAR_BACKPACK = 4430;
public static final int STRANGE_CUBE = 4436;
public static final int INSTANT_KARMA = 4448;
public static final int MACHETITO = 4452;
public static final int LEAFBLOWER = 4455;
public static final int SNAILMAIL_BITS = 4457;
public static final int CHOCOLATE_SEAL_CLUBBING_CLUB = 4462;
public static final int CHOCOLATE_TURTLE_TOTEM = 4463;
public static final int CHOCOLATE_PASTA_SPOON = 4464;
public static final int CHOCOLATE_SAUCEPAN = 4465;
public static final int CHOCOLATE_DISCO_BALL = 4466;
public static final int CHOCOLATE_STOLEN_ACCORDION = 4467;
public static final int BRICKO_BOOK = 4468;
public static final int BRICKO_EYE = 4470;
public static final int BRICKO_HAT = 4471;
public static final int BRICKO_PANTS = 4472;
public static final int BRICKO_SWORD = 4473;
public static final int BRICKO_OOZE = 4474;
public static final int BRICKO_BAT = 4475;
public static final int BRICKO_OYSTER = 4476;
public static final int BRICKO_TURTLE = 4477;
public static final int BRICKO_ELEPHANT = 4478;
public static final int BRICKO_OCTOPUS = 4479;
public static final int BRICKO_PYTHON = 4480;
public static final int BRICKO_VACUUM_CLEANER = 4481;
public static final int BRICKO_AIRSHIP = 4482;
public static final int BRICKO_CATHEDRAL = 4483;
public static final int BRICKO_CHICKEN = 4484;
public static final int BRICKO_PYRAMID = 4485;
public static final int RECORDING_BALLAD = 4497;
public static final int RECORDING_BENETTON = 4498;
public static final int RECORDING_ELRON = 4499;
public static final int RECORDING_CHORALE = 4500;
public static final int RECORDING_PRELUDE = 4501;
public static final int RECORDING_DONHO = 4502;
public static final int RECORDING_INIGO = 4503;
public static final int CLAN_LOOKING_GLASS = 4507;
public static final int DRINK_ME_POTION = 4508;
public static final int REFLECTION_OF_MAP = 4509;
public static final int WALRUS_ICE_CREAM = 4510;
public static final int BEAUTIFUL_SOUP = 4511;
public static final int HUMPTY_DUMPLINGS = 4514;
public static final int LOBSTER_QUA_GRILL = 4515;
public static final int MISSING_WINE = 4516;
public static final int ITTAH_BITTAH_HOOKAH = 4519;
public static final int QUEEN_COOKIE = 4535;
public static final int STUFFED_POCKETWATCH = 4545;
public static final int JACKING_MAP = 4560;
public static final int TINY_FLY_GLASSES = 4566;
public static final int LEGENDARY_BEAT = 4573;
public static final int BUGGED_BEANIE = 4575;
public static final int BUGGED_BONNET = 4577;
public static final int BUGGED_MEAT_CLUB = 4578;
public static final int BUGGED_POTION = 4579;
public static final int BUGGED_KNICKERBOCKERS = 4580;
public static final int BUGGED_BAIO = 4581;
public static final int PIXEL_WHIP = 4589;
public static final int PIXEL_CHAIN_WHIP = 4590;
public static final int PIXEL_MORNING_STAR = 4591;
public static final int PIXEL_ORB = 4592;
public static final int KEGGER_MAP = 4600;
public static final int ORQUETTES_PHONE_NUMBER = 4602;
public static final int BOTTLE_OF_GOLDENSCHNOCKERED = 4605;
public static final int ESSENTIAL_TOFU = 4609;
public static final int HATSEAT = 4614;
public static final int GG_TOKEN = 4621;
public static final int GG_TICKET = 4622;
public static final int COFFEE_PIXIE_STICK = 4625;
public static final int SPIDER_RING = 4629;
public static final int SINISTER_DEMON_MASK = 4637;
public static final int CHAMPION_BELT = 4638;
public static final int SPACE_TRIP_HEADPHONES = 4639;
public static final int KOL_CON_SIX_PACK = 4641;
public static final int JUJU_MOJO_MASK = 4644;
public static final int METEOID_ICE_BEAM = 4646;
public static final int DUNGEON_FIST_GAUNTLET = 4647;
public static final int IRONIC_MOUSTACHE = 4651;
public static final int BLACKBERRY_GALOSHES = 4659;
public static final int ELLSBURY_BOOK = 4663;
public static final int HOT_PLATE = 4665;
public static final int INSULT_PUPPET = 4667;
public static final int OBSERVATIONAL_GLASSES = 4668;
public static final int COMEDY_PROP = 4669;
public static final int BEER_SCENTED_TEDDY_BEAR = 4670;
public static final int BOOZE_SOAKED_CHERRY = 4671;
public static final int COMFY_PILLOW = 4672;
public static final int GIANT_MARSHMALLOW = 4673;
public static final int SPONGE_CAKE = 4674;
public static final int GIN_SOAKED_BLOTTER_PAPER = 4675;
public static final int TREE_HOLED_COIN = 4676;
public static final int UNEARTHED_METEOROID = 4677;
public static final int VOLCANIC_ASH = 4679;
public static final int FOSSILIZED_BAT_SKULL = 4687;
public static final int FOSSILIZED_SERPENT_SKULL = 4688;
public static final int FOSSILIZED_BABOON_SKULL = 4689;
public static final int FOSSILIZED_WYRM_SKULL = 4690;
public static final int FOSSILIZED_WING = 4691;
public static final int FOSSILIZED_LIMB = 4692;
public static final int FOSSILIZED_TORSO = 4693;
public static final int FOSSILIZED_SPINE = 4694;
public static final int GREAT_PANTS = 4696;
public static final int IMP_AIR = 4698;
public static final int BUS_PASS = 4699;
public static final int FOSSILIZED_SPIKE = 4700;
public static final int ARCHAEOLOGING_SHOVEL = 4702;
public static final int FOSSILIZED_DEMON_SKULL = 4704;
public static final int FOSSILIZED_SPIDER_SKULL = 4705;
public static final int SINISTER_ANCIENT_TABLET = 4706;
public static final int OVEN = 4707;
public static final int SHAKER = 4708;
public static final int OLD_SWEATPANTS = 4711;
public static final int MARIACHI_HAT = 4718;
public static final int HOLLANDAISE_HELMET = 4719;
public static final int MICROWAVE_STOGIE = 4721;
public static final int LIVER_PIE = 4722;
public static final int BADASS_PIE = 4723;
public static final int FISH_PIE = 4724;
public static final int PIPING_PIE = 4725;
public static final int IGLOO_PIE = 4726;
public static final int TURNOVER = 4727;
public static final int DEAD_PIE = 4728;
public static final int THROBBING_PIE = 4729;
public static final int BONE_CHIPS = 4743;
public static final int STABONIC_SCROLL = 4757;
public static final int PUMPKIN_SEEDS = 4760;
public static final int PUMPKIN = 4761;
public static final int HUGE_PUMPKIN = 4762;
public static final int PUMPKIN_BOMB = 4766;
public static final int PUMPKIN_CARRIAGE = 4769;
public static final int DESERT_BUS_PASS = 4770;
public static final int GINORMOUS_PUMPKIN = 4771;
public static final int ESSENCE_OF_ANNOYANCE = 4804;
public static final int HOLIDAY_FUN_BOOK = 4810;
public static final int ANTAGONISTIC_SNOWMAN_KIT = 4812;
public static final int SLEEPING_STOCKING = 4842;
public static final int KANSAS_TOYMAKER = 4843;
public static final int WASSAILING_BOOK = 4844;
public static final int UNCLE_HOBO_BEARD = 4846;
public static final int CHOCOLATE_CIGAR = 4851;
public static final int CRIMBCO_SCRIP = 4854;
public static final int BLANK_OUT_BOTTLE = 4857;
public static final int CRIMBCO_MANUAL_1 = 4859;
public static final int CRIMBCO_MANUAL_2 = 4860;
public static final int CRIMBCO_MANUAL_3 = 4861;
public static final int CRIMBCO_MANUAL_4 = 4862;
public static final int CRIMBCO_MANUAL_5 = 4863;
public static final int PHOTOCOPIER = 4864;
public static final int CLAN_FAX_MACHINE = 4865;
public static final int WORKYTIME_TEA = 4866;
public static final int GLOB_OF_BLANK_OUT = 4872;
public static final int PHOTOCOPIED_MONSTER = 4873;
public static final int GAUDY_KEY = 4874;
public static final int CRIMBCO_MUG = 4880;
public static final int CRIMBCO_WINE = 4881;
public static final int BGE_SHOTGLASS = 4893;
public static final int BGE_TATTOO = 4900;
public static final int COAL_PAPERWEIGHT = 4905;
public static final int JINGLE_BELL = 4906;
public static final int LOATHING_LEGION_KNIFE = 4908;
public static final int LOATHING_LEGION_MANY_PURPOSE_HOOK = 4909;
public static final int LOATHING_LEGION_MOONDIAL = 4910;
public static final int LOATHING_LEGION_NECKTIE = 4911;
public static final int LOATHING_LEGION_ELECTRIC_KNIFE = 4912;
public static final int LOATHING_LEGION_CORKSCREW = 4913;
public static final int LOATHING_LEGION_CAN_OPENER = 4914;
public static final int LOATHING_LEGION_CHAINSAW = 4915;
public static final int LOATHING_LEGION_ROLLERBLADES = 4916;
public static final int LOATHING_LEGION_FLAMETHROWER = 4917;
public static final int LOATHING_LEGION_TATTOO_NEEDLE = 4918;
public static final int LOATHING_LEGION_DEFIBRILLATOR = 4919;
public static final int LOATHING_LEGION_DOUBLE_PRISM = 4920;
public static final int LOATHING_LEGION_TAPE_MEASURE = 4921;
public static final int LOATHING_LEGION_KITCHEN_SINK = 4922;
public static final int LOATHING_LEGION_ABACUS = 4923;
public static final int LOATHING_LEGION_HELICOPTER = 4924;
public static final int LOATHING_LEGION_PIZZA_STONE = 4925;
public static final int LOATHING_LEGION_UNIVERSAL_SCREWDRIVER = 4926;
public static final int LOATHING_LEGION_JACKHAMMER = 4927;
public static final int LOATHING_LEGION_HAMMER = 4928;
public static final int QUAKE_OF_ARROWS = 4938;
public static final int KNOB_CAKE = 4942;
public static final int MENAGERIE_KEY = 4947;
public static final int GOTO = 4948;
public static final int WEREMOOSE_SPIT = 4949;
public static final int ABOMINABLE_BLUBBER = 4950;
public static final int SUBJECT_37_FILE = 4961;
public static final int EVILOMETER = 4964;
public static final int CARD_GAME_BOOK = 4965;
public static final int CARD_SLEEVE = 5009;
public static final int EVIL_EYE = 5010;
public static final int SNACK_VOUCHER = 5012;
public static final int WASABI_FOOD = 5013;
public static final int TOBIKO_FOOD = 5014;
public static final int NATTO_FOOD = 5015;
public static final int WASABI_BOOZE = 5016;
public static final int TOBIKO_BOOZE = 5017;
public static final int NATTO_BOOZE = 5018;
public static final int WASABI_POTION = 5019;
public static final int TOBIKO_POTION = 5020;
public static final int NATTO_POTION = 5021;
public static final int PET_SWEATER = 5040;
public static final int ASTRAL_HOT_DOG = 5043;
public static final int ASTRAL_PILSNER = 5044;
public static final int CLAN_SHOWER = 5047;
public static final int LARS_THE_CYBERIAN = 5053;
public static final int CREEPY_VOODOO_DOLL = 5062;
public static final int SPAGHETTI_CON_CALAVERAS = 5065;
public static final int SMORE_GUN = 5066;
public static final int TINY_BLACK_HOLE = 5069;
public static final int SMORE = 5071;
public static final int RUSSIAN_ICE = 5073;
public static final int STRESS_BALL = 5109;
public static final int PEN_PAL_KIT = 5112;
public static final int RUSTY_HEDGE_TRIMMERS = 5115;
public static final int AWOL_COMMENDATION = 5116;
public static final int RECONSTITUTED_CROW = 5117;
public static final int BIRD_BRAIN = 5118;
public static final int BUSTED_WINGS = 5119;
public static final int MARAUDER_MOCKERY_MANUAL = 5120;
public static final int SKELETON_BOOK = 5124;
public static final int LUNAR_ISOTOPE = 5134;
public static final int EMU_JOYSTICK = 5135;
public static final int EMU_ROCKET = 5136;
public static final int EMU_HELMET = 5137;
public static final int EMU_HARNESS = 5138;
public static final int ASTRAL_ENERGY_DRINK = 5140;
public static final int EMU_UNIT = 5143;
public static final int HONEYPOT = 5145;
public static final int SPOOKY_LITTLE_GIRL = 5165;
public static final int SYNTHETIC_DOG_HAIR_PILL = 5167;
public static final int DISTENTION_PILL = 5168;
public static final int TRANSPORTER_TRANSPONDER = 5170;
public static final int RONALD_SHELTER_MAP = 5171;
public static final int GRIMACE_SHELTER_MAP = 5172;
public static final int MOON_BOOZE_1 = 5174;
public static final int MOON_BOOZE_2 = 5175;
public static final int MOON_BOOZE_3 = 5176;
public static final int MOON_FOOD_1 = 5177;
public static final int MOON_FOOD_2 = 5178;
public static final int MOON_FOOD_3 = 5179;
public static final int MOON_POTION_1 = 5180;
public static final int MOON_POTION_2 = 5181;
public static final int MOON_POTION_3 = 5182;
public static final int DOUBLE_ICE_GUM = 5189;
public static final int PATRIOT_SHIELD = 5190;
public static final int BIG_KNOB_SAUSAGE = 5193;
public static final int EXORCISED_SANDWICH = 5194;
public static final int GOOEY_PASTE = 5198;
public static final int BEASTLY_PASTE = 5199;
public static final int OILY_PASTE = 5200;
public static final int ECTOPLASMIC = 5201;
public static final int GREASY_PASTE = 5202;
public static final int BUG_PASTE = 5203;
public static final int HIPPY_PASTE = 5204;
public static final int ORC_PASTE = 5205;
public static final int DEMONIC_PASTE = 5206;
public static final int INDESCRIBABLY_HORRIBLE_PASTE = 5207;
public static final int FISHY_PASTE = 5208;
public static final int GOBLIN_PASTE = 5209;
public static final int PIRATE_PASTE = 5210;
public static final int CHLOROPHYLL_PASTE = 5211;
public static final int STRANGE_PASTE = 5212;
public static final int MER_KIN_PASTE = 5213;
public static final int SLIMY_PASTE = 5214;
public static final int PENGUIN_PASTE = 5215;
public static final int ELEMENTAL_PASTE = 5216;
public static final int COSMIC_PASTE = 5217;
public static final int HOBO_PASTE = 5218;
public static final int CRIMBO_PASTE = 5219;
public static final int TEACHINGS_OF_THE_FIST = 5220;
public static final int FAT_LOOT_TOKEN = 5221;
public static final int CLIP_ART_BOOK = 5223;
public static final int BUCKET_OF_WINE = 5227;
public static final int CRYSTAL_SKULL = 5231;
public static final int BORROWED_TIME = 5232;
public static final int BOX_OF_HAMMERS = 5233;
public static final int SHINING_HALO = 5234;
public static final int TIME_HALO = 5237;
public static final int LUMINEUX_LIMNIO = 5238;
public static final int MORTO_MORETO = 5239;
public static final int TEMPS_TEMPRANILLO = 5240;
public static final int BORDEAUX_MARTEAUX = 5241;
public static final int FROMAGE_PINOTAGE = 5242;
public static final int BEIGNET_MILGRANET = 5243;
public static final int MUSCHAT = 5244;
public static final int FIELD_GAR_POTION = 5257;
public static final int DICE_BOOK = 5284;
public static final int D4 = 5285;
public static final int D6 = 5286;
public static final int D8 = 5287;
public static final int D10 = 5288;
public static final int D12 = 5289;
public static final int D20 = 5290;
public static final int PLASTIC_VAMPIRE_FANGS = 5299;
public static final int STAFF_GUIDE = 5307;
public static final int CHAINSAW_CHAIN = 5309;
public static final int SILVER_SHOTGUN_SHELL = 5310;
public static final int FUNHOUSE_MIRROR = 5311;
public static final int GHOSTLY_BODY_PAINT = 5312;
public static final int NECROTIZING_BODY_SPRAY = 5313;
public static final int BITE_LIPSTICK = 5314;
public static final int WHISKER_PENCIL = 5315;
public static final int PRESS_ON_RIBS = 5316;
public static final int BB_WINE_COOLER = 5323;
public static final int NECBRONOMICON = 5341;
public static final int NECBRONOMICON_USED = 5343;
public static final int CRIMBO_CAROL_V1_USED = 5347;
public static final int CRIMBO_CAROL_V2_USED = 5348;
public static final int CRIMBO_CAROL_V3_USED = 5349;
public static final int CRIMBO_CAROL_V4_USED = 5350;
public static final int CRIMBO_CAROL_V5_USED = 5351;
public static final int CRIMBO_CAROL_V6_USED = 5352;
public static final int JAR_OF_OIL = 5353;
public static final int SLAPFIGHTING_BOOK_USED = 5354;
public static final int UNCLE_ROMULUS_USED = 5355;
public static final int SNAKE_CHARMING_BOOK_USED = 5356;
public static final int ZU_MANNKASE_DIENEN_USED = 5357;
public static final int DYNAMITE_SUPERMAN_JONES_USED = 5358;
public static final int INIGO_BOOK_USED = 5359;
public static final int KANSAS_TOYMAKER_USED = 5360;
public static final int WASSAILING_BOOK_USED = 5361;
public static final int CRIMBCO_MANUAL_1_USED = 5362;
public static final int CRIMBCO_MANUAL_2_USED = 5363;
public static final int CRIMBCO_MANUAL_3_USED = 5364;
public static final int CRIMBCO_MANUAL_4_USED = 5365;
public static final int CRIMBCO_MANUAL_5_USED = 5366;
public static final int SKELETON_BOOK_USED = 5367;
public static final int ELLSBURY_BOOK_USED = 5368;
public static final int GROOSE_GREASE = 5379;
public static final int LOLLIPOP_STICK = 5380;
public static final int PEPPERMINT_SPROUT = 5395;
public static final int PEPPERMINT_PARASOL = 5401;
public static final int GIANT_CANDY_CANE = 5402;
public static final int PEPPERMINT_PACKET = 5404;
public static final int FUDGECULE = 5435;
public static final int FUDGE_WAND = 5441;
public static final int DEVILISH_FOLIO = 5444;
public static final int FURIOUS_STONE = 5448;
public static final int VANITY_STONE = 5449;
public static final int LECHEROUS_STONE = 5450;
public static final int JEALOUSY_STONE = 5451;
public static final int AVARICE_STONE = 5452;
public static final int GLUTTONOUS_STONE = 5453;
public static final int FUDGIE_ROLL = 5457;
public static final int FUDGE_BUNNY = 5458;
public static final int FUDGE_SPORK = 5459;
public static final int FUDGECYCLE = 5460;
public static final int FUDGE_CUBE = 5461;
public static final int RESOLUTION_BOOK = 5463;
public static final int RESOLUTION_KINDER = 5470;
public static final int RESOLUTION_ADVENTUROUS = 5471;
public static final int RESOLUTION_LUCKIER = 5472;
public static final int RED_DRUNKI_BEAR = 5482;
public static final int GREEN_DRUNKI_BEAR = 5483;
public static final int YELLOW_DRUNKI_BEAR = 5484;
public static final int ALL_YEAR_SUCKER = 5497;
public static final int DARK_CHOCOLATE_HEART = 5498;
public static final int JACKASS_PLUMBER_GAME = 5501;
public static final int TRIVIAL_AVOCATIONS_GAME = 5502;
public static final int PACK_OF_POGS = 5505;
public static final int WHAT_CARD = 5511;
public static final int WHEN_CARD = 5512;
public static final int WHO_CARD = 5513;
public static final int WHERE_CARD = 5514;
public static final int PLANT_BOOK = 5546;
public static final int CLANCY_SACKBUT = 5547;
public static final int GHOST_BOOK = 5548;
public static final int CLANCY_CRUMHORN = 5549;
public static final int TATTLE_BOOK = 5550;
public static final int CLANCY_LUTE = 5551;
public static final int TRUSTY = 5552;
public static final int RAIN_DOH_BOX = 5563;
public static final int RAIN_DOH_MONSTER = 5564;
public static final int GROARS_FUR = 5571;
public static final int GLOWING_FUNGUS = 5641;
public static final int STONE_WOOL = 5643;
public static final int NOSTRIL_OF_THE_SERPENT = 5645;
public static final int BORIS_HELM = 5648;
public static final int BORIS_HELM_ASKEW = 5650;
public static final int MIME_SOUL_FRAGMENT = 5651;
public static final int KEYOTRON = 5653;
public static final int FETTUCINI_EPINES_INCONNU_RECIPE = 5657;
public static final int SLAP_AND_SLAP_AGAIN_RECIPE = 5658;
public static final int CLAN_SWIMMING_POOL = 5662;
public static final int CURSED_MICROWAVE = 5663;
public static final int CURSED_KEG = 5664;
public static final int JERK_BOOK = 5665;
public static final int GRUDGE_BOOK = 5666;
public static final int LOST_KEY = 5680;
public static final int NOTE_FROM_CLANCY = 5682;
public static final int BURT = 5683;
public static final int AUTOPSY_TWEEZERS = 5687;
public static final int ONE_MEAT = 5697;
public static final int LOST_GLASSES = 5698;
public static final int LITTLE_MANNEQUIN = 5702;
public static final int CRAYON_SHAVINGS = 5703;
public static final int WAX_BUGBEAR = 5704;
public static final int FDKOL_COMMENDATION = 5707;
public static final int HJODOR_GUIDE = 5715;
public static final int HJODOR_GUIDE_USED = 5716;
public static final int LORD_FLAMEFACES_CLOAK = 5735;
public static final int CSA_FIRE_STARTING_KIT = 5739;
public static final int CRAPPY_BRAIN = 5752;
public static final int DECENT_BRAIN = 5753;
public static final int GOOD_BRAIN = 5754;
public static final int BOSS_BRAIN = 5755;
public static final int HUNTER_BRAIN = 5756;
public static final int FUZZY_BUSBY = 5764;
public static final int FUZZY_EARMUFFS = 5765;
public static final int FUZZY_MONTERA = 5766;
public static final int GNOMISH_EAR = 5768;
public static final int GNOMISH_LUNG = 5769;
public static final int GNOMISH_ELBOW = 5770;
public static final int GNOMISH_KNEE = 5771;
public static final int GNOMISH_FOOT = 5772;
public static final int SOFT_GREEN_ECHO_ANTIDOTE_MARTINI = 5781;
public static final int MORNINGWOOD_PLANK = 5782;
public static final int HARDWOOD_PLANK = 5783;
public static final int WEIRDWOOD_PLANK = 5784;
public static final int THICK_CAULK = 5785;
public static final int LONG_SCREW = 5786;
public static final int BUTT_JOINT = 5787;
public static final int BUBBLIN_CRUDE = 5789;
public static final int BOX_OF_BEAR_ARM = 5790;
public static final int RIGHT_BEAR_ARM = 5791;
public static final int LEFT_BEAR_ARM = 5792;
public static final int RAD_LIB_BOOK = 5862;
public static final int PAPIER_MACHETE = 5868;
public static final int PAPIER_MACHINE_GUN = 5869;
public static final int PAPIER_MASK = 5870;
public static final int PAPIER_MITRE = 5871;
public static final int PAPIER_MACHURIDARS = 5872;
public static final int DRAGON_TEETH = 5880;
public static final int SKELETON = 5881;
public static final int SKIFF = 5885;
public static final int LAZYBONES_RECLINER = 5888;
public static final int UNCONSCIOUS_COLLECTIVE_DREAM_JAR = 5897;
public static final int SUSPICIOUS_JAR = 5898;
public static final int GOURD_JAR = 5899;
public static final int MYSTIC_JAR = 5900;
public static final int OLD_MAN_JAR = 5901;
public static final int ARTIST_JAR = 5902;
public static final int MEATSMITH_JAR = 5903;
public static final int JICK_JAR = 5905;
public static final int CHIBIBUDDY_ON = 5908;
public static final int NANORHINO_CREDIT_CARD = 5911;
public static final int BEET_MEDIOCREBAR = 5915;
public static final int CORN_MEDIOCREBAR = 5916;
public static final int CABBAGE_MEDIOCREBAR = 5917;
public static final int CHIBIBUDDY_OFF = 5925;
public static final int BITTYCAR_MEATCAR = 5926;
public static final int BITTYCAR_HOTCAR = 5927;
public static final int ELECTRONIC_DULCIMER_PANTS = 5963;
public static final int BOO_CLUE = 5964;
public static final int INFURIATING_SILENCE_RECORD = 5971;
public static final int INFURIATING_SILENCE_RECORD_USED = 5972;
public static final int TRANQUIL_SILENCE_RECORD = 5973;
public static final int TRANQUIL_SILENCE_RECORD_USED = 5974;
public static final int MENACING_SILENCE_RECORD = 5975;
public static final int MENACING_SILENCE_RECORD_USED = 5976;
public static final int SLICE_OF_PIZZA = 5978;
public static final int BOTTLE_OF_WINE = 5990;
public static final int BOSS_HELM = 6002;
public static final int BOSS_CLOAK = 6003;
public static final int BOSS_SWORD = 6004;
public static final int BOSS_SHIELD = 6005;
public static final int BOSS_PANTS = 6006;
public static final int BOSS_GAUNTLETS = 6007;
public static final int BOSS_BOOTS = 6008;
public static final int BOSS_BELT = 6009;
public static final int TRIPPLES = 6027;
public static final int DRESS_PANTS = 6030;
public static final int INCREDIBLE_PIZZA = 6038;
public static final int OIL_PAN = 6042;
public static final int BITTYCAR_SOULCAR = 6046;
public static final int MISTY_CLOAK = 6047;
public static final int MISTY_ROBE = 6048;
public static final int MISTY_CAPE = 6049;
public static final int TACO_FLIER = 6051;
public static final int PSYCHOANALYTIC_JAR = 6055;
public static final int CRIMBO_CREEPY_HEAD = 6058;
public static final int CRIMBO_STOGIE_ODORIZER = 6059;
public static final int CRIMBO_HOT_MUG = 6060;
public static final int CRIMBO_TREE_FLOCKER = 6061;
public static final int CRIMBO_RUDOLPH_DOLL = 6062;
public static final int GEEKY_BOOK = 6071;
public static final int LED_CLOCK = 6072;
public static final int HAGGIS_SOCKS = 6080;
public static final int CLASSY_MONKEY = 6097;
public static final int PILE_OF_USELESS_ROBOT_PARTS = 6100;
public static final int CEO_OFFICE_CARD = 6116;
public static final int STRANGE_GOGGLES = 6118;
public static final int BONSAI_TREE = 6120;
public static final int LUCKY_CAT_STATUE = 6122;
public static final int GOLD_PIECE = 6130;
public static final int JICK_SWORD = 6146;
public static final int SNOW_SUIT = 6150;
public static final int CARROT_NOSE = 6151;
public static final int CARROT_CLARET = 6153;
public static final int PIXEL_POWER_CELL = 6155;
public static final int ANGER_BLASTER = 6158;
public static final int DOUBT_CANNON = 6159;
public static final int FEAR_CONDENSER = 6160;
public static final int REGRET_HOSE = 6161;
public static final int GAMEPRO_MAGAZINE = 6174;
public static final int GAMEPRO_WALKTHRU = 6175;
public static final int COSMIC_EGG = 6176;
public static final int COSMIC_VEGETABLE = 6178;
public static final int COSMIC_POTATO = 6181;
public static final int COSMIC_CREAM = 6182;
public static final int MEDIOCRE_LAGER = 6215;
public static final int COSMIC_SIX_PACK = 6237;
public static final int WALBERG_BOOK = 6253;
public static final int OCELOT_BOOK = 6254;
public static final int DRESCHER_BOOK = 6255;
public static final int STAFF_OF_BREAKFAST = 6258;
public static final int STAFF_OF_LIFE = 6259;
public static final int STAFF_OF_CHEESE = 6261;
public static final int STAFF_OF_STEAK = 6263;
public static final int STAFF_OF_CREAM = 6265;
public static final int YE_OLDE_MEAD = 6276;
public static final int MARK_V_STEAM_HAT = 6289;
public static final int ROCKETSHIP = 6290;
public static final int DRUM_N_BASS_RECORD = 6295;
public static final int JARLSBERG_SOUL_FRAGMENT = 6297;
public static final int MODEL_AIRSHIP = 6299;
public static final int RING_OF_DETECT_BORING_DOORS = 6303;
public static final int JARLS_COSMIC_PAN = 6304;
public static final int JARLS_PAN = 6305;
public static final int UNCLE_BUCK = 6311;
public static final int FISH_MEAT_CRATE = 6312;
public static final int DAMP_WALLET = 6313;
public static final int FISHY_PIPE = 6314;
public static final int OLD_SCUBA_TANK = 6315;
public static final int SUSHI_DOILY = 6328;
public static final int COZY_SCIMITAR = 6332;
public static final int COZY_STAFF = 6333;
public static final int COZY_BAZOOKA = 6334;
public static final int SALTWATERBED = 6338;
public static final int DREADSCROLL = 6353;
public static final int MERKIN_WORKTEA = 6356;
public static final int MERKIN_KNUCKLEBONE = 6357;
public static final int TAFFY_BOOK = 6360;
public static final int YELLOW_TAFFY = 6361;
public static final int INDIGO_TAFFY = 6362;
public static final int GREEN_TAFFY = 6363;
public static final int MERKIN_HALLPASS = 6368;
public static final int LUMP_OF_CLAY = 6369;
public static final int TWISTED_PIECE_OF_WIRE = 6370;
public static final int FRUITY_WINE = 6372;
public static final int ANGRY_INCH = 6374;
public static final int ERASER_NUBBIN = 6378;
public static final int CHLORINE_CRYSTAL = 6379;
public static final int PH_BALANCER = 6380;
public static final int MYSTERIOUS_CHEMICAL_RESIDUE = 6381;
public static final int NUGGET_OF_SODIUM = 6382;
public static final int JIGSAW_BLADE = 6384;
public static final int WOOD_SCREW = 6385;
public static final int BALSA_PLANK = 6386;
public static final int BLOB_OF_WOOD_GLUE = 6387;
public static final int ENVYFISH_EGG = 6388;
public static final int ANEMONE_SAUCE = 6394;
public static final int INKY_SQUID_SAUCE = 6395;
public static final int MERKIN_WEAKSAUCE = 6396;
public static final int PEANUT_SAUCE = 6397;
public static final int BLACK_GLASS = 6398;
public static final int POCKET_SQUARE = 6407;
public static final int CORRUPTED_STARDUST = 6408;
public static final int SHAKING_SKULL = 6412;
public static final int TWIST_OF_LIME = 6417;
public static final int TONIC_DJINN = 6421;
public static final int TALES_OF_DREAD = 6423;
public static final int DREADSYLVANIAN_SKELETON_KEY = 6424;
public static final int BRASS_DREAD_FLASK = 6428;
public static final int SILVER_DREAD_FLASK = 6429;
public static final int KRUEGERAND = 6433;
public static final int MARK_OF_THE_BUGBEAR = 6434;
public static final int MARK_OF_THE_WEREWOLF = 6435;
public static final int MARK_OF_THE_ZOMBIE = 6436;
public static final int MARK_OF_THE_GHOST = 6437;
public static final int MARK_OF_THE_VAMPIRE = 6438;
public static final int MARK_OF_THE_SKELETON = 6439;
public static final int HELPS_YOU_SLEEP = 6443;
public static final int GETS_YOU_DRUNK = 6446;
public static final int GREAT_WOLFS_LEFT_PAW = 6448;
public static final int GREAT_WOLFS_RIGHT_PAW = 6449;
public static final int GREAT_WOLFS_ROCKET_LAUNCHER = 6450;
public static final int HUNGER_SAUCE = 6453;
public static final int ZOMBIE_ACCORDION = 6455;
public static final int MAYOR_GHOSTS_GAVEL = 6465;
public static final int GHOST_PEPPER = 6468;
public static final int DRUNKULA_WINEGLASS = 6474;
public static final int BLOODWEISER = 6475;
public static final int ELECTRIC_KOOL_AID = 6483;
public static final int DREAD_TARRAGON = 6484;
public static final int BONE_FLOUR = 6485;
public static final int DREADFUL_ROAST = 6486;
public static final int STINKING_AGARICUS = 6487;
public static final int SHEPHERDS_PIE = 6488;
public static final int INTRICATE_MUSIC_BOX_PARTS = 6489;
public static final int WAX_BANANA = 6492;
public static final int WAX_LOCK_IMPRESSION = 6493;
public static final int REPLICA_KEY = 6494;
public static final int AUDITORS_BADGE = 6495;
public static final int BLOOD_KIWI = 6496;
public static final int EAU_DE_MORT = 6497;
public static final int BLOODY_KIWITINI = 6498;
public static final int MOON_AMBER = 6499;
public static final int MOON_AMBER_NECKLACE = 6501;
public static final int DREAD_POD = 6502;
public static final int GHOST_PENCIL = 6503;
public static final int DREADSYLVANIAN_CLOCKWORK_KEY = 6506;
public static final int COOL_IRON_INGOT = 6507;
public static final int GHOST_SHAWL = 6511;
public static final int SKULL_CAPACITOR = 6512;
public static final int WARM_FUR = 6513;
public static final int GHOST_THREAD = 6525;
public static final int HOTHAMMER = 6528;
public static final int MUDDY_SKIRT = 6531;
public static final int FRYING_BRAINPAN = 6538;
public static final int OLD_BALL_AND_CHAIN = 6539;
public static final int OLD_DRY_BONE = 6540;
public static final int WEEDY_SKIRT = 6545;
public static final int HOT_CLUSTER = 6551;
public static final int COLD_CLUSTER = 6552;
public static final int SPOOKY_CLUSTER = 6553;
public static final int STENCH_CLUSTER = 6554;
public static final int SLEAZE_CLUSTER = 6555;
public static final int PHIAL_OF_HOTNESS = 6556;
public static final int PHIAL_OF_COLDNESS = 6557;
public static final int PHIAL_OF_SPOOKINESS = 6558;
public static final int PHIAL_OF_STENCH = 6559;
public static final int PHIAL_OF_SLEAZINESS = 6560;
public static final int DREADSYLVANIAN_ALMANAC = 6579;
public static final int CLAN_HOT_DOG_STAND = 6582;
public static final int VICIOUS_SPIKED_COLLAR = 6583;
public static final int ANCIENT_HOT_DOG_WRAPPER = 6584;
public static final int DEBONAIR_DEBONER = 6585;
public static final int CHICLE_DE_SALCHICA = 6586;
public static final int JAR_OF_FROSTIGKRAUT = 6587;
public static final int GNAWED_UP_DOG_BONE = 6588;
public static final int GREY_GUANON = 6589;
public static final int ENGORGED_SAUSAGES_AND_YOU = 6590;
public static final int DREAM_OF_A_DOG = 6591;
public static final int OPTIMAL_SPREADSHEET = 6592;
public static final int DEFECTIVE_TOKEN = 6593;
public static final int HOT_DREADSYLVANIAN_COCOA = 6594;
public static final int CUCKOO_CLOCK = 6614;
public static final int SPAGHETTI_BREAKFAST = 6616;
public static final int FOLDER_HOLDER = 6617;
public static final int FOLDER_01 = 6618;
public static final int FOLDER_02 = 6619;
public static final int FOLDER_03 = 6620;
public static final int FOLDER_04 = 6621;
public static final int FOLDER_05 = 6622;
public static final int FOLDER_06 = 6623;
public static final int FOLDER_07 = 6624;
public static final int FOLDER_08 = 6625;
public static final int FOLDER_09 = 6626;
public static final int FOLDER_10 = 6627;
public static final int FOLDER_11 = 6628;
public static final int FOLDER_12 = 6629;
public static final int FOLDER_13 = 6630;
public static final int FOLDER_14 = 6631;
public static final int FOLDER_15 = 6632;
public static final int FOLDER_16 = 6633;
public static final int FOLDER_17 = 6634;
public static final int FOLDER_18 = 6635;
public static final int FOLDER_19 = 6636;
public static final int FOLDER_20 = 6637;
public static final int FOLDER_21 = 6638;
public static final int FOLDER_22 = 6639;
public static final int FOLDER_23 = 6640;
public static final int FOLDER_24 = 6641;
public static final int FOLDER_25 = 6642;
public static final int FOLDER_26 = 6643;
public static final int FOLDER_27 = 6644;
public static final int FOLDER_28 = 6645;
public static final int MOUNTAIN_STREAM_CODE_BLACK_ALERT = 6650;
public static final int SURGICAL_TAPE = 6653;
public static final int ILLEGAL_FIRECRACKER = 6656;
public static final int SCRAP_METAL = 6659;
public static final int SPIRIT_SOCKET_SET = 6660;
public static final int MINIATURE_SUSPENSION_BRIDGE = 6661;
public static final int STAFF_OF_THE_LUNCH_LADY = 6662;
public static final int UNIVERSAL_KEY = 6663;
public static final int WORLDS_MOST_DANGEROUS_BIRDHOUSE = 6664;
public static final int DEATHCHUCKS = 6665;
public static final int GIANT_ERASER = 6666;
public static final int QUASIRELGIOUS_SCULPTURE = 6667;
public static final int GIANT_FARADAY_CAGE = 6668;
public static final int MODELING_CLAYMORE = 6669;
public static final int STICKY_CLAY_HOMUNCULUS = 6670;
public static final int SODIUM_PENTASOMETHING = 6671;
public static final int GRAINS_OF_SALT = 6672;
public static final int YELLOWCAKE_BOMB = 6673;
public static final int DIRTY_STINKBOMB = 6674;
public static final int SUPERWATER = 6675;
public static final int CRUDE_SCULPTURE = 6677;
public static final int YEARBOOK_CAMERA = 6678;
public static final int ANTIQUE_MACHETE = 6679;
public static final int BOWL_OF_SCORPIONS = 6681;
public static final int BOOK_OF_MATCHES = 6683;
public static final int MCCLUSKY_FILE_PAGE1 = 6689;
public static final int MCCLUSKY_FILE_PAGE2 = 6690;
public static final int MCCLUSKY_FILE_PAGE3 = 6691;
public static final int MCCLUSKY_FILE_PAGE4 = 6692;
public static final int MCCLUSKY_FILE_PAGE5 = 6693;
public static final int BINDER_CLIP = 6694;
public static final int MCCLUSKY_FILE = 6695;
public static final int BOWLING_BALL = 6696;
public static final int MOSS_COVERED_STONE_SPHERE = 6697;
public static final int DRIPPING_STONE_SPHERE = 6698;
public static final int CRACKLING_STONE_SPHERE = 6699;
public static final int SCORCHED_STONE_SPHERE = 6700;
public static final int STONE_TRIANGLE = 6701;
public static final int BONE_ABACUS = 6712;
public static final int SHIP_TRIP_SCRIP = 6725;
public static final int UV_RESISTANT_COMPASS = 6729;
public static final int FUNKY_JUNK_KEY = 6730;
public static final int WORSE_HOMES_GARDENS = 6731;
public static final int JUNK_JUNK = 6735;
public static final int ETERNAL_CAR_BATTERY = 6741;
public static final int BEER_SEEDS = 6751;
public static final int BARLEY = 6752;
public static final int HOPS = 6753;
public static final int FANCY_BEER_BOTTLE = 6754;
public static final int FANCY_BEER_LABEL = 6755;
public static final int TIN_ROOF = 6773;
public static final int TIN_LIZZIE = 6775;
public static final int ABYSSAL_BATTLE_PLANS = 6782;
public static final int TOY_ACCORDION = 6808;
public static final int ANTIQUE_ACCORDION = 6809;
public static final int BEER_BATTERED_ACCORDION = 6810;
public static final int BARITONE_ACCORDION = 6811;
public static final int MAMAS_SQUEEZEBOX = 6812;
public static final int GUANCERTINA = 6813;
public static final int ACCORDION_FILE = 6814;
public static final int ACCORD_ION = 6815;
public static final int BONE_BANDONEON = 6816;
public static final int PENTATONIC_ACCORDION = 6817;
public static final int NON_EUCLIDEAN_NON_ACCORDION = 6818;
public static final int ACCORDION_OF_JORDION = 6819;
public static final int AUTOCALLIOPE = 6820;
public static final int ACCORDIONOID_ROCCA = 6821;
public static final int PYGMY_CONCERTINETTE = 6822;
public static final int GHOST_ACCORDION = 6823;
public static final int PEACE_ACCORDION = 6824;
public static final int ALARM_ACCORDION = 6825;
public static final int SWIZZLER = 6837;
public static final int WALKIE_TALKIE = 6846;
public static final int KILLING_JAR = 6847;
public static final int HUGE_BOWL_OF_CANDY = 6851;
public static final int ULTRA_MEGA_SOUR_BALL = 6852;
public static final int DESERT_PAMPHLET = 6854;
public static final int SUSPICIOUS_ADDRESS = 6855;
public static final int BAL_MUSETTE_ACCORDION = 6856;
public static final int CAJUN_ACCORDION = 6857;
public static final int QUIRKY_ACCORDION = 6858;
public static final int SKIPPERS_ACCORDION = 6859;
public static final int PANTSGIVING = 6860;
public static final int BLUE_LINT = 6877;
public static final int GREEN_LINT = 6878;
public static final int WHITE_LINT = 6879;
public static final int ORANGE_LINT = 6880;
public static final int SPIRIT_PILLOW = 6886;
public static final int SPIRIT_SHEET = 6887;
public static final int SPIRIT_MATTRESS = 6888;
public static final int SPIRIT_BLANKET = 6889;
public static final int SPIRIT_BED = 6890;
public static final int CHEF_BOY_BUSINESS_CARD = 6898;
public static final int PASTA_ADDITIVE = 6900;
public static final int WARBEAR_WHOSIT = 6913;
public static final int WARBEAR_BATTERY = 6916;
public static final int WARBEAR_BADGE = 6917;
public static final int WARBEAR_FEASTING_MEAD = 6924;
public static final int WARBEAR_BEARSERKER_MEAD = 6925;
public static final int WARBEAR_BLIZZARD_MEAD = 6926;
public static final int WARBEAR_OIL_PAN = 6961;
public static final int JACKHAMMER_DRILL_PRESS = 6964;
public static final int AUTO_ANVIL = 6965;
public static final int INDUCTION_OVEN = 6966;
public static final int CHEMISTRY_LAB = 6967;
public static final int WARBEAR_EMPATHY_CHIP = 6969;
public static final int SMITH_BOOK = 7003;
public static final int LUMP_OF_BRITUMINOUS_COAL = 7005;
public static final int HANDFUL_OF_SMITHEREENS = 7006;
public static final int GOLDEN_LIGHT = 7013;
public static final int LOUDER_THAN_BOMB = 7014;
public static final int WORK_IS_A_FOUR_LETTER_SWORD = 7016;
public static final int OUIJA_BOARD = 7025;
public static final int SAUCEPANIC = 7027;
public static final int SHAKESPEARES_SISTERS_ACCORDION = 7029;
public static final int LOOSE_PURSE_STRINGS = 7031;
public static final int WARBEAR_BLACK_BOX = 7035;
public static final int HIGH_EFFICIENCY_STILL = 7036;
public static final int LP_ROM_BURNER = 7037;
public static final int WARBEAR_GYROCOPTER = 7038;
public static final int WARBEAR_METALWORKING_PRIMER = 7042;
public static final int WARBEAR_GYROCOPTER_BROKEN = 7049;
public static final int WARBEAR_METALWORKING_PRIMER_USED = 7052;
public static final int WARBEAR_EMPATHY_CHIP_USED = 7053;
public static final int WARBEAR_BREAKFAST_MACHINE = 7056;
public static final int WARBEAR_SODA_MACHINE = 7059;
public static final int WARBEAR_BANK = 7060;
public static final int GRIMSTONE_MASK = 7061;
public static final int GRIM_FAIRY_TALE = 7065;
public static final int WINTER_SEEDS = 7070;
public static final int SNOW_BERRIES = 7071;
public static final int ICE_HARVEST = 7072;
public static final int FROST_FLOWER = 7073;
public static final int SNOW_BOARDS = 7076;
public static final int UNFINISHED_ICE_SCULPTURE = 7079;
public static final int ICE_SCULPTURE = 7080;
public static final int ICE_HOUSE = 7081;
public static final int SNOW_MACHINE = 7082;
public static final int SNOW_FORT = 7089;
public static final int JERKS_HEALTH_MAGAZINE = 7100;
public static final int MULLED_BERRY_WINE = 7119;
public static final int MAGNUM_OF_FANCY_CHAMPAGNE = 7130;
public static final int LUPINE_APPETITE_HORMONES = 7133;
public static final int WOLF_WHISTLE = 7134;
public static final int MID_LEVEL_MEDIEVAL_MEAD = 7138;
public static final int SPINNING_WHEEL = 7140;
public static final int ODD_SILVER_COIN = 7144;
public static final int EXPENSIVE_CHAMPAGNE = 7146;
public static final int FANCY_OIL_PAINTING = 7148;
public static final int SOLID_GOLD_ROSARY = 7149;
public static final int DOWSING_ROD = 7150;
public static final int STRAW = 7151;
public static final int LEATHER = 7152;
public static final int CLAY = 7153;
public static final int FILLING = 7154;
public static final int PARCHMENT = 7155;
public static final int GLASS = 7156;
public static final int CRAPPY_CAMERA = 7173;
public static final int SHAKING_CRAPPY_CAMERA = 7176;
public static final int COPPERHEAD_CHARM = 7178;
public static final int FIRST_PIZZA = 7179;
public static final int LACROSSE_STICK = 7180;
public static final int EYE_OF_THE_STARS = 7181;
public static final int STANKARA_STONE = 7182;
public static final int MURPHYS_FLAG = 7183;
public static final int SHIELD_OF_BROOK = 7184;
public static final int ZEPPELIN_TICKET = 7185;
public static final int COPPERHEAD_CHARM_RAMPANT = 7186;
public static final int UNNAMED_COCKTAIL = 7187;
public static final int TOMMY_GUN = 7190;
public static final int TOMMY_AMMO = 7191;
public static final int BUDDY_BJORN = 7200;
public static final int LYNYRD_SNARE = 7204;
public static final int FLEETWOOD_MAC_N_CHEESE = 7215;
public static final int PRICELESS_DIAMOND = 7221;
public static final int FLAMIN_WHATSHISNAME = 7222;
public static final int RED_RED_WINE = 7229;
public static final int RED_BUTTON = 7243;
public static final int GLARK_CABLE = 7246;
public static final int PETE_JACKET = 7250;
public static final int SNEAKY_PETE_SHOT = 7252;
public static final int MINI_MARTINI = 7255;
public static final int SMOKE_GRENADE = 7256;
public static final int PALINDROME_BOOK_1 = 7262;
public static final int PHOTOGRAPH_OF_DOG = 7263;
public static final int PHOTOGRAPH_OF_RED_NUGGET = 7264;
public static final int PHOTOGRAPH_OF_OSTRICH_EGG = 7265;
public static final int DISPOSABLE_CAMERA = 7266;
public static final int PETE_JACKET_COLLAR = 7267;
public static final int LETTER_FOR_MELVIGN = 7268;
public static final int PROFESSOR_WHAT_GARMENT = 7269;
public static final int PALINDROME_BOOK_2 = 7270;
public static final int THINKNERD_PACKAGE = 7278;
public static final int ELEVENT = 7295;
public static final int PROFESSOR_WHAT_TSHIRT = 7297;
public static final int BENDY_STRAW = 7398;
public static final int PLANT_FOOD = 7399;
public static final int SEWING_KIT = 7300;
public static final int BILLIARDS_KEY = 7301;
public static final int LIBRARY_KEY = 7302;
public static final int SPOOKYRAVEN_NECKLACE = 7303;
public static final int SPOOKYRAVEN_TELEGRAM = 7304;
public static final int POWDER_PUFF = 7305;
public static final int FINEST_GOWN = 7306;
public static final int DANCING_SHOES = 7307;
public static final int DUSTY_POPPET = 7314;
public static final int RICKETY_ROCKING_HORSE = 7315;
public static final int ANTIQUE_JACK_IN_THE_BOX = 7316;
public static final int BABY_GHOSTS = 7317;
public static final int GHOST_NECKLACE = 7318;
public static final int ELIZABETH_DOLLIE = 7319;
public static final int STEPHEN_LAB_COAT = 7321;
public static final int HAUNTED_BATTERY = 7324;
public static final int SYNTHETIC_MARROW = 7327;
public static final int FUNK = 7330;
public static final int CREEPY_VOICE_BOX = 7334;
public static final int TINY_DANCER = 7338;
public static final int SPOOKY_MUSIC_BOX_MECHANISM = 7339;
public static final int PICTURE_OF_YOU = 7350;
public static final int COAL_SHOVEL = 7355;
public static final int HOT_COAL = 7356;
public static final int LAUNDRY_SHERRY = 7366;
public static final int PSYCHOTIC_TRAIN_WINE = 7370;
public static final int DNA_LAB = 7382;
public static final int DNA_SYRINGE = 7383;
public static final int STEAM_FIST_1 = 7406;
public static final int STEAM_FIST_2 = 7407;
public static final int STEAM_FIST_3 = 7408;
public static final int STEAM_TRIP_1 = 7409;
public static final int STEAM_TRIP_2 = 7410;
public static final int STEAM_TRIP_3 = 7411;
public static final int STEAM_METEOID_1 = 7412;
public static final int STEAM_METEOID_2 = 7413;
public static final int STEAM_METEOID_3 = 7414;
public static final int STEAM_DEMON_1 = 7415;
public static final int STEAM_DEMON_2 = 7416;
public static final int STEAM_DEMON_3 = 7417;
public static final int STEAM_PLUMBER_1 = 7418;
public static final int STEAM_PLUMBER_2 = 7419;
public static final int STEAM_PLUMBER_3 = 7420;
public static final int PENCIL_THIN_MUSHROOM = 7421;
public static final int CHEESEBURGER_RECIPE = 7422;
public static final int SAILOR_SALT = 7423;
public static final int BROUPON = 7424;
public static final int TACO_DAN_SAUCE_BOTTLE = 7425;
public static final int SPRINKLE_SHAKER = 7426;
public static final int TACO_DAN_RECEIPT = 7428;
public static final int BEACH_BUCK = 7429;
public static final int BEEFY_CRUNCH_PASTACO = 7438;
public static final int OVERPOWERING_MUSHROOM_WINE = 7444;
public static final int COMPLEX_MUSHROOM_WINE = 7445;
public static final int SMOOTH_MUSHROOM_WINE = 7446;
public static final int BLOOD_RED_MUSHROOM_WINE = 7447;
public static final int BUZZING_MUSHROOM_WINE = 7448;
public static final int SWIRLING_MUSHROOM_WINE = 7449;
public static final int TACO_DAN_FISH_TACO = 7451;
public static final int TACO_DAN_TACO_SAUCE = 7452;
public static final int BROBERRY_BROGURT = 7455;
public static final int BROCOLATE_BROGURT = 7456;
public static final int FRENCH_BRONILLA_BROGURT = 7457;
public static final int OFFENSIVE_JOKE_BOOK = 7458;
public static final int COOKING_WITH_GREASE_BOOK = 7459;
public static final int DINER_HANDBOOK = 7460;
public static final int ANTI_FUNGAL_SPRAY = 7461;
public static final int SPRING_BEACH_TATTOO_COUPON = 7465;
public static final int SPRING_BEACH_CHARTER = 7466;
public static final int SPRING_BEACH_TICKET = 7467;
public static final int MOIST_BEADS = 7475;
public static final int MIND_DESTROYER = 7476;
public static final int SWEET_TOOTH = 7481;
public static final int LOOSENING_POWDER = 7485;
public static final int POWDERED_CASTOREUM = 7486;
public static final int DRAIN_DISSOLVER = 7487;
public static final int TRIPLE_DISTILLED_TURPENTINE = 7488;
public static final int DETARTRATED_ANHYDROUS_SUBLICALC = 7489;
public static final int TRIATOMACEOUS_DUST = 7490;
public static final int BOTTLE_OF_CHATEAU_DE_VINEGAR = 7491;
public static final int UNSTABLE_FULMINATE = 7493;
public static final int WINE_BOMB = 7494;
public static final int MORTAR_DISSOLVING_RECIPE = 7495;
public static final int GHOST_FORMULA = 7497;
public static final int BLACK_MAP = 7500;
public static final int BLACK_LABEL = 7508;
public static final int CRUMBLING_WHEEL = 7511;
public static final int ALIEN_SOURCE_CODE = 7533;
public static final int ALIEN_SOURCE_CODE_USED = 7534;
public static final int SPACE_BEAST_FUR = 7536;
public static final int SPACE_HEATER = 7543;
public static final int SPACE_PORT = 7545;
public static final int HOT_ASHES = 7548;
public static final int DRY_RUB = 7553;
public static final int WHITE_PAGE = 7555;
public static final int WHITE_WINE = 7558;
public static final int TIME_TWITCHING_TOOLBELT = 7566;
public static final int CHRONER = 7567;
public static final int SOLID_SHIFTING_TIME_WEIRDNESS = 7581;
public static final int CLAN_SPEAKEASY = 7588;
public static final int GLASS_OF_MILK = 7589;
public static final int CUP_OF_TEA = 7590;
public static final int THERMOS_OF_WHISKEY = 7591;
public static final int LUCKY_LINDY = 7592;
public static final int BEES_KNEES = 7593;
public static final int SOCKDOLLAGER = 7594;
public static final int ISH_KABIBBLE = 7595;
public static final int HOT_SOCKS = 7596;
public static final int PHONUS_BALONUS = 7597;
public static final int FLIVVER = 7598;
public static final int SLOPPY_JALOPY = 7599;
public static final int HEAVY_DUTY_UMBRELLA = 7643;
public static final int POOL_SKIMMER = 7644;
public static final int MINI_LIFE_PRESERVER = 7645;
public static final int LIGHTNING_MILK = 7646;
public static final int AQUA_BRAIN = 7647;
public static final int THUNDER_THIGH = 7648;
public static final int FRESHWATER_FISHBONE = 7651;
public static final int NEOPRENE_SKULLCAP = 7659;
public static final int GOBLIN_WATER = 7660;
public static final int LIQUID_ICE = 7665;
public static final int GROLL_DOLL = 7694;
public static final int CAP_GUN = 7695;
public static final int CONFISCATOR_BOOK = 7706;
public static final int THORS_PLIERS = 7709;
public static final int WATER_WINGS_FOR_BABIES = 7711;
public static final int BEAUTIFUL_RAINBOW = 7712;
public static final int CHRONER_CROSS = 7723;
public static final int MERCURY_BLESSING = 7728;
public static final int CHRONER_TRIGGER = 7729;
public static final int BLACK_BARTS_BOOTY = 7732;
public static final int XIBLAXIAN_CIRCUITRY = 7733;
public static final int XIBLAXIAN_POLYMER = 7734;
public static final int XIBLAXIAN_ALLOY = 7735;
public static final int XIBLAXIAN_CRYSTAL = 7736;
public static final int XIBLAXIAN_HOLOTRAINING_SIMCODE = 7739;
public static final int XIBLAXIAN_POLITICAL_PRISONER = 7742;
public static final int XIBLAXIAN_SCHEMATIC_COWL = 7743;
public static final int XIBLAXIAN_SCHEMATIC_TROUSERS = 7744;
public static final int XIBLAXIAN_SCHEMATIC_VEST = 7745;
public static final int XIBLAXIAN_SCHEMATIC_BURRITO = 7746;
public static final int XIBLAXIAN_SCHEMATIC_WHISKEY = 7747;
public static final int XIBLAXIAN_SCHEMATIC_RESIDENCE = 7748;
public static final int XIBLAXIAN_SCHEMATIC_GOGGLES = 7749;
public static final int FIVE_D_PRINTER = 7750;
public static final int RESIDENCE_CUBE = 7758;
public static final int XIBLAXIAN_HOLOWRIST_PUTER = 7765;
public static final int CONSPIRACY_ISLAND_CHARTER = 7767;
public static final int CONSPIRACY_ISLAND_TICKET = 7768;
public static final int COINSPIRACY = 7769;
public static final int VENTILATION_UNIT = 7770;
public static final int SASQ_WATCH = 7776;
public static final int CUDDLY_TEDDY_BEAR = 7787;
public static final int FIRST_AID_POUCH = 7789;
public static final int SHAWARMA_KEYCARD = 7792;
public static final int BOTTLE_OPENER_KEYCARD = 7793;
public static final int ARMORY_KEYCARD = 7794;
public static final int HYPERSANE_BOOK = 7803;
public static final int INTIMIDATING_MIEN_BOOK = 7804;
public static final int EXPERIMENTAL_SERUM_P00 = 7830;
public static final int FINGERNAIL_CLIPPERS = 7831;
public static final int MINI_CASSETTE_RECORDER = 7832;
public static final int GORE_BUCKET = 7833;
public static final int PACK_OF_SMOKES = 7834;
public static final int ESP_COLLAR = 7835;
public static final int GPS_WATCH = 7836;
public static final int PROJECT_TLB = 7837;
public static final int MINING_OIL = 7856;
public static final int CRIMBONIUM_FUEL_ROD = 7863;
public static final int CRIMBOT_TORSO_2 = 7865;
public static final int CRIMBOT_TORSO_3 = 7866;
public static final int CRIMBOT_TORSO_4 = 7867;
public static final int CRIMBOT_TORSO_5 = 7868;
public static final int CRIMBOT_TORSO_6 = 7869;
public static final int CRIMBOT_TORSO_7 = 7870;
public static final int CRIMBOT_TORSO_8 = 7871;
public static final int CRIMBOT_TORSO_9 = 7872;
public static final int CRIMBOT_TORSO_10 = 7873;
public static final int CRIMBOT_TORSO_11 = 7874;
public static final int CRIMBOT_LEFTARM_2 = 7875;
public static final int CRIMBOT_LEFTARM_3 = 7876;
public static final int CRIMBOT_LEFTARM_4 = 7877;
public static final int CRIMBOT_LEFTARM_5 = 7878;
public static final int CRIMBOT_LEFTARM_6 = 7879;
public static final int CRIMBOT_LEFTARM_7 = 7880;
public static final int CRIMBOT_LEFTARM_8 = 7881;
public static final int CRIMBOT_LEFTARM_9 = 7882;
public static final int CRIMBOT_LEFTARM_10 = 7883;
public static final int CRIMBOT_LEFTARM_11 = 7884;
public static final int CRIMBOT_RIGHTARM_2 = 7885;
public static final int CRIMBOT_RIGHTARM_3 = 7886;
public static final int CRIMBOT_RIGHTARM_4 = 7887;
public static final int CRIMBOT_RIGHTARM_5 = 7888;
public static final int CRIMBOT_RIGHTARM_6 = 7889;
public static final int CRIMBOT_RIGHTARM_7 = 7890;
public static final int CRIMBOT_RIGHTARM_8 = 7891;
public static final int CRIMBOT_RIGHTARM_9 = 7892;
public static final int CRIMBOT_RIGHTARM_10 = 7893;
public static final int CRIMBOT_RIGHTARM_11 = 7894;
public static final int CRIMBOT_PROPULSION_2 = 7895;
public static final int CRIMBOT_PROPULSION_3 = 7896;
public static final int CRIMBOT_PROPULSION_4 = 7897;
public static final int CRIMBOT_PROPULSION_5 = 7898;
public static final int CRIMBOT_PROPULSION_6 = 7899;
public static final int CRIMBOT_PROPULSION_7 = 7900;
public static final int CRIMBOT_PROPULSION_8 = 7901;
public static final int CRIMBOT_PROPULSION_9 = 7902;
public static final int CRIMBOT_PROPULSION_10 = 7903;
public static final int CRIMBOT_PROPULSION_11 = 7904;
public static final int FRIENDLY_TURKEY = 7922;
public static final int AGITATED_TURKEY = 7923;
public static final int AMBITIOUS_TURKEY = 7924;
public static final int SNEAKY_WRAPPING_PAPER = 7934;
public static final int PICKY_TWEEZERS = 7936;
public static final int CRIMBO_CREDIT = 7937;
public static final int SLEEVE_DEUCE = 7941;
public static final int POCKET_ACE = 7942;
public static final int MININ_DYNAMITE = 7950;
public static final int BIG_BAG_OF_MONEY = 7955;
public static final int ED_DIARY = 7960;
public static final int ED_STAFF = 7961;
public static final int ED_EYE = 7962;
public static final int ED_AMULET = 7963;
public static final int ED_FATS_STAFF = 7964;
public static final int ED_HOLY_MACGUFFIN = 7965;
public static final int KA_COIN = 7966;
public static final int TOPIARY_NUGGLET = 7968;
public static final int BEEHIVE = 7969;
public static final int ELECTRIC_BONING_KNIFE = 7970;
public static final int MUMMIFIED_FIG = 7972;
public static final int ANCIENT_CURE_ALL = 7982;
public static final int CHOCO_CRIMBOT = 7999;
public static final int TOY_CRIMBOT_FACE = 8002;
public static final int TOY_CRIMBOT_GLOVE = 8003;
public static final int TOY_CRIMBOT_FIST = 8004;
public static final int TOY_CRIMBOT_LEGS = 8005;
public static final int ROM_RAPID_PROTOTYPING = 8007;
public static final int ROM_MATHMATICAL_PRECISION = 8008;
public static final int ROM_RUTHLESS_EFFICIENCY = 8009;
public static final int ROM_RAPID_PROTOTYPING_DIRTY = 8013;
public static final int ROM_MATHMATICAL_PRECISION_DIRTY = 8014;
public static final int ROM_RUTHLESS_EFFICIENCY_DIRTY = 8015;
public static final int TAINTED_MINING_OIL = 8017;
public static final int RED_GREEN_RAIN_STICK = 8018;
public static final int CHATEAU_ROOM_KEY = 8019;
public static final int CHATEAU_MUSCLE = 8023;
public static final int CHATEAU_MYST = 8024;
public static final int CHATEAU_MOXIE = 8025;
public static final int CHATEAU_FAN = 8026;
public static final int CHATEAU_CHANDELIER = 8027;
public static final int CHATEAU_SKYLIGHT = 8028;
public static final int CHATEAU_BANK = 8029;
public static final int CHATEAU_JUICE_BAR = 8030;
public static final int CHATEAU_PENS = 8031;
public static final int CHATEAU_WATERCOLOR = 8033;
public static final int SPELUNKY_WHIP = 8040;
public static final int SPELUNKY_SKULL = 8041;
public static final int SPELUNKY_ROCK = 8042;
public static final int SPELUNKY_POT = 8043;
public static final int SPELUNKY_FEDORA = 8044;
public static final int SPELUNKY_MACHETE = 8045;
public static final int SPELUNKY_SHOTGUN = 8046;
public static final int SPELUNKY_BOOMERANG = 8047;
public static final int SPELUNKY_HELMET = 8049;
public static final int SPELUNKY_GOGGLES = 8050;
public static final int SPELUNKY_CAPE = 8051;
public static final int SPELUNKY_JETPACK = 8052;
public static final int SPELUNKY_SPRING_BOOTS = 8053;
public static final int SPELUNKY_SPIKED_BOOTS = 8054;
public static final int SPELUNKY_PICKAXE = 8055;
public static final int SPELUNKY_TORCH = 8056;
public static final int SPELUNKY_RIFLE = 8058;
public static final int SPELUNKY_STAFF = 8059;
public static final int SPELUNKY_JOKE_BOOK = 8060;
public static final int SPELUNKY_CROWN = 8061;
public static final int SPELUNKY_COFFEE_CUP = 8062;
public static final int TALES_OF_SPELUNKING = 8063;
public static final int POWDERED_GOLD = 8066;
public static final int WAREHOUSE_MAP_PAGE = 8070;
public static final int WAREHOUSE_INVENTORY_PAGE = 8071;
public static final int SPELUNKER_FORTUNE = 8073;
public static final int SPELUNKER_FORTUNE_USED = 8085;
public static final int STILL_BEATING_SPLEEN = 8086;
public static final int SCARAB_BEETLE_STATUETTE = 8087;
public static final int WICKERBITS = 8098;
public static final int BAKELITE_BITS = 8105;
public static final int AEROGEL_ACCORDION = 8111;
public static final int AEROSOLIZED_AEROGEL = 8112;
public static final int WROUGHT_IRON_FLAKES = 8119;
public static final int GABARDINE_GIRDLE = 8124;
public static final int GABARDEEN_SMITHEREENS = 8126;
public static final int FIBERGLASS_FIBERS = 8133;
public static final int LOVEBUG_PHEROMONES = 8134;
public static final int WINGED_YETI_FUR = 8135;
public static final int SESHAT_TALISMAN = 8144;
public static final int MEATSMITH_CHECK = 8156;
public static final int BONE_WITH_A_PRICE_TAG = 8158;
public static final int MAGICAL_BAGUETTE = 8167;
public static final int ENCHANTED_ICING = 8168;
public static final int CARTON_OF_SNAKE_MILK = 8172;
public static final int RING_OF_TELLING_SKELETONS_WHAT_TO_DO = 8179;
public static final int MAP_TO_KOKOMO = 8182;
public static final int CROWN_OF_ED = 8185;
public static final int BOOZE_MAP = 8187;
public static final int HYPNOTIC_BREADCRUMBS = 8199;
public static final int POPULAR_TART = 8200;
public static final int NO_HANDED_PIE = 8201;
public static final int DOC_VITALITY_SERUM = 8202;
public static final int DINSEY_CHARTER = 8203;
public static final int DINSEY_TICKET = 8204;
public static final int FUNFUNDS = 8205;
public static final int FILTHY_CHILD_LEASH = 8209;
public static final int GARBAGE_BAG = 8211;
public static final int SEWAGE_CLOGGED_PISTOL = 8215;
public static final int TOXIC_GLOBULE = 8218;
public static final int JAR_OF_SWAMP_HONEY = 8226;
public static final int BRAIN_PRESERVATION_FLUID = 8238;
public static final int DINSEY_REFRESHMENTS = 8243;
public static final int LUBE_SHOES = 8244;
public static final int TRASH_NET = 8245;
public static final int MASCOT_MASK = 8246;
public static final int DINSEY_GUIDE_BOOK = 8253;
public static final int TRASH_MEMOIR_BOOK = 8254;
public static final int DINSEY_MAINTENANCE_MANUAL = 8255;
public static final int DINSEY_AN_AFTERLIFE = 8258;
public static final int LOTS_ENGAGEMENT_RING = 8259;
public static final int MAYO_CLINIC = 8260;
public static final int MAYONEX = 8261;
public static final int MAYODIOL = 8262;
public static final int MAYOSTAT = 8263;
public static final int MAYOZAPINE = 8264;
public static final int MAYOFLEX = 8265;
public static final int MIRACLE_WHIP = 8266;
public static final int SPHYGMAYOMANOMETER = 8267;
public static final int REFLEX_HAMMER = 8268;
public static final int MAYO_LANCE = 8269;
public static final int ESSENCE_OF_BEAR = 8277;
public static final int RESORT_CHIP = 8279;
public static final int GOLDEN_RESORT_CHIP = 8280;
public static final int COCKTAIL_SHAKER = 8283;
public static final int MAYO_MINDER = 8285;
public static final int YELLOW_PIXEL = 8298;
public static final int POWER_PILL = 8300;
public static final int YELLOW_SUBMARINE = 8376;
public static final int DECK_OF_EVERY_CARD = 8382;
public static final int POPULAR_PART = 8383;
public static final int WHITE_MANA = 8387;
public static final int BLACK_MANA = 8388;
public static final int RED_MANA = 8389;
public static final int GREEN_MANA = 8390;
public static final int BLUE_MANA = 8391;
public static final int GIFT_CARD = 8392;
public static final int LINGUINI_IMMONDIZIA_BIANCO = 8419;
public static final int SHELLS_A_LA_SHELLFISH = 8420;
public static final int GOLD_1970 = 8424;
public static final int NEW_AGE_HEALING_CRYSTAL = 8425;
public static final int VOLCOINO = 8426;
public static final int FIZZING_SPORE_POD = 8427;
public static final int INSULATED_GOLD_WIRE = 8439;
public static final int EMPTY_LAVA_BOTTLE = 8440;
public static final int VISCOUS_LAVA_GLOBS = 8442;
public static final int HEAT_RESISTANT_SHEET_METAL = 8453;
public static final int GLOWING_NEW_AGE_CRYSTAL = 8455;
public static final int CRYSTALLINE_LIGHT_BULB = 8456;
public static final int GOOEY_LAVA_GLOBS = 8470;
public static final int LAVA_MINERS_DAUGHTER = 8482;
public static final int PSYCHO_FROM_THE_HEAT = 8483;
public static final int THE_FIREGATE_TAPES = 8484;
public static final int VOLCANO_TICKET = 8486;
public static final int VOLCANO_CHARTER = 8487;
public static final int MANUAL_OF_NUMBEROLOGY = 8488;
public static final int SMOOCH_BRACERS = 8517;
public static final int SUPERDUPERHEATED_METAL = 8522;
public static final int SUPERHEATED_METAL = 8524;
public static final int FETTRIS = 8542;
public static final int FUSILLOCYBIN = 8543;
public static final int PRESCRIPTION_NOODLES = 8544;
public static final int SHRINE_BARREL_GOD = 8564;
public static final int BARREL_LID = 8565;
public static final int BARREL_HOOP_EARRING = 8566;
public static final int BANKRUPTCY_BARREL = 8567;
public static final int LITTLE_FIRKIN = 8568;
public static final int NORMAL_BARREL = 8569;
public static final int BIG_TUN = 8570;
public static final int WEATHERED_BARREL = 8571;
public static final int DUSTY_BARREL = 8572;
public static final int DISINTEGRATING_BARREL = 8573;
public static final int MOIST_BARREL = 8574;
public static final int ROTTING_BARREL = 8575;
public static final int MOULDERING_BARREL = 8576;
public static final int BARNACLED_BARREL = 8577;
public static final int BARREL_MAP = 8599;
public static final int POTTED_TEA_TREE = 8600;
public static final int FLAMIBILI_TEA = 8601;
public static final int YET_TEA = 8602;
public static final int BOO_TEA = 8603;
public static final int NAS_TEA = 8604;
public static final int IMPROPRIE_TEA = 8605;
public static final int FROST_TEA = 8606;
public static final int TOAST_TEA = 8607;
public static final int NET_TEA = 8608;
public static final int PROPRIE_TEA = 8609;
public static final int MORBIDI_TEA = 8610;
public static final int CHARI_TEA = 8611;
public static final int SERENDIPI_TEA = 8612;
public static final int FEROCI_TEA = 8613;
public static final int PHYSICALI_TEA = 8614;
public static final int WIT_TEA = 8615;
public static final int NEUROPLASTICI_TEA = 8616;
public static final int DEXTERI_TEA = 8617;
public static final int FLEXIBILI_TEA = 8618;
public static final int IMPREGNABILI_TEA = 8619;
public static final int OBSCURI_TEA = 8620;
public static final int IRRITABILI_TEA = 8621;
public static final int MEDIOCRI_TEA = 8622;
public static final int LOYAL_TEA = 8623;
public static final int ACTIVI_TEA = 8624;
public static final int CRUEL_TEA = 8625;
public static final int ALACRI_TEA = 8626;
public static final int VITALI_TEA = 8627;
public static final int MANA_TEA = 8628;
public static final int MONSTROSI_TEA = 8629;
public static final int TWEN_TEA = 8630;
public static final int GILL_TEA = 8631;
public static final int UNCERTAIN_TEA = 8632;
public static final int VORACI_TEA = 8633;
public static final int SOBRIE_TEA = 8634;
public static final int ROYAL_TEA = 8635;
public static final int CRAFT_TEA = 8636;
public static final int INSANI_TEA = 8637;
public static final int HAUNTED_DOGHOUSE = 8639;
public static final int GHOST_DOG_CHOW = 8640;
public static final int TENNIS_BALL = 8650;
public static final int TWELVE_NIGHT_ENERGY = 8666;
public static final int ROSE = 8668;
public static final int WHITE_TULIP = 8669;
public static final int RED_TULIP = 8670;
public static final int BLUE_TULIP = 8671;
public static final int WALFORDS_BUCKET = 8672;
public static final int WALMART_GIFT_CERTIFICATE = 8673;
public static final int GLACIEST_CHARTER = 8674;
public static final int GLACIEST_TICKET = 8675;
public static final int TO_BUILD_AN_IGLOO = 8682;
public static final int CHILL_OF_THE_WILD = 8683;
public static final int COLD_FANG = 8684;
public static final int PERFECT_ICE_CUBE = 8686;
public static final int COLD_WEATHER_BARTENDER_GUIDE = 8687;
public static final int BAG_OF_FOREIGN_BRIBES = 8691;
public static final int ICE_HOTEL_BELL = 8694;
public static final int ANCIENT_MEDICINAL_HERBS = 8696;
public static final int ICE_RICE = 8697;
public static final int ICED_PLUM_WINE = 8698;
public static final int TRAINING_BELT = 8699;
public static final int TRAINING_LEGWARMERS = 8700;
public static final int TRAINING_HELMET = 8701;
public static final int SCROLL_SHATTERING_PUNCH = 8702;
public static final int SCROLL_SNOKEBOMB = 8703;
public static final int SCROLL_SHIVERING_MONKEY = 8704;
public static final int SNOWMAN_CRATE = 8705;
public static final int ABSTRACTION_ACTION = 8708;
public static final int ABSTRACTION_THOUGHT = 8709;
public static final int ABSTRACTION_SENSATION = 8710;
public static final int ABSTRACTION_PURPOSE = 8711;
public static final int ABSTRACTION_CATEGORY = 8712;
public static final int ABSTRACTION_PERCEPTION = 8713;
public static final int VYKEA_FRENZY_RUNE = 8722;
public static final int VYKEA_BLOOD_RUNE = 8723;
public static final int VYKEA_LIGHTNING_RUNE = 8724;
public static final int VYKEA_PLANK = 8725;
public static final int VYKEA_RAIL = 8726;
public static final int VYKEA_BRACKET = 8727;
public static final int VYKEA_DOWEL = 8728;
public static final int VYKEA_HEX_KEY = 8729;
public static final int VYKEA_INSTRUCTIONS = 8730;
public static final int PERFECT_NEGRONI = 8738;
public static final int MACHINE_SNOWGLOBE = 8749;
public static final int BACON = 8763;
public static final int BUNDLE_OF_FRAGRANT_HERBS = 8777;
public static final int NUCLEAR_STOCKPILE = 8778;
public static final int CIRCLE_DRUM = 8784;
public static final int COMMUNISM_BOOK = 8785;
public static final int COMMUNISM_BOOK_USED = 8794;
public static final int BAT_OOMERANG = 8797;
public static final int BAT_JUTE = 8798;
public static final int BAT_O_MITE = 8799;
public static final int ROM_OF_OPTIMALITY = 8800;
public static final int INCRIMINATING_EVIDENCE = 8801;
public static final int DANGEROUS_CHEMICALS = 8802;
public static final int KIDNAPPED_ORPHAN = 8803;
public static final int HIGH_GRADE_METAL = 8804;
public static final int HIGH_TENSILE_STRENGTH_FIBERS = 8805;
public static final int HIGH_GRADE_EXPLOSIVES = 8806;
public static final int EXPERIMENTAL_GENE_THERAPY = 8807;
public static final int ULTRACOAGULATOR = 8808;
public static final int SELF_DEFENSE_TRAINING = 8809;
public static final int FINGERPRINT_DUSTING_KIT = 8810;
public static final int CONFIDENCE_BUILDING_HUG = 8811;
public static final int EXPLODING_KICKBALL = 8812;
public static final int GLOB_OF_BAT_GLUE = 8813;
public static final int BAT_AID_BANDAGE = 8814;
public static final int BAT_BEARING = 8815;
public static final int KUDZU_SALAD = 8816;
public static final int MANSQUITO_SERUM = 8817;
public static final int MISS_GRAVES_VERMOUTH = 8818;
public static final int PLUMBERS_MUSHROOM_STEW = 8819;
public static final int AUTHORS_INK = 8820;
public static final int MAD_LIQUOR = 8821;
public static final int DOC_CLOCKS_THYME_COCKTAIL = 8822;
public static final int MR_BURNSGER = 8823;
public static final int INQUISITORS_UNIDENTIFIABLE_OBJECT = 8824;
public static final int REPLICA_BAT_OOMERANG = 8829;
public static final int ROBIN_EGG = 8833;
public static final int TELEGRAPH_OFFICE_DEED = 8836;
public static final int PLAINTIVE_TELEGRAM = 8837;
public static final int COWBOY_BOOTS = 8850;
public static final int INFLATABLE_TELEGRAPH_OFFICE = 8851;
public static final int HEIMZ_BEANS = 8866;
public static final int TESLA_BEANS = 8867;
public static final int MIXED_BEANS = 8868;
public static final int HELLFIRE_BEANS = 8869;
public static final int FRIGID_BEANS = 8870;
public static final int BLACKEST_EYED_PEAS = 8871;
public static final int STINKBEANS = 8872;
public static final int PORK_N_BEANS = 8873;
public static final int PREMIUM_BEANS = 8875;
public static final int MUS_BEANS_PLATE = 8876;
public static final int MYS_BEANS_PLATE = 8877;
public static final int MOX_BEANS_PLATE = 8878;
public static final int HOT_BEANS_PLATE = 8879;
public static final int COLD_BEANS_PLATE = 8880;
public static final int SPOOKY_BEANS_PLATE = 8881;
public static final int STENCH_BEANS_PLATE = 8882;
public static final int SLEAZE_BEANS_PLATE = 8883;
public static final int PREMIUM_BEANS_PLATE = 8885;
public static final int GLENN_DICE = 8890;
public static final int CLARA_BELL = 8893;
public static final int BUFFALO_DIME = 8895;
public static final int WESTERN_BOOK_BRAGGADOCCIO = 8916;
public static final int WESTERN_BOOK_HELL = 8917;
public static final int WESTERN_BOOK_LOOK = 8918;
public static final int WESTERN_SLANG_VOL_1 = 8920;
public static final int WESTERN_SLANG_VOL_2 = 8921;
public static final int WESTERN_SLANG_VOL_3 = 8922;
public static final int STRANGE_DISC_WHITE = 8923;
public static final int STRANGE_DISC_BLACK = 8924;
public static final int STRANGE_DISC_RED = 8925;
public static final int STRANGE_DISC_GREEN = 8926;
public static final int STRANGE_DISC_BLUE = 8927;
public static final int STRANGE_DISC_YELLOW = 8928;
public static final int MOUNTAIN_SKIN = 8937;
public static final int GRIZZLED_SKIN = 8938;
public static final int DIAMONDBACK_SKIN = 8939;
public static final int COAL_SKIN = 8940;
public static final int FRONTWINDER_SKIN = 8941;
public static final int ROTTING_SKIN = 8942;
public static final int QUICKSILVER_SPURS = 8947;
public static final int THICKSILVER_SPURS = 8948;
public static final int WICKSILVER_SPURS = 8949;
public static final int SLICKSILVER_SPURS = 8950;
public static final int SICKSILVER_SPURS = 8951;
public static final int NICKSILVER_SPURS = 8952;
public static final int TICKSILVER_SPURS = 8953;
public static final int COW_PUNCHING_TALES = 8955;
public static final int BEAN_SLINGING_TALES = 8956;
public static final int SNAKE_OILING_TALES = 8957;
public static final int SNAKE_OIL = 8971;
public static final int MEMORIES_OF_COW_PUNCHING = 8986;
public static final int MEMORIES_OF_BEAN_SLINGING = 8987;
public static final int MEMORIES_OF_SNAKE_OILING = 8988;
public static final int WITCHESS_SET = 8989;
public static final int BRAIN_TRAINER_GAME = 8990;
public static final int LASER_EYE_SURGERY_KIT = 8991;
public static final int SACRAMENTO_WINE = 8994;
public static final int CLAN_FLOUNDRY = 9000;
public static final int CARPE = 9001;
public static final int CODPIECE = 9002;
public static final int TROUTSERS = 9003;
public static final int BASS_CLARINET = 9004;
public static final int FISH_HATCHET = 9005;
public static final int TUNAC = 9006;
public static final int FISHING_POLE = 9007;
public static final int WRIGGLING_WORM = 9008;
public static final int FISHING_LINE = 9010;
public static final int FISHING_HAT = 9011;
public static final int TROUT_FISHING_IN_LOATHING = 9012;
public static final int ANTIQUE_TACKLEBOX = 9015;
public static final int VIRAL_VIDEO = 9017;
public static final int MEME_GENERATOR = 9019;
public static final int PLUS_ONE = 9020;
public static final int GALLON_OF_MILK = 9021;
public static final int PRINT_SCREEN = 9022;
public static final int SCREENCAPPED_MONSTER = 9023;
public static final int DAILY_DUNGEON_MALWARE = 9024;
public static final int BACON_MACHINE = 9025;
public static final int NO_SPOON = 9029;
public static final int SOURCE_TERMINAL = 9033;
public static final int SOURCE_ESSENCE = 9034;
public static final int BROWSER_COOKIE = 9035;
public static final int HACKED_GIBSON = 9036;
public static final int SOURCE_SHADES = 9037;
public static final int SOFTWARE_BUG = 9038;
public static final int SOURCE_TERMINAL_PRAM_CHIP = 9040;
public static final int SOURCE_TERMINAL_GRAM_CHIP = 9041;
public static final int SOURCE_TERMINAL_SPAM_CHIP = 9042;
public static final int SOURCE_TERMINAL_CRAM_CHIP = 9043;
public static final int SOURCE_TERMINAL_DRAM_CHIP = 9044;
public static final int SOURCE_TERMINAL_TRAM_CHIP = 9045;
public static final int SOURCE_TERMINAL_INGRAM_CHIP = 9046;
public static final int SOURCE_TERMINAL_DIAGRAM_CHIP = 9047;
public static final int SOURCE_TERMINAL_ASHRAM_CHIP = 9048;
public static final int SOURCE_TERMINAL_SCRAM_CHIP = 9049;
public static final int SOURCE_TERMINAL_TRIGRAM_CHIP = 9050;
public static final int SOURCE_TERMINAL_SUBSTATS_ENH = 9051;
public static final int SOURCE_TERMINAL_DAMAGE_ENH = 9052;
public static final int SOURCE_TERMINAL_CRITICAL_ENH = 9053;
public static final int SOURCE_TERMINAL_PROTECT_ENQ = 9054;
public static final int SOURCE_TERMINAL_STATS_ENQ = 9055;
public static final int SOURCE_TERMINAL_COMPRESS_EDU = 9056;
public static final int SOURCE_TERMINAL_DUPLICATE_EDU = 9057;
public static final int SOURCE_TERMINAL_PORTSCAN_EDU = 9058;
public static final int SOURCE_TERMINAL_TURBO_EDU = 9059;
public static final int SOURCE_TERMINAL_FAMILIAR_EXT = 9060;
public static final int SOURCE_TERMINAL_PRAM_EXT = 9061;
public static final int SOURCE_TERMINAL_GRAM_EXT = 9062;
public static final int SOURCE_TERMINAL_SPAM_EXT = 9063;
public static final int SOURCE_TERMINAL_CRAM_EXT = 9064;
public static final int SOURCE_TERMINAL_DRAM_EXT = 9065;
public static final int SOURCE_TERMINAL_TRAM_EXT = 9066;
public static final int COP_DOLLAR = 9072;
public static final int DETECTIVE_APPLICATION = 9073;
public static final int PROTON_ACCELERATOR = 9082;
public static final int STANDARDS_AND_PRACTICES = 9095;
public static final int RAD = 9100;
public static final int WRIST_BOY = 9102;
public static final int TIME_SPINNER = 9104;
public static final int HOLORECORD_SHRIEKING_WEASEL = 9109;
public static final int HOLORECORD_POWERGUY = 9110;
public static final int HOLORECORD_LUCKY_STRIKES = 9111;
public static final int HOLORECORD_EMD = 9112;
public static final int HOLORECORD_SUPERDRIFTER = 9113;
public static final int HOLORECORD_PIGS = 9114;
public static final int HOLORECORD_DRUNK_UNCLES = 9115;
public static final int TIME_RESIDUE = 9116;
public static final int EARL_GREY = 9122;
public static final int SCHOOL_OF_HARD_KNOCKS_DIPLOMA = 9123;
public static final int KOL_COL_13_SNOWGLOBE = 9133;
public static final int TRICK_TOT_KNIGHT = 9137;
public static final int TRICK_TOT_UNICORN = 9138;
public static final int TRICK_TOT_CANDY = 9139;
public static final int TRICK_TOT_ROBOT = 9143;
public static final int TRICK_TOT_EYEBALL = 9144;
public static final int TRICK_TOT_LIBERTY = 9145;
public static final int HOARDED_CANDY_WAD = 9146;
public static final int TWITCHING_TELEVISION_TATTOO = 9148;
public static final int STUFFING_FLUFFER = 9164;
public static final int TURKEY_BLASTER = 9166;
public static final int CANDIED_SWEET_POTATOES = 9171;
public static final int BREAD_ROLL = 9179;
public static final int CORNUCOPIA = 9183;
public static final int MEGACOPIA = 9184;
public static final int GIANT_PILGRIM_HAT = 9185;
public static final int THANKSGARDEN_SEEDS = 9186;
public static final int CASHEW = 9187;
public static final int BOMB_OF_UNKNOWN_ORIGIN = 9188;
public static final int GINGERBREAD_CITY = 9203;
public static final int COUNTERFEIT_CITY = 9204;
public static final int SPRINKLES = 9205;
public static final int VIGILANTE_BOOK = 9206;
public static final int BROKEN_CHOCOLATE_POCKETWATCH = 9215;
public static final int CLOD_OF_DIRT = 9216;
public static final int GINGERBREAD_RESTRAINING_ORDER = 9217;
public static final int GINGERBREAD_WINE = 9220;
public static final int GINGERBREAD_MUG = 9221;
public static final int GINGERSERVO = 9223;
public static final int GINGERBEARD = 9225;
public static final int CREME_BRULEE_TORCH = 9230;
public static final int GINGERBREAD_DOG_TREAT = 9233;
public static final int GINGERBREAD_CIGARETTE = 9237;
public static final int SPARE_CHOCOLATE_PARTS = 9240;
public static final int HIGH_END_GINGER_WINE = 9243;
public static final int MY_LIFE_OF_CRIME_BOOK = 9258;
public static final int POP_ART_BOOK = 9259;
public static final int NO_HATS_BOOK = 9260;
public static final int RETHINKING_CANDY_BOOK = 9261;
public static final int FRUIT_LEATHER_NEGATIVE = 9262;
public static final int GINGERBREAD_BLACKMAIL_PHOTOS = 9263;
public static final int TEETHPICK = 9265;
public static final int CHOCOLATE_SCULPTURE = 9269;
public static final int NO_HAT = 9270;
public static final int NEGATIVE_LUMP = 9272;
public static final int LUMP_STACKING_BOOK = 9285;
public static final int HOT_JELLY = 9291;
public static final int COLD_JELLY = 9292;
public static final int SPOOKY_JELLY = 9293;
public static final int SLEAZE_JELLY = 9294;
public static final int STENCH_JELLY = 9295;
public static final int HOT_TOAST = 9297;
public static final int COLD_TOAST = 9298;
public static final int SPOOKY_TOAST = 9299;
public static final int SLEAZE_TOAST = 9300;
public static final int STENCH_TOAST = 9301;
public static final int WAX_HAND = 9305;
public static final int MINIATURE_CANDLE = 9306;
public static final int WAX_PANCAKE = 9307;
public static final int WAX_FACE = 9308;
public static final int WAX_BOOZE = 9309;
public static final int WAX_GLOB = 9310;
public static final int HEART_SHAPED_CRATE = 9316;
public static final int LOVE_BOOMERANG = 9323;
public static final int LOVE_CHOCOLATE = 9325;
public static final int LOVE_ENTRANCE_PASS = 9330;
public static final int ELDRITCH_ICHOR = 9333;
public static final int ELDRITCH_TINCTURE = 9335;
public static final int ELDRITCH_TINCTURE_DEPLETED = 9336;
public static final int DIRTY_BOTTLECAP = 9343;
public static final int DISCARDED_BUTTON = 9344;
public static final int GUMMY_MEMORY = 9345;
public static final int NOVELTY_HOT_SAUCE = 9349;
public static final int COCKTAIL_MUSHROOM = 9353;
public static final int GRANOLA_LIQUEUR = 9354;
public static final int GREGNADIGNE = 9357;
public static final int FISH_HEAD = 9360;
public static final int BABY_OIL_SHOOTER = 9359;
public static final int LIMEPATCH = 9361;
public static final int LITERAL_GRASSHOPPER = 9365;
public static final int PISCATINI = 9378;
public static final int DRIVE_BY_SHOOTING = 9396;
public static final int PHIL_COLLINS = 9400;
public static final int TOGGLE_SWITCH_BARTEND = 9402;
public static final int TOGGLE_SWITCH_BOUNCE = 9403;
public static final int SPACEGATE_ACCESS_BADGE = 9404;
public static final int FILTER_HELMET = 9405;
public static final int EXO_SERVO_LEG_BRACES = 9406;
public static final int RAD_CLOAK = 9407;
public static final int GATE_TRANCEIVER = 9408;
public static final int HIGH_FRICTION_BOOTS = 9409;
public static final int SPACEGATE_RESEARCH = 9410;
public static final int ALIEN_ROCK_SAMPLE = 9411;
public static final int ALIEN_GEMSTONE = 9412;
public static final int ALIEN_PLANT_FIBERS = 9416;
public static final int ALIEN_PLANT_SAMPLE = 9417;
public static final int COMPLEX_ALIEN_PLANT_SAMPLE = 9418;
public static final int FASCINATING_ALIEN_PLANT_SAMPLE = 9419;
public static final int ALIEN_PLANT_POD = 9421;
public static final int ALIEN_TOENAILS = 9424;
public static final int ALIEN_ZOOLOGICAL_SAMPLE = 9425;
public static final int COMPLEX_ALIEN_ZOOLOGICAL_SAMPLE = 9426;
public static final int FASCINATING_ALIEN_ZOOLOGICAL_SAMPLE = 9427;
public static final int ALIEN_ANIMAL_MILK = 9429;
public static final int SPANT_EGG_CASING = 9430;
public static final int MURDERBOT_DATA_CORE = 9431;
public static final int SPANT_CHITIN = 9441;
public static final int PRIMITIVE_ALIEN_TOTEM = 9439;
public static final int SPANT_TENDON = 9442;
public static final int MURDERBOT_MEMORY_CHIP = 9457;
public static final int SPACE_PIRATE_TREASURE_MAP = 9458;
public static final int SPACE_PIRATE_ASTROGATION_HANDBOOK = 9459;
public static final int NON_EUCLIDEAN_FINANCE = 9460;
public static final int PEEK_A_BOO = 9461;
public static final int PROCRASTINATOR_LOCKER_KEY = 9462;
public static final int SPACE_BABY_CHILDRENS_BOOK = 9463;
public static final int SPACE_BABY_BAWBAW = 9464;
public static final int PORTABLE_SPACEGATE = 9465;
public static final int OPEN_PORTABLE_SPACEGATE = 9477;
public static final int NEW_YOU_CLUB_MEMBERSHIP_FORM = 9478;
public static final int AFFIRMATION_SUPERFICIALLY_INTERESTED = 9481;
public static final int AFFIRMATION_MIND_MASTER = 9483;
public static final int AFFIRMATION_HATE = 9485;
public static final int AFFIRMATION_COOKIE = 9486;
public static final int LICENSE_TO_KILL = 9487;
public static final int VICTOR_SPOILS = 9493;
public static final int KREMLIN_BRIEFCASE = 9493;
public static final int LICENSE_TO_CHILL = 9503;
public static final int CELSIUS_233 = 9504;
public static final int CELSIUS_233_SINGED = 9505;
public static final int LAZENBY = 9506;
public static final int ASDON_MARTIN = 9508;
public static final int METEORITE_ADE = 9513;
public static final int METAL_METEOROID = 9516;
public static final int METEORTARBOARD = 9517;
public static final int METEORITE_GUARD = 9518;
public static final int METEORB = 9519;
public static final int ASTEROID_BELT = 9520;
public static final int METEORTHOPEDIC_SHOES = 9521;
public static final int SHOOTING_MORNING_STAR = 9522;
public static final int PERFECTLY_FAIR_COIN = 9526;
public static final int CORKED_GENIE_BOTTLE = 9528;
public static final int GENIE_BOTTLE = 9529;
public static final int POCKET_WISH = 9537;
public static final int SHOVELFUL_OF_EARTH = 9539;
public static final int HUNK_OF_GRANITE = 9540;
public static final int X = 9543;
public static final int O = 9544;
public static final int MAFIA_PINKY_RING = 9546;
public static final int FLASK_OF_PORT = 9547;
public static final int BRIDGE_TRUSS = 9556;
public static final int AMORPHOUS_BLOB = 9558;
public static final int GIANT_AMORPHOUS_BLOB = 9561;
public static final int MAFIA_THUMB_RING = 9564;
public static final int PORTABLE_PANTOGRAM = 9573;
public static final int PANTOGRAM_PANTS = 9574;
public static final int MUMMING_TRUNK = 9592;
public static final int EARTHENWARE_MUFFIN_TIN = 9596;
public static final int BRAN_MUFFIN = 9597;
public static final int BLUEBERRY_MUFFIN = 9598;
public static final int CRYSTALLINE_CHEER = 9625;
public static final int WAREHOUSE_KEY = 9627;
public static final int MIME_SCIENCE_VOL_1 = 9635;
public static final int MIME_SCIENCE_VOL_1_USED = 9636;
public static final int MIME_SCIENCE_VOL_2 = 9637;
public static final int MIME_SCIENCE_VOL_2_USED = 9638;
public static final int MIME_SCIENCE_VOL_3 = 9639;
public static final int MIME_SCIENCE_VOL_3_USED = 9640;
public static final int MIME_SCIENCE_VOL_4 = 9641;
public static final int MIME_SCIENCE_VOL_4_USED = 9642;
public static final int MIME_SCIENCE_VOL_5 = 9643;
public static final int MIME_SCIENCE_VOL_5_USED = 9644;
public static final int MIME_SCIENCE_VOL_6 = 9645;
public static final int MIME_SCIENCE_VOL_6_USED = 9646;
public static final int GOD_LOBSTER = 9661;
public static final int DONATED_BOOZE = 9662;
public static final int DONATED_FOOD = 9663;
public static final int DONATED_CANDY = 9664;
public static final int MIME_ARMY_INSIGNIA_INFANTRY = 9667;
public static final int MIME_ARMY_INFILTRATION_GLOVE = 9675;
public static final int MIME_SHOTGLASS = 9676;
public static final int TOASTED_HALF_SANDWICH = 9681;
public static final int MULLED_HOBO_WINE = 9682;
public static final int BURNING_NEWSPAPER = 9683;
public static final int BURNING_HAT = 9684;
public static final int BURNING_CAPE = 9685;
public static final int BURNING_SLIPPERS = 9686;
public static final int BURNING_JORTS = 9687;
public static final int BURNING_CRANE = 9688;
public static final int GARBAGE_TOTE = 9690;
public static final int DECEASED_TREE = 9691;
public static final int BROKEN_CHAMPAGNE = 9692;
public static final int TINSEL_TIGHTS = 9693;
public static final int WAD_OF_TAPE = 9694;
public static final int MAKESHIFT_GARBAGE_SHIRT = 9699;
public static final int DIETING_PILL = 9707;
public static final int CLAN_CARNIVAL_GAME = 9712;
public static final int GET_BIG_BOOK = 9713;
public static final int GALAPAGOS_BOOK = 9714;
public static final int FUTURE_BOOK = 9715;
public static final int LOVE_POTION_BOOK = 9716;
public static final int RHINESTONE_BOOK = 9717;
public static final int LOVE_SONG_BOOK = 9718;
public static final int MYSTERIOUS_RED_BOX = 9739;
public static final int MYSTERIOUS_GREEN_BOX = 9740;
public static final int MYSTERIOUS_BLUE_BOX = 9741;
public static final int MYSTERIOUS_BLACK_BOX = 9742;
public static final int LOVE_POTION_XYZ = 9745;
public static final int POKEDOLLAR_BILLS = 9747;
public static final int METANDIENONE = 9748;
public static final int RIBOFLAVIN = 9749;
public static final int BRONZE = 9750;
public static final int PIRACETAM = 9751;
public static final int ULTRACALCIUM = 9752;
public static final int GINSENG = 9753;
public static final int TALL_GRASS_SEEDS = 9760;
public static final int POKE_GROW_FERTILIZER = 9761;
public static final int LUCK_INCENSE = 9821;
public static final int SHELL_BELL = 9822;
public static final int MUSCLE_BAND = 9823;
public static final int AMULET_COIN = 9824;
public static final int RAZOR_FANG = 9825;
public static final int SMOKE_BALL = 9826;
public static final int GREEN_ROCKET = 9827;
public static final int MAGNIFICENT_OYSTER_EGG = 9828;
public static final int BRILLIANT_OYSTER_EGG = 9829;
public static final int GLISTENING_OYSTER_EGG = 9830;
public static final int SCINTILATING_OYSTER_EGG = 9831;
public static final int PEARLESCENT_OYSTER_EGG = 9832;
public static final int LUSTROUS_OYSTER_EGG = 9833;
public static final int GLEAMING_OYSTER_EGG = 9834;
public static final int FR_MEMBER = 9835;
public static final int FR_GUEST = 9836;
public static final int FANTASY_REALM_GEM = 9837;
public static final int RUBEE = 9838;
public static final int FR_WARRIOR_HELM = 9839;
public static final int FR_MAGE_HAT = 9840;
public static final int FR_ROGUE_MASK = 9841;
public static final int FR_KEY = 9844;
public static final int FR_PURPLE_MUSHROOM = 9845;
public static final int FR_TAINTED_MARSHMALLOW = 9846;
public static final int FR_CHESWICKS_NOTES = 9847;
public static final int MY_FIRST_ART_OF_WAR = 9850;
public static final int FR_DRAGON_ORE = 9851;
public static final int FR_POISONED_SMORE = 9853;
public static final int FR_DRUIDIC_ORB = 9854;
public static final int FR_HOLY_WATER = 9856;
public static final int CONTRACTOR_MANUAL = 9861;
public static final int FR_CHESWICKS_COMPASS = 9865;
public static final int FR_ARREST_WARRANT = 9866;
public static final int FR_MOUNTAIN_MAP = 9873;
public static final int FR_WOOD_MAP = 9874;
public static final int FR_SWAMP_MAP = 9875;
public static final int FR_VILLAGE_MAP = 9876;
public static final int FR_CEMETARY_MAP = 9877;
public static final int FR_CHARGED_ORB = 9895;
public static final int FR_NOTARIZED_WARRANT = 9897;
public static final int CLARIFIED_BUTTER = 9908;
public static final int G = 9909;
public static final int GARLAND_OF_GREATNESS = 9910;
public static final int GLUED_BOO_CLUE = 9913;
public static final int BOOMBOX = 9919;
public static final int GUIDE_TO_SAFARI = 9921;
public static final int SHIELDING_POTION = 9922;
public static final int PUNCHING_POTION = 9923;
public static final int SPECIAL_SEASONING = 9924;
public static final int NIGHTMARE_FUEL = 9925;
public static final int MEAT_CLIP = 9926;
public static final int CHEESE_WHEEL = 9937;
public static final int BASTILLE_LOANER_VOUCHER = 9938;
public static final int NEVERENDING_PARTY_INVITE = 9942;
public static final int NEVERENDING_PARTY_INVITE_DAILY = 9943;
public static final int PARTY_HARD_T_SHIRT = 9944;
public static final int ELECTRONICS_KIT = 9952;
public static final int PAINT_PALETTE = 9956;
public static final int PURPLE_BEAST_ENERGY_DRINK = 9958;
public static final int PUMP_UP_HIGH_TOPS = 9961;
public static final int VERY_SMALL_RED_DRESS = 9963;
public static final int EVERFULL_GLASS = 9966;
public static final int JAM_BAND_BOOTLEG = 9968;
public static final int INTIMIDATING_CHAINSAW = 9972;
public static final int PARTY_PLANNING_BOOK = 9978;
public static final int PARTYCRASHER = 9983;
public static final int DRINKING_TO_DRINK_BOOK = 9984;
public static final int LATTE_MUG = 9987;
public static final int VOTER_REGISTRATION_FORM = 9989;
public static final int I_VOTED_STICKER = 9990;
public static final int VOTER_BALLOT = 9991;
public static final int BLACK_SLIME_GLOB = 9996;
public static final int GREEN_SLIME_GLOB = 9997;
public static final int ORANGE_SLIME_GLOB = 9998;
public static final int GOVERNMENT_REQUISITION_FORM = 10003;
public static final int HAUNTED_HELL_RAMEN = 10018;
public static final int WALRUS_BLUBBER = 10034;
public static final int TINY_BOMB = 10036;
public static final int MOOSEFLANK = 10038;
public static final int BOXING_DAY_CARE = 10049;
public static final int BOXING_DAY_PASS = 10056;
public static final int SAUSAGE_O_MATIC = 10058;
public static final int MAGICAL_SAUSAGE_CASING = 10059;
public static final int MAGICAL_SAUSAGE = 10060;
public static final int CRIMBO_CANDLE = 10072;
public static final int CHALK_CHUNKS = 10088;
public static final int MARBLE_MOECULES = 10096;
public static final int PARAFFIN_PSEUDOACCORDION = 10103;
public static final int PARAFFIN_PIECES = 10104;
public static final int TERRA_COTTA_TIDBITS = 10112;
public static final int TRYPTOPHAN_DART = 10159;
public static final int DOCTOR_BAG = 10166;
public static final int BOOKE_OF_VAMPYRIC_KNOWLEDGE = 10180;
public static final int VAMPYRE_BLOOD = 10185;
public static final int GLITCH_ITEM = 10207;
public static final int PR_MEMBER = 10187;
public static final int PR_GUEST = 10188;
public static final int CURSED_COMPASS = 10191;
public static final int ISLAND_DRINKIN = 10211;
public static final int PIRATE_REALM_FUN_LOG = 10225;
public static final int PIRATE_FORK = 10227;
public static final int SCURVY_AND_SOBRIETY_PREVENTION = 10228;
public static final int LUCKY_GOLD_RING = 10229;
public static final int VAMPYRIC_CLOAKE = 10242;
public static final int FOURTH_SABER = 10251;
public static final int RING = 10252;
public static final int HEWN_MOON_RUNE_SPOON = 10254;
public static final int BEACH_COMB = 10258;
public static final int ETCHED_HOURGLASS = 10265;
public static final int PIECE_OF_DRIFTWOOD = 10281;
public static final int DRIFTWOOD_BEACH_COMB = 10291;
public static final int STICK_OF_FIREWOOD = 10293;
public static final int GETAWAY_BROCHURE = 10292;
public static final int RARE_MEAT_ISOTOPE = 10310;
public static final int BURNT_STICK = 10311;
public static final int BUNDLE_OF_FIREWOOD = 10312;
public static final int CAMPFIRE_SMOKE = 10313;
public static final int THE_IMPLODED_WORLD = 10322;
public static final int POCKET_PROFESSOR_MEMORY_CHIP = 10324;
public static final int LAW_OF_AVERAGES = 10325;
public static final int PILL_KEEPER = 10333;
public static final int DIABOLIC_PIZZA_CUBE = 10335;
public static final int DIABOLIC_PIZZA = 10336;
public static final int HUMAN_MUSK = 10350;
public static final int EXTRA_WARM_FUR = 10351;
public static final int INDUSTRIAL_LUBRICANT = 10352;
public static final int UNFINISHED_PLEASURE = 10353;
public static final int HUMANOID_GROWTH_HORMONE = 10354;
public static final int BUG_LYMPH = 10355;
public static final int ORGANIC_POTPOURRI = 10356;
public static final int BOOT_FLASK = 10357;
public static final int INFERNAL_SNOWBALL = 10358;
public static final int POWDERED_MADNESS = 10359;
public static final int FISH_SAUCE = 10360;
public static final int GUFFIN = 10361;
public static final int SHANTIX = 10362;
public static final int GOODBERRY = 10363;
public static final int EUCLIDEAN_ANGLE = 10364;
public static final int PEPPERMINT_SYRUP = 10365;
public static final int MERKIN_EYEDROPS = 10366;
public static final int EXTRA_STRENGTH_GOO = 10367;
public static final int ENVELOPE_MEAT = 10368;
public static final int LIVID_ENERGY = 10369;
public static final int MICRONOVA = 10370;
public static final int BEGGIN_COLOGNE = 10371;
public static final int THE_SPIRIT_OF_GIVING = 10380;
public static final int PEPPERMINT_EEL_SAUCE = 10416;
public static final int GREEN_AND_RED_BEAN = 10417;
public static final int TEMPURA_GREEN_AND_RED_BEAN = 10425;
public static final int BIRD_A_DAY_CALENDAR = 10434;
public static final int POWERFUL_GLOVE = 10438;
public static final int DRIP_HARNESS = 10441;
public static final int DRIPPY_TRUNCHEON = 10442;
public static final int DRIPLET = 10443;
public static final int DRIPPY_SNAIL_SHELL = 10444;
public static final int DRIPPY_NUGGET = 10445;
public static final int DRIPPY_WINE = 10446;
public static final int DRIPPY_CAVIAR = 10447;
public static final int DRIPPY_PLUM = 10448;
public static final int EYE_OF_THE_THING = 10450;
public static final int DRIPPY_SHIELD = 10452;
public static final int FIRST_PLUMBER_QUEST_ITEM = 10454;
public static final int COIN = 10454;
public static final int MUSHROOM = 10455;
public static final int DELUXE_MUSHROOM = 10456;
public static final int SUPER_DELUXE_MUSHROOM = 10457;
public static final int HAMMER = 10460;
public static final int HEAVY_HAMMER = 10461;
public static final int PLUMBER_FIRE_FLOWER = 10462;
public static final int BONFIRE_FLOWER = 10463;
public static final int WORK_BOOTS = 10464;
public static final int FANCY_BOOTS = 10465;
public static final int POWER_PANTS = 10469;
public static final int FROSTY_BUTTON = 10473;
public static final int LAST_PLUMBER_QUEST_ITEM = 10474;
public static final int MUSHROOM_SPORES = 10482;
public static final int FREE_RANGE_MUSHROOM = 10483;
public static final int PLUMP_FREE_RANGE_MUSHROOM = 10484;
public static final int BULKY_FREE_RANGE_MUSHROOM = 10485;
public static final int GIANT_FREE_RANGE_MUSHROOM = 10486;
public static final int IMMENSE_FREE_RANGE_MUSHROOM = 10487;
public static final int COLOSSAL_FREE_RANGE_MUSHROOM = 10488;
public static final int HOUSE_SIZED_MUSHROOM = 10497;
public static final int RED_PLUMBERS_BOOTS = 10501;
public static final int DRIPPY_STEIN = 10524;
public static final int DRIPPY_PILSNER = 10525;
public static final int DRIPPY_STAFF = 10526;
public static final int GUZZLR_TABLET = 10533;
public static final int GUZZLR_COCKTAIL_SET = 10534;
public static final int GUZZLRBUCK = 10535;
public static final int GUZZLR_SHOES = 10537;
public static final int CLOWN_CAR_KEY = 10547;
public static final int BATTING_CAGE_KEY = 10548;
public static final int AQUI = 10549;
public static final int KNOB_LABINET_KEY = 10550;
public static final int WEREMOOSE_KEY = 10551;
public static final int PEG_KEY = 10552;
public static final int KEKEKEY = 10553;
public static final int RABBITS_FOOT_KEY = 10554;
public static final int KNOB_SHAFT_SKATE_KEY = 10555;
public static final int ICE_KEY = 10556;
public static final int ANCHOVY_CAN_KEY = 10557;
public static final int CACTUS_KEY = 10558;
public static final int F_C_LE_SH_C_LE_K_Y = 10559;
public static final int TREASURE_CHEST_KEY = 10560;
public static final int DEMONIC_KEY = 10561;
public static final int KEY_SAUSAGE = 10562;
public static final int KNOB_TREASURY_KEY = 10563;
public static final int SCRAP_METAL_KEY = 10564;
public static final int BLACK_ROSE_KEY = 10565;
public static final int MUSIC_BOX_KEY = 10566;
public static final int ACTUAL_SKELETON_KEY = 10567;
public static final int DEEP_FRIED_KEY = 10568;
public static final int DISCARDED_BIKE_LOCK_KEY = 10569;
public static final int MANUAL_OF_LOCK_PICKING = 10571;
public static final int DROMEDARY_DRINKING_HELMENT = 10580;
public static final int SPINMASTER = 10582;
public static final int FLIMSY_HARDWOOD_SCRAPS = 10583;
public static final int DREADSYLVANIAN_HEMLOCK = 10589;
public static final int HEMLOCK_HELM = 10590;
public static final int SWEATY_BALSAM = 10591;
public static final int BALSAM_BARREL = 10592;
public static final int ANCIENT_REDWOOD = 10593;
public static final int REDWOOD_RAIN_STICK = 10594;
public static final int PURPLEHEART_LOGS = 10595;
public static final int PURPLEHEART_PANTS = 10596;
public static final int WORMWOOD_STICK = 10597;
public static final int WORMWOOD_WEDDING_RING = 10598;
public static final int DRIPWOOD_SLAB = 10599;
public static final int DRIPPY_DIADEM = 10600;
public static final int GREY_GOO_RING = 10602;
public static final int SIZZLING_DESK_BELL = 10617;
public static final int FROST_RIMED_DESK_BELL = 10618;
public static final int UNCANNY_DESK_BELL = 10619;
public static final int NASTY_DESK_BELL = 10620;
public static final int GREASY_DESK_BELL = 10621;
public static final int FANCY_CHESS_SET = 10622;
public static final int ONYX_KING = 10623;
public static final int ONYX_QUEEN = 10624;
public static final int ONYX_ROOK = 10625;
public static final int ONYX_BISHOP = 10626;
public static final int ONYX_KNIGHT = 10627;
public static final int ONYX_PAWN = 10628;
public static final int ALABASTER_KING = 10629;
public static final int ALABASTER_QUEEN = 10630;
public static final int ALABASTER_ROOK = 10631;
public static final int ALABASTER_BISHOP = 10632;
public static final int ALABASTER_KNIGHT = 10633;
public static final int ALABASTER_PAWN = 10634;
public static final int CARGO_CULTIST_SHORTS = 10636;
public static final int UNIVERSAL_SEASONING = 10640;
public static final int CHOCOLATE_CHIP_MUFFIN = 10643;
public static final int KNOCK_OFF_RETRO_SUPERHERO_CAPE = 10647;
public static final int SUBSCRIPTION_COCOA_DISPENSER = 10652;
public static final int OVERFLOWING_GIFT_BASKET = 10670;
public static final int FOOD_DRIVE_BUTTON = 10691;
public static final int BOOZE_DRIVE_BUTTON = 10692;
public static final int CANDY_DRIVE_BUTTON = 10693;
public static final int FOOD_MAILING_LIST = 10694;
public static final int BOOZE_MAILING_LIST = 10695;
public static final int CANDY_MAILING_LIST = 10696;
public static final int GOVERNMENT_FOOD_SHIPMENT = 10685;
public static final int GOVERNMENT_BOOZE_SHIPMENT = 10686;
public static final int GOVERNMENT_CANDY_SHIPMENT = 10687;
public static final int MINIATURE_CRYSTAL_BALL = 10730;
public static final int COAT_OF_PAINT = 10732;
public static final int SPINAL_FLUID_COVERED_EMOTION_CHIP = 10734;
public static final int BATTERY_9V = 10742;
public static final int BATTERY_LANTERN = 10743;
public static final int BATTERY_CAR = 10744;
public static final int GREEN_MARSHMALLOW = 10746;
public static final int MARSHMALLOW_BOMB = 10747;
public static final int BACKUP_CAMERA = 10749;
public static final int BLUE_PLATE = 10751;
public static final int FAMILIAR_SCRAPBOOK = 10759;
public static final int CLAN_UNDERGROUND_FIREWORKS_SHOP = 10761;
public static final int FEDORA_MOUNTED_FOUNTAIN = 10762;
public static final int PORKPIE_MOUNTED_POPPER = 10763;
public static final int SOMBRERO_MOUNTED_SPARKLER = 10764;
public static final int CATHERINE_WHEEL = 10770;
public static final int ROCKET_BOOTS = 10771;
public static final int OVERSIZED_SPARKLER = 10772;
public static final int EXTRA_WIDE_HEAD_CANDLE = 10783;
public static final int BLART = 10790;
public static final int RAINPROOF_BARREL_CAULK = 10794;
public static final int PUMP_GREASE = 10795;
public static final int INDUSTRIAL_FIRE_EXTINGUISHER = 10797;
public static final int VAMPIRE_VINTNER_WINE = 10800;
public static final int DAYLIGHT_SHAVINGS_HELMET = 10804;
public static final int COLD_MEDICINE_CABINET = 10815;
public static final int HOMEBODYL = 10828;
public static final int EXTROVERMECTIN = 10829;
public static final int BREATHITIN = 10830;
public static final int FLESHAZOLE = 10831;
public static final int GOOIFIED_ANIMAL_MATTER = 10844;
public static final int GOOIFIED_VEGETABLE_MATTER = 10845;
public static final int GOOIFIED_MINERAL_MATTER = 10846;
public static final int CARNIVOROUS_POTTED_PLANT = 10864;
public static final int MEATBALL_MACHINE = 10878;
public static final int REFURBISHED_AIR_FRYER = 10879;
public static final int ELEVEN_LEAF_CLOVER = 10881;
public static final int CURSED_MAGNIFYING_GLASS = 10885;
public static final int COSMIC_BOWLING_BALL = 10891;
public static final int COMBAT_LOVERS_LOCKET = 10893;
public static final int UNBREAKABLE_UMBRELLA = 10899;
public static final int MAYDAY_SUPPLY_PACKAGE = 10901;
public static final int SURVIVAL_KNIFE = 10903;
public static final int THE_BIG_BOOK_OF_EVERY_SKILL = 10917;
public static final int JUNE_CLEAVER = 10920;
public static final int MOTHERS_NECKLACE = 10925;
public static final int DESIGNER_SWEATPANTS = 10929;
public static final int STILLSUIT = 10932;
public static final int DINODOLLAR = 10944;
public static final int DINOSAUR_DROPPINGS = 10945;
public static final int JURASSIC_PARKA = 10952;
public static final int AUTUMNATON = 10954;
public static final int ROBY_RATATOUILLE_DE_JARLSBERG = 10979;
public static final int ROBY_JARLSBERGS_VEGETABLE_SOUP = 10980;
public static final int ROBY_ROASTED_VEGETABLE_OF_J = 10981;
public static final int ROBY_PETES_SNEAKY_SMOOTHIE = 10982;
public static final int ROBY_PETES_WILY_WHEY_BAR = 10983;
public static final int ROBY_PETES_RICH_RICOTTA = 10984;
public static final int ROBY_BORIS_BEER = 10985;
public static final int ROBY_HONEY_BUN_OF_BORIS = 10986;
public static final int ROBY_BORIS_BREAD = 10987;
public static final int PIZZA_OF_LEGEND = 10991;
public static final int CALZONE_OF_LEGEND = 10992;
public static final int ROBY_CALZONE_OF_LEGEND = 10993;
public static final int ROBY_PIZZA_OF_LEGEND = 10994;
public static final int ROBY_ROASTED_VEGETABLE_FOCACCIA = 10995;
public static final int ROBY_PLAIN_CALZONE = 10996;
public static final int ROBY_BAKED_VEGGIE_RICOTTA = 10997;
public static final int ROBY_DEEP_DISH_OF_LEGEND = 10999;
public static final int DEEP_DISH_OF_LEGEND = 11000;
public static final int DEED_TO_OLIVERS_PLACE = 11001;
public static final int DRINK_CHIT = 11002;
public static final int GOVERNMENT_PER_DIEM = 11003;
public static final int MILK_CAP = 11012;
public static final int CHARLESTON_CHOO_CHOO = 11013;
public static final int VELVET_VEIL = 11014;
public static final int MARLTINI = 11015;
public static final int STRONG_SILENT_TYPE = 11016;
public static final int MYSTERIOUS_STRANGER = 11017;
public static final int CHAMPAGNE_SHIMMY = 11018;
public static final int THE_SOTS_PARCEL = 11019;
public static final int MODEL_TRAIN_SET = 11045;
public static final int CRIMBO_TRAINING_MANUAL = 11046;
public static final int PING_PONG_PADDLE = 11056;
public static final int PING_PONG_BALL = 11057;
public static final int TRAINBOT_HARNESS = 11058;
public static final int PING_PONG_TABLE = 11059;
public static final int TRAINBOT_AUTOASSEMBLY_MODULE = 11061;
public static final int CRIMBO_CRYSTAL_SHARDS = 11066;
public static final int LOST_ELF_LUGGAGE = 11068;
public static final int TRAINBOT_LUGGAGE_HOOK = 11069;
public static final int WHITE_ARM_TOWEL = 11073;
public static final int TRAINBOT_SLAG = 11076;
public static final int PORTABLE_STEAM_UNIT = 11081;
public static final int CRYSTAL_CRIMBO_GOBLET = 11082;
public static final int CRYSTAL_CRIMBO_PLATTER = 11083;
public static final int GRUBBY_WOOL = 11091;
public static final int GRUBBY_WOOL_HAT = 11092;
public static final int GRUBBY_WOOL_SCARF = 11093;
public static final int GRUBBY_WOOL_TROUSERS = 11094;
public static final int GRUBBY_WOOL_GLOVES = 11095;
public static final int GRUBBY_WOOL_BEERWARMER = 11096;
public static final int NICE_WARM_BEER = 11097;
public static final int GRUBBY_WOOLBALL = 11098;
public static final int ROCK_SEEDS = 11100;
public static final int GROVELING_GRAVEL = 11101;
public static final int FRUITY_PEBBLE = 11102;
public static final int LODESTONE = 11103;
public static final int MILESTONE = 11104;
public static final int BOLDER_BOULDER = 11105;
public static final int MOLEHILL_MOUNTAIN = 11106;
public static final int WHETSTONE = 11107;
public static final int HARD_ROCK = 11108;
public static final int STRANGE_STALAGMITE = 11109;
public static final int CHOCOLATE_COVERED_PING_PONG_BALL = 11110;
public static final int SIT_COURSE_COMPLETION_CERTIFICATE = 11116;
public static final int SHADOW_SAUSAGE = 11135;
public static final int SHADOW_SKIN = 11136;
public static final int SHADOW_FLAME = 11137;
public static final int SHADOW_BREAD = 11138;
public static final int SHADOW_ICE = 11139;
public static final int SHADOW_FLUID = 11140;
public static final int SHADOW_GLASS = 11141;
public static final int SHADOW_BRICK = 11142;
public static final int SHADOW_SINEW = 11143;
public static final int SHADOW_VENOM = 11144;
public static final int SHADOW_NECTAR = 11145;
public static final int SHADOW_STICK = 11146;
public static final int ADVANCED_PIG_SKINNING = 11163;
public static final int THE_CHEESE_WIZARDS_COMPANION = 11164;
public static final int JAZZ_AGENT_SHEET_MUSIC = 11165;
public static final int SHADOWY_CHEAT_SHEET = 11167;
public static final int CLOSED_CIRCUIT_PAY_PHONE = 11169;
public static final int SHADOW_LIGHTER = 11170;
public static final int SHADOW_HEPTAHEDRON = 11171;
public static final int SHADOW_SNOWFLAKE = 11172;
public static final int SHADOW_HEART = 11173;
public static final int SHADOW_BUCKET = 11174;
public static final int SHADOW_WAVE = 11175;
public static final int RUFUS_SHADOW_LODESTONE = 11176;
public static final int SHADOW_CHEFS_HAT = 11177;
public static final int SHADOW_TROUSERS = 11178;
public static final int SHADOW_HAMMER = 11179;
public static final int SHADOW_MONOCLE = 11180;
public static final int SHADOW_CANDLE = 11181;
public static final int SHADOW_HOT_DOG = 11182;
public static final int SHADOW_MARTINI = 11183;
public static final int SHADOW_PILL = 11184;
public static final int SHADOW_NEEDLE = 11185;
public static final int CURSED_MONKEY_PAW = 11186;
public static final int REPLICA_MR_ACCESSORY = 11189;
public static final int REPLICA_DARK_JILL = 11190;
public static final int REPLICA_HAND_TURKEY = 11191;
public static final int REPLICA_CRIMBO_ELF = 11192;
public static final int REPLICA_BUGBEAR_SHAMAN = 11193;
public static final int REPLICA_SNOWCONE_BOOK = 11197;
public static final int REPLICA_JEWEL_EYED_WIZARD_HAT = 11199;
public static final int REPLICA_BOTTLE_ROCKET = 11200;
public static final int REPLICA_NAVEL_RING = 11201;
public static final int REPLICA_V_MASK = 11202;
public static final int REPLICA_HAIKU_KATANA = 11203;
public static final int REPLICA_FIREWORKS = 11204;
public static final int REPLICA_COTTON_CANDY_COCOON = 11205;
public static final int REPLICA_ELVISH_SUNGLASSES = 11206;
public static final int REPLICA_SQUAMOUS_POLYP = 11207;
public static final int REPLICA_GREAT_PANTS = 11209;
public static final int REPLICA_ORGAN_GRINDER = 11210;
public static final int REPLICA_JUJU_MOJO_MASK = 11211;
public static final int REPLICA_PATRIOT_SHIELD = 11212;
public static final int REPLICA_RESOLUTION_BOOK = 11213;
public static final int REPLICA_PLASTIC_VAMPIRE_FANGS = 11214;
public static final int REPLICA_CUTE_ANGEL = 11215;
public static final int REPLICA_DEACTIVATED_NANOBOTS = 11217;
public static final int REPLICA_BANDERSNATCH = 11218;
public static final int REPLICA_SMITH_BOOK = 11219;
public static final int REPLICA_FOLDER_HOLDER = 11220;
public static final int CINCHO_DE_MAYO = 11223;
public static final int REPLICA_STILL_GRILL = 11226;
public static final int REPLICA_CRIMBO_SAPLING = 11227;
public static final int REPLICA_YELLOW_PUCK = 11228;
public static final int REPLICA_CHATEAU_ROOM_KEY = 11229;
public static final int REPLICA_DECK_OF_EVERY_CARD = 11230;
public static final int REPLICA_INTERGNAT = 11232;
public static final int REPLICA_WITCHESS_SET = 11233;
public static final int REPLICA_GENIE_BOTTLE = 11234;
public static final int REPLICA_SPACE_PLANULA = 11235;
public static final int REPLICA_ROBORTENDER = 11236;
public static final int REPLICA_NEVERENDING_PARTY_INVITE = 11237;
public static final int REPLICA_GOD_LOBSTER = 11239;
public static final int REPLICA_SAUSAGE_O_MATIC = 11241;
public static final int REPLICA_CAMELCALF = 11243;
public static final int REPLICA_POWERFUL_GLOVE = 11244;
public static final int REPLICA_GREY_GOSLING = 11250;
public static final int REPLICA_DESIGNER_SWEATPANTS = 11251;
public static final int REPLICA_TEN_DOLLARS = 11253;
public static final int REPLICA_CINCHO_DE_MAYO = 11254;
private ItemPool() {}
public static final AdventureResult get(String itemName, int count) {
int itemId = ItemDatabase.getItemId(itemName, 1, false);
if (itemId != -1) {
return ItemPool.get(itemId, count);
}
return AdventureResult.tallyItem(itemName, count, false);
}
public static final AdventureResult get(int itemId, int count) {
return new AdventureResult(itemId, count, false);
}
public static final AdventureResult get(int itemId) {
return new AdventureResult(itemId, 1, false);
}
// Support for various classes of items:
// El Vibrato helmet
public static final String[] EV_HELMET_CONDUITS =
new String[] {
"ATTACK", "BUILD", "BUFF", "MODIFY", "REPAIR", "TARGET", "SELF", "DRONE", "WALL"
};
public static final List<String> EV_HELMET_LEVELS =
Arrays.asList(
"PA",
"ZERO",
"NOKGAGA",
"NEGLIGIBLE",
"GABUHO NO",
"EXTREMELY LOW",
"GA NO",
"VERY LOW",
"NO",
"LOW",
"FUZEVENI",
"MODERATE",
"PAPACHA",
"ELEVATED",
"FU",
"HIGH",
"GA FU",
"VERY HIGH",
"GABUHO FU",
"EXTREMELY HIGH",
"CHOSOM",
"MAXIMAL");
// BANG POTIONS and SLIME VIALS
public static final String[][] bangPotionStrings = {
// name, combat use mssage, inventory use message
{"inebriety", "wino", "liquid fire"},
{"healing", "better", "You gain"},
{"confusion", "confused", "Confused"},
{"blessing", "stylish", "Izchak's Blessing"},
{"detection", "blink", "Object Detection"},
{"sleepiness", "yawn", "Sleepy"},
{"mental acuity", "smarter", "Strange Mental Acuity"},
{"ettin strength", "stronger", "Strength of Ten Ettins"},
{"teleportitis", "disappearing", "Teleportitis"},
};
public static final String[][][] slimeVialStrings = {
// name, inventory use mssage
{ // primary
{"strong", "Slimily Strong"},
{"sagacious", "Slimily Sagacious"},
{"speedy", "Slimily Speedy"},
},
{ // secondary
{"brawn", "Bilious Brawn"},
{"brains", "Bilious Brains"},
{"briskness", "Bilious Briskness"},
},
{ // tertiary
{"slimeform", "Slimeform"},
{"eyesight", "Ichorous Eyesight"},
{"intensity", "Ichorous Intensity"},
{"muscle", "Mucilaginous Muscle"},
{"mentalism", "Mucilaginous Mentalism"},
{"moxiousness", "Mucilaginous Moxiousness"},
},
};
public static final boolean eliminationProcessor(
final String[][] strings,
final int index,
final int id,
final int minId,
final int maxId,
final String baseName,
final String joiner) {
String effect = strings[index][0];
Preferences.setString(baseName + id, effect);
String name = ItemDatabase.getItemName(id);
String testName = name + joiner + effect;
String testPlural = ItemDatabase.getPluralName(id) + joiner + effect;
ItemDatabase.registerItemAlias(id, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
HashSet<String> possibilities = new HashSet<>();
for (int i = 0; i < strings.length; ++i) {
possibilities.add(strings[i][0]);
}
int missing = 0;
for (int i = minId; i <= maxId; ++i) {
effect = Preferences.getString(baseName + i);
if (effect.equals("")) {
if (missing != 0) {
// more than one missing item in set
return false;
}
missing = i;
} else {
possibilities.remove(effect);
}
}
if (missing == 0) {
// no missing items
return false;
}
if (possibilities.size() != 1) {
// something's screwed up if this happens
return false;
}
effect = possibilities.iterator().next();
Preferences.setString(baseName + missing, effect);
name = ItemDatabase.getItemName(missing);
testName = name + joiner + effect;
testPlural = ItemDatabase.getPluralName(missing) + joiner + effect;
ItemDatabase.registerItemAlias(missing, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
return true;
}
// Suggest one or two items from a permutation group that need to be identified.
// Strategy: identify the items the player has the most of first,
// to maximize the usefulness of having identified them.
// If two items remain unidentified, only identify one, since
// eliminationProcessor will handle the other.
public static final void suggestIdentify(
final List<Integer> items, final int minId, final int maxId, final String baseName) {
// Can't autoidentify in G-Lover
if (KoLCharacter.inGLover()) {
return;
}
ArrayList<Integer> possible = new ArrayList<>();
int unknown = 0;
for (int i = minId; i <= maxId; ++i) {
if (!Preferences.getString(baseName + i).equals("")) {
continue; // already identified;
}
++unknown;
AdventureResult item = new AdventureResult(i, 1, false);
int count = item.getCount(KoLConstants.inventory);
if (count <= 0) {
continue; // can't identify yet
}
possible.add(i | Math.min(count, 127) << 24);
}
int count = possible.size();
// Nothing to do if we have no items that qualify
if (count == 0) {
return;
}
if (count > 1) {
possible.sort(Collections.reverseOrder());
}
// Identify the item we have the most of
items.add(possible.get(0) & 0x00FFFFFF);
// If only two items are unknown, that's enough, since the
// other will be identified by eliminationProcessor
if (unknown == 2) {
return;
}
// If we have three or more unknowns, try for a second
if (count > 1) {
items.add(possible.get(1) & 0x00FFFFFF);
}
}
}
| pnudpwls1103/kolmafia | src/net/sourceforge/kolmafia/objectpool/ItemPool.java |
732 | package net.sourceforge.kolmafia.objectpool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import net.sourceforge.kolmafia.AdventureResult;
import net.sourceforge.kolmafia.KoLCharacter;
import net.sourceforge.kolmafia.KoLConstants;
import net.sourceforge.kolmafia.persistence.ItemDatabase;
import net.sourceforge.kolmafia.preferences.Preferences;
public class ItemPool {
public static final int SEAL_CLUB = 1;
public static final int SEAL_TOOTH = 2;
public static final int HELMET_TURTLE = 3;
public static final int TURTLE_TOTEM = 4;
public static final int PASTA_SPOON = 5;
public static final int RAVIOLI_HAT = 6;
public static final int SAUCEPAN = 7;
public static final int SPICES = 8;
public static final int DISCO_MASK = 9;
public static final int DISCO_BALL = 10;
public static final int STOLEN_ACCORDION = 11;
public static final int MARIACHI_PANTS = 12;
public static final int WORTHLESS_ITEM = 13; // Pseudo item
public static final int MOXIE_WEED = 14;
public static final int ASPARAGUS_KNIFE = 19;
public static final int CHEWING_GUM = 23;
public static final int TEN_LEAF_CLOVER = 24;
public static final int MEAT_PASTE = 25;
public static final int DOLPHIN_KING_MAP = 26;
public static final int SPIDER_WEB = 27;
public static final int BIG_ROCK = 30;
public static final int BJORNS_HAMMER = 32;
public static final int VIKING_HELMET = 37;
public static final int CASINO_PASS = 40;
public static final int SCHLITZ = 41;
public static final int HERMIT_PERMIT = 42;
public static final int WORTHLESS_TRINKET = 43;
public static final int WORTHLESS_GEWGAW = 44;
public static final int WORTHLESS_KNICK_KNACK = 45;
public static final int WOODEN_FIGURINE = 46;
public static final int BUTTERED_ROLL = 47;
public static final int ROCK_N_ROLL_LEGEND = 50;
public static final int BANJO_STRINGS = 52;
public static final int STONE_BANJO = 53;
public static final int DISCO_BANJO = 54;
public static final int JABANERO_PEPPER = 55;
public static final int FIVE_ALARM_SAUCEPAN = 57;
public static final int MACE_OF_THE_TORTOISE = 60;
public static final int FORTUNE_COOKIE = 61;
public static final int GOLDEN_TWIG = 66;
public static final int PASTA_SPOON_OF_PERIL = 68;
public static final int NEWBIESPORT_TENT = 69;
public static final int BAR_SKIN = 70;
public static final int WOODEN_STAKES = 71;
public static final int BARSKIN_TENT = 73;
public static final int SPOOKY_MAP = 74;
public static final int SPOOKY_SAPLING = 75;
public static final int SPOOKY_FERTILIZER = 76;
public static final int PRETTY_BOUQUET = 78;
public static final int GRAVY_BOAT = 80;
public static final int WILLER = 81;
public static final int LOCKED_LOCKER = 84;
public static final int TBONE_KEY = 86;
public static final int MEAT_FROM_YESTERDAY = 87;
public static final int MEAT_STACK = 88;
public static final int MEAT_GOLEM = 101;
public static final int SCARECROW = 104;
public static final int KETCHUP = 106;
public static final int CATSUP = 107;
public static final int SPRING = 118;
public static final int SPROCKET = 119;
public static final int COG = 120;
public static final int GNOLLISH_AUTOPLUNGER = 127;
public static final int FRILLY_SKIRT = 131;
public static final int BITCHIN_MEATCAR = 134;
public static final int SWEET_RIMS = 135;
public static final int ICE_COLD_SIX_PACK = 138;
public static final int VALUABLE_TRINKET = 139;
public static final int DINGY_PLANKS = 140;
public static final int DINGY_DINGHY = 141;
public static final int ANTICHEESE = 142;
public static final int COTTAGE = 143;
public static final int BARBED_FENCE = 145;
public static final int DINGHY_PLANS = 146;
public static final int SCALP_OF_GORGOLOK = 150;
public static final int ELDER_TURTLE_SHELL = 151;
public static final int COLANDER_OF_EMERIL = 152;
public static final int ANCIENT_SAUCEHELM = 153;
public static final int DISCO_FRO_PICK = 154;
public static final int EL_SOMBRERO_DE_LOPEZ = 155;
public static final int RANGE = 157;
public static final int DOUGH = 159;
public static final int SKELETON_BONE = 163;
public static final int SMART_SKULL = 164;
public static final int BONE_RATTLE = 168;
public static final int TACO_SHELL = 173;
public static final int BRIEFCASE = 184;
public static final int FAT_STACKS_OF_CASH = 185;
public static final int ENCHANTED_BEAN = 186;
public static final int LOOSE_TEETH = 187;
public static final int BAT_GUANO = 188;
public static final int BATSKIN_BELT = 191;
public static final int MR_ACCESSORY = 194;
public static final int DISASSEMBLED_CLOVER = 196;
public static final int RAT_WHISKER = 197;
public static final int SHINY_RING = 199;
public static final int FENG_SHUI = 210;
public static final int FOUNTAIN = 211;
public static final int WINDCHIMES = 212;
public static final int DREADSACK = 214;
public static final int HEMP_STRING = 218;
public static final int EYEPATCH = 224;
public static final int PUNGENT_UNGUENT = 231;
public static final int COCKTAIL_KIT = 236;
public static final int BOTTLE_OF_GIN = 237;
public static final int GRAPEFRUIT = 243;
public static final int TOMATO = 246;
public static final int FERMENTING_POWDER = 247;
public static final int MARTINI = 251;
public static final int DENSE_STACK = 258;
public static final int MULLET_WIG = 267;
public static final int PICKET_FENCE = 270;
public static final int MOSQUITO_LARVA = 275;
public static final int PICKOMATIC_LOCKPICKS = 280;
public static final int BORIS_KEY = 282;
public static final int JARLSBERG_KEY = 283;
public static final int SNEAKY_PETE_KEY = 284;
public static final int RUBBER_AXE = 292;
public static final int FLAT_DOUGH = 301;
public static final int DRY_NOODLES = 304;
public static final int KNOB_GOBLIN_PERFUME = 307;
public static final int KNOB_GOBLIN_HELM = 308;
public static final int KNOB_GOBLIN_PANTS = 309;
public static final int KNOB_GOBLIN_POLEARM = 310;
public static final int KNOB_GOBLIN_CROWN = 313;
public static final int GOAT_CHEESE = 322;
public static final int PLAIN_PIZZA = 323;
public static final int SAUSAGE_PIZZA = 324;
public static final int GOAT_CHEESE_PIZZA = 325;
public static final int MUSHROOM_PIZZA = 326;
public static final int TENDER_HAMMER = 338;
public static final int LAB_KEY = 339;
public static final int SELTZER = 344;
public static final int REAGENT = 346;
public static final int DYSPEPSI_COLA = 347;
public static final int ICY_KATANA_HILT = 349;
public static final int HOT_KATANA_BLADE = 350;
public static final int ICY_HOT_KATANA = 351;
public static final int MINERS_HELMET = 360;
public static final int MINERS_PANTS = 361;
public static final int MATTOCK = 362;
public static final int LINOLEUM_ORE = 363;
public static final int ASBESTOS_ORE = 364;
public static final int CHROME_ORE = 365;
public static final int YETI_FUR = 388;
public static final int PENGUIN_SKIN = 393;
public static final int YAK_SKIN = 394;
public static final int HIPPOPOTAMUS_SKIN = 395;
public static final int ACOUSTIC_GUITAR = 404;
public static final int PIRATE_CHEST = 405;
public static final int PIRATE_PELVIS = 406;
public static final int PIRATE_SKULL = 407;
public static final int JOLLY_CHARRRM = 411;
public static final int JOLLY_BRACELET = 413;
public static final int BEANBAG_CHAIR = 429;
public static final int LONG_SKINNY_BALLOON = 433;
public static final int BALLOON_MONKEY = 436;
public static final int CHEF = 438;
public static final int BARTENDER = 440;
public static final int BEER_LENS = 443;
public static final int PRETENTIOUS_PAINTBRUSH = 450;
public static final int PRETENTIOUS_PALETTE = 451;
public static final int RUSTY_SCREWDRIVER = 454;
public static final int DRY_MARTINI = 456;
public static final int TRANSFUNCTIONER = 458;
public static final int WHITE_PIXEL = 459;
public static final int BLACK_PIXEL = 460;
public static final int RED_PIXEL = 461;
public static final int GREEN_PIXEL = 462;
public static final int BLUE_PIXEL = 463;
public static final int RED_PIXEL_POTION = 464;
public static final int RUBY_W = 468;
public static final int HOT_WING = 471;
public static final int DODECAGRAM = 479;
public static final int CANDLES = 480;
public static final int BUTTERKNIFE = 481;
public static final int MR_CONTAINER = 482;
public static final int NEWBIESPORT_BACKPACK = 483;
public static final int HEMP_BACKPACK = 484;
public static final int SNAKEHEAD_CHARM = 485;
public static final int TALISMAN = 486;
public static final int KETCHUP_HOUND = 493;
public static final int PAPAYA = 498;
public static final int ELF_FARM_RAFFLE_TICKET = 500;
public static final int PAGODA_PLANS = 502;
public static final int HEAVY_METAL_GUITAR = 507;
public static final int HEY_DEZE_NUTS = 509;
public static final int BORIS_PIE = 513;
public static final int JARLSBERG_PIE = 514;
public static final int SNEAKY_PETE_PIE = 515;
public static final int HEY_DEZE_MAP = 516;
public static final int MMJ = 518;
public static final int MOXIE_MAGNET = 519;
public static final int STRANGE_LEAFLET = 520;
public static final int HOUSE = 526;
public static final int VOLLEYBALL = 527;
public static final int SPECIAL_SAUCE_GLOVE = 531;
public static final int ABRIDGED = 534;
public static final int BRIDGE = 535;
public static final int DICTIONARY = 536;
public static final int LOWERCASE_N = 539;
public static final int ELITE_TROUSERS = 542;
public static final int SCROLL_334 = 547;
public static final int SCROLL_668 = 548;
public static final int SCROLL_30669 = 549;
public static final int SCROLL_33398 = 550;
public static final int SCROLL_64067 = 551;
public static final int GATES_SCROLL = 552;
public static final int ELITE_SCROLL = 553;
public static final int CAN_LID = 559;
public static final int SONAR = 563;
public static final int HERMIT_SCRIPT = 567;
public static final int LUCIFER = 571;
public static final int HELL_RAMEN = 578;
public static final int FETTUCINI_INCONNU = 583;
public static final int SPAGHETTI_WITH_SKULLHEADS = 584;
public static final int GNOCCHETTI_DI_NIETZSCHE = 585;
public static final int REMEDY = 588;
public static final int TINY_HOUSE = 592;
public static final int PHONICS_DOWN = 593;
public static final int EXTREME_AMULET = 594;
public static final int DRASTIC_HEALING = 595;
public static final int TITANIUM_UMBRELLA = 596;
public static final int MOHAWK_WIG = 597;
public static final int SLUG_LORD_MAP = 598;
public static final int DR_HOBO_MAP = 601;
public static final int SHOPPING_LIST = 602;
public static final int TISSUE_PAPER_IMMATERIA = 605;
public static final int TIN_FOIL_IMMATERIA = 606;
public static final int GAUZE_IMMATERIA = 607;
public static final int PLASTIC_WRAP_IMMATERIA = 608;
public static final int SOCK = 609;
public static final int HEAVY_D = 611;
public static final int CHAOS_BUTTERFLY = 615;
public static final int FURRY_FUR = 616;
public static final int GIANT_NEEDLE = 619;
public static final int BLACK_CANDLE = 620;
public static final int WARM_SUBJECT = 621;
public static final int AWFUL_POETRY_JOURNAL = 622;
public static final int WA = 623;
public static final int NG = 624;
public static final int WAND_OF_NAGAMAR = 626;
public static final int ND = 627;
public static final int METALLIC_A = 628;
public static final int MEAT_GLOBE = 636;
public static final int TOASTER = 637;
public static final int TOAST = 641;
public static final int SKELETON_KEY = 642;
public static final int SKELETON_KEY_RING = 643;
public static final int ROWBOAT = 653;
public static final int STAR = 654;
public static final int LINE = 655;
public static final int STAR_CHART = 656;
public static final int STAR_SWORD = 657;
public static final int STAR_CROSSBOW = 658;
public static final int STAR_STAFF = 659;
public static final int STAR_HAT = 661;
public static final int STAR_STARFISH = 664;
public static final int STAR_KEY = 665;
public static final int STEAMING_EVIL = 666;
public static final int GIANT_CASTLE_MAP = 667;
public static final int CRANBERRIES = 672;
public static final int BONERDAGON_SKULL = 675;
public static final int DRAGONBONE_BELT_BUCKLE = 676;
public static final int BADASS_BELT = 677;
public static final int BONERDAGON_CHEST = 678;
public static final int SUMP_M_SUMP_M = 682;
public static final int DIGITAL_KEY = 691;
public static final int HAMETHYST = 704;
public static final int BACONSTONE = 705;
public static final int PORQUOISE = 706;
public static final int JEWELRY_PLIERS = 709;
public static final int BACONSTONE_EARRING = 715;
public static final int BACONSTONE_BRACELET = 717;
public static final int MIRROR_SHARD = 726;
public static final int PUZZLE_PIECE = 727;
public static final int HEDGE_KEY = 728;
public static final int FISHBOWL = 729;
public static final int FISHTANK = 730;
public static final int FISH_HOSE = 731;
public static final int HOSED_TANK = 732;
public static final int HOSED_FISHBOWL = 733;
public static final int SCUBA_GEAR = 734;
public static final int SINISTER_STRUMMING = 736;
public static final int SQUEEZINGS_OF_WOE = 737;
public static final int REALLY_EVIL_RHYTHM = 738;
public static final int TAMBOURINE = 740;
public static final int BROKEN_SKULL = 741;
public static final int SERRATED_PROBOSCIS_EXTENSION = 745;
public static final int KNOB_FIRECRACKER = 747;
public static final int FLAMING_MUSHROOM = 755;
public static final int FROZEN_MUSHROOM = 756;
public static final int STINKY_MUSHROOM = 757;
public static final int CUMMERBUND = 778;
public static final int MAFIA_ARIA = 781;
public static final int RAFFLE_TICKET = 785;
public static final int STRAWBERRY = 786;
public static final int GOLDEN_MR_ACCESSORY = 792;
public static final int ROCKIN_WAGON = 797;
public static final int PLUS_SIGN = 818;
public static final int FIRST_BANG_POTION = 819;
public static final int MILKY_POTION = 819;
public static final int SWIRLY_POTION = 820;
public static final int BUBBLY_POTION = 821;
public static final int SMOKY_POTION = 822;
public static final int CLOUDY_POTION = 823;
public static final int EFFERVESCENT_POTION = 824;
public static final int FIZZY_POTION = 825;
public static final int DARK_POTION = 826;
public static final int LAST_BANG_POTION = 827;
public static final int MURKY_POTION = 827;
public static final int ANTIDOTE = 829;
public static final int ROYAL_JELLY = 830;
public static final int SHOCK_COLLAR = 856;
public static final int MOONGLASSES = 857;
public static final int LEAD_NECKLACE = 865;
public static final int TEARS = 869;
public static final int ROLLING_PIN = 873;
public static final int UNROLLING_PIN = 874;
public static final int GOOFBALLS = 879;
public static final int ONE_HUNDRED_WATT_BULB = 902;
public static final int YUMMY_TUMMY_BEAN = 905;
public static final int DWARF_BREAD = 910;
public static final int PLASTIC_SWORD = 938;
public static final int DIRTY_MARTINI = 948;
public static final int GROGTINI = 949;
public static final int CHERRY_BOMB = 950;
public static final int WHITE_CHOCOLATE_AND_TOMATO_PIZZA = 958;
public static final int MAID = 1000;
public static final int TEQUILA = 1004;
public static final int BOXED_WINE = 1005;
public static final int VODKA_MARTINI = 1009;
public static final int DRY_VODKA_MARTINI = 1019;
public static final int VESPER = 1023;
public static final int BODYSLAM = 1024;
public static final int SANGRIA_DEL_DIABLO = 1025;
public static final int VALENTINE = 1026;
public static final int TAM_O_SHANTER = 1040;
public static final int GREEN_BEER = 1041;
public static final int RED_STRIPED_EGG = 1048;
public static final int RED_POLKA_EGG = 1049;
public static final int RED_PAISLEY_EGG = 1050;
public static final int BLUE_STRIPED_EGG = 1052;
public static final int BLUE_POLKA_EGG = 1053;
public static final int BLUE_PAISLEY_EGG = 1054;
public static final int OYSTER_BASKET = 1080;
public static final int TARGETING_CHIP = 1102;
public static final int CLOCKWORK_BARTENDER = 1111;
public static final int CLOCKWORK_CHEF = 1112;
public static final int CLOCKWORK_MAID = 1113;
public static final int ANNOYING_PITCHFORK = 1116;
public static final int PREGNANT_FLAMING_MUSHROOM = 1118;
public static final int PREGNANT_FROZEN_MUSHROOM = 1119;
public static final int PREGNANT_STINKY_MUSHROOM = 1120;
public static final int INEXPLICABLY_GLOWING_ROCK = 1121;
public static final int SPOOKY_GLOVE = 1125;
public static final int SPOOKY_BICYCLE_CHAIN = 1137;
public static final int FLAMING_MUSHROOM_WINE = 1139;
public static final int ICY_MUSHROOM_WINE = 1140;
public static final int STINKY_MUSHROOM_WINE = 1141;
public static final int POINTY_MUSHROOM_WINE = 1142;
public static final int FLAT_MUSHROOM_WINE = 1143;
public static final int COOL_MUSHROOM_WINE = 1144;
public static final int KNOB_MUSHROOM_WINE = 1145;
public static final int KNOLL_MUSHROOM_WINE = 1146;
public static final int SPOOKY_MUSHROOM_WINE = 1147;
public static final int GRAVY_MAYPOLE = 1152;
public static final int GIFT1 = 1167;
public static final int GIFT2 = 1168;
public static final int GIFT3 = 1169;
public static final int GIFT4 = 1170;
public static final int GIFT5 = 1171;
public static final int GIFT6 = 1172;
public static final int GIFT7 = 1173;
public static final int GIFT8 = 1174;
public static final int GIFT9 = 1175;
public static final int GIFT10 = 1176;
public static final int GIFT11 = 1177;
public static final int POTTED_FERN = 1180;
public static final int TULIP = 1181;
public static final int VENUS_FLYTRAP = 1182;
public static final int ALL_PURPOSE_FLOWER = 1183;
public static final int EXOTIC_ORCHID = 1184;
public static final int LONG_STEMMED_ROSE = 1185;
public static final int GILDED_LILY = 1186;
public static final int DEADLY_NIGHTSHADE = 1187;
public static final int BLACK_LOTUS = 1188;
public static final int STUFFED_GHUOL_WHELP = 1191;
public static final int STUFFED_ZMOBIE = 1192;
public static final int RAGGEDY_HIPPY_DOLL = 1193;
public static final int STUFFED_STAB_BAT = 1194;
public static final int APATHETIC_LIZARDMAN_DOLL = 1195;
public static final int STUFFED_YETI = 1196;
public static final int STUFFED_MOB_PENGUIN = 1197;
public static final int STUFFED_SABRE_TOOTHED_LIME = 1198;
public static final int GIANT_STUFFED_BUGBEAR = 1199;
public static final int HAPPY_BIRTHDAY_CLAUDE_CAKE = 1202;
public static final int PERSONALIZED_BIRTHDAY_CAKE = 1203;
public static final int THREE_TIERED_WEDDING_CAKE = 1204;
public static final int BABYCAKES = 1205;
public static final int BLUE_VELVET_CAKE = 1206;
public static final int CONGRATULATORY_CAKE = 1207;
public static final int ANGEL_FOOD_CAKE = 1208;
public static final int DEVILS_FOOD_CAKE = 1209;
public static final int BIRTHDAY_PARTY_JELLYBEAN_CHEESECAKE = 1210;
public static final int HEART_SHAPED_BALLOON = 1213;
public static final int ANNIVERSARY_BALLOON = 1214;
public static final int MYLAR_BALLOON = 1215;
public static final int KEVLAR_BALLOON = 1216;
public static final int THOUGHT_BALLOON = 1217;
public static final int RAT_BALLOON = 1218;
public static final int MINI_ZEPPELIN = 1219;
public static final int MR_BALLOON = 1220;
public static final int RED_BALLOON = 1221;
public static final int STAINLESS_STEEL_SOLITAIRE = 1226;
public static final int PLEXIGLASS_PITH_HELMET = 1231;
public static final int PLEXIGLASS_POCKETWATCH = 1232;
public static final int PLEXIGLASS_PENDANT = 1235;
public static final int TOY_HOVERCRAFT = 1243;
public static final int KNOB_GOBLIN_BALLS = 1244;
public static final int KNOB_GOBLIN_CODPIECE = 1245;
public static final int BONERDAGON_VERTEBRA = 1247;
public static final int BONERDAGON_NECKLACE = 1248;
public static final int PRETENTIOUS_PAIL = 1258;
public static final int WAX_LIPS = 1260;
public static final int NOSE_BONE_FETISH = 1264;
public static final int GLOOMY_BLACK_MUSHROOM = 1266;
public static final int DEAD_MIMIC = 1267;
public static final int PINE_WAND = 1268;
public static final int EBONY_WAND = 1269;
public static final int HEXAGONAL_WAND = 1270;
public static final int ALUMINUM_WAND = 1271;
public static final int MARBLE_WAND = 1272;
public static final int MEDICINAL_HERBS = 1274;
public static final int MAKEUP_KIT = 1305;
public static final int COMFY_BLANKET = 1311;
public static final int FACSIMILE_DICTIONARY = 1316;
public static final int TIME_HELMET = 1323;
public static final int TIME_SWORD = 1325;
public static final int DYSPEPSI_HELMET = 1326;
public static final int CLOACA_SHIELD = 1327;
public static final int CLOACA_FATIGUES = 1328;
public static final int DYSPEPSI_SHIELD = 1329;
public static final int DYSPEPSI_FATIGUES = 1330;
public static final int CLOACA_HELMET = 1331;
public static final int CLOACA_COLA = 1334;
public static final int FANCY_CHOCOLATE = 1382;
public static final int TOY_SOLDIER = 1397;
public static final int SNOWCONE_BOOK = 1411;
public static final int PURPLE_SNOWCONE = 1412;
public static final int GREEN_SNOWCONE = 1413;
public static final int ORANGE_SNOWCONE = 1414;
public static final int RED_SNOWCONE = 1415;
public static final int BLUE_SNOWCONE = 1416;
public static final int BLACK_SNOWCONE = 1417;
public static final int TEDDY_SEWING_KIT = 1419;
public static final int ICEBERGLET = 1423;
public static final int ICE_SICKLE = 1424;
public static final int ICE_BABY = 1425;
public static final int ICE_PICK = 1426;
public static final int ICE_SKATES = 1427;
public static final int OILY_GOLDEN_MUSHROOM = 1432;
public static final int USELESS_POWDER = 1437;
public static final int TWINKLY_WAD = 1450;
public static final int HOT_WAD = 1451;
public static final int COLD_WAD = 1452;
public static final int SPOOKY_WAD = 1453;
public static final int STENCH_WAD = 1454;
public static final int SLEAZE_WAD = 1455;
public static final int GIFTV = 1460;
public static final int LUCKY_RABBIT_FOOT = 1485;
public static final int MINIATURE_DORMOUSE = 1489;
public static final int GLOOMY_MUSHROOM_WINE = 1496;
public static final int OILY_MUSHROOM_WINE = 1497;
public static final int HILARIOUS_BOOK = 1498;
public static final int RUBBER_EMO_ROE = 1503;
public static final int FAKE_HAND = 1511;
public static final int PET_BUFFING_SPRAY = 1512;
public static final int VAMPIRE_HEART = 1518;
public static final int BAKULA = 1519;
public static final int RADIO_KOL_COFFEE_MUG = 1520;
public static final int JOYBUZZER = 1525;
public static final int SNOOTY_DISGUISE = 1526;
public static final int GIFTR = 1534;
public static final int WEEGEE_SQOUIJA = 1537;
public static final int TAM_O_SHATNER = 1539;
public static final int GRIMACITE_GOGGLES = 1540;
public static final int GRIMACITE_GLAIVE = 1541;
public static final int GRIMACITE_GREAVES = 1542;
public static final int GRIMACITE_GARTER = 1543;
public static final int GRIMACITE_GALOSHES = 1544;
public static final int GRIMACITE_GORGET = 1545;
public static final int GRIMACITE_GUAYABERA = 1546;
public static final int MSG = 1549;
public static final int BOXED_CHAMPAGNE = 1556;
public static final int COCKTAIL_ONION = 1560;
public static final int VODKA_GIBSON = 1569;
public static final int GIBSON = 1570;
public static final int HOT_HI_MEIN = 1592;
public static final int COLD_HI_MEIN = 1593;
public static final int SPOOKY_HI_MEIN = 1594;
public static final int STINKY_HI_MEIN = 1595;
public static final int SLEAZY_HI_MEIN = 1596;
public static final int CATALYST = 1605;
public static final int ULTIMATE_WAD = 1606;
public static final int C_CLOCHE = 1615;
public static final int C_CULOTTES = 1616;
public static final int C_CROSSBOW = 1617;
public static final int ICE_STEIN = 1618;
public static final int MUNCHIES_PILL = 1619;
public static final int HOMEOPATHIC = 1620;
public static final int ASTRAL_MUSHROOM = 1622;
public static final int BADGER_BADGE = 1623;
public static final int BLUE_CUPCAKE = 1624;
public static final int GREEN_CUPCAKE = 1625;
public static final int ORANGE_CUPCAKE = 1626;
public static final int PURPLE_CUPCAKE = 1627;
public static final int PINK_CUPCAKE = 1628;
public static final int SPANISH_FLY = 1633;
public static final int BRICK = 1649;
public static final int MILK_OF_MAGNESIUM = 1650;
public static final int JEWEL_EYED_WIZARD_HAT = 1653;
public static final int CITADEL_SATCHEL = 1656;
public static final int CHERRY_CLOACA_COLA = 1658;
public static final int FRAUDWORT = 1670;
public static final int SHYSTERWEED = 1671;
public static final int SWINDLEBLOSSOM = 1672;
public static final int CARDBOARD_ORE = 1675;
public static final int STYROFOAM_ORE = 1676;
public static final int BUBBLEWRAP_ORE = 1677;
public static final int GROUCHO_DISGUISE = 1678;
public static final int EXPRESS_CARD = 1687;
public static final int MUCULENT_MACHETE = 1721;
public static final int SWORD_PREPOSITIONS = 1734;
public static final int GOULAUNCHER = 1748;
public static final int GALLERY_KEY = 1765;
public static final int BALLROOM_KEY = 1766;
public static final int PACK_OF_CHEWING_GUM = 1767;
public static final int TRAVOLTAN_TROUSERS = 1792;
public static final int POOL_CUE = 1793;
public static final int HAND_CHALK = 1794;
public static final int DUSTY_ANIMAL_SKULL = 1799;
public static final int ONE_BALL = 1900;
public static final int TWO_BALL = 1901;
public static final int THREE_BALL = 1902;
public static final int FOUR_BALL = 1903;
public static final int FIVE_BALL = 1904;
public static final int SIX_BALL = 1905;
public static final int SEVEN_BALL = 1906;
public static final int EIGHT_BALL = 1907;
public static final int CLOCKWORK_HANDLE = 1913;
public static final int SPOOKYRAVEN_SPECTACLES = 1916;
public static final int ENGLISH_TO_A_F_U_E_DICTIONARY = 1919;
public static final int BIZARRE_ILLEGIBLE_SHEET_MUSIC = 1920;
public static final int TOILET_PAPER = 1923;
public static final int TATTERED_WOLF_STANDARD = 1924;
public static final int TATTERED_SNAKE_STANDARD = 1925;
public static final int TUNING_FORK = 1928;
public static final int ANTIQUE_GREAVES = 1929;
public static final int ANTIQUE_HELMET = 1930;
public static final int ANTIQUE_SPEAR = 1931;
public static final int ANTIQUE_SHIELD = 1932;
public static final int CHINTZY_SEAL_PENDANT = 1941;
public static final int CHINTZY_TURTLE_BROOCH = 1942;
public static final int CHINTZY_NOODLE_RING = 1943;
public static final int CHINTZY_SAUCEPAN_EARRING = 1944;
public static final int CHINTZY_DISCO_BALL_PENDANT = 1945;
public static final int CHINTZY_ACCORDION_PIN = 1946;
public static final int MANETWICH = 1949;
public static final int VANGOGHBITUSSIN = 1950;
public static final int PINOT_RENOIR = 1951;
public static final int FLAT_CHAMPAGNE = 1953;
public static final int QUILL_PEN = 1957;
public static final int INKWELL = 1958;
public static final int SCRAP_OF_PAPER = 1959;
public static final int EVIL_SCROLL = 1960;
public static final int DANCE_CARD = 1963;
public static final int OPERA_MASK = 1964;
public static final int PUMPKIN_BUCKET = 1971;
public static final int SILVER_SHRIMP_FORK = 1972;
public static final int STUFFED_COCOABO = 1974;
public static final int RUBBER_WWTNSD_BRACELET = 1994;
public static final int SPADE_NECKLACE = 2017;
public static final int HIPPY_PROTEST_BUTTON = 2029;
public static final int WICKER_SHIELD = 2034;
public static final int PATCHOULI_OIL_BOMB = 2040;
public static final int EXPLODING_HACKY_SACK = 2042;
public static final int MACGUFFIN_DIARY = 2044;
public static final int BROKEN_WINGS = 2050;
public static final int SUNKEN_EYES = 2051;
public static final int REASSEMBLED_BLACKBIRD = 2052;
public static final int BLACKBERRY = 2063;
public static final int FORGED_ID_DOCUMENTS = 2064;
public static final int PADL_PHONE = 2065;
public static final int TEQUILA_GRENADE = 2068;
public static final int BEER_HELMET = 2069;
public static final int DISTRESSED_DENIM_PANTS = 2070;
public static final int NOVELTY_BUTTON = 2072;
public static final int MAKESHIFT_TURBAN = 2079;
public static final int MAKESHIFT_CAPE = 2080;
public static final int MAKESHIFT_SKIRT = 2081;
public static final int MAKESHIFT_CRANE = 2083;
public static final int CAN_OF_STARCH = 2084;
public static final int ANTIQUE_HAND_MIRROR = 2092;
public static final int TOWEL = 2095;
public static final int GMOB_POLLEN = 2096;
public static final int SEVENTEEN_BALL = 2097;
public static final int LUCRE = 2098;
public static final int ASCII_SHIRT = 2121;
public static final int TOY_MERCENARY = 2139;
public static final int EVIL_TEDDY_SEWING_KIT = 2147;
public static final int TRIANGULAR_STONE = 2173;
public static final int ANCIENT_AMULET = 2180;
public static final int HAROLDS_HAMMER_HEAD = 2182;
public static final int HAROLDS_HAMMER = 2184;
public static final int UNLIT_BIRTHDAY_CAKE = 2186;
public static final int LIT_BIRTHDAY_CAKE = 2187;
public static final int ANCIENT_CAROLS = 2191;
public static final int SHEET_MUSIC = 2192;
public static final int FANCY_EVIL_CHOCOLATE = 2197;
public static final int CRIMBO_UKELELE = 2209;
public static final int LIARS_PANTS = 2222;
public static final int JUGGLERS_BALLS = 2223;
public static final int PINK_SHIRT = 2224;
public static final int FAMILIAR_DOPPELGANGER = 2225;
public static final int EYEBALL_PENDANT = 2226;
public static final int CALAVERA_CONCERTINA = 2234;
public static final int TURTLE_PHEROMONES = 2236;
public static final int PHOTOGRAPH_OF_GOD = 2259;
public static final int WET_STUNT_NUT_STEW = 2266;
public static final int MEGA_GEM = 2267;
public static final int STAFF_OF_FATS = 2268;
public static final int DUSTY_BOTTLE_OF_MERLOT = 2271;
public static final int DUSTY_BOTTLE_OF_PORT = 2272;
public static final int DUSTY_BOTTLE_OF_PINOT_NOIR = 2273;
public static final int DUSTY_BOTTLE_OF_ZINFANDEL = 2274;
public static final int DUSTY_BOTTLE_OF_MARSALA = 2275;
public static final int DUSTY_BOTTLE_OF_MUSCAT = 2276;
public static final int FERNSWARTHYS_KEY = 2277;
public static final int DUSTY_BOOK = 2279;
public static final int MUS_MANUAL = 2280;
public static final int MYS_MANUAL = 2281;
public static final int MOX_MANUAL = 2282;
public static final int SEAL_HELMET = 2283;
public static final int PETRIFIED_NOODLES = 2284;
public static final int CHISEL = 2285;
public static final int EYE_OF_ED = 2286;
public static final int RED_PAPER_CLIP = 2289;
public static final int REALLY_BIG_TINY_HOUSE = 2290;
public static final int NONESSENTIAL_AMULET = 2291;
public static final int WHITE_WINE_VINAIGRETTE = 2292;
public static final int CUP_OF_STRONG_TEA = 2293;
public static final int CURIOUSLY_SHINY_AX = 2294;
public static final int MARINATED_STAKES = 2295;
public static final int KNOB_BUTTER = 2296;
public static final int VIAL_OF_ECTOPLASM = 2297;
public static final int BOOCK_OF_MAGICKS = 2298;
public static final int EZ_PLAY_HARMONICA_BOOK = 2299;
public static final int FINGERLESS_HOBO_GLOVES = 2300;
public static final int CHOMSKYS_COMICS = 2301;
public static final int WORM_RIDING_HOOKS = 2302;
public static final int CANDY_BOOK = 2303;
public static final int GREEN_CANDY = 2309;
public static final int ANCIENT_BRONZE_TOKEN = 2317;
public static final int ANCIENT_BOMB = 2318;
public static final int CARVED_WOODEN_WHEEL = 2319;
public static final int WORM_RIDING_MANUAL_PAGE = 2320;
public static final int HEADPIECE_OF_ED = 2323;
public static final int STAFF_OF_ED = 2325;
public static final int STONE_ROSE = 2326;
public static final int BLACK_PAINT = 2327;
public static final int DRUM_MACHINE = 2328;
public static final int CONFETTI = 2329;
public static final int CHOCOLATE_COVERED_DIAMOND_STUDDED_ROSES = 2330;
public static final int BOUQUET_OF_CIRCULAR_SAW_BLADES = 2331;
public static final int BETTER_THAN_CUDDLING_CAKE = 2332;
public static final int STUFFED_NINJA_SNOWMAN = 2333;
public static final int HOLY_MACGUFFIN = 2334;
public static final int REINFORCED_BEADED_HEADBAND = 2337;
public static final int BLACK_PUDDING = 2338;
public static final int BLACKFLY_CHARDONNAY = 2339;
public static final int BLACK_TAN = 2340;
public static final int FILTHWORM_HATCHLING_GLAND = 2344;
public static final int FILTHWORM_DRONE_GLAND = 2345;
public static final int FILTHWORM_GUARD_GLAND = 2346;
public static final int FILTHWORM_QUEEN_HEART = 2347;
public static final int BEJEWELED_PLEDGE_PIN = 2353;
public static final int COMMUNICATIONS_WINDCHIMES = 2354;
public static final int ZIM_MERMANS_GUITAR = 2364;
public static final int FILTHY_POULTICE = 2369;
public static final int BOTTLE_OPENER_BELT_BUCKLE = 2385;
public static final int MOLOTOV_COCKTAIL_COCKTAIL = 2400;
public static final int GAUZE_GARTER = 2402;
public static final int GUNPOWDER = 2403;
public static final int JAM_BAND_FLYERS = 2404;
public static final int ROCK_BAND_FLYERS = 2405;
public static final int RHINO_HORMONES = 2419;
public static final int MAGIC_SCROLL = 2420;
public static final int PIRATE_JUICE = 2421;
public static final int PET_SNACKS = 2422;
public static final int INHALER = 2423;
public static final int CYCLOPS_EYEDROPS = 2424;
public static final int SPINACH = 2425;
public static final int FIRE_FLOWER = 2426;
public static final int ICE_CUBE = 2427;
public static final int FAKE_BLOOD = 2428;
public static final int GUANEAU = 2429;
public static final int LARD = 2430;
public static final int MYSTIC_SHELL = 2431;
public static final int LIP_BALM = 2432;
public static final int ANTIFREEZE = 2433;
public static final int BLACK_EYEDROPS = 2434;
public static final int DOGSGOTNONOZ = 2435;
public static final int FLIPBOOK = 2436;
public static final int NEW_CLOACA_COLA = 2437;
public static final int MASSAGE_OIL = 2438;
public static final int POLTERGEIST = 2439;
public static final int ENCRYPTION_KEY = 2441;
public static final int COBBS_KNOB_MAP = 2442;
public static final int SUPERNOVA_CHAMPAGNE = 2444;
public static final int GOATSKIN_UMBRELLA = 2451;
public static final int BAR_WHIP = 2455;
public static final int ODOR_EXTRACTOR = 2462;
public static final int OLFACTION_BOOK = 2463;
public static final int OREILLE_DIVISEE_BRANDY = 2465;
public static final int TUXEDO_SHIRT = 2489;
public static final int SHIRT_KIT = 2491;
public static final int TROPICAL_ORCHID = 2492;
public static final int MOLYBDENUM_MAGNET = 2497;
public static final int MOLYBDENUM_HAMMER = 2498;
public static final int MOLYBDENUM_SCREWDRIVER = 2499;
public static final int MOLYBDENUM_PLIERS = 2500;
public static final int MOLYBDENUM_WRENCH = 2501;
public static final int JEWELRY_BOOK = 2502;
public static final int WOVEN_BALING_WIRE_BRACELETS = 2514;
public static final int CRUELTY_FREE_WINE = 2521;
public static final int THISTLE_WINE = 2522;
public static final int FISHY_FISH_LASAGNA = 2527;
public static final int FILET_OF_TANGY_GNAT = 2528;
public static final int GNAT_LASAGNA = 2531;
public static final int LONG_PORK_LASAGNA = 2535;
public static final int TOMB_RATCHET = 2540;
public static final int MAYFLOWER_BOUQUET = 2541;
public static final int LESSER_GRODULATED_VIOLET = 2542;
public static final int TIN_MAGNOLIA = 2543;
public static final int BEGPWNIA = 2544;
public static final int UPSY_DAISY = 2545;
public static final int HALF_ORCHID = 2546;
public static final int OUTRAGEOUS_SOMBRERO = 2548;
public static final int PEPPERCORNS_OF_POWER = 2550;
public static final int VIAL_OF_MOJO = 2551;
public static final int GOLDEN_REEDS = 2552;
public static final int TURTLE_CHAIN = 2553;
public static final int DISTILLED_SEAL_BLOOD = 2554;
public static final int HIGH_OCTANE_OLIVE_OIL = 2555;
public static final int SHAGADELIC_DISCO_BANJO = 2556;
public static final int SQUEEZEBOX_OF_THE_AGES = 2557;
public static final int CHELONIAN_MORNINGSTAR = 2558;
public static final int HAMMER_OF_SMITING = 2559;
public static final int SEVENTEEN_ALARM_SAUCEPAN = 2560;
public static final int GREEK_PASTA_OF_PERIL = 2561;
public static final int AZAZELS_UNICORN = 2566;
public static final int AZAZELS_LOLLIPOP = 2567;
public static final int AZAZELS_TUTU = 2568;
public static final int ANT_HOE = 2570;
public static final int ANT_RAKE = 2571;
public static final int ANT_PITCHFORK = 2572;
public static final int ANT_SICKLE = 2573;
public static final int ANT_PICK = 2574;
public static final int HANDFUL_OF_SAND = 2581;
public static final int SAND_BRICK = 2582;
public static final int TASTY_TART = 2591;
public static final int LUNCHBOX = 2592;
public static final int KNOB_PASTY = 2593;
public static final int KNOB_COFFEE = 2594;
public static final int TELESCOPE = 2599;
public static final int TUESDAYS_RUBY = 2604;
public static final int PALM_FROND = 2605;
public static final int PALM_FROND_FAN = 2606;
public static final int MOJO_FILTER = 2614;
public static final int WEAVING_MANUAL = 2630;
public static final int PAT_A_CAKE_PENDANT = 2633;
public static final int MUMMY_WRAP = 2634;
public static final int GAUZE_HAMMOCK = 2638;
public static final int MAXWELL_HAMMER = 2642;
public static final int ABSINTHE = 2655;
public static final int BOTTLE_OF_REALPAGNE = 2658;
public static final int SPIKY_COLLAR = 2667;
public static final int LIBRARY_CARD = 2672;
public static final int SPECTRE_SCEPTER = 2678;
public static final int SPARKLER = 2679;
public static final int SNAKE = 2680;
public static final int M282 = 2681;
public static final int DETUNED_RADIO = 2682;
public static final int GIFTW = 2683;
public static final int MASSIVE_SITAR = 2693;
public static final int DUCT_TAPE = 2697;
public static final int SHRINKING_POWDER = 2704;
public static final int PARROT_CRACKER = 2710;
public static final int SPARE_KIDNEY = 2718;
public static final int HAND_CARVED_BOKKEN = 2719;
public static final int HAND_CARVED_BOW = 2720;
public static final int HAND_CARVED_STAFF = 2721;
public static final int JUNIPER_BERRIES = 2726;
public static final int PLUM_WINE = 2730;
public static final int BUNCH_OF_SQUARE_GRAPES = 2733;
public static final int STEEL_STOMACH = 2742;
public static final int STEEL_LIVER = 2743;
public static final int STEEL_SPLEEN = 2744;
public static final int HAROLDS_BELL = 2765;
public static final int GOLD_BOWLING_BALL = 2766;
public static final int SOLID_BACONSTONE_EARRING = 2780;
public static final int BRIMSTONE_BERET = 2813;
public static final int BRIMSTONE_BLUDGEON = 2814;
public static final int BRIMSTONE_BUNKER = 2815;
public static final int BRIMSTONE_BRACELET = 2818;
public static final int GRIMACITE_GASMASK = 2819;
public static final int GRIMACITE_GAT = 2820;
public static final int GRIMACITE_GAITERS = 2821;
public static final int GRIMACITE_GAUNTLETS = 2822;
public static final int GRIMACITE_GO_GO_BOOTS = 2823;
public static final int GRIMACITE_GIRDLE = 2824;
public static final int GRIMACITE_GOWN = 2825;
public static final int REALLY_DENSE_MEAT_STACK = 2829;
public static final int BOTTLE_ROCKET = 2834;
public static final int COOKING_SHERRY = 2840;
public static final int NAVEL_RING = 2844;
public static final int PLASTIC_BIB = 2846;
public static final int GNOME_DEMODULIZER = 2848;
public static final int GREAT_TREE_BRANCH = 2852;
public static final int PHIL_BUNION_AXE = 2853;
public static final int SWAMP_ROSE_BOUQUET = 2854;
public static final int PARTY_HAT = 2945;
public static final int V_MASK = 2946;
public static final int PIRATE_INSULT_BOOK = 2947;
public static final int CARONCH_MAP = 2950;
public static final int FRATHOUSE_BLUEPRINTS = 2951;
public static final int CHARRRM_BRACELET = 2953;
public static final int COCKTAIL_NAPKIN = 2956;
public static final int RUM_CHARRRM = 2957;
public static final int RUM_BRACELET = 2959;
public static final int RIGGING_SHAMPOO = 2963;
public static final int BALL_POLISH = 2964;
public static final int MIZZENMAST_MOP = 2965;
public static final int GRUMPY_CHARRRM = 2972;
public static final int GRUMPY_BRACELET = 2973;
public static final int TARRRNISH_CHARRRM = 2974;
public static final int TARRRNISH_BRACELET = 2975;
public static final int BILGE_WINE = 2976;
public static final int BOOTY_CHARRRM = 2980;
public static final int BOOTY_BRACELET = 2981;
public static final int CANNONBALL_CHARRRM = 2982;
public static final int CANNONBALL_BRACELET = 2983;
public static final int COPPER_CHARRRM = 2984;
public static final int COPPER_BRACELET = 2985;
public static final int TONGUE_CHARRRM = 2986;
public static final int TONGUE_BRACELET = 2987;
public static final int CLINGFILM = 2988;
public static final int CARONCH_NASTY_BOOTY = 2999;
public static final int CARONCH_DENTURES = 3000;
public static final int IDOL_AKGYXOTH = 3009;
public static final int EMBLEM_AKGYXOTH = 3010;
public static final int SIMPLE_CURSED_KEY = 3013;
public static final int ORNATE_CURSED_KEY = 3014;
public static final int GILDED_CURSED_KEY = 3015;
public static final int ANCIENT_CURSED_FOOTLOCKER = 3016;
public static final int ORNATE_CURSED_CHEST = 3017;
public static final int GILDED_CURSED_CHEST = 3018;
public static final int PIRATE_FLEDGES = 3033;
public static final int CURSED_PIECE_OF_THIRTEEN = 3034;
public static final int FOIL_BOW = 3043;
public static final int FOIL_RADAR = 3044;
public static final int POWER_SPHERE = 3049;
public static final int FOIL_CAT_EARS = 3056;
public static final int LASER_CANON = 3069;
public static final int CHIN_STRAP = 3070;
public static final int GLUTEAL_SHIELD = 3071;
public static final int CARBONITE_VISOR = 3072;
public static final int UNOBTAINIUM_STRAPS = 3073;
public static final int FASTENING_APPARATUS = 3074;
public static final int GENERAL_ASSEMBLY_MODULE = 3075;
public static final int LASER_TARGETING_CHIP = 3076;
public static final int LEG_ARMOR = 3077;
public static final int KEVLATEFLOCITE_HELMET = 3078;
public static final int TEDDY_BORG_SEWING_KIT = 3087;
public static final int VITACHOC_CAPSULE = 3091;
public static final int HOBBY_HORSE = 3092;
public static final int BALL_IN_A_CUP = 3093;
public static final int SET_OF_JACKS = 3094;
public static final int FISH_SCALER = 3097;
public static final int MINIBORG_STOMPER = 3109;
public static final int MINIBORG_STRANGLER = 3110;
public static final int MINIBORG_LASER = 3111;
public static final int MINIBORG_BEEPER = 3112;
public static final int MINIBORG_HIVEMINDER = 3113;
public static final int MINIBORG_DESTROYOBOT = 3114;
public static final int DIVINE_BOOK = 3117;
public static final int DIVINE_NOISEMAKER = 3118;
public static final int DIVINE_SILLY_STRING = 3119;
public static final int DIVINE_BLOWOUT = 3120;
public static final int DIVINE_CHAMPAGNE_POPPER = 3121;
public static final int DIVINE_CRACKER = 3122;
public static final int DIVINE_FLUTE = 3123;
public static final int HOBO_NICKEL = 3126;
public static final int SANDCASTLE = 3127;
public static final int MARSHMALLOW = 3128;
public static final int ROASTED_MARSHMALLOW = 3129;
public static final int TORN_PAPER_STRIP = 3144;
public static final int PUNCHCARD_ATTACK = 3146;
public static final int PUNCHCARD_REPAIR = 3147;
public static final int PUNCHCARD_BUFF = 3148;
public static final int PUNCHCARD_MODIFY = 3149;
public static final int PUNCHCARD_BUILD = 3150;
public static final int PUNCHCARD_TARGET = 3151;
public static final int PUNCHCARD_SELF = 3152;
public static final int PUNCHCARD_FLOOR = 3153;
public static final int PUNCHCARD_DRONE = 3154;
public static final int PUNCHCARD_WALL = 3155;
public static final int PUNCHCARD_SPHERE = 3156;
public static final int DRONE = 3157;
public static final int EL_VIBRATO_HELMET = 3162;
public static final int EL_VIBRATO_SPEAR = 3163;
public static final int EL_VIBRATO_PANTS = 3164;
public static final int BROKEN_DRONE = 3165;
public static final int REPAIRED_DRONE = 3166;
public static final int AUGMENTED_DRONE = 3167;
public static final int FORTUNE_TELLER = 3193;
public static final int ORIGAMI_MAGAZINE = 3194;
public static final int PAPER_SHURIKEN = 3195;
public static final int ORIGAMI_PASTIES = 3196;
public static final int RIDING_CROP = 3197;
public static final int TRAPEZOID = 3198;
public static final int LUMP_OF_COAL = 3199;
public static final int THICK_PADDED_ENVELOPE = 3201;
public static final int DWARVISH_WAR_HELMET = 3204;
public static final int DWARVISH_WAR_MATTOCK = 3205;
public static final int DWARVISH_WAR_KILT = 3206;
public static final int DWARVISH_PUNCHCARD = 3207;
public static final int SMALL_LAMINATED_CARD = 3208;
public static final int LITTLE_LAMINATED_CARD = 3209;
public static final int NOTBIG_LAMINATED_CARD = 3210;
public static final int UNLARGE_LAMINATED_CARD = 3211;
public static final int DWARVISH_DOCUMENT = 3212;
public static final int DWARVISH_PAPER = 3213;
public static final int DWARVISH_PARCHMENT = 3214;
public static final int OVERCHARGED_POWER_SPHERE = 3215;
public static final int HOBO_CODE_BINDER = 3220;
public static final int GATORSKIN_UMBRELLA = 3222;
public static final int SEWER_WAD = 3224;
public static final int OOZE_O = 3226;
public static final int DUMPLINGS = 3228;
public static final int OIL_OF_OILINESS = 3230;
public static final int TATTERED_PAPER_CROWN = 3231;
public static final int INFLATABLE_DUCK = 3233;
public static final int WATER_WINGS = 3234;
public static final int FOAM_NOODLE = 3235;
public static final int KISSIN_COUSINS = 3236;
public static final int TALES_FROM_THE_FIRESIDE = 3237;
public static final int BLIZZARDS_I_HAVE_DIED_IN = 3238;
public static final int MAXING_RELAXING = 3239;
public static final int BIDDY_CRACKERS_COOKBOOK = 3240;
public static final int TRAVELS_WITH_JERRY = 3241;
public static final int LET_ME_BE = 3242;
public static final int ASLEEP_IN_THE_CEMETERY = 3243;
public static final int SUMMER_NIGHTS = 3244;
public static final int SENSUAL_MASSAGE_FOR_CREEPS = 3245;
public static final int BAG_OF_CANDY = 3261;
public static final int TASTEFUL_BOOK = 3263;
public static final int LITTLE_ROUND_PEBBLE = 3464;
public static final int CROTCHETY_PANTS = 3271;
public static final int SACCHARINE_MAPLE_PENDANT = 3272;
public static final int WILLOWY_BONNET = 3273;
public static final int BLACK_BLUE_LIGHT = 3276;
public static final int LOUDMOUTH_LARRY = 3277;
public static final int CHEAP_STUDDED_BELT = 3278;
public static final int PERSONAL_MASSAGER = 3279;
public static final int PLASMA_BALL = 3281;
public static final int STICK_ON_EYEBROW_PIERCING = 3282;
public static final int MACARONI_FRAGMENTS = 3287;
public static final int SHIMMERING_TENDRILS = 3288;
public static final int SCINTILLATING_POWDER = 3289;
public static final int VOLCANO_MAP = 3291;
public static final int PRETTY_PINK_BOW = 3298;
public static final int SMILEY_FACE_STICKER = 3299;
public static final int FARFALLE_BOW_TIE = 3300;
public static final int JALAPENO_SLICES = 3301;
public static final int SOLAR_PANELS = 3302;
public static final int TINY_SOMBRERO = 3303;
public static final int EPIC_WAD = 3316;
public static final int MAYFLY_BAIT_NECKLACE = 3322;
public static final int SCRATCHS_FORK = 3323;
public static final int FROSTYS_MUG = 3324;
public static final int FERMENTED_PICKLE_JUICE = 3325;
public static final int EXTRA_GREASY_SLIDER = 3327;
public static final int CRUMPLED_FELT_FEDORA = 3328;
public static final int DOUBLE_SIDED_TAPE = 3336;
public static final int HOT_BEDDING = 3344; // bed of coals
public static final int COLD_BEDDING = 3345; // frigid air mattress
public static final int STENCH_BEDDING = 3346; // filth-encrusted futon
public static final int SPOOKY_BEDDING = 3347; // comfy coffin
public static final int SLEAZE_BEDDING = 3348; // stained mattress
public static final int ZEN_MOTORCYCLE = 3352;
public static final int GONG = 3353;
public static final int GRUB = 3356;
public static final int MOTH = 3357;
public static final int FIRE_ANT = 3358;
public static final int ICE_ANT = 3359;
public static final int STINKBUG = 3360;
public static final int DEATH_WATCH_BEETLE = 3361;
public static final int LOUSE = 3362;
public static final int INTERESTING_TWIG = 3367;
public static final int TWIG_HOUSE = 3374;
public static final int RICHIE_THINGFINDER = 3375;
public static final int MEDLEY_OF_DIVERSITY = 3376;
public static final int EXPLOSIVE_ETUDE = 3377;
public static final int CHORALE_OF_COMPANIONSHIP = 3378;
public static final int PRELUDE_OF_PRECISION = 3379;
public static final int CHESTER_GLASSES = 3383;
public static final int EMPTY_EYE = 3388;
public static final int ICEBALL = 3391;
public static final int NEVERENDING_SODA = 3393;
public static final int HODGMANS_PORKPIE_HAT = 3395;
public static final int HODGMANS_LOBSTERSKIN_PANTS = 3396;
public static final int HODGMANS_BOW_TIE = 3397;
public static final int SQUEEZE = 3399;
public static final int FISHYSOISSE = 3400;
public static final int LAMP_SHADE = 3401;
public static final int GARBAGE_JUICE = 3402;
public static final int LEWD_CARD = 3403;
public static final int HODGMAN_JOURNAL_1 = 3412;
public static final int HODGMAN_JOURNAL_2 = 3413;
public static final int HODGMAN_JOURNAL_3 = 3414;
public static final int HODGMAN_JOURNAL_4 = 3415;
public static final int HOBO_FORTRESS = 3416;
public static final int FIREWORKS = 3421;
public static final int GIFTH = 3430;
public static final int SPICE_MELANGE = 3433;
public static final int RAINBOWS_GRAVITY = 3439;
public static final int COTTON_CANDY_CONDE = 3449;
public static final int COTTON_CANDY_PINCH = 3450;
public static final int COTTON_CANDY_SMIDGEN = 3451;
public static final int COTTON_CANDY_SKOSHE = 3452;
public static final int COTTON_CANDY_PLUG = 3453;
public static final int COTTON_CANDY_PILLOW = 3454;
public static final int COTTON_CANDY_BALE = 3455;
public static final int STYX_SPRAY = 3458;
public static final int BASH_OS_CEREAL = 3465;
public static final int HAIKU_KATANA = 3466;
public static final int BATHYSPHERE = 3470;
public static final int DAMP_OLD_BOOT = 3471;
public static final int BOXTOP = 3473;
public static final int DULL_FISH_SCALE = 3486;
public static final int ROUGH_FISH_SCALE = 3487;
public static final int PRISTINE_FISH_SCALE = 3488;
public static final int FISH_SCIMITAR = 3492;
public static final int FISH_STICK = 3493;
public static final int FISH_BAZOOKA = 3494;
public static final int SEA_SALT_CRYSTAL = 3495;
public static final int LARP_MEMBERSHIP_CARD = 3506;
public static final int STICKER_BOOK = 3507;
public static final int STICKER_SWORD = 3508;
public static final int UNICORN_STICKER = 3509;
public static final int APPLE_STICKER = 3510;
public static final int UPC_STICKER = 3511;
public static final int WRESTLER_STICKER = 3512;
public static final int DRAGON_STICKER = 3513;
public static final int ROCK_BAND_STICKER = 3514;
public static final int EELSKIN_HAT = 3517;
public static final int EELSKIN_PANTS = 3518;
public static final int EELSKIN_SHIELD = 3519;
public static final int STICKER_CROSSBOW = 3526;
public static final int PLANS_FOR_GRIMACITE_HAMMER = 3535;
public static final int PLANS_FOR_GRIMACITE_GRAVY_BOAT = 3536;
public static final int PLANS_FOR_GRIMACITE_WEIGHTLIFTING_BELT = 3537;
public static final int PLANS_FOR_GRIMACITE_GRAPPLING_HOOK = 3538;
public static final int PLANS_FOR_GRIMACITE_NINJA_MASK = 3539;
public static final int PLANS_FOR_GRIMACITE_SHINGUARDS = 3540;
public static final int PLANS_FOR_GRIMACITE_ASTROLABE = 3541;
public static final int GRIMACITE_HAMMER = 3542;
public static final int GRIMACITE_GRAVY_BOAT = 3543;
public static final int GRIMACITE_WEIGHTLIFTING_BELT = 3544;
public static final int GRIMACITE_GRAPPLING_HOOK = 3545;
public static final int GRIMACITE_NINJA_MASK = 3546;
public static final int GRIMACITE_SHINGUARDS = 3547;
public static final int GRIMACITE_ASTROLABE = 3548;
public static final int SEED_PACKET = 3553;
public static final int GREEN_SLIME = 3554;
public static final int SEA_CARROT = 3555;
public static final int SEA_CUCUMBER = 3556;
public static final int SEA_AVOCADO = 3557;
public static final int POTION_OF_PUISSANCE = 3561;
public static final int POTION_OF_PERSPICACITY = 3562;
public static final int POTION_OF_PULCHRITUDE = 3563;
public static final int SPONGE_HELMET = 3568;
public static final int SAND_DOLLAR = 3575;
public static final int BEZOAR_RING = 3577;
public static final int WRIGGLING_FLYTRAP_PELLET = 3580;
public static final int SUSHI_ROLLING_MAT = 3581;
public static final int WHITE_RICE = 3582;
public static final int RUSTY_BROKEN_DIVING_HELMET = 3602;
public static final int BUBBLIN_STONE = 3605;
public static final int AERATED_DIVING_HELMET = 3607;
public static final int DAS_BOOT = 3609;
public static final int IMITATION_WHETSTONE = 3610;
public static final int PARASITIC_CLAW = 3624;
public static final int PARASITIC_TENTACLES = 3625;
public static final int PARASITIC_HEADGNAWER = 3626;
public static final int PARASITIC_STRANGLEWORM = 3627;
public static final int BURROWGRUB_HIVE = 3629;
public static final int JAMFISH_JAM = 3641;
public static final int DRAGONFISH_CAVIAR = 3642;
public static final int GRIMACITE_KNEECAPPING_STICK = 3644;
public static final int CANTEEN_OF_WINE = 3645;
public static final int MADNESS_REEF_MAP = 3649;
public static final int MINIATURE_ANTLERS = 3651;
public static final int SPOOKY_PUTTY_MITRE = 3662;
public static final int SPOOKY_PUTTY_LEOTARD = 3663;
public static final int SPOOKY_PUTTY_BALL = 3664;
public static final int SPOOKY_PUTTY_SHEET = 3665;
public static final int SPOOKY_PUTTY_SNAKE = 3666;
public static final int SPOOKY_PUTTY_MONSTER = 3667;
public static final int RAGE_GLAND = 3674;
public static final int MERKIN_PRESSUREGLOBE = 3675;
public static final int GLOWING_ESCA = 3680;
public static final int MARINARA_TRENCH_MAP = 3683;
public static final int TEMPURA_CARROT = 3684;
public static final int TEMPURA_CUCUMBER = 3685;
public static final int TEMPURA_AVOCADO = 3686;
public static final int TEMPURA_BROCCOLI = 3689;
public static final int TEMPURA_CAULIFLOWER = 3690;
public static final int POTION_OF_PERCEPTION = 3693;
public static final int POTION_OF_PROFICIENCY = 3694;
public static final int VELCRO_ORE = 3698;
public static final int TEFLON_ORE = 3699;
public static final int VINYL_ORE = 3700;
public static final int ANEMONE_MINE_MAP = 3701;
public static final int VINYL_BOOTS = 3716;
public static final int GNOLL_EYE = 3731;
public static final int CHEAP_CIGAR_BUTT = 3732;
public static final int BOOZEHOUND_TOKEN = 3739;
public static final int UNSTABLE_QUARK = 3743;
public static final int FUMBLE_FORMULA = 3745;
public static final int MOTHERS_SECRET_RECIPE = 3747;
public static final int LOVE_BOOK = 3753;
public static final int VAGUE_AMBIGUITY = 3754;
public static final int SMOLDERING_PASSION = 3755;
public static final int ICY_REVENGE = 3756;
public static final int SUGARY_CUTENESS = 3757;
public static final int DISTURBING_OBSESSION = 3758;
public static final int NAUGHTY_INNUENDO = 3759;
public static final int DIVE_BAR_MAP = 3774;
public static final int MERKIN_PINKSLIP = 3775;
public static final int PARANORMAL_RICOTTA = 3784;
public static final int SMOKING_TALON = 3785;
public static final int VAMPIRE_GLITTER = 3786;
public static final int WINE_SOAKED_BONE_CHIPS = 3787;
public static final int CRUMBLING_RAT_SKULL = 3788;
public static final int TWITCHING_TRIGGER_FINGER = 3789;
public static final int AQUAVIOLET_JUBJUB_BIRD = 3800;
public static final int CRIMSILION_JUBJUB_BIRD = 3801;
public static final int CHARPUCE_JUBJUB_BIRD = 3802;
public static final int MERKIN_TRAILMAP = 3808;
public static final int MERKIN_LOCKKEY = 3810;
public static final int MERKIN_STASHBOX = 3811;
public static final int SEA_RADISH = 3817;
public static final int EEL_SAUCE = 3819;
public static final int FISHY_WAND = 3822;
public static final int GRANDMAS_NOTE = 3824;
public static final int FUCHSIA_YARN = 3825;
public static final int CHARTREUSE_YARN = 3826;
public static final int GRANDMAS_MAP = 3828;
public static final int TEMPURA_RADISH = 3829;
public static final int TINY_COSTUME_WARDROBE = 3835;
public static final int ELVISH_SUNGLASSES = 3836;
public static final int OOT_BIWA = 3842;
public static final int JUNGLE_DRUM = 3846;
public static final int HIPPY_BONGO = 3847;
public static final int GUITAR_4D = 3849;
public static final int HALF_GUITAR = 3852;
public static final int BASS_DRUM = 3853;
public static final int SMALLEST_VIOLIN = 3855;
public static final int BONE_FLUTE = 3858;
public static final int PLASTIC_GUITAR = 3863;
public static final int FINGER_CYMBALS = 3864;
public static final int KETTLE_DRUM = 3865;
public static final int HELLSEAL_HIDE = 3874;
public static final int HELLSEAL_BRAIN = 3876;
public static final int HELLSEAL_SINEW = 3878;
public static final int HELLSEAL_DISGUISE = 3880;
public static final int FOUET_DE_TORTUE_DRESSAGE = 3881;
public static final int CULT_MEMO = 3883;
public static final int DECODED_CULT_DOCUMENTS = 3884;
public static final int FIRST_SLIME_VIAL = 3885;
public static final int VIAL_OF_RED_SLIME = 3885;
public static final int VIAL_OF_YELLOW_SLIME = 3886;
public static final int VIAL_OF_BLUE_SLIME = 3887;
public static final int VIAL_OF_ORANGE_SLIME = 3888;
public static final int VIAL_OF_GREEN_SLIME = 3889;
public static final int VIAL_OF_VIOLET_SLIME = 3890;
public static final int VIAL_OF_VERMILION_SLIME = 3891;
public static final int VIAL_OF_AMBER_SLIME = 3892;
public static final int VIAL_OF_CHARTREUSE_SLIME = 3893;
public static final int VIAL_OF_TEAL_SLIME = 3894;
public static final int VIAL_OF_INDIGO_SLIME = 3895;
public static final int VIAL_OF_PURPLE_SLIME = 3896;
public static final int LAST_SLIME_VIAL = 3897;
public static final int VIAL_OF_BROWN_SLIME = 3897;
public static final int BOTTLE_OF_GU_GONE = 3898;
public static final int SEAL_BLUBBER_CANDLE = 3901;
public static final int WRETCHED_SEAL = 3902;
public static final int CUTE_BABY_SEAL = 3903;
public static final int ARMORED_SEAL = 3904;
public static final int ANCIENT_SEAL = 3905;
public static final int SLEEK_SEAL = 3906;
public static final int SHADOWY_SEAL = 3907;
public static final int STINKING_SEAL = 3908;
public static final int CHARRED_SEAL = 3909;
public static final int COLD_SEAL = 3910;
public static final int SLIPPERY_SEAL = 3911;
public static final int IMBUED_SEAL_BLUBBER_CANDLE = 3912;
public static final int TURTLE_WAX = 3914;
public static final int TURTLE_WAX_HELMET = 3916;
public static final int TURTLE_WAX_GREAVES = 3917;
public static final int TURTLEMAIL_BITS = 3919;
public static final int TURTLING_ROD = 3927;
public static final int SEAL_IRON_INGOT = 3932;
public static final int HYPERINFLATED_SEAL_LUNG = 3935;
public static final int VIP_LOUNGE_KEY = 3947;
public static final int STUFFED_CHEST = 3949;
public static final int STUFFED_KEY = 3950;
public static final int STUFFED_BARON = 3951;
public static final int CLAN_POOL_TABLE = 3963;
public static final int TINY_CELL_PHONE = 3964;
public static final int DUELING_BANJO = 3984;
public static final int SAMURAI_TURTLE = 3986;
public static final int SLIME_SOAKED_HYPOPHYSIS = 3991;
public static final int SLIME_SOAKED_BRAIN = 3992;
public static final int SLIME_SOAKED_SWEAT_GLAND = 3993;
public static final int DOLPHIN_WHISTLE = 3997;
public static final int AGUA_DE_VIDA = 4001;
public static final int MOONTAN_LOTION = 4003;
public static final int BALLAST_TURTLE = 4005;
public static final int AMINO_ACIDS = 4006;
public static final int CA_BASE_PAIR = 4011;
public static final int CG_BASE_PAIR = 4012;
public static final int CT_BASE_PAIR = 4013;
public static final int AG_BASE_PAIR = 4014;
public static final int AT_BASE_PAIR = 4015;
public static final int GT_BASE_PAIR = 4016;
public static final int CONTACT_LENSES = 4019;
public static final int GRAPPLING_HOOK = 4029;
public static final int SMALL_STONE_BLOCK = 4030;
public static final int LITTLE_STONE_BLOCK = 4031;
public static final int HALF_STONE_CIRCLE = 4032;
public static final int STONE_HALF_CIRCLE = 4033;
public static final int IRON_KEY = 4034;
public static final int CULTIST_ROBE = 4040;
public static final int WUMPUS_HAIR = 4044;
public static final int RING_OF_TELEPORTATION = 4051;
public static final int INDIGO_PARTY_INVITATION = 4060;
public static final int VIOLET_HUNT_INVITATION = 4061;
public static final int BLUE_MILK_CLUB_CARD = 4062;
public static final int MECHA_MAYHEM_CLUB_CARD = 4063;
public static final int SMUGGLER_SHOT_FIRST_BUTTON = 4064;
public static final int SPACEFLEET_COMMUNICATOR_BADGE = 4065;
public static final int RUBY_ROD = 4066;
public static final int ESSENCE_OF_HEAT = 4067;
public static final int ESSENCE_OF_KINK = 4068;
public static final int ESSENCE_OF_COLD = 4069;
public static final int ESSENCE_OF_STENCH = 4070;
public static final int ESSENCE_OF_FRIGHT = 4071;
public static final int ESSENCE_OF_CUTE = 4072;
public static final int SUPREME_BEING_GLOSSARY = 4073;
public static final int MULTI_PASS = 4074;
public static final int GRISLY_SHIELD = 4080;
public static final int CYBER_MATTOCK = 4086;
public static final int GREEN_PEAWEE_MARBLE = 4095;
public static final int BROWN_CROCK_MARBLE = 4096;
public static final int RED_CHINA_MARBLE = 4097;
public static final int LEMONADE_MARBLE = 4098;
public static final int BUMBLEBEE_MARBLE = 4099;
public static final int JET_BENNIE_MARBLE = 4100;
public static final int BEIGE_CLAMBROTH_MARBLE = 4101;
public static final int STEELY_MARBLE = 4102;
public static final int BEACH_BALL_MARBLE = 4103;
public static final int BLACK_CATSEYE_MARBLE = 4104;
public static final int BIG_BUMBOOZER_MARBLE = 4105;
public static final int MONSTROUS_MONOCLE = 4108;
public static final int MUSTY_MOCCASINS = 4109;
public static final int MOLTEN_MEDALLION = 4110;
public static final int BRAZEN_BRACELET = 4111;
public static final int BITTER_BOWTIE = 4112;
public static final int BEWITCHING_BOOTS = 4113;
public static final int SECRET_FROM_THE_FUTURE = 4114;
public static final int EMPTY_AGUA_DE_VIDA_BOTTLE = 4130;
public static final int TEMPURA_AIR = 4133;
public static final int PRESSURIZED_PNEUMATICITY = 4134;
public static final int MOVEABLE_FEAST = 4135;
public static final int BAG_O_TRICKS = 4136;
public static final int SLIME_STACK = 4137;
public static final int RUMPLED_PAPER_STRIP = 4138;
public static final int CREASED_PAPER_STRIP = 4139;
public static final int FOLDED_PAPER_STRIP = 4140;
public static final int CRINKLED_PAPER_STRIP = 4141;
public static final int CRUMPLED_PAPER_STRIP = 4142;
public static final int RAGGED_PAPER_STRIP = 4143;
public static final int RIPPED_PAPER_STRIP = 4144;
public static final int QUADROCULARS = 4149;
public static final int CAMERA = 4169;
public static final int SHAKING_CAMERA = 4170;
public static final int SPAGHETTI_CULT_ROBE = 4175;
public static final int SUGAR_SHEET = 4176;
public static final int SUGAR_BOOK = 4177;
public static final int SUGAR_SHOTGUN = 4178;
public static final int SUGAR_SHILLELAGH = 4179;
public static final int SUGAR_SHANK = 4180;
public static final int SUGAR_CHAPEAU = 4181;
public static final int SUGAR_SHORTS = 4182;
public static final int SUGAR_SHIELD = 4183;
public static final int SUGAR_SHIRT = 4191;
public static final int SUGAR_SHARD = 4192;
public static final int RAVE_VISOR = 4193;
public static final int BAGGY_RAVE_PANTS = 4194;
public static final int PACIFIER_NECKLACE = 4195;
public static final int SEA_COWBELL = 4196;
public static final int SEA_LASSO = 4198;
public static final int MERKIN_CHEATSHEET = 4204;
public static final int MERKIN_WORDQUIZ = 4205;
public static final int SKATE_PARK_MAP = 4222;
public static final int AMPHIBIOUS_TOPHAT = 4229;
public static final int HACIENDA_KEY = 4233;
public static final int SILVER_PATE_KNIFE = 4234;
public static final int SILVER_CHEESE_SLICER = 4237;
public static final int SLEEP_MASK = 4241;
public static final int FISHERMANS_SACK = 4250;
public static final int FISH_OIL_SMOKE_BOMB = 4251;
public static final int VIAL_OF_SQUID_INK = 4252;
public static final int POTION_OF_FISHY_SPEED = 4253;
public static final int WOLFMAN_MASK = 4260;
public static final int PUMPKINHEAD_MASK = 4261;
public static final int MUMMY_COSTUME = 4262;
public static final int KRAKROXS_LOINCLOTH = 4267;
public static final int GALAPAGOSIAN_CUISSES = 4268;
public static final int ANGELHAIR_CULOTTES = 4269;
public static final int NEWMANS_OWN_TROUSERS = 4270;
public static final int VOLARTTAS_BELLBOTTOMS = 4271;
public static final int LEDERHOSEN_OF_THE_NIGHT = 4272;
public static final int UNDERWORLD_ACORN = 4274;
public static final int CRAPPY_MASK = 4282;
public static final int GLADIATOR_MASK = 4284;
public static final int SCHOLAR_MASK = 4285;
public static final int MERKIN_DODGEBALL = 4292;
public static final int MERKIN_DRAGNET = 4293;
public static final int MERKIN_SWITCHBLADE = 4294;
public static final int CRYSTAL_ORB = 4295;
public static final int DEPLETED_URANIUM_SEAL = 4296;
public static final int VIOLENCE_STOMPERS = 4297;
public static final int VIOLENCE_BRAND = 4298;
public static final int VIOLENCE_LENS = 4300;
public static final int VIOLENCE_PANTS = 4302;
public static final int HATRED_STONE = 4303;
public static final int HATRED_GIRDLE = 4304;
public static final int HATRED_STAFF = 4305;
public static final int HATRED_PANTS = 4306;
public static final int HATRED_SLIPPERS = 4307;
public static final int HATRED_LENS = 4308;
public static final int SLEDGEHAMMER_OF_THE_VAELKYR = 4316;
public static final int FLAIL_OF_THE_SEVEN_ASPECTS = 4317;
public static final int WRATH_OF_THE_PASTALORDS = 4318;
public static final int WINDSOR_PAN_OF_THE_SOURCE = 4319;
public static final int SEEGERS_BANJO = 4320;
public static final int TRICKSTER_TRIKITIXA = 4321;
public static final int INFERNAL_SEAL_CLAW = 4322;
public static final int TURTLE_POACHER_GARTER = 4323;
public static final int SPAGHETTI_BANDOLIER = 4324;
public static final int SAUCEBLOB_BELT = 4325;
public static final int NEW_WAVE_BLING = 4326;
public static final int BELT_BUCKLE_OF_LOPEZ = 4327;
public static final int BAG_OF_MANY_CONFECTIONS = 4329;
public static final int FANCY_CHOCOLATE_CAR = 4334;
public static final int CRIMBUCK = 4343;
public static final int GINGERBREAD_HOUSE = 4347;
public static final int CRIMBOUGH = 4353;
public static final int CRIMBO_CAROL_V1 = 4354;
public static final int CRIMBO_CAROL_V2 = 4355;
public static final int CRIMBO_CAROL_V3 = 4356;
public static final int CRIMBO_CAROL_V4 = 4357;
public static final int CRIMBO_CAROL_V5 = 4358;
public static final int CRIMBO_CAROL_V6 = 4359;
public static final int ELF_RESISTANCE_BUTTON = 4363;
public static final int WRENCH_HANDLE = 4368;
public static final int HEADLESS_BOLTS = 4369;
public static final int AGITPROP_INK = 4370;
public static final int HANDFUL_OF_WIRES = 4371;
public static final int CHUNK_OF_CEMENT = 4372;
public static final int PENGUIN_GRAPPLING_HOOK = 4373;
public static final int CARDBOARD_ELF_EAR = 4374;
public static final int SPIRALING_SHAPE = 4375;
public static final int CRIMBOMINATION_CONTRAPTION = 4376;
public static final int RED_AND_GREEN_SWEATER = 4391;
public static final int CRIMBO_CANDY_COOKBOOK = 4392;
public static final int STINKY_CHEESE_BALL = 4398;
public static final int STINKY_CHEESE_SWORD = 4399;
public static final int STINKY_CHEESE_DIAPER = 4400;
public static final int STINKY_CHEESE_WHEEL = 4401;
public static final int STINKY_CHEESE_EYE = 4402;
public static final int STINKY_CHEESE_STAFF = 4403;
public static final int SLAPFIGHTING_BOOK = 4406;
public static final int UNCLE_ROMULUS = 4407;
public static final int SNAKE_CHARMING_BOOK = 4408;
public static final int ZU_MANNKASE_DIENEN = 4409;
public static final int DYNAMITE_SUPERMAN_JONES = 4410;
public static final int INIGO_BOOK = 4411;
public static final int QUANTUM_TACO = 4412;
public static final int SCHRODINGERS_THERMOS = 4413;
public static final int BLACK_HYMNAL = 4426;
public static final int GLOWSTICK_ON_A_STRING = 4428;
public static final int CANDY_NECKLACE = 4429;
public static final int TEDDYBEAR_BACKPACK = 4430;
public static final int STRANGE_CUBE = 4436;
public static final int INSTANT_KARMA = 4448;
public static final int MACHETITO = 4452;
public static final int LEAFBLOWER = 4455;
public static final int SNAILMAIL_BITS = 4457;
public static final int CHOCOLATE_SEAL_CLUBBING_CLUB = 4462;
public static final int CHOCOLATE_TURTLE_TOTEM = 4463;
public static final int CHOCOLATE_PASTA_SPOON = 4464;
public static final int CHOCOLATE_SAUCEPAN = 4465;
public static final int CHOCOLATE_DISCO_BALL = 4466;
public static final int CHOCOLATE_STOLEN_ACCORDION = 4467;
public static final int BRICKO_BOOK = 4468;
public static final int BRICKO_EYE = 4470;
public static final int BRICKO_HAT = 4471;
public static final int BRICKO_PANTS = 4472;
public static final int BRICKO_SWORD = 4473;
public static final int BRICKO_OOZE = 4474;
public static final int BRICKO_BAT = 4475;
public static final int BRICKO_OYSTER = 4476;
public static final int BRICKO_TURTLE = 4477;
public static final int BRICKO_ELEPHANT = 4478;
public static final int BRICKO_OCTOPUS = 4479;
public static final int BRICKO_PYTHON = 4480;
public static final int BRICKO_VACUUM_CLEANER = 4481;
public static final int BRICKO_AIRSHIP = 4482;
public static final int BRICKO_CATHEDRAL = 4483;
public static final int BRICKO_CHICKEN = 4484;
public static final int BRICKO_PYRAMID = 4485;
public static final int RECORDING_BALLAD = 4497;
public static final int RECORDING_BENETTON = 4498;
public static final int RECORDING_ELRON = 4499;
public static final int RECORDING_CHORALE = 4500;
public static final int RECORDING_PRELUDE = 4501;
public static final int RECORDING_DONHO = 4502;
public static final int RECORDING_INIGO = 4503;
public static final int CLAN_LOOKING_GLASS = 4507;
public static final int DRINK_ME_POTION = 4508;
public static final int REFLECTION_OF_MAP = 4509;
public static final int WALRUS_ICE_CREAM = 4510;
public static final int BEAUTIFUL_SOUP = 4511;
public static final int HUMPTY_DUMPLINGS = 4514;
public static final int LOBSTER_QUA_GRILL = 4515;
public static final int MISSING_WINE = 4516;
public static final int ITTAH_BITTAH_HOOKAH = 4519;
public static final int QUEEN_COOKIE = 4535;
public static final int STUFFED_POCKETWATCH = 4545;
public static final int JACKING_MAP = 4560;
public static final int TINY_FLY_GLASSES = 4566;
public static final int LEGENDARY_BEAT = 4573;
public static final int BUGGED_BEANIE = 4575;
public static final int BUGGED_BONNET = 4577;
public static final int BUGGED_MEAT_CLUB = 4578;
public static final int BUGGED_POTION = 4579;
public static final int BUGGED_KNICKERBOCKERS = 4580;
public static final int BUGGED_BAIO = 4581;
public static final int PIXEL_WHIP = 4589;
public static final int PIXEL_CHAIN_WHIP = 4590;
public static final int PIXEL_MORNING_STAR = 4591;
public static final int PIXEL_ORB = 4592;
public static final int KEGGER_MAP = 4600;
public static final int ORQUETTES_PHONE_NUMBER = 4602;
public static final int BOTTLE_OF_GOLDENSCHNOCKERED = 4605;
public static final int ESSENTIAL_TOFU = 4609;
public static final int HATSEAT = 4614;
public static final int GG_TOKEN = 4621;
public static final int GG_TICKET = 4622;
public static final int COFFEE_PIXIE_STICK = 4625;
public static final int SPIDER_RING = 4629;
public static final int SINISTER_DEMON_MASK = 4637;
public static final int CHAMPION_BELT = 4638;
public static final int SPACE_TRIP_HEADPHONES = 4639;
public static final int KOL_CON_SIX_PACK = 4641;
public static final int JUJU_MOJO_MASK = 4644;
public static final int METEOID_ICE_BEAM = 4646;
public static final int DUNGEON_FIST_GAUNTLET = 4647;
public static final int IRONIC_MOUSTACHE = 4651;
public static final int BLACKBERRY_GALOSHES = 4659;
public static final int ELLSBURY_BOOK = 4663;
public static final int HOT_PLATE = 4665;
public static final int INSULT_PUPPET = 4667;
public static final int OBSERVATIONAL_GLASSES = 4668;
public static final int COMEDY_PROP = 4669;
public static final int BEER_SCENTED_TEDDY_BEAR = 4670;
public static final int BOOZE_SOAKED_CHERRY = 4671;
public static final int COMFY_PILLOW = 4672;
public static final int GIANT_MARSHMALLOW = 4673;
public static final int SPONGE_CAKE = 4674;
public static final int GIN_SOAKED_BLOTTER_PAPER = 4675;
public static final int TREE_HOLED_COIN = 4676;
public static final int UNEARTHED_METEOROID = 4677;
public static final int VOLCANIC_ASH = 4679;
public static final int FOSSILIZED_BAT_SKULL = 4687;
public static final int FOSSILIZED_SERPENT_SKULL = 4688;
public static final int FOSSILIZED_BABOON_SKULL = 4689;
public static final int FOSSILIZED_WYRM_SKULL = 4690;
public static final int FOSSILIZED_WING = 4691;
public static final int FOSSILIZED_LIMB = 4692;
public static final int FOSSILIZED_TORSO = 4693;
public static final int FOSSILIZED_SPINE = 4694;
public static final int GREAT_PANTS = 4696;
public static final int IMP_AIR = 4698;
public static final int BUS_PASS = 4699;
public static final int FOSSILIZED_SPIKE = 4700;
public static final int ARCHAEOLOGING_SHOVEL = 4702;
public static final int FOSSILIZED_DEMON_SKULL = 4704;
public static final int FOSSILIZED_SPIDER_SKULL = 4705;
public static final int SINISTER_ANCIENT_TABLET = 4706;
public static final int OVEN = 4707;
public static final int SHAKER = 4708;
public static final int OLD_SWEATPANTS = 4711;
public static final int MARIACHI_HAT = 4718;
public static final int HOLLANDAISE_HELMET = 4719;
public static final int MICROWAVE_STOGIE = 4721;
public static final int LIVER_PIE = 4722;
public static final int BADASS_PIE = 4723;
public static final int FISH_PIE = 4724;
public static final int PIPING_PIE = 4725;
public static final int IGLOO_PIE = 4726;
public static final int TURNOVER = 4727;
public static final int DEAD_PIE = 4728;
public static final int THROBBING_PIE = 4729;
public static final int BONE_CHIPS = 4743;
public static final int STABONIC_SCROLL = 4757;
public static final int PUMPKIN_SEEDS = 4760;
public static final int PUMPKIN = 4761;
public static final int HUGE_PUMPKIN = 4762;
public static final int PUMPKIN_BOMB = 4766;
public static final int PUMPKIN_CARRIAGE = 4769;
public static final int DESERT_BUS_PASS = 4770;
public static final int GINORMOUS_PUMPKIN = 4771;
public static final int ESSENCE_OF_ANNOYANCE = 4804;
public static final int HOLIDAY_FUN_BOOK = 4810;
public static final int ANTAGONISTIC_SNOWMAN_KIT = 4812;
public static final int SLEEPING_STOCKING = 4842;
public static final int KANSAS_TOYMAKER = 4843;
public static final int WASSAILING_BOOK = 4844;
public static final int UNCLE_HOBO_BEARD = 4846;
public static final int CHOCOLATE_CIGAR = 4851;
public static final int CRIMBCO_SCRIP = 4854;
public static final int BLANK_OUT_BOTTLE = 4857;
public static final int CRIMBCO_MANUAL_1 = 4859;
public static final int CRIMBCO_MANUAL_2 = 4860;
public static final int CRIMBCO_MANUAL_3 = 4861;
public static final int CRIMBCO_MANUAL_4 = 4862;
public static final int CRIMBCO_MANUAL_5 = 4863;
public static final int PHOTOCOPIER = 4864;
public static final int CLAN_FAX_MACHINE = 4865;
public static final int WORKYTIME_TEA = 4866;
public static final int GLOB_OF_BLANK_OUT = 4872;
public static final int PHOTOCOPIED_MONSTER = 4873;
public static final int GAUDY_KEY = 4874;
public static final int CRIMBCO_MUG = 4880;
public static final int CRIMBCO_WINE = 4881;
public static final int BGE_SHOTGLASS = 4893;
public static final int BGE_TATTOO = 4900;
public static final int COAL_PAPERWEIGHT = 4905;
public static final int JINGLE_BELL = 4906;
public static final int LOATHING_LEGION_KNIFE = 4908;
public static final int LOATHING_LEGION_MANY_PURPOSE_HOOK = 4909;
public static final int LOATHING_LEGION_MOONDIAL = 4910;
public static final int LOATHING_LEGION_NECKTIE = 4911;
public static final int LOATHING_LEGION_ELECTRIC_KNIFE = 4912;
public static final int LOATHING_LEGION_CORKSCREW = 4913;
public static final int LOATHING_LEGION_CAN_OPENER = 4914;
public static final int LOATHING_LEGION_CHAINSAW = 4915;
public static final int LOATHING_LEGION_ROLLERBLADES = 4916;
public static final int LOATHING_LEGION_FLAMETHROWER = 4917;
public static final int LOATHING_LEGION_TATTOO_NEEDLE = 4918;
public static final int LOATHING_LEGION_DEFIBRILLATOR = 4919;
public static final int LOATHING_LEGION_DOUBLE_PRISM = 4920;
public static final int LOATHING_LEGION_TAPE_MEASURE = 4921;
public static final int LOATHING_LEGION_KITCHEN_SINK = 4922;
public static final int LOATHING_LEGION_ABACUS = 4923;
public static final int LOATHING_LEGION_HELICOPTER = 4924;
public static final int LOATHING_LEGION_PIZZA_STONE = 4925;
public static final int LOATHING_LEGION_UNIVERSAL_SCREWDRIVER = 4926;
public static final int LOATHING_LEGION_JACKHAMMER = 4927;
public static final int LOATHING_LEGION_HAMMER = 4928;
public static final int QUAKE_OF_ARROWS = 4938;
public static final int KNOB_CAKE = 4942;
public static final int MENAGERIE_KEY = 4947;
public static final int GOTO = 4948;
public static final int WEREMOOSE_SPIT = 4949;
public static final int ABOMINABLE_BLUBBER = 4950;
public static final int SUBJECT_37_FILE = 4961;
public static final int EVILOMETER = 4964;
public static final int CARD_GAME_BOOK = 4965;
public static final int CARD_SLEEVE = 5009;
public static final int EVIL_EYE = 5010;
public static final int SNACK_VOUCHER = 5012;
public static final int WASABI_FOOD = 5013;
public static final int TOBIKO_FOOD = 5014;
public static final int NATTO_FOOD = 5015;
public static final int WASABI_BOOZE = 5016;
public static final int TOBIKO_BOOZE = 5017;
public static final int NATTO_BOOZE = 5018;
public static final int WASABI_POTION = 5019;
public static final int TOBIKO_POTION = 5020;
public static final int NATTO_POTION = 5021;
public static final int PET_SWEATER = 5040;
public static final int ASTRAL_HOT_DOG = 5043;
public static final int ASTRAL_PILSNER = 5044;
public static final int CLAN_SHOWER = 5047;
public static final int LARS_THE_CYBERIAN = 5053;
public static final int CREEPY_VOODOO_DOLL = 5062;
public static final int SPAGHETTI_CON_CALAVERAS = 5065;
public static final int SMORE_GUN = 5066;
public static final int TINY_BLACK_HOLE = 5069;
public static final int SMORE = 5071;
public static final int RUSSIAN_ICE = 5073;
public static final int STRESS_BALL = 5109;
public static final int PEN_PAL_KIT = 5112;
public static final int RUSTY_HEDGE_TRIMMERS = 5115;
public static final int AWOL_COMMENDATION = 5116;
public static final int RECONSTITUTED_CROW = 5117;
public static final int BIRD_BRAIN = 5118;
public static final int BUSTED_WINGS = 5119;
public static final int MARAUDER_MOCKERY_MANUAL = 5120;
public static final int SKELETON_BOOK = 5124;
public static final int LUNAR_ISOTOPE = 5134;
public static final int EMU_JOYSTICK = 5135;
public static final int EMU_ROCKET = 5136;
public static final int EMU_HELMET = 5137;
public static final int EMU_HARNESS = 5138;
public static final int ASTRAL_ENERGY_DRINK = 5140;
public static final int EMU_UNIT = 5143;
public static final int HONEYPOT = 5145;
public static final int SPOOKY_LITTLE_GIRL = 5165;
public static final int SYNTHETIC_DOG_HAIR_PILL = 5167;
public static final int DISTENTION_PILL = 5168;
public static final int TRANSPORTER_TRANSPONDER = 5170;
public static final int RONALD_SHELTER_MAP = 5171;
public static final int GRIMACE_SHELTER_MAP = 5172;
public static final int MOON_BOOZE_1 = 5174;
public static final int MOON_BOOZE_2 = 5175;
public static final int MOON_BOOZE_3 = 5176;
public static final int MOON_FOOD_1 = 5177;
public static final int MOON_FOOD_2 = 5178;
public static final int MOON_FOOD_3 = 5179;
public static final int MOON_POTION_1 = 5180;
public static final int MOON_POTION_2 = 5181;
public static final int MOON_POTION_3 = 5182;
public static final int DOUBLE_ICE_GUM = 5189;
public static final int PATRIOT_SHIELD = 5190;
public static final int BIG_KNOB_SAUSAGE = 5193;
public static final int EXORCISED_SANDWICH = 5194;
public static final int GOOEY_PASTE = 5198;
public static final int BEASTLY_PASTE = 5199;
public static final int OILY_PASTE = 5200;
public static final int ECTOPLASMIC = 5201;
public static final int GREASY_PASTE = 5202;
public static final int BUG_PASTE = 5203;
public static final int HIPPY_PASTE = 5204;
public static final int ORC_PASTE = 5205;
public static final int DEMONIC_PASTE = 5206;
public static final int INDESCRIBABLY_HORRIBLE_PASTE = 5207;
public static final int FISHY_PASTE = 5208;
public static final int GOBLIN_PASTE = 5209;
public static final int PIRATE_PASTE = 5210;
public static final int CHLOROPHYLL_PASTE = 5211;
public static final int STRANGE_PASTE = 5212;
public static final int MER_KIN_PASTE = 5213;
public static final int SLIMY_PASTE = 5214;
public static final int PENGUIN_PASTE = 5215;
public static final int ELEMENTAL_PASTE = 5216;
public static final int COSMIC_PASTE = 5217;
public static final int HOBO_PASTE = 5218;
public static final int CRIMBO_PASTE = 5219;
public static final int TEACHINGS_OF_THE_FIST = 5220;
public static final int FAT_LOOT_TOKEN = 5221;
public static final int CLIP_ART_BOOK = 5223;
public static final int BUCKET_OF_WINE = 5227;
public static final int CRYSTAL_SKULL = 5231;
public static final int BORROWED_TIME = 5232;
public static final int BOX_OF_HAMMERS = 5233;
public static final int SHINING_HALO = 5234;
public static final int TIME_HALO = 5237;
public static final int LUMINEUX_LIMNIO = 5238;
public static final int MORTO_MORETO = 5239;
public static final int TEMPS_TEMPRANILLO = 5240;
public static final int BORDEAUX_MARTEAUX = 5241;
public static final int FROMAGE_PINOTAGE = 5242;
public static final int BEIGNET_MILGRANET = 5243;
public static final int MUSCHAT = 5244;
public static final int FIELD_GAR_POTION = 5257;
public static final int DICE_BOOK = 5284;
public static final int D4 = 5285;
public static final int D6 = 5286;
public static final int D8 = 5287;
public static final int D10 = 5288;
public static final int D12 = 5289;
public static final int D20 = 5290;
public static final int PLASTIC_VAMPIRE_FANGS = 5299;
public static final int STAFF_GUIDE = 5307;
public static final int CHAINSAW_CHAIN = 5309;
public static final int SILVER_SHOTGUN_SHELL = 5310;
public static final int FUNHOUSE_MIRROR = 5311;
public static final int GHOSTLY_BODY_PAINT = 5312;
public static final int NECROTIZING_BODY_SPRAY = 5313;
public static final int BITE_LIPSTICK = 5314;
public static final int WHISKER_PENCIL = 5315;
public static final int PRESS_ON_RIBS = 5316;
public static final int BB_WINE_COOLER = 5323;
public static final int NECBRONOMICON = 5341;
public static final int NECBRONOMICON_USED = 5343;
public static final int CRIMBO_CAROL_V1_USED = 5347;
public static final int CRIMBO_CAROL_V2_USED = 5348;
public static final int CRIMBO_CAROL_V3_USED = 5349;
public static final int CRIMBO_CAROL_V4_USED = 5350;
public static final int CRIMBO_CAROL_V5_USED = 5351;
public static final int CRIMBO_CAROL_V6_USED = 5352;
public static final int JAR_OF_OIL = 5353;
public static final int SLAPFIGHTING_BOOK_USED = 5354;
public static final int UNCLE_ROMULUS_USED = 5355;
public static final int SNAKE_CHARMING_BOOK_USED = 5356;
public static final int ZU_MANNKASE_DIENEN_USED = 5357;
public static final int DYNAMITE_SUPERMAN_JONES_USED = 5358;
public static final int INIGO_BOOK_USED = 5359;
public static final int KANSAS_TOYMAKER_USED = 5360;
public static final int WASSAILING_BOOK_USED = 5361;
public static final int CRIMBCO_MANUAL_1_USED = 5362;
public static final int CRIMBCO_MANUAL_2_USED = 5363;
public static final int CRIMBCO_MANUAL_3_USED = 5364;
public static final int CRIMBCO_MANUAL_4_USED = 5365;
public static final int CRIMBCO_MANUAL_5_USED = 5366;
public static final int SKELETON_BOOK_USED = 5367;
public static final int ELLSBURY_BOOK_USED = 5368;
public static final int GROOSE_GREASE = 5379;
public static final int LOLLIPOP_STICK = 5380;
public static final int PEPPERMINT_SPROUT = 5395;
public static final int PEPPERMINT_PARASOL = 5401;
public static final int GIANT_CANDY_CANE = 5402;
public static final int PEPPERMINT_PACKET = 5404;
public static final int FUDGECULE = 5435;
public static final int FUDGE_WAND = 5441;
public static final int DEVILISH_FOLIO = 5444;
public static final int FURIOUS_STONE = 5448;
public static final int VANITY_STONE = 5449;
public static final int LECHEROUS_STONE = 5450;
public static final int JEALOUSY_STONE = 5451;
public static final int AVARICE_STONE = 5452;
public static final int GLUTTONOUS_STONE = 5453;
public static final int FUDGIE_ROLL = 5457;
public static final int FUDGE_BUNNY = 5458;
public static final int FUDGE_SPORK = 5459;
public static final int FUDGECYCLE = 5460;
public static final int FUDGE_CUBE = 5461;
public static final int RESOLUTION_BOOK = 5463;
public static final int RESOLUTION_KINDER = 5470;
public static final int RESOLUTION_ADVENTUROUS = 5471;
public static final int RESOLUTION_LUCKIER = 5472;
public static final int RED_DRUNKI_BEAR = 5482;
public static final int GREEN_DRUNKI_BEAR = 5483;
public static final int YELLOW_DRUNKI_BEAR = 5484;
public static final int ALL_YEAR_SUCKER = 5497;
public static final int DARK_CHOCOLATE_HEART = 5498;
public static final int JACKASS_PLUMBER_GAME = 5501;
public static final int TRIVIAL_AVOCATIONS_GAME = 5502;
public static final int PACK_OF_POGS = 5505;
public static final int WHAT_CARD = 5511;
public static final int WHEN_CARD = 5512;
public static final int WHO_CARD = 5513;
public static final int WHERE_CARD = 5514;
public static final int PLANT_BOOK = 5546;
public static final int CLANCY_SACKBUT = 5547;
public static final int GHOST_BOOK = 5548;
public static final int CLANCY_CRUMHORN = 5549;
public static final int TATTLE_BOOK = 5550;
public static final int CLANCY_LUTE = 5551;
public static final int TRUSTY = 5552;
public static final int RAIN_DOH_BOX = 5563;
public static final int RAIN_DOH_MONSTER = 5564;
public static final int GROARS_FUR = 5571;
public static final int GLOWING_FUNGUS = 5641;
public static final int STONE_WOOL = 5643;
public static final int NOSTRIL_OF_THE_SERPENT = 5645;
public static final int BORIS_HELM = 5648;
public static final int BORIS_HELM_ASKEW = 5650;
public static final int MIME_SOUL_FRAGMENT = 5651;
public static final int KEYOTRON = 5653;
public static final int FETTUCINI_EPINES_INCONNU_RECIPE = 5657;
public static final int SLAP_AND_SLAP_AGAIN_RECIPE = 5658;
public static final int CLAN_SWIMMING_POOL = 5662;
public static final int CURSED_MICROWAVE = 5663;
public static final int CURSED_KEG = 5664;
public static final int JERK_BOOK = 5665;
public static final int GRUDGE_BOOK = 5666;
public static final int LOST_KEY = 5680;
public static final int NOTE_FROM_CLANCY = 5682;
public static final int BURT = 5683;
public static final int AUTOPSY_TWEEZERS = 5687;
public static final int ONE_MEAT = 5697;
public static final int LOST_GLASSES = 5698;
public static final int LITTLE_MANNEQUIN = 5702;
public static final int CRAYON_SHAVINGS = 5703;
public static final int WAX_BUGBEAR = 5704;
public static final int FDKOL_COMMENDATION = 5707;
public static final int HJODOR_GUIDE = 5715;
public static final int HJODOR_GUIDE_USED = 5716;
public static final int LORD_FLAMEFACES_CLOAK = 5735;
public static final int CSA_FIRE_STARTING_KIT = 5739;
public static final int CRAPPY_BRAIN = 5752;
public static final int DECENT_BRAIN = 5753;
public static final int GOOD_BRAIN = 5754;
public static final int BOSS_BRAIN = 5755;
public static final int HUNTER_BRAIN = 5756;
public static final int FUZZY_BUSBY = 5764;
public static final int FUZZY_EARMUFFS = 5765;
public static final int FUZZY_MONTERA = 5766;
public static final int GNOMISH_EAR = 5768;
public static final int GNOMISH_LUNG = 5769;
public static final int GNOMISH_ELBOW = 5770;
public static final int GNOMISH_KNEE = 5771;
public static final int GNOMISH_FOOT = 5772;
public static final int SOFT_GREEN_ECHO_ANTIDOTE_MARTINI = 5781;
public static final int MORNINGWOOD_PLANK = 5782;
public static final int HARDWOOD_PLANK = 5783;
public static final int WEIRDWOOD_PLANK = 5784;
public static final int THICK_CAULK = 5785;
public static final int LONG_SCREW = 5786;
public static final int BUTT_JOINT = 5787;
public static final int BUBBLIN_CRUDE = 5789;
public static final int BOX_OF_BEAR_ARM = 5790;
public static final int RIGHT_BEAR_ARM = 5791;
public static final int LEFT_BEAR_ARM = 5792;
public static final int RAD_LIB_BOOK = 5862;
public static final int PAPIER_MACHETE = 5868;
public static final int PAPIER_MACHINE_GUN = 5869;
public static final int PAPIER_MASK = 5870;
public static final int PAPIER_MITRE = 5871;
public static final int PAPIER_MACHURIDARS = 5872;
public static final int DRAGON_TEETH = 5880;
public static final int SKELETON = 5881;
public static final int SKIFF = 5885;
public static final int LAZYBONES_RECLINER = 5888;
public static final int UNCONSCIOUS_COLLECTIVE_DREAM_JAR = 5897;
public static final int SUSPICIOUS_JAR = 5898;
public static final int GOURD_JAR = 5899;
public static final int MYSTIC_JAR = 5900;
public static final int OLD_MAN_JAR = 5901;
public static final int ARTIST_JAR = 5902;
public static final int MEATSMITH_JAR = 5903;
public static final int JICK_JAR = 5905;
public static final int CHIBIBUDDY_ON = 5908;
public static final int NANORHINO_CREDIT_CARD = 5911;
public static final int BEET_MEDIOCREBAR = 5915;
public static final int CORN_MEDIOCREBAR = 5916;
public static final int CABBAGE_MEDIOCREBAR = 5917;
public static final int CHIBIBUDDY_OFF = 5925;
public static final int BITTYCAR_MEATCAR = 5926;
public static final int BITTYCAR_HOTCAR = 5927;
public static final int ELECTRONIC_DULCIMER_PANTS = 5963;
public static final int BOO_CLUE = 5964;
public static final int INFURIATING_SILENCE_RECORD = 5971;
public static final int INFURIATING_SILENCE_RECORD_USED = 5972;
public static final int TRANQUIL_SILENCE_RECORD = 5973;
public static final int TRANQUIL_SILENCE_RECORD_USED = 5974;
public static final int MENACING_SILENCE_RECORD = 5975;
public static final int MENACING_SILENCE_RECORD_USED = 5976;
public static final int SLICE_OF_PIZZA = 5978;
public static final int BOTTLE_OF_WINE = 5990;
public static final int BOSS_HELM = 6002;
public static final int BOSS_CLOAK = 6003;
public static final int BOSS_SWORD = 6004;
public static final int BOSS_SHIELD = 6005;
public static final int BOSS_PANTS = 6006;
public static final int BOSS_GAUNTLETS = 6007;
public static final int BOSS_BOOTS = 6008;
public static final int BOSS_BELT = 6009;
public static final int TRIPPLES = 6027;
public static final int DRESS_PANTS = 6030;
public static final int INCREDIBLE_PIZZA = 6038;
public static final int OIL_PAN = 6042;
public static final int BITTYCAR_SOULCAR = 6046;
public static final int MISTY_CLOAK = 6047;
public static final int MISTY_ROBE = 6048;
public static final int MISTY_CAPE = 6049;
public static final int TACO_FLIER = 6051;
public static final int PSYCHOANALYTIC_JAR = 6055;
public static final int CRIMBO_CREEPY_HEAD = 6058;
public static final int CRIMBO_STOGIE_ODORIZER = 6059;
public static final int CRIMBO_HOT_MUG = 6060;
public static final int CRIMBO_TREE_FLOCKER = 6061;
public static final int CRIMBO_RUDOLPH_DOLL = 6062;
public static final int GEEKY_BOOK = 6071;
public static final int LED_CLOCK = 6072;
public static final int HAGGIS_SOCKS = 6080;
public static final int CLASSY_MONKEY = 6097;
public static final int PILE_OF_USELESS_ROBOT_PARTS = 6100;
public static final int CEO_OFFICE_CARD = 6116;
public static final int STRANGE_GOGGLES = 6118;
public static final int BONSAI_TREE = 6120;
public static final int LUCKY_CAT_STATUE = 6122;
public static final int GOLD_PIECE = 6130;
public static final int JICK_SWORD = 6146;
public static final int SNOW_SUIT = 6150;
public static final int CARROT_NOSE = 6151;
public static final int CARROT_CLARET = 6153;
public static final int PIXEL_POWER_CELL = 6155;
public static final int ANGER_BLASTER = 6158;
public static final int DOUBT_CANNON = 6159;
public static final int FEAR_CONDENSER = 6160;
public static final int REGRET_HOSE = 6161;
public static final int GAMEPRO_MAGAZINE = 6174;
public static final int GAMEPRO_WALKTHRU = 6175;
public static final int COSMIC_EGG = 6176;
public static final int COSMIC_VEGETABLE = 6178;
public static final int COSMIC_POTATO = 6181;
public static final int COSMIC_CREAM = 6182;
public static final int CONSUMMATE_BAGEL = 6188;
public static final int MEDIOCRE_LAGER = 6215;
public static final int VODKA_DOG = 6231;
public static final int COSMIC_SIX_PACK = 6237;
public static final int WALBERG_BOOK = 6253;
public static final int OCELOT_BOOK = 6254;
public static final int DRESCHER_BOOK = 6255;
public static final int STAFF_OF_BREAKFAST = 6258;
public static final int STAFF_OF_LIFE = 6259;
public static final int STAFF_OF_CHEESE = 6261;
public static final int STAFF_OF_STEAK = 6263;
public static final int STAFF_OF_CREAM = 6265;
public static final int YE_OLDE_MEAD = 6276;
public static final int MARK_V_STEAM_HAT = 6289;
public static final int ROCKETSHIP = 6290;
public static final int DRUM_N_BASS_RECORD = 6295;
public static final int JARLSBERG_SOUL_FRAGMENT = 6297;
public static final int MODEL_AIRSHIP = 6299;
public static final int RING_OF_DETECT_BORING_DOORS = 6303;
public static final int JARLS_COSMIC_PAN = 6304;
public static final int JARLS_PAN = 6305;
public static final int UNCLE_BUCK = 6311;
public static final int FISH_MEAT_CRATE = 6312;
public static final int DAMP_WALLET = 6313;
public static final int FISHY_PIPE = 6314;
public static final int OLD_SCUBA_TANK = 6315;
public static final int SUSHI_DOILY = 6328;
public static final int COZY_SCIMITAR = 6332;
public static final int COZY_STAFF = 6333;
public static final int COZY_BAZOOKA = 6334;
public static final int SALTWATERBED = 6338;
public static final int DREADSCROLL = 6353;
public static final int MERKIN_WORKTEA = 6356;
public static final int MERKIN_KNUCKLEBONE = 6357;
public static final int TAFFY_BOOK = 6360;
public static final int YELLOW_TAFFY = 6361;
public static final int INDIGO_TAFFY = 6362;
public static final int GREEN_TAFFY = 6363;
public static final int MERKIN_HALLPASS = 6368;
public static final int LUMP_OF_CLAY = 6369;
public static final int TWISTED_PIECE_OF_WIRE = 6370;
public static final int FRUITY_WINE = 6372;
public static final int ANGRY_INCH = 6374;
public static final int ERASER_NUBBIN = 6378;
public static final int CHLORINE_CRYSTAL = 6379;
public static final int PH_BALANCER = 6380;
public static final int MYSTERIOUS_CHEMICAL_RESIDUE = 6381;
public static final int NUGGET_OF_SODIUM = 6382;
public static final int JIGSAW_BLADE = 6384;
public static final int WOOD_SCREW = 6385;
public static final int BALSA_PLANK = 6386;
public static final int BLOB_OF_WOOD_GLUE = 6387;
public static final int ENVYFISH_EGG = 6388;
public static final int ANEMONE_SAUCE = 6394;
public static final int INKY_SQUID_SAUCE = 6395;
public static final int MERKIN_WEAKSAUCE = 6396;
public static final int PEANUT_SAUCE = 6397;
public static final int BLACK_GLASS = 6398;
public static final int POCKET_SQUARE = 6407;
public static final int CORRUPTED_STARDUST = 6408;
public static final int SHAKING_SKULL = 6412;
public static final int GREEN_THUMB = 6413;
public static final int TWIST_OF_LIME = 6417;
public static final int TONIC_DJINN = 6421;
public static final int TALES_OF_DREAD = 6423;
public static final int DREADSYLVANIAN_SKELETON_KEY = 6424;
public static final int BRASS_DREAD_FLASK = 6428;
public static final int SILVER_DREAD_FLASK = 6429;
public static final int KRUEGERAND = 6433;
public static final int MARK_OF_THE_BUGBEAR = 6434;
public static final int MARK_OF_THE_WEREWOLF = 6435;
public static final int MARK_OF_THE_ZOMBIE = 6436;
public static final int MARK_OF_THE_GHOST = 6437;
public static final int MARK_OF_THE_VAMPIRE = 6438;
public static final int MARK_OF_THE_SKELETON = 6439;
public static final int HELPS_YOU_SLEEP = 6443;
public static final int GETS_YOU_DRUNK = 6446;
public static final int GREAT_WOLFS_LEFT_PAW = 6448;
public static final int GREAT_WOLFS_RIGHT_PAW = 6449;
public static final int GREAT_WOLFS_ROCKET_LAUNCHER = 6450;
public static final int HUNGER_SAUCE = 6453;
public static final int ZOMBIE_ACCORDION = 6455;
public static final int MAYOR_GHOSTS_GAVEL = 6465;
public static final int GHOST_PEPPER = 6468;
public static final int DRUNKULA_WINEGLASS = 6474;
public static final int BLOODWEISER = 6475;
public static final int ELECTRIC_KOOL_AID = 6483;
public static final int DREAD_TARRAGON = 6484;
public static final int BONE_FLOUR = 6485;
public static final int DREADFUL_ROAST = 6486;
public static final int STINKING_AGARICUS = 6487;
public static final int SHEPHERDS_PIE = 6488;
public static final int INTRICATE_MUSIC_BOX_PARTS = 6489;
public static final int WAX_BANANA = 6492;
public static final int WAX_LOCK_IMPRESSION = 6493;
public static final int REPLICA_KEY = 6494;
public static final int AUDITORS_BADGE = 6495;
public static final int BLOOD_KIWI = 6496;
public static final int EAU_DE_MORT = 6497;
public static final int BLOODY_KIWITINI = 6498;
public static final int MOON_AMBER = 6499;
public static final int MOON_AMBER_NECKLACE = 6501;
public static final int DREAD_POD = 6502;
public static final int GHOST_PENCIL = 6503;
public static final int DREADSYLVANIAN_CLOCKWORK_KEY = 6506;
public static final int COOL_IRON_INGOT = 6507;
public static final int GHOST_SHAWL = 6511;
public static final int SKULL_CAPACITOR = 6512;
public static final int WARM_FUR = 6513;
public static final int GHOST_THREAD = 6525;
public static final int HOTHAMMER = 6528;
public static final int MUDDY_SKIRT = 6531;
public static final int FRYING_BRAINPAN = 6538;
public static final int OLD_BALL_AND_CHAIN = 6539;
public static final int OLD_DRY_BONE = 6540;
public static final int WEEDY_SKIRT = 6545;
public static final int HOT_CLUSTER = 6551;
public static final int COLD_CLUSTER = 6552;
public static final int SPOOKY_CLUSTER = 6553;
public static final int STENCH_CLUSTER = 6554;
public static final int SLEAZE_CLUSTER = 6555;
public static final int PHIAL_OF_HOTNESS = 6556;
public static final int PHIAL_OF_COLDNESS = 6557;
public static final int PHIAL_OF_SPOOKINESS = 6558;
public static final int PHIAL_OF_STENCH = 6559;
public static final int PHIAL_OF_SLEAZINESS = 6560;
public static final int DREADSYLVANIAN_ALMANAC = 6579;
public static final int CLAN_HOT_DOG_STAND = 6582;
public static final int VICIOUS_SPIKED_COLLAR = 6583;
public static final int ANCIENT_HOT_DOG_WRAPPER = 6584;
public static final int DEBONAIR_DEBONER = 6585;
public static final int CHICLE_DE_SALCHICHA = 6586;
public static final int JAR_OF_FROSTIGKRAUT = 6587;
public static final int GNAWED_UP_DOG_BONE = 6588;
public static final int GREY_GUANON = 6589;
public static final int ENGORGED_SAUSAGES_AND_YOU = 6590;
public static final int DREAM_OF_A_DOG = 6591;
public static final int OPTIMAL_SPREADSHEET = 6592;
public static final int DEFECTIVE_TOKEN = 6593;
public static final int HOT_DREADSYLVANIAN_COCOA = 6594;
public static final int CUCKOO_CLOCK = 6614;
public static final int SPAGHETTI_BREAKFAST = 6616;
public static final int FOLDER_HOLDER = 6617;
public static final int FOLDER_01 = 6618;
public static final int FOLDER_02 = 6619;
public static final int FOLDER_03 = 6620;
public static final int FOLDER_04 = 6621;
public static final int FOLDER_05 = 6622;
public static final int FOLDER_06 = 6623;
public static final int FOLDER_07 = 6624;
public static final int FOLDER_08 = 6625;
public static final int FOLDER_09 = 6626;
public static final int FOLDER_10 = 6627;
public static final int FOLDER_11 = 6628;
public static final int FOLDER_12 = 6629;
public static final int FOLDER_13 = 6630;
public static final int FOLDER_14 = 6631;
public static final int FOLDER_15 = 6632;
public static final int FOLDER_16 = 6633;
public static final int FOLDER_17 = 6634;
public static final int FOLDER_18 = 6635;
public static final int FOLDER_19 = 6636;
public static final int FOLDER_20 = 6637;
public static final int FOLDER_21 = 6638;
public static final int FOLDER_22 = 6639;
public static final int FOLDER_23 = 6640;
public static final int FOLDER_24 = 6641;
public static final int FOLDER_25 = 6642;
public static final int FOLDER_26 = 6643;
public static final int FOLDER_27 = 6644;
public static final int FOLDER_28 = 6645;
public static final int MOUNTAIN_STREAM_CODE_BLACK_ALERT = 6650;
public static final int SURGICAL_TAPE = 6653;
public static final int ILLEGAL_FIRECRACKER = 6656;
public static final int SCRAP_METAL = 6659;
public static final int SPIRIT_SOCKET_SET = 6660;
public static final int MINIATURE_SUSPENSION_BRIDGE = 6661;
public static final int STAFF_OF_THE_LUNCH_LADY = 6662;
public static final int UNIVERSAL_KEY = 6663;
public static final int WORLDS_MOST_DANGEROUS_BIRDHOUSE = 6664;
public static final int DEATHCHUCKS = 6665;
public static final int GIANT_ERASER = 6666;
public static final int QUASIRELGIOUS_SCULPTURE = 6667;
public static final int GIANT_FARADAY_CAGE = 6668;
public static final int MODELING_CLAYMORE = 6669;
public static final int STICKY_CLAY_HOMUNCULUS = 6670;
public static final int SODIUM_PENTASOMETHING = 6671;
public static final int GRAINS_OF_SALT = 6672;
public static final int YELLOWCAKE_BOMB = 6673;
public static final int DIRTY_STINKBOMB = 6674;
public static final int SUPERWATER = 6675;
public static final int CRUDE_SCULPTURE = 6677;
public static final int YEARBOOK_CAMERA = 6678;
public static final int ANTIQUE_MACHETE = 6679;
public static final int BOWL_OF_SCORPIONS = 6681;
public static final int BOOK_OF_MATCHES = 6683;
public static final int MCCLUSKY_FILE_PAGE1 = 6689;
public static final int MCCLUSKY_FILE_PAGE2 = 6690;
public static final int MCCLUSKY_FILE_PAGE3 = 6691;
public static final int MCCLUSKY_FILE_PAGE4 = 6692;
public static final int MCCLUSKY_FILE_PAGE5 = 6693;
public static final int BINDER_CLIP = 6694;
public static final int MCCLUSKY_FILE = 6695;
public static final int BOWLING_BALL = 6696;
public static final int MOSS_COVERED_STONE_SPHERE = 6697;
public static final int DRIPPING_STONE_SPHERE = 6698;
public static final int CRACKLING_STONE_SPHERE = 6699;
public static final int SCORCHED_STONE_SPHERE = 6700;
public static final int STONE_TRIANGLE = 6701;
public static final int BONE_ABACUS = 6712;
public static final int SHIP_TRIP_SCRIP = 6725;
public static final int UV_RESISTANT_COMPASS = 6729;
public static final int FUNKY_JUNK_KEY = 6730;
public static final int WORSE_HOMES_GARDENS = 6731;
public static final int JUNK_JUNK = 6735;
public static final int ETERNAL_CAR_BATTERY = 6741;
public static final int BEER_SEEDS = 6751;
public static final int BARLEY = 6752;
public static final int HOPS = 6753;
public static final int FANCY_BEER_BOTTLE = 6754;
public static final int FANCY_BEER_LABEL = 6755;
public static final int TIN_ROOF = 6773;
public static final int TIN_LIZZIE = 6775;
public static final int ABYSSAL_BATTLE_PLANS = 6782;
public static final int TOY_ACCORDION = 6808;
public static final int ANTIQUE_ACCORDION = 6809;
public static final int BEER_BATTERED_ACCORDION = 6810;
public static final int BARITONE_ACCORDION = 6811;
public static final int MAMAS_SQUEEZEBOX = 6812;
public static final int GUANCERTINA = 6813;
public static final int ACCORDION_FILE = 6814;
public static final int ACCORD_ION = 6815;
public static final int BONE_BANDONEON = 6816;
public static final int PENTATONIC_ACCORDION = 6817;
public static final int NON_EUCLIDEAN_NON_ACCORDION = 6818;
public static final int ACCORDION_OF_JORDION = 6819;
public static final int AUTOCALLIOPE = 6820;
public static final int ACCORDIONOID_ROCCA = 6821;
public static final int PYGMY_CONCERTINETTE = 6822;
public static final int GHOST_ACCORDION = 6823;
public static final int PEACE_ACCORDION = 6824;
public static final int ALARM_ACCORDION = 6825;
public static final int SWIZZLER = 6837;
public static final int WALKIE_TALKIE = 6846;
public static final int KILLING_JAR = 6847;
public static final int HUGE_BOWL_OF_CANDY = 6851;
public static final int ULTRA_MEGA_SOUR_BALL = 6852;
public static final int DESERT_PAMPHLET = 6854;
public static final int SUSPICIOUS_ADDRESS = 6855;
public static final int BAL_MUSETTE_ACCORDION = 6856;
public static final int CAJUN_ACCORDION = 6857;
public static final int QUIRKY_ACCORDION = 6858;
public static final int SKIPPERS_ACCORDION = 6859;
public static final int PANTSGIVING = 6860;
public static final int BLUE_LINT = 6877;
public static final int GREEN_LINT = 6878;
public static final int WHITE_LINT = 6879;
public static final int ORANGE_LINT = 6880;
public static final int SPIRIT_PILLOW = 6886;
public static final int SPIRIT_SHEET = 6887;
public static final int SPIRIT_MATTRESS = 6888;
public static final int SPIRIT_BLANKET = 6889;
public static final int SPIRIT_BED = 6890;
public static final int CHEF_BOY_BUSINESS_CARD = 6898;
public static final int PASTA_ADDITIVE = 6900;
public static final int WARBEAR_WHOSIT = 6913;
public static final int WARBEAR_BATTERY = 6916;
public static final int WARBEAR_BADGE = 6917;
public static final int WARBEAR_FEASTING_MEAD = 6924;
public static final int WARBEAR_BEARSERKER_MEAD = 6925;
public static final int WARBEAR_BLIZZARD_MEAD = 6926;
public static final int WARBEAR_OIL_PAN = 6961;
public static final int JACKHAMMER_DRILL_PRESS = 6964;
public static final int AUTO_ANVIL = 6965;
public static final int INDUCTION_OVEN = 6966;
public static final int CHEMISTRY_LAB = 6967;
public static final int WARBEAR_EMPATHY_CHIP = 6969;
public static final int SMITH_BOOK = 7003;
public static final int LUMP_OF_BRITUMINOUS_COAL = 7005;
public static final int HANDFUL_OF_SMITHEREENS = 7006;
public static final int GOLDEN_LIGHT = 7013;
public static final int LOUDER_THAN_BOMB = 7014;
public static final int WORK_IS_A_FOUR_LETTER_SWORD = 7016;
public static final int OUIJA_BOARD = 7025;
public static final int SAUCEPANIC = 7027;
public static final int SHAKESPEARES_SISTERS_ACCORDION = 7029;
public static final int LOOSE_PURSE_STRINGS = 7031;
public static final int WARBEAR_BLACK_BOX = 7035;
public static final int HIGH_EFFICIENCY_STILL = 7036;
public static final int LP_ROM_BURNER = 7037;
public static final int WARBEAR_GYROCOPTER = 7038;
public static final int WARBEAR_METALWORKING_PRIMER = 7042;
public static final int WARBEAR_GYROCOPTER_BROKEN = 7049;
public static final int WARBEAR_METALWORKING_PRIMER_USED = 7052;
public static final int WARBEAR_EMPATHY_CHIP_USED = 7053;
public static final int WARBEAR_BREAKFAST_MACHINE = 7056;
public static final int WARBEAR_SODA_MACHINE = 7059;
public static final int WARBEAR_BANK = 7060;
public static final int GRIMSTONE_MASK = 7061;
public static final int GRIM_FAIRY_TALE = 7065;
public static final int WINTER_SEEDS = 7070;
public static final int SNOW_BERRIES = 7071;
public static final int ICE_HARVEST = 7072;
public static final int FROST_FLOWER = 7073;
public static final int SNOW_BOARDS = 7076;
public static final int UNFINISHED_ICE_SCULPTURE = 7079;
public static final int ICE_SCULPTURE = 7080;
public static final int ICE_HOUSE = 7081;
public static final int SNOW_MACHINE = 7082;
public static final int SNOW_FORT = 7089;
public static final int JERKS_HEALTH_MAGAZINE = 7100;
public static final int MULLED_BERRY_WINE = 7119;
public static final int MAGNUM_OF_FANCY_CHAMPAGNE = 7130;
public static final int LUPINE_APPETITE_HORMONES = 7133;
public static final int WOLF_WHISTLE = 7134;
public static final int MID_LEVEL_MEDIEVAL_MEAD = 7138;
public static final int SPINNING_WHEEL = 7140;
public static final int ODD_SILVER_COIN = 7144;
public static final int EXPENSIVE_CHAMPAGNE = 7146;
public static final int FANCY_OIL_PAINTING = 7148;
public static final int SOLID_GOLD_ROSARY = 7149;
public static final int DOWSING_ROD = 7150;
public static final int STRAW = 7151;
public static final int LEATHER = 7152;
public static final int CLAY = 7153;
public static final int FILLING = 7154;
public static final int PARCHMENT = 7155;
public static final int GLASS = 7156;
public static final int CRAPPY_CAMERA = 7173;
public static final int SHAKING_CRAPPY_CAMERA = 7176;
public static final int COPPERHEAD_CHARM = 7178;
public static final int FIRST_PIZZA = 7179;
public static final int LACROSSE_STICK = 7180;
public static final int EYE_OF_THE_STARS = 7181;
public static final int STANKARA_STONE = 7182;
public static final int MURPHYS_FLAG = 7183;
public static final int SHIELD_OF_BROOK = 7184;
public static final int ZEPPELIN_TICKET = 7185;
public static final int COPPERHEAD_CHARM_RAMPANT = 7186;
public static final int UNNAMED_COCKTAIL = 7187;
public static final int TOMMY_GUN = 7190;
public static final int TOMMY_AMMO = 7191;
public static final int BUDDY_BJORN = 7200;
public static final int LYNYRD_SNARE = 7204;
public static final int FLEETWOOD_MAC_N_CHEESE = 7215;
public static final int PRICELESS_DIAMOND = 7221;
public static final int FLAMIN_WHATSHISNAME = 7222;
public static final int RED_RED_WINE = 7229;
public static final int RED_BUTTON = 7243;
public static final int GLARK_CABLE = 7246;
public static final int PETE_JACKET = 7250;
public static final int SNEAKY_PETE_SHOT = 7252;
public static final int MINI_MARTINI = 7255;
public static final int SMOKE_GRENADE = 7256;
public static final int PALINDROME_BOOK_1 = 7262;
public static final int PHOTOGRAPH_OF_DOG = 7263;
public static final int PHOTOGRAPH_OF_RED_NUGGET = 7264;
public static final int PHOTOGRAPH_OF_OSTRICH_EGG = 7265;
public static final int DISPOSABLE_CAMERA = 7266;
public static final int PETE_JACKET_COLLAR = 7267;
public static final int LETTER_FOR_MELVIGN = 7268;
public static final int PROFESSOR_WHAT_GARMENT = 7269;
public static final int PALINDROME_BOOK_2 = 7270;
public static final int THINKNERD_PACKAGE = 7278;
public static final int ELEVENT = 7295;
public static final int PROFESSOR_WHAT_TSHIRT = 7297;
public static final int BENDY_STRAW = 7398;
public static final int PLANT_FOOD = 7399;
public static final int SEWING_KIT = 7300;
public static final int BILLIARDS_KEY = 7301;
public static final int LIBRARY_KEY = 7302;
public static final int SPOOKYRAVEN_NECKLACE = 7303;
public static final int SPOOKYRAVEN_TELEGRAM = 7304;
public static final int POWDER_PUFF = 7305;
public static final int FINEST_GOWN = 7306;
public static final int DANCING_SHOES = 7307;
public static final int DUSTY_POPPET = 7314;
public static final int RICKETY_ROCKING_HORSE = 7315;
public static final int ANTIQUE_JACK_IN_THE_BOX = 7316;
public static final int BABY_GHOSTS = 7317;
public static final int GHOST_NECKLACE = 7318;
public static final int ELIZABETH_DOLLIE = 7319;
public static final int STEPHEN_LAB_COAT = 7321;
public static final int HAUNTED_BATTERY = 7324;
public static final int SYNTHETIC_MARROW = 7327;
public static final int FUNK = 7330;
public static final int CREEPY_VOICE_BOX = 7334;
public static final int TINY_DANCER = 7338;
public static final int SPOOKY_MUSIC_BOX_MECHANISM = 7339;
public static final int PICTURE_OF_YOU = 7350;
public static final int COAL_SHOVEL = 7355;
public static final int HOT_COAL = 7356;
public static final int LAUNDRY_SHERRY = 7366;
public static final int PSYCHOTIC_TRAIN_WINE = 7370;
public static final int DNA_LAB = 7382;
public static final int DNA_SYRINGE = 7383;
public static final int STEAM_FIST_1 = 7406;
public static final int STEAM_FIST_2 = 7407;
public static final int STEAM_FIST_3 = 7408;
public static final int STEAM_TRIP_1 = 7409;
public static final int STEAM_TRIP_2 = 7410;
public static final int STEAM_TRIP_3 = 7411;
public static final int STEAM_METEOID_1 = 7412;
public static final int STEAM_METEOID_2 = 7413;
public static final int STEAM_METEOID_3 = 7414;
public static final int STEAM_DEMON_1 = 7415;
public static final int STEAM_DEMON_2 = 7416;
public static final int STEAM_DEMON_3 = 7417;
public static final int STEAM_PLUMBER_1 = 7418;
public static final int STEAM_PLUMBER_2 = 7419;
public static final int STEAM_PLUMBER_3 = 7420;
public static final int PENCIL_THIN_MUSHROOM = 7421;
public static final int CHEESEBURGER_RECIPE = 7422;
public static final int SAILOR_SALT = 7423;
public static final int BROUPON = 7424;
public static final int TACO_DAN_SAUCE_BOTTLE = 7425;
public static final int SPRINKLE_SHAKER = 7426;
public static final int TACO_DAN_RECEIPT = 7428;
public static final int BEACH_BUCK = 7429;
public static final int BEEFY_CRUNCH_PASTACO = 7438;
public static final int OVERPOWERING_MUSHROOM_WINE = 7444;
public static final int COMPLEX_MUSHROOM_WINE = 7445;
public static final int SMOOTH_MUSHROOM_WINE = 7446;
public static final int BLOOD_RED_MUSHROOM_WINE = 7447;
public static final int BUZZING_MUSHROOM_WINE = 7448;
public static final int SWIRLING_MUSHROOM_WINE = 7449;
public static final int TACO_DAN_FISH_TACO = 7451;
public static final int TACO_DAN_TACO_SAUCE = 7452;
public static final int BROBERRY_BROGURT = 7455;
public static final int BROCOLATE_BROGURT = 7456;
public static final int FRENCH_BRONILLA_BROGURT = 7457;
public static final int OFFENSIVE_JOKE_BOOK = 7458;
public static final int COOKING_WITH_GREASE_BOOK = 7459;
public static final int DINER_HANDBOOK = 7460;
public static final int ANTI_FUNGAL_SPRAY = 7461;
public static final int SPRING_BEACH_TATTOO_COUPON = 7465;
public static final int SPRING_BEACH_CHARTER = 7466;
public static final int SPRING_BEACH_TICKET = 7467;
public static final int MOIST_BEADS = 7475;
public static final int MIND_DESTROYER = 7476;
public static final int SWEET_TOOTH = 7481;
public static final int LOOSENING_POWDER = 7485;
public static final int POWDERED_CASTOREUM = 7486;
public static final int DRAIN_DISSOLVER = 7487;
public static final int TRIPLE_DISTILLED_TURPENTINE = 7488;
public static final int DETARTRATED_ANHYDROUS_SUBLICALC = 7489;
public static final int TRIATOMACEOUS_DUST = 7490;
public static final int BOTTLE_OF_CHATEAU_DE_VINEGAR = 7491;
public static final int UNSTABLE_FULMINATE = 7493;
public static final int WINE_BOMB = 7494;
public static final int MORTAR_DISSOLVING_RECIPE = 7495;
public static final int GHOST_FORMULA = 7497;
public static final int BLACK_MAP = 7500;
public static final int BLACK_LABEL = 7508;
public static final int CRUMBLING_WHEEL = 7511;
public static final int ALIEN_SOURCE_CODE = 7533;
public static final int ALIEN_SOURCE_CODE_USED = 7534;
public static final int SPACE_BEAST_FUR = 7536;
public static final int SPACE_HEATER = 7543;
public static final int SPACE_PORT = 7545;
public static final int HOT_ASHES = 7548;
public static final int DRY_RUB = 7553;
public static final int WHITE_PAGE = 7555;
public static final int WHITE_WINE = 7558;
public static final int TIME_TWITCHING_TOOLBELT = 7566;
public static final int CHRONER = 7567;
public static final int SOLID_SHIFTING_TIME_WEIRDNESS = 7581;
public static final int CLAN_SPEAKEASY = 7588;
public static final int GLASS_OF_MILK = 7589;
public static final int CUP_OF_TEA = 7590;
public static final int THERMOS_OF_WHISKEY = 7591;
public static final int LUCKY_LINDY = 7592;
public static final int BEES_KNEES = 7593;
public static final int SOCKDOLLAGER = 7594;
public static final int ISH_KABIBBLE = 7595;
public static final int HOT_SOCKS = 7596;
public static final int PHONUS_BALONUS = 7597;
public static final int FLIVVER = 7598;
public static final int SLOPPY_JALOPY = 7599;
public static final int HEAVY_DUTY_UMBRELLA = 7643;
public static final int POOL_SKIMMER = 7644;
public static final int MINI_LIFE_PRESERVER = 7645;
public static final int LIGHTNING_MILK = 7646;
public static final int AQUA_BRAIN = 7647;
public static final int THUNDER_THIGH = 7648;
public static final int FRESHWATER_FISHBONE = 7651;
public static final int NEOPRENE_SKULLCAP = 7659;
public static final int GOBLIN_WATER = 7660;
public static final int LIQUID_ICE = 7665;
public static final int GROLL_DOLL = 7694;
public static final int CAP_GUN = 7695;
public static final int CONFISCATOR_BOOK = 7706;
public static final int THORS_PLIERS = 7709;
public static final int WATER_WINGS_FOR_BABIES = 7711;
public static final int BEAUTIFUL_RAINBOW = 7712;
public static final int CHRONER_CROSS = 7723;
public static final int MERCURY_BLESSING = 7728;
public static final int CHRONER_TRIGGER = 7729;
public static final int BLACK_BARTS_BOOTY = 7732;
public static final int XIBLAXIAN_CIRCUITRY = 7733;
public static final int XIBLAXIAN_POLYMER = 7734;
public static final int XIBLAXIAN_ALLOY = 7735;
public static final int XIBLAXIAN_CRYSTAL = 7736;
public static final int XIBLAXIAN_HOLOTRAINING_SIMCODE = 7739;
public static final int XIBLAXIAN_POLITICAL_PRISONER = 7742;
public static final int XIBLAXIAN_SCHEMATIC_COWL = 7743;
public static final int XIBLAXIAN_SCHEMATIC_TROUSERS = 7744;
public static final int XIBLAXIAN_SCHEMATIC_VEST = 7745;
public static final int XIBLAXIAN_SCHEMATIC_BURRITO = 7746;
public static final int XIBLAXIAN_SCHEMATIC_WHISKEY = 7747;
public static final int XIBLAXIAN_SCHEMATIC_RESIDENCE = 7748;
public static final int XIBLAXIAN_SCHEMATIC_GOGGLES = 7749;
public static final int FIVE_D_PRINTER = 7750;
public static final int RESIDENCE_CUBE = 7758;
public static final int XIBLAXIAN_HOLOWRIST_PUTER = 7765;
public static final int CONSPIRACY_ISLAND_CHARTER = 7767;
public static final int CONSPIRACY_ISLAND_TICKET = 7768;
public static final int COINSPIRACY = 7769;
public static final int VENTILATION_UNIT = 7770;
public static final int SASQ_WATCH = 7776;
public static final int CUDDLY_TEDDY_BEAR = 7787;
public static final int FIRST_AID_POUCH = 7789;
public static final int SHAWARMA_KEYCARD = 7792;
public static final int BOTTLE_OPENER_KEYCARD = 7793;
public static final int ARMORY_KEYCARD = 7794;
public static final int HYPERSANE_BOOK = 7803;
public static final int INTIMIDATING_MIEN_BOOK = 7804;
public static final int EXPERIMENTAL_SERUM_P00 = 7830;
public static final int FINGERNAIL_CLIPPERS = 7831;
public static final int MINI_CASSETTE_RECORDER = 7832;
public static final int GORE_BUCKET = 7833;
public static final int PACK_OF_SMOKES = 7834;
public static final int ESP_COLLAR = 7835;
public static final int GPS_WATCH = 7836;
public static final int PROJECT_TLB = 7837;
public static final int MINING_OIL = 7856;
public static final int CRIMBONIUM_FUEL_ROD = 7863;
public static final int CRIMBOT_TORSO_2 = 7865;
public static final int CRIMBOT_TORSO_3 = 7866;
public static final int CRIMBOT_TORSO_4 = 7867;
public static final int CRIMBOT_TORSO_5 = 7868;
public static final int CRIMBOT_TORSO_6 = 7869;
public static final int CRIMBOT_TORSO_7 = 7870;
public static final int CRIMBOT_TORSO_8 = 7871;
public static final int CRIMBOT_TORSO_9 = 7872;
public static final int CRIMBOT_TORSO_10 = 7873;
public static final int CRIMBOT_TORSO_11 = 7874;
public static final int CRIMBOT_LEFTARM_2 = 7875;
public static final int CRIMBOT_LEFTARM_3 = 7876;
public static final int CRIMBOT_LEFTARM_4 = 7877;
public static final int CRIMBOT_LEFTARM_5 = 7878;
public static final int CRIMBOT_LEFTARM_6 = 7879;
public static final int CRIMBOT_LEFTARM_7 = 7880;
public static final int CRIMBOT_LEFTARM_8 = 7881;
public static final int CRIMBOT_LEFTARM_9 = 7882;
public static final int CRIMBOT_LEFTARM_10 = 7883;
public static final int CRIMBOT_LEFTARM_11 = 7884;
public static final int CRIMBOT_RIGHTARM_2 = 7885;
public static final int CRIMBOT_RIGHTARM_3 = 7886;
public static final int CRIMBOT_RIGHTARM_4 = 7887;
public static final int CRIMBOT_RIGHTARM_5 = 7888;
public static final int CRIMBOT_RIGHTARM_6 = 7889;
public static final int CRIMBOT_RIGHTARM_7 = 7890;
public static final int CRIMBOT_RIGHTARM_8 = 7891;
public static final int CRIMBOT_RIGHTARM_9 = 7892;
public static final int CRIMBOT_RIGHTARM_10 = 7893;
public static final int CRIMBOT_RIGHTARM_11 = 7894;
public static final int CRIMBOT_PROPULSION_2 = 7895;
public static final int CRIMBOT_PROPULSION_3 = 7896;
public static final int CRIMBOT_PROPULSION_4 = 7897;
public static final int CRIMBOT_PROPULSION_5 = 7898;
public static final int CRIMBOT_PROPULSION_6 = 7899;
public static final int CRIMBOT_PROPULSION_7 = 7900;
public static final int CRIMBOT_PROPULSION_8 = 7901;
public static final int CRIMBOT_PROPULSION_9 = 7902;
public static final int CRIMBOT_PROPULSION_10 = 7903;
public static final int CRIMBOT_PROPULSION_11 = 7904;
public static final int FRIENDLY_TURKEY = 7922;
public static final int AGITATED_TURKEY = 7923;
public static final int AMBITIOUS_TURKEY = 7924;
public static final int SNEAKY_WRAPPING_PAPER = 7934;
public static final int PICKY_TWEEZERS = 7936;
public static final int CRIMBO_CREDIT = 7937;
public static final int SLEEVE_DEUCE = 7941;
public static final int POCKET_ACE = 7942;
public static final int MININ_DYNAMITE = 7950;
public static final int BIG_BAG_OF_MONEY = 7955;
public static final int ED_DIARY = 7960;
public static final int ED_STAFF = 7961;
public static final int ED_EYE = 7962;
public static final int ED_AMULET = 7963;
public static final int ED_FATS_STAFF = 7964;
public static final int ED_HOLY_MACGUFFIN = 7965;
public static final int KA_COIN = 7966;
public static final int TOPIARY_NUGGLET = 7968;
public static final int BEEHIVE = 7969;
public static final int ELECTRIC_BONING_KNIFE = 7970;
public static final int MUMMIFIED_FIG = 7972;
public static final int ANCIENT_CURE_ALL = 7982;
public static final int CHOCO_CRIMBOT = 7999;
public static final int TOY_CRIMBOT_FACE = 8002;
public static final int TOY_CRIMBOT_GLOVE = 8003;
public static final int TOY_CRIMBOT_FIST = 8004;
public static final int TOY_CRIMBOT_LEGS = 8005;
public static final int ROM_RAPID_PROTOTYPING = 8007;
public static final int ROM_MATHMATICAL_PRECISION = 8008;
public static final int ROM_RUTHLESS_EFFICIENCY = 8009;
public static final int ROM_RAPID_PROTOTYPING_DIRTY = 8013;
public static final int ROM_MATHMATICAL_PRECISION_DIRTY = 8014;
public static final int ROM_RUTHLESS_EFFICIENCY_DIRTY = 8015;
public static final int TAINTED_MINING_OIL = 8017;
public static final int RED_GREEN_RAIN_STICK = 8018;
public static final int CHATEAU_ROOM_KEY = 8019;
public static final int CHATEAU_MUSCLE = 8023;
public static final int CHATEAU_MYST = 8024;
public static final int CHATEAU_MOXIE = 8025;
public static final int CHATEAU_FAN = 8026;
public static final int CHATEAU_CHANDELIER = 8027;
public static final int CHATEAU_SKYLIGHT = 8028;
public static final int CHATEAU_BANK = 8029;
public static final int CHATEAU_JUICE_BAR = 8030;
public static final int CHATEAU_PENS = 8031;
public static final int CHATEAU_WATERCOLOR = 8033;
public static final int SPELUNKY_WHIP = 8040;
public static final int SPELUNKY_SKULL = 8041;
public static final int SPELUNKY_ROCK = 8042;
public static final int SPELUNKY_POT = 8043;
public static final int SPELUNKY_FEDORA = 8044;
public static final int SPELUNKY_MACHETE = 8045;
public static final int SPELUNKY_SHOTGUN = 8046;
public static final int SPELUNKY_BOOMERANG = 8047;
public static final int SPELUNKY_HELMET = 8049;
public static final int SPELUNKY_GOGGLES = 8050;
public static final int SPELUNKY_CAPE = 8051;
public static final int SPELUNKY_JETPACK = 8052;
public static final int SPELUNKY_SPRING_BOOTS = 8053;
public static final int SPELUNKY_SPIKED_BOOTS = 8054;
public static final int SPELUNKY_PICKAXE = 8055;
public static final int SPELUNKY_TORCH = 8056;
public static final int SPELUNKY_RIFLE = 8058;
public static final int SPELUNKY_STAFF = 8059;
public static final int SPELUNKY_JOKE_BOOK = 8060;
public static final int SPELUNKY_CROWN = 8061;
public static final int SPELUNKY_COFFEE_CUP = 8062;
public static final int TALES_OF_SPELUNKING = 8063;
public static final int POWDERED_GOLD = 8066;
public static final int WAREHOUSE_MAP_PAGE = 8070;
public static final int WAREHOUSE_INVENTORY_PAGE = 8071;
public static final int SPELUNKER_FORTUNE = 8073;
public static final int SPELUNKER_FORTUNE_USED = 8085;
public static final int STILL_BEATING_SPLEEN = 8086;
public static final int SCARAB_BEETLE_STATUETTE = 8087;
public static final int WICKERBITS = 8098;
public static final int BAKELITE_BITS = 8105;
public static final int AEROGEL_ACCORDION = 8111;
public static final int AEROSOLIZED_AEROGEL = 8112;
public static final int WROUGHT_IRON_FLAKES = 8119;
public static final int GABARDINE_GIRDLE = 8124;
public static final int GABARDEEN_SMITHEREENS = 8126;
public static final int FIBERGLASS_FIBERS = 8133;
public static final int LOVEBUG_PHEROMONES = 8134;
public static final int WINGED_YETI_FUR = 8135;
public static final int SESHAT_TALISMAN = 8144;
public static final int MEATSMITH_CHECK = 8156;
public static final int BONE_WITH_A_PRICE_TAG = 8158;
public static final int MAGICAL_BAGUETTE = 8167;
public static final int ENCHANTED_ICING = 8168;
public static final int CARTON_OF_SNAKE_MILK = 8172;
public static final int RING_OF_TELLING_SKELETONS_WHAT_TO_DO = 8179;
public static final int MAP_TO_KOKOMO = 8182;
public static final int CROWN_OF_ED = 8185;
public static final int BOOZE_MAP = 8187;
public static final int HYPNOTIC_BREADCRUMBS = 8199;
public static final int POPULAR_TART = 8200;
public static final int NO_HANDED_PIE = 8201;
public static final int DOC_VITALITY_SERUM = 8202;
public static final int DINSEY_CHARTER = 8203;
public static final int DINSEY_TICKET = 8204;
public static final int FUNFUNDS = 8205;
public static final int FILTHY_CHILD_LEASH = 8209;
public static final int GARBAGE_BAG = 8211;
public static final int SEWAGE_CLOGGED_PISTOL = 8215;
public static final int TOXIC_GLOBULE = 8218;
public static final int JAR_OF_SWAMP_HONEY = 8226;
public static final int BRAIN_PRESERVATION_FLUID = 8238;
public static final int DINSEY_REFRESHMENTS = 8243;
public static final int LUBE_SHOES = 8244;
public static final int TRASH_NET = 8245;
public static final int MASCOT_MASK = 8246;
public static final int DINSEY_GUIDE_BOOK = 8253;
public static final int TRASH_MEMOIR_BOOK = 8254;
public static final int DINSEY_MAINTENANCE_MANUAL = 8255;
public static final int DINSEY_AN_AFTERLIFE = 8258;
public static final int LOTS_ENGAGEMENT_RING = 8259;
public static final int MAYO_CLINIC = 8260;
public static final int MAYONEX = 8261;
public static final int MAYODIOL = 8262;
public static final int MAYOSTAT = 8263;
public static final int MAYOZAPINE = 8264;
public static final int MAYOFLEX = 8265;
public static final int MIRACLE_WHIP = 8266;
public static final int SPHYGMAYOMANOMETER = 8267;
public static final int REFLEX_HAMMER = 8268;
public static final int MAYO_LANCE = 8269;
public static final int ESSENCE_OF_BEAR = 8277;
public static final int RESORT_CHIP = 8279;
public static final int GOLDEN_RESORT_CHIP = 8280;
public static final int COCKTAIL_SHAKER = 8283;
public static final int MAYO_MINDER = 8285;
public static final int YELLOW_PIXEL = 8298;
public static final int POWER_PILL = 8300;
public static final int YELLOW_SUBMARINE = 8376;
public static final int DECK_OF_EVERY_CARD = 8382;
public static final int POPULAR_PART = 8383;
public static final int WHITE_MANA = 8387;
public static final int BLACK_MANA = 8388;
public static final int RED_MANA = 8389;
public static final int GREEN_MANA = 8390;
public static final int BLUE_MANA = 8391;
public static final int GIFT_CARD = 8392;
public static final int LINGUINI_IMMONDIZIA_BIANCO = 8419;
public static final int SHELLS_A_LA_SHELLFISH = 8420;
public static final int GOLD_1970 = 8424;
public static final int NEW_AGE_HEALING_CRYSTAL = 8425;
public static final int VOLCOINO = 8426;
public static final int FIZZING_SPORE_POD = 8427;
public static final int INSULATED_GOLD_WIRE = 8439;
public static final int EMPTY_LAVA_BOTTLE = 8440;
public static final int VISCOUS_LAVA_GLOBS = 8442;
public static final int HEAT_RESISTANT_SHEET_METAL = 8453;
public static final int GLOWING_NEW_AGE_CRYSTAL = 8455;
public static final int CRYSTALLINE_LIGHT_BULB = 8456;
public static final int GOOEY_LAVA_GLOBS = 8470;
public static final int LAVA_MINERS_DAUGHTER = 8482;
public static final int PSYCHO_FROM_THE_HEAT = 8483;
public static final int THE_FIREGATE_TAPES = 8484;
public static final int VOLCANO_TICKET = 8486;
public static final int VOLCANO_CHARTER = 8487;
public static final int MANUAL_OF_NUMBEROLOGY = 8488;
public static final int SMOOCH_BRACERS = 8517;
public static final int SUPERDUPERHEATED_METAL = 8522;
public static final int SUPERHEATED_METAL = 8524;
public static final int FETTRIS = 8542;
public static final int FUSILLOCYBIN = 8543;
public static final int PRESCRIPTION_NOODLES = 8544;
public static final int SHRINE_BARREL_GOD = 8564;
public static final int BARREL_LID = 8565;
public static final int BARREL_HOOP_EARRING = 8566;
public static final int BANKRUPTCY_BARREL = 8567;
public static final int LITTLE_FIRKIN = 8568;
public static final int NORMAL_BARREL = 8569;
public static final int BIG_TUN = 8570;
public static final int WEATHERED_BARREL = 8571;
public static final int DUSTY_BARREL = 8572;
public static final int DISINTEGRATING_BARREL = 8573;
public static final int MOIST_BARREL = 8574;
public static final int ROTTING_BARREL = 8575;
public static final int MOULDERING_BARREL = 8576;
public static final int BARNACLED_BARREL = 8577;
public static final int BARREL_MAP = 8599;
public static final int POTTED_TEA_TREE = 8600;
public static final int FLAMIBILI_TEA = 8601;
public static final int YET_TEA = 8602;
public static final int BOO_TEA = 8603;
public static final int NAS_TEA = 8604;
public static final int IMPROPRIE_TEA = 8605;
public static final int FROST_TEA = 8606;
public static final int TOAST_TEA = 8607;
public static final int NET_TEA = 8608;
public static final int PROPRIE_TEA = 8609;
public static final int MORBIDI_TEA = 8610;
public static final int CHARI_TEA = 8611;
public static final int SERENDIPI_TEA = 8612;
public static final int FEROCI_TEA = 8613;
public static final int PHYSICALI_TEA = 8614;
public static final int WIT_TEA = 8615;
public static final int NEUROPLASTICI_TEA = 8616;
public static final int DEXTERI_TEA = 8617;
public static final int FLEXIBILI_TEA = 8618;
public static final int IMPREGNABILI_TEA = 8619;
public static final int OBSCURI_TEA = 8620;
public static final int IRRITABILI_TEA = 8621;
public static final int MEDIOCRI_TEA = 8622;
public static final int LOYAL_TEA = 8623;
public static final int ACTIVI_TEA = 8624;
public static final int CRUEL_TEA = 8625;
public static final int ALACRI_TEA = 8626;
public static final int VITALI_TEA = 8627;
public static final int MANA_TEA = 8628;
public static final int MONSTROSI_TEA = 8629;
public static final int TWEN_TEA = 8630;
public static final int GILL_TEA = 8631;
public static final int UNCERTAIN_TEA = 8632;
public static final int VORACI_TEA = 8633;
public static final int SOBRIE_TEA = 8634;
public static final int ROYAL_TEA = 8635;
public static final int CRAFT_TEA = 8636;
public static final int INSANI_TEA = 8637;
public static final int HAUNTED_DOGHOUSE = 8639;
public static final int GHOST_DOG_CHOW = 8640;
public static final int TENNIS_BALL = 8650;
public static final int TWELVE_NIGHT_ENERGY = 8666;
public static final int ROSE = 8668;
public static final int WHITE_TULIP = 8669;
public static final int RED_TULIP = 8670;
public static final int BLUE_TULIP = 8671;
public static final int WALFORDS_BUCKET = 8672;
public static final int WALMART_GIFT_CERTIFICATE = 8673;
public static final int GLACIEST_CHARTER = 8674;
public static final int GLACIEST_TICKET = 8675;
public static final int TO_BUILD_AN_IGLOO = 8682;
public static final int CHILL_OF_THE_WILD = 8683;
public static final int COLD_FANG = 8684;
public static final int PERFECT_ICE_CUBE = 8686;
public static final int COLD_WEATHER_BARTENDER_GUIDE = 8687;
public static final int BAG_OF_FOREIGN_BRIBES = 8691;
public static final int ICE_HOTEL_BELL = 8694;
public static final int ANCIENT_MEDICINAL_HERBS = 8696;
public static final int ICE_RICE = 8697;
public static final int ICED_PLUM_WINE = 8698;
public static final int TRAINING_BELT = 8699;
public static final int TRAINING_LEGWARMERS = 8700;
public static final int TRAINING_HELMET = 8701;
public static final int SCROLL_SHATTERING_PUNCH = 8702;
public static final int SCROLL_SNOKEBOMB = 8703;
public static final int SCROLL_SHIVERING_MONKEY = 8704;
public static final int SNOWMAN_CRATE = 8705;
public static final int ABSTRACTION_ACTION = 8708;
public static final int ABSTRACTION_THOUGHT = 8709;
public static final int ABSTRACTION_SENSATION = 8710;
public static final int ABSTRACTION_PURPOSE = 8711;
public static final int ABSTRACTION_CATEGORY = 8712;
public static final int ABSTRACTION_PERCEPTION = 8713;
public static final int VYKEA_FRENZY_RUNE = 8722;
public static final int VYKEA_BLOOD_RUNE = 8723;
public static final int VYKEA_LIGHTNING_RUNE = 8724;
public static final int VYKEA_PLANK = 8725;
public static final int VYKEA_RAIL = 8726;
public static final int VYKEA_BRACKET = 8727;
public static final int VYKEA_DOWEL = 8728;
public static final int VYKEA_HEX_KEY = 8729;
public static final int VYKEA_INSTRUCTIONS = 8730;
public static final int PERFECT_NEGRONI = 8738;
public static final int MACHINE_SNOWGLOBE = 8749;
public static final int BACON = 8763;
public static final int BUNDLE_OF_FRAGRANT_HERBS = 8777;
public static final int NUCLEAR_STOCKPILE = 8778;
public static final int CIRCLE_DRUM = 8784;
public static final int COMMUNISM_BOOK = 8785;
public static final int COMMUNISM_BOOK_USED = 8794;
public static final int BAT_OOMERANG = 8797;
public static final int BAT_JUTE = 8798;
public static final int BAT_O_MITE = 8799;
public static final int ROM_OF_OPTIMALITY = 8800;
public static final int INCRIMINATING_EVIDENCE = 8801;
public static final int DANGEROUS_CHEMICALS = 8802;
public static final int KIDNAPPED_ORPHAN = 8803;
public static final int HIGH_GRADE_METAL = 8804;
public static final int HIGH_TENSILE_STRENGTH_FIBERS = 8805;
public static final int HIGH_GRADE_EXPLOSIVES = 8806;
public static final int EXPERIMENTAL_GENE_THERAPY = 8807;
public static final int ULTRACOAGULATOR = 8808;
public static final int SELF_DEFENSE_TRAINING = 8809;
public static final int FINGERPRINT_DUSTING_KIT = 8810;
public static final int CONFIDENCE_BUILDING_HUG = 8811;
public static final int EXPLODING_KICKBALL = 8812;
public static final int GLOB_OF_BAT_GLUE = 8813;
public static final int BAT_AID_BANDAGE = 8814;
public static final int BAT_BEARING = 8815;
public static final int KUDZU_SALAD = 8816;
public static final int MANSQUITO_SERUM = 8817;
public static final int MISS_GRAVES_VERMOUTH = 8818;
public static final int PLUMBERS_MUSHROOM_STEW = 8819;
public static final int AUTHORS_INK = 8820;
public static final int MAD_LIQUOR = 8821;
public static final int DOC_CLOCKS_THYME_COCKTAIL = 8822;
public static final int MR_BURNSGER = 8823;
public static final int INQUISITORS_UNIDENTIFIABLE_OBJECT = 8824;
public static final int REPLICA_BAT_OOMERANG = 8829;
public static final int ROBIN_EGG = 8833;
public static final int TELEGRAPH_OFFICE_DEED = 8836;
public static final int PLAINTIVE_TELEGRAM = 8837;
public static final int COWBOY_BOOTS = 8850;
public static final int INFLATABLE_TELEGRAPH_OFFICE = 8851;
public static final int HEIMZ_BEANS = 8866;
public static final int TESLA_BEANS = 8867;
public static final int MIXED_BEANS = 8868;
public static final int HELLFIRE_BEANS = 8869;
public static final int FRIGID_BEANS = 8870;
public static final int BLACKEST_EYED_PEAS = 8871;
public static final int STINKBEANS = 8872;
public static final int PORK_N_BEANS = 8873;
public static final int PREMIUM_BEANS = 8875;
public static final int MUS_BEANS_PLATE = 8876;
public static final int MYS_BEANS_PLATE = 8877;
public static final int MOX_BEANS_PLATE = 8878;
public static final int HOT_BEANS_PLATE = 8879;
public static final int COLD_BEANS_PLATE = 8880;
public static final int SPOOKY_BEANS_PLATE = 8881;
public static final int STENCH_BEANS_PLATE = 8882;
public static final int SLEAZE_BEANS_PLATE = 8883;
public static final int PREMIUM_BEANS_PLATE = 8885;
public static final int GLENN_DICE = 8890;
public static final int CLARA_BELL = 8893;
public static final int BUFFALO_DIME = 8895;
public static final int WESTERN_BOOK_BRAGGADOCCIO = 8916;
public static final int WESTERN_BOOK_HELL = 8917;
public static final int WESTERN_BOOK_LOOK = 8918;
public static final int WESTERN_SLANG_VOL_1 = 8920;
public static final int WESTERN_SLANG_VOL_2 = 8921;
public static final int WESTERN_SLANG_VOL_3 = 8922;
public static final int STRANGE_DISC_WHITE = 8923;
public static final int STRANGE_DISC_BLACK = 8924;
public static final int STRANGE_DISC_RED = 8925;
public static final int STRANGE_DISC_GREEN = 8926;
public static final int STRANGE_DISC_BLUE = 8927;
public static final int STRANGE_DISC_YELLOW = 8928;
public static final int MOUNTAIN_SKIN = 8937;
public static final int GRIZZLED_SKIN = 8938;
public static final int DIAMONDBACK_SKIN = 8939;
public static final int COAL_SKIN = 8940;
public static final int FRONTWINDER_SKIN = 8941;
public static final int ROTTING_SKIN = 8942;
public static final int QUICKSILVER_SPURS = 8947;
public static final int THICKSILVER_SPURS = 8948;
public static final int WICKSILVER_SPURS = 8949;
public static final int SLICKSILVER_SPURS = 8950;
public static final int SICKSILVER_SPURS = 8951;
public static final int NICKSILVER_SPURS = 8952;
public static final int TICKSILVER_SPURS = 8953;
public static final int COW_PUNCHING_TALES = 8955;
public static final int BEAN_SLINGING_TALES = 8956;
public static final int SNAKE_OILING_TALES = 8957;
public static final int SNAKE_OIL = 8971;
public static final int MEMORIES_OF_COW_PUNCHING = 8986;
public static final int MEMORIES_OF_BEAN_SLINGING = 8987;
public static final int MEMORIES_OF_SNAKE_OILING = 8988;
public static final int WITCHESS_SET = 8989;
public static final int BRAIN_TRAINER_GAME = 8990;
public static final int LASER_EYE_SURGERY_KIT = 8991;
public static final int SACRAMENTO_WINE = 8994;
public static final int CLAN_FLOUNDRY = 9000;
public static final int CARPE = 9001;
public static final int CODPIECE = 9002;
public static final int TROUTSERS = 9003;
public static final int BASS_CLARINET = 9004;
public static final int FISH_HATCHET = 9005;
public static final int TUNAC = 9006;
public static final int FISHING_POLE = 9007;
public static final int WRIGGLING_WORM = 9008;
public static final int FISHING_LINE = 9010;
public static final int FISHING_HAT = 9011;
public static final int TROUT_FISHING_IN_LOATHING = 9012;
public static final int ANTIQUE_TACKLEBOX = 9015;
public static final int VIRAL_VIDEO = 9017;
public static final int MEME_GENERATOR = 9019;
public static final int PLUS_ONE = 9020;
public static final int GALLON_OF_MILK = 9021;
public static final int PRINT_SCREEN = 9022;
public static final int SCREENCAPPED_MONSTER = 9023;
public static final int DAILY_DUNGEON_MALWARE = 9024;
public static final int BACON_MACHINE = 9025;
public static final int NO_SPOON = 9029;
public static final int SOURCE_TERMINAL = 9033;
public static final int SOURCE_ESSENCE = 9034;
public static final int BROWSER_COOKIE = 9035;
public static final int HACKED_GIBSON = 9036;
public static final int SOURCE_SHADES = 9037;
public static final int SOFTWARE_BUG = 9038;
public static final int SOURCE_TERMINAL_PRAM_CHIP = 9040;
public static final int SOURCE_TERMINAL_GRAM_CHIP = 9041;
public static final int SOURCE_TERMINAL_SPAM_CHIP = 9042;
public static final int SOURCE_TERMINAL_CRAM_CHIP = 9043;
public static final int SOURCE_TERMINAL_DRAM_CHIP = 9044;
public static final int SOURCE_TERMINAL_TRAM_CHIP = 9045;
public static final int SOURCE_TERMINAL_INGRAM_CHIP = 9046;
public static final int SOURCE_TERMINAL_DIAGRAM_CHIP = 9047;
public static final int SOURCE_TERMINAL_ASHRAM_CHIP = 9048;
public static final int SOURCE_TERMINAL_SCRAM_CHIP = 9049;
public static final int SOURCE_TERMINAL_TRIGRAM_CHIP = 9050;
public static final int SOURCE_TERMINAL_SUBSTATS_ENH = 9051;
public static final int SOURCE_TERMINAL_DAMAGE_ENH = 9052;
public static final int SOURCE_TERMINAL_CRITICAL_ENH = 9053;
public static final int SOURCE_TERMINAL_PROTECT_ENQ = 9054;
public static final int SOURCE_TERMINAL_STATS_ENQ = 9055;
public static final int SOURCE_TERMINAL_COMPRESS_EDU = 9056;
public static final int SOURCE_TERMINAL_DUPLICATE_EDU = 9057;
public static final int SOURCE_TERMINAL_PORTSCAN_EDU = 9058;
public static final int SOURCE_TERMINAL_TURBO_EDU = 9059;
public static final int SOURCE_TERMINAL_FAMILIAR_EXT = 9060;
public static final int SOURCE_TERMINAL_PRAM_EXT = 9061;
public static final int SOURCE_TERMINAL_GRAM_EXT = 9062;
public static final int SOURCE_TERMINAL_SPAM_EXT = 9063;
public static final int SOURCE_TERMINAL_CRAM_EXT = 9064;
public static final int SOURCE_TERMINAL_DRAM_EXT = 9065;
public static final int SOURCE_TERMINAL_TRAM_EXT = 9066;
public static final int COP_DOLLAR = 9072;
public static final int DETECTIVE_APPLICATION = 9073;
public static final int PROTON_ACCELERATOR = 9082;
public static final int STANDARDS_AND_PRACTICES = 9095;
public static final int RAD = 9100;
public static final int WRIST_BOY = 9102;
public static final int TIME_SPINNER = 9104;
public static final int HOLORECORD_SHRIEKING_WEASEL = 9109;
public static final int HOLORECORD_POWERGUY = 9110;
public static final int HOLORECORD_LUCKY_STRIKES = 9111;
public static final int HOLORECORD_EMD = 9112;
public static final int HOLORECORD_SUPERDRIFTER = 9113;
public static final int HOLORECORD_PIGS = 9114;
public static final int HOLORECORD_DRUNK_UNCLES = 9115;
public static final int TIME_RESIDUE = 9116;
public static final int EARL_GREY = 9122;
public static final int SCHOOL_OF_HARD_KNOCKS_DIPLOMA = 9123;
public static final int KOL_COL_13_SNOWGLOBE = 9133;
public static final int TRICK_TOT_KNIGHT = 9137;
public static final int TRICK_TOT_UNICORN = 9138;
public static final int TRICK_TOT_CANDY = 9139;
public static final int TRICK_TOT_ROBOT = 9143;
public static final int TRICK_TOT_EYEBALL = 9144;
public static final int TRICK_TOT_LIBERTY = 9145;
public static final int HOARDED_CANDY_WAD = 9146;
public static final int TWITCHING_TELEVISION_TATTOO = 9148;
public static final int STUFFING_FLUFFER = 9164;
public static final int TURKEY_BLASTER = 9166;
public static final int CANDIED_SWEET_POTATOES = 9171;
public static final int BREAD_ROLL = 9179;
public static final int CORNUCOPIA = 9183;
public static final int MEGACOPIA = 9184;
public static final int GIANT_PILGRIM_HAT = 9185;
public static final int THANKSGARDEN_SEEDS = 9186;
public static final int CASHEW = 9187;
public static final int BOMB_OF_UNKNOWN_ORIGIN = 9188;
public static final int GINGERBREAD_CITY = 9203;
public static final int COUNTERFEIT_CITY = 9204;
public static final int SPRINKLES = 9205;
public static final int VIGILANTE_BOOK = 9206;
public static final int BROKEN_CHOCOLATE_POCKETWATCH = 9215;
public static final int CLOD_OF_DIRT = 9216;
public static final int GINGERBREAD_RESTRAINING_ORDER = 9217;
public static final int GINGERBREAD_WINE = 9220;
public static final int GINGERBREAD_MUG = 9221;
public static final int GINGERSERVO = 9223;
public static final int GINGERBEARD = 9225;
public static final int CREME_BRULEE_TORCH = 9230;
public static final int GINGERBREAD_DOG_TREAT = 9233;
public static final int GINGERBREAD_CIGARETTE = 9237;
public static final int SPARE_CHOCOLATE_PARTS = 9240;
public static final int HIGH_END_GINGER_WINE = 9243;
public static final int MY_LIFE_OF_CRIME_BOOK = 9258;
public static final int POP_ART_BOOK = 9259;
public static final int NO_HATS_BOOK = 9260;
public static final int RETHINKING_CANDY_BOOK = 9261;
public static final int FRUIT_LEATHER_NEGATIVE = 9262;
public static final int GINGERBREAD_BLACKMAIL_PHOTOS = 9263;
public static final int TEETHPICK = 9265;
public static final int CHOCOLATE_SCULPTURE = 9269;
public static final int NO_HAT = 9270;
public static final int NEGATIVE_LUMP = 9272;
public static final int LUMP_STACKING_BOOK = 9285;
public static final int HOT_JELLY = 9291;
public static final int COLD_JELLY = 9292;
public static final int SPOOKY_JELLY = 9293;
public static final int SLEAZE_JELLY = 9294;
public static final int STENCH_JELLY = 9295;
public static final int HOT_TOAST = 9297;
public static final int COLD_TOAST = 9298;
public static final int SPOOKY_TOAST = 9299;
public static final int SLEAZE_TOAST = 9300;
public static final int STENCH_TOAST = 9301;
public static final int WAX_HAND = 9305;
public static final int MINIATURE_CANDLE = 9306;
public static final int WAX_PANCAKE = 9307;
public static final int WAX_FACE = 9308;
public static final int WAX_BOOZE = 9309;
public static final int WAX_GLOB = 9310;
public static final int HEART_SHAPED_CRATE = 9316;
public static final int LOVE_BOOMERANG = 9323;
public static final int LOVE_CHOCOLATE = 9325;
public static final int LOVE_ENTRANCE_PASS = 9330;
public static final int ELDRITCH_ICHOR = 9333;
public static final int ELDRITCH_TINCTURE = 9335;
public static final int ELDRITCH_TINCTURE_DEPLETED = 9336;
public static final int DIRTY_BOTTLECAP = 9343;
public static final int DISCARDED_BUTTON = 9344;
public static final int GUMMY_MEMORY = 9345;
public static final int NOVELTY_HOT_SAUCE = 9349;
public static final int COCKTAIL_MUSHROOM = 9353;
public static final int GRANOLA_LIQUEUR = 9354;
public static final int GREGNADIGNE = 9357;
public static final int FISH_HEAD = 9360;
public static final int BABY_OIL_SHOOTER = 9359;
public static final int LIMEPATCH = 9361;
public static final int LITERAL_GRASSHOPPER = 9365;
public static final int PISCATINI = 9378;
public static final int DRIVE_BY_SHOOTING = 9396;
public static final int PHIL_COLLINS = 9400;
public static final int TOGGLE_SWITCH_BARTEND = 9402;
public static final int TOGGLE_SWITCH_BOUNCE = 9403;
public static final int SPACEGATE_ACCESS_BADGE = 9404;
public static final int FILTER_HELMET = 9405;
public static final int EXO_SERVO_LEG_BRACES = 9406;
public static final int RAD_CLOAK = 9407;
public static final int GATE_TRANSCEIVER = 9408;
public static final int HIGH_FRICTION_BOOTS = 9409;
public static final int SPACEGATE_RESEARCH = 9410;
public static final int ALIEN_ROCK_SAMPLE = 9411;
public static final int ALIEN_GEMSTONE = 9412;
public static final int ALIEN_PLANT_FIBERS = 9416;
public static final int ALIEN_PLANT_SAMPLE = 9417;
public static final int COMPLEX_ALIEN_PLANT_SAMPLE = 9418;
public static final int FASCINATING_ALIEN_PLANT_SAMPLE = 9419;
public static final int ALIEN_PLANT_POD = 9421;
public static final int ALIEN_TOENAILS = 9424;
public static final int ALIEN_ZOOLOGICAL_SAMPLE = 9425;
public static final int COMPLEX_ALIEN_ZOOLOGICAL_SAMPLE = 9426;
public static final int FASCINATING_ALIEN_ZOOLOGICAL_SAMPLE = 9427;
public static final int ALIEN_ANIMAL_MILK = 9429;
public static final int SPANT_EGG_CASING = 9430;
public static final int MURDERBOT_DATA_CORE = 9431;
public static final int SPANT_CHITIN = 9441;
public static final int PRIMITIVE_ALIEN_TOTEM = 9439;
public static final int SPANT_TENDON = 9442;
public static final int MURDERBOT_MEMORY_CHIP = 9457;
public static final int SPACE_PIRATE_TREASURE_MAP = 9458;
public static final int SPACE_PIRATE_ASTROGATION_HANDBOOK = 9459;
public static final int NON_EUCLIDEAN_FINANCE = 9460;
public static final int PEEK_A_BOO = 9461;
public static final int PROCRASTINATOR_LOCKER_KEY = 9462;
public static final int SPACE_BABY_CHILDRENS_BOOK = 9463;
public static final int SPACE_BABY_BAWBAW = 9464;
public static final int PORTABLE_SPACEGATE = 9465;
public static final int OPEN_PORTABLE_SPACEGATE = 9477;
public static final int NEW_YOU_CLUB_MEMBERSHIP_FORM = 9478;
public static final int AFFIRMATION_SUPERFICIALLY_INTERESTED = 9481;
public static final int AFFIRMATION_MIND_MASTER = 9483;
public static final int AFFIRMATION_HATE = 9485;
public static final int AFFIRMATION_COOKIE = 9486;
public static final int LICENSE_TO_KILL = 9487;
public static final int VICTOR_SPOILS = 9489;
public static final int KREMLIN_BRIEFCASE = 9493;
public static final int CAN_OF_MINIONS_BE_GONE = 9498;
public static final int LICENSE_TO_CHILL = 9503;
public static final int CELSIUS_233 = 9504;
public static final int CELSIUS_233_SINGED = 9505;
public static final int LAZENBY = 9506;
public static final int ASDON_MARTIN = 9508;
public static final int METEORITE_ADE = 9513;
public static final int METAL_METEOROID = 9516;
public static final int METEORTARBOARD = 9517;
public static final int METEORITE_GUARD = 9518;
public static final int METEORB = 9519;
public static final int ASTEROID_BELT = 9520;
public static final int METEORTHOPEDIC_SHOES = 9521;
public static final int SHOOTING_MORNING_STAR = 9522;
public static final int PERFECTLY_FAIR_COIN = 9526;
public static final int CORKED_GENIE_BOTTLE = 9528;
public static final int GENIE_BOTTLE = 9529;
public static final int POCKET_WISH = 9537;
public static final int SHOVELFUL_OF_EARTH = 9539;
public static final int HUNK_OF_GRANITE = 9540;
public static final int X = 9543;
public static final int O = 9544;
public static final int MAFIA_PINKY_RING = 9546;
public static final int FLASK_OF_PORT = 9547;
public static final int BRIDGE_TRUSS = 9556;
public static final int AMORPHOUS_BLOB = 9558;
public static final int GIANT_AMORPHOUS_BLOB = 9561;
public static final int MAFIA_THUMB_RING = 9564;
public static final int PORTABLE_PANTOGRAM = 9573;
public static final int PANTOGRAM_PANTS = 9574;
public static final int MUMMING_TRUNK = 9592;
public static final int EARTHENWARE_MUFFIN_TIN = 9596;
public static final int BRAN_MUFFIN = 9597;
public static final int BLUEBERRY_MUFFIN = 9598;
public static final int CRYSTALLINE_CHEER = 9625;
public static final int WAREHOUSE_KEY = 9627;
public static final int MIME_SCIENCE_VOL_1 = 9635;
public static final int MIME_SCIENCE_VOL_1_USED = 9636;
public static final int MIME_SCIENCE_VOL_2 = 9637;
public static final int MIME_SCIENCE_VOL_2_USED = 9638;
public static final int MIME_SCIENCE_VOL_3 = 9639;
public static final int MIME_SCIENCE_VOL_3_USED = 9640;
public static final int MIME_SCIENCE_VOL_4 = 9641;
public static final int MIME_SCIENCE_VOL_4_USED = 9642;
public static final int MIME_SCIENCE_VOL_5 = 9643;
public static final int MIME_SCIENCE_VOL_5_USED = 9644;
public static final int MIME_SCIENCE_VOL_6 = 9645;
public static final int MIME_SCIENCE_VOL_6_USED = 9646;
public static final int GOD_LOBSTER = 9661;
public static final int DONATED_BOOZE = 9662;
public static final int DONATED_FOOD = 9663;
public static final int DONATED_CANDY = 9664;
public static final int MIME_ARMY_INSIGNIA_INFANTRY = 9667;
public static final int MIME_ARMY_INFILTRATION_GLOVE = 9675;
public static final int MIME_SHOTGLASS = 9676;
public static final int TOASTED_HALF_SANDWICH = 9681;
public static final int MULLED_HOBO_WINE = 9682;
public static final int BURNING_NEWSPAPER = 9683;
public static final int BURNING_HAT = 9684;
public static final int BURNING_CAPE = 9685;
public static final int BURNING_SLIPPERS = 9686;
public static final int BURNING_JORTS = 9687;
public static final int BURNING_CRANE = 9688;
public static final int GARBAGE_TOTE = 9690;
public static final int DECEASED_TREE = 9691;
public static final int BROKEN_CHAMPAGNE = 9692;
public static final int TINSEL_TIGHTS = 9693;
public static final int WAD_OF_TAPE = 9694;
public static final int MAKESHIFT_GARBAGE_SHIRT = 9699;
public static final int DIETING_PILL = 9707;
public static final int CLAN_CARNIVAL_GAME = 9712;
public static final int GET_BIG_BOOK = 9713;
public static final int GALAPAGOS_BOOK = 9714;
public static final int FUTURE_BOOK = 9715;
public static final int LOVE_POTION_BOOK = 9716;
public static final int RHINESTONE_BOOK = 9717;
public static final int LOVE_SONG_BOOK = 9718;
public static final int MYSTERIOUS_RED_BOX = 9739;
public static final int MYSTERIOUS_GREEN_BOX = 9740;
public static final int MYSTERIOUS_BLUE_BOX = 9741;
public static final int MYSTERIOUS_BLACK_BOX = 9742;
public static final int LOVE_POTION_XYZ = 9745;
public static final int POKEDOLLAR_BILLS = 9747;
public static final int METANDIENONE = 9748;
public static final int RIBOFLAVIN = 9749;
public static final int BRONZE = 9750;
public static final int PIRACETAM = 9751;
public static final int ULTRACALCIUM = 9752;
public static final int GINSENG = 9753;
public static final int TALL_GRASS_SEEDS = 9760;
public static final int POKE_GROW_FERTILIZER = 9761;
public static final int LUCK_INCENSE = 9821;
public static final int SHELL_BELL = 9822;
public static final int MUSCLE_BAND = 9823;
public static final int AMULET_COIN = 9824;
public static final int RAZOR_FANG = 9825;
public static final int SMOKE_BALL = 9826;
public static final int GREEN_ROCKET = 9827;
public static final int MAGNIFICENT_OYSTER_EGG = 9828;
public static final int BRILLIANT_OYSTER_EGG = 9829;
public static final int GLISTENING_OYSTER_EGG = 9830;
public static final int SCINTILLATING_OYSTER_EGG = 9831;
public static final int PEARLESCENT_OYSTER_EGG = 9832;
public static final int LUSTROUS_OYSTER_EGG = 9833;
public static final int GLEAMING_OYSTER_EGG = 9834;
public static final int FR_MEMBER = 9835;
public static final int FR_GUEST = 9836;
public static final int FANTASY_REALM_GEM = 9837;
public static final int RUBEE = 9838;
public static final int FR_WARRIOR_HELM = 9839;
public static final int FR_MAGE_HAT = 9840;
public static final int FR_ROGUE_MASK = 9841;
public static final int FR_KEY = 9844;
public static final int FR_PURPLE_MUSHROOM = 9845;
public static final int FR_TAINTED_MARSHMALLOW = 9846;
public static final int FR_CHESWICKS_NOTES = 9847;
public static final int MY_FIRST_ART_OF_WAR = 9850;
public static final int FR_DRAGON_ORE = 9851;
public static final int FR_POISONED_SMORE = 9853;
public static final int FR_DRUIDIC_ORB = 9854;
public static final int FR_HOLY_WATER = 9856;
public static final int CONTRACTOR_MANUAL = 9861;
public static final int FR_CHESWICKS_COMPASS = 9865;
public static final int FR_ARREST_WARRANT = 9866;
public static final int FR_MOUNTAIN_MAP = 9873;
public static final int FR_WOOD_MAP = 9874;
public static final int FR_SWAMP_MAP = 9875;
public static final int FR_VILLAGE_MAP = 9876;
public static final int FR_CEMETARY_MAP = 9877;
public static final int FR_CHARGED_ORB = 9895;
public static final int FR_NOTARIZED_WARRANT = 9897;
public static final int CLARIFIED_BUTTER = 9908;
public static final int G = 9909;
public static final int GARLAND_OF_GREATNESS = 9910;
public static final int GLUED_BOO_CLUE = 9913;
public static final int BOOMBOX = 9919;
public static final int GUIDE_TO_SAFARI = 9921;
public static final int SHIELDING_POTION = 9922;
public static final int PUNCHING_POTION = 9923;
public static final int SPECIAL_SEASONING = 9924;
public static final int NIGHTMARE_FUEL = 9925;
public static final int MEAT_CLIP = 9926;
public static final int CHEESE_WHEEL = 9937;
public static final int BASTILLE_LOANER_VOUCHER = 9938;
public static final int NEVERENDING_PARTY_INVITE = 9942;
public static final int NEVERENDING_PARTY_INVITE_DAILY = 9943;
public static final int PARTY_HARD_T_SHIRT = 9944;
public static final int ELECTRONICS_KIT = 9952;
public static final int PAINT_PALETTE = 9956;
public static final int UNREMARKABLE_DUFFEL_BAG = 9957;
public static final int PURPLE_BEAST_ENERGY_DRINK = 9958;
public static final int PUMP_UP_HIGH_TOPS = 9961;
public static final int VERY_SMALL_RED_DRESS = 9963;
public static final int EVERFULL_GLASS = 9966;
public static final int VAN_KEY = 9967;
public static final int JAM_BAND_BOOTLEG = 9968;
public static final int INTIMIDATING_CHAINSAW = 9972;
public static final int PARTY_PLANNING_BOOK = 9978;
public static final int PARTYCRASHER = 9983;
public static final int DRINKING_TO_DRINK_BOOK = 9984;
public static final int LATTE_MUG = 9987;
public static final int VOTER_REGISTRATION_FORM = 9989;
public static final int I_VOTED_STICKER = 9990;
public static final int VOTER_BALLOT = 9991;
public static final int BLACK_SLIME_GLOB = 9996;
public static final int GREEN_SLIME_GLOB = 9997;
public static final int ORANGE_SLIME_GLOB = 9998;
public static final int GOVERNMENT_REQUISITION_FORM = 10003;
public static final int HAUNTED_HELL_RAMEN = 10018;
public static final int WALRUS_BLUBBER = 10034;
public static final int TINY_BOMB = 10036;
public static final int MOOSEFLANK = 10038;
public static final int BOXING_DAY_CARE = 10049;
public static final int BOXING_DAY_PASS = 10056;
public static final int SAUSAGE_O_MATIC = 10058;
public static final int MAGICAL_SAUSAGE_CASING = 10059;
public static final int MAGICAL_SAUSAGE = 10060;
public static final int CRIMBO_CANDLE = 10072;
public static final int CHALK_CHUNKS = 10088;
public static final int MARBLE_MOLECULES = 10096;
public static final int PARAFFIN_PSEUDOACCORDION = 10103;
public static final int PARAFFIN_PIECES = 10104;
public static final int TERRA_COTTA_TIDBITS = 10112;
public static final int TRYPTOPHAN_DART = 10159;
public static final int DOCTOR_BAG = 10166;
public static final int BLOOD_SNOWCONE = 10173;
public static final int VAMPAGNE = 10178;
public static final int BOOKE_OF_VAMPYRIC_KNOWLEDGE = 10180;
public static final int VAMPYRE_BLOOD = 10185;
public static final int GLITCH_ITEM = 10207;
public static final int PR_MEMBER = 10187;
public static final int PR_GUEST = 10188;
public static final int CURSED_COMPASS = 10191;
public static final int ISLAND_DRINKIN = 10211;
public static final int PIRATE_REALM_FUN_LOG = 10225;
public static final int PIRATE_FORK = 10227;
public static final int SCURVY_AND_SOBRIETY_PREVENTION = 10228;
public static final int LUCKY_GOLD_RING = 10229;
public static final int VAMPYRIC_CLOAKE = 10242;
public static final int FOURTH_SABER = 10251;
public static final int RING = 10252;
public static final int HEWN_MOON_RUNE_SPOON = 10254;
public static final int BEACH_COMB = 10258;
public static final int ETCHED_HOURGLASS = 10265;
public static final int PIECE_OF_DRIFTWOOD = 10281;
public static final int DRIFTWOOD_BEACH_COMB = 10291;
public static final int STICK_OF_FIREWOOD = 10293;
public static final int GETAWAY_BROCHURE = 10292;
public static final int RARE_MEAT_ISOTOPE = 10310;
public static final int BURNT_STICK = 10311;
public static final int BUNDLE_OF_FIREWOOD = 10312;
public static final int CAMPFIRE_SMOKE = 10313;
public static final int THE_IMPLODED_WORLD = 10322;
public static final int POCKET_PROFESSOR_MEMORY_CHIP = 10324;
public static final int LAW_OF_AVERAGES = 10325;
public static final int PILL_KEEPER = 10333;
public static final int DIABOLIC_PIZZA_CUBE = 10335;
public static final int DIABOLIC_PIZZA = 10336;
public static final int HUMAN_MUSK = 10350;
public static final int EXTRA_WARM_FUR = 10351;
public static final int INDUSTRIAL_LUBRICANT = 10352;
public static final int UNFINISHED_PLEASURE = 10353;
public static final int HUMANOID_GROWTH_HORMONE = 10354;
public static final int BUG_LYMPH = 10355;
public static final int ORGANIC_POTPOURRI = 10356;
public static final int BOOT_FLASK = 10357;
public static final int INFERNAL_SNOWBALL = 10358;
public static final int POWDERED_MADNESS = 10359;
public static final int FISH_SAUCE = 10360;
public static final int GUFFIN = 10361;
public static final int SHANTIX = 10362;
public static final int GOODBERRY = 10363;
public static final int EUCLIDEAN_ANGLE = 10364;
public static final int PEPPERMINT_SYRUP = 10365;
public static final int MERKIN_EYEDROPS = 10366;
public static final int EXTRA_STRENGTH_GOO = 10367;
public static final int ENVELOPE_MEAT = 10368;
public static final int LIVID_ENERGY = 10369;
public static final int MICRONOVA = 10370;
public static final int BEGGIN_COLOGNE = 10371;
public static final int THE_SPIRIT_OF_GIVING = 10380;
public static final int PEPPERMINT_EEL_SAUCE = 10416;
public static final int GREEN_AND_RED_BEAN = 10417;
public static final int TEMPURA_GREEN_AND_RED_BEAN = 10425;
public static final int BIRD_A_DAY_CALENDAR = 10434;
public static final int POWERFUL_GLOVE = 10438;
public static final int DRIP_HARNESS = 10441;
public static final int DRIPPY_TRUNCHEON = 10442;
public static final int DRIPLET = 10443;
public static final int DRIPPY_SNAIL_SHELL = 10444;
public static final int DRIPPY_NUGGET = 10445;
public static final int DRIPPY_WINE = 10446;
public static final int DRIPPY_CAVIAR = 10447;
public static final int DRIPPY_PLUM = 10448;
public static final int EYE_OF_THE_THING = 10450;
public static final int DRIPPY_SHIELD = 10452;
public static final int FIRST_PLUMBER_QUEST_ITEM = 10454;
public static final int COIN = 10454;
public static final int MUSHROOM = 10455;
public static final int DELUXE_MUSHROOM = 10456;
public static final int SUPER_DELUXE_MUSHROOM = 10457;
public static final int HAMMER = 10460;
public static final int HEAVY_HAMMER = 10461;
public static final int PLUMBER_FIRE_FLOWER = 10462;
public static final int BONFIRE_FLOWER = 10463;
public static final int WORK_BOOTS = 10464;
public static final int FANCY_BOOTS = 10465;
public static final int POWER_PANTS = 10469;
public static final int FROSTY_BUTTON = 10473;
public static final int LAST_PLUMBER_QUEST_ITEM = 10474;
public static final int MUSHROOM_SPORES = 10482;
public static final int FREE_RANGE_MUSHROOM = 10483;
public static final int PLUMP_FREE_RANGE_MUSHROOM = 10484;
public static final int BULKY_FREE_RANGE_MUSHROOM = 10485;
public static final int GIANT_FREE_RANGE_MUSHROOM = 10486;
public static final int IMMENSE_FREE_RANGE_MUSHROOM = 10487;
public static final int COLOSSAL_FREE_RANGE_MUSHROOM = 10488;
public static final int HOUSE_SIZED_MUSHROOM = 10497;
public static final int RED_PLUMBERS_BOOTS = 10501;
public static final int DRIPPY_STEIN = 10524;
public static final int DRIPPY_PILSNER = 10525;
public static final int DRIPPY_STAFF = 10526;
public static final int GUZZLR_TABLET = 10533;
public static final int GUZZLR_COCKTAIL_SET = 10534;
public static final int GUZZLRBUCK = 10535;
public static final int GUZZLR_SHOES = 10537;
public static final int CLOWN_CAR_KEY = 10547;
public static final int BATTING_CAGE_KEY = 10548;
public static final int AQUI = 10549;
public static final int KNOB_LABINET_KEY = 10550;
public static final int WEREMOOSE_KEY = 10551;
public static final int PEG_KEY = 10552;
public static final int KEKEKEY = 10553;
public static final int RABBITS_FOOT_KEY = 10554;
public static final int KNOB_SHAFT_SKATE_KEY = 10555;
public static final int ICE_KEY = 10556;
public static final int ANCHOVY_CAN_KEY = 10557;
public static final int CACTUS_KEY = 10558;
public static final int F_C_LE_SH_C_LE_K_Y = 10559;
public static final int TREASURE_CHEST_KEY = 10560;
public static final int DEMONIC_KEY = 10561;
public static final int KEY_SAUSAGE = 10562;
public static final int KNOB_TREASURY_KEY = 10563;
public static final int SCRAP_METAL_KEY = 10564;
public static final int BLACK_ROSE_KEY = 10565;
public static final int MUSIC_BOX_KEY = 10566;
public static final int ACTUAL_SKELETON_KEY = 10567;
public static final int DEEP_FRIED_KEY = 10568;
public static final int DISCARDED_BIKE_LOCK_KEY = 10569;
public static final int MANUAL_OF_LOCK_PICKING = 10571;
public static final int DROMEDARY_DRINKING_HELMET = 10580;
public static final int SPINMASTER = 10582;
public static final int FLIMSY_HARDWOOD_SCRAPS = 10583;
public static final int DREADSYLVANIAN_HEMLOCK = 10589;
public static final int HEMLOCK_HELM = 10590;
public static final int SWEATY_BALSAM = 10591;
public static final int BALSAM_BARREL = 10592;
public static final int ANCIENT_REDWOOD = 10593;
public static final int REDWOOD_RAIN_STICK = 10594;
public static final int PURPLEHEART_LOGS = 10595;
public static final int PURPLEHEART_PANTS = 10596;
public static final int WORMWOOD_STICK = 10597;
public static final int WORMWOOD_WEDDING_RING = 10598;
public static final int DRIPWOOD_SLAB = 10599;
public static final int DRIPPY_DIADEM = 10600;
public static final int GREY_GOO_RING = 10602;
public static final int SIZZLING_DESK_BELL = 10617;
public static final int FROST_RIMED_DESK_BELL = 10618;
public static final int UNCANNY_DESK_BELL = 10619;
public static final int NASTY_DESK_BELL = 10620;
public static final int GREASY_DESK_BELL = 10621;
public static final int FANCY_CHESS_SET = 10622;
public static final int ONYX_KING = 10623;
public static final int ONYX_QUEEN = 10624;
public static final int ONYX_ROOK = 10625;
public static final int ONYX_BISHOP = 10626;
public static final int ONYX_KNIGHT = 10627;
public static final int ONYX_PAWN = 10628;
public static final int ALABASTER_KING = 10629;
public static final int ALABASTER_QUEEN = 10630;
public static final int ALABASTER_ROOK = 10631;
public static final int ALABASTER_BISHOP = 10632;
public static final int ALABASTER_KNIGHT = 10633;
public static final int ALABASTER_PAWN = 10634;
public static final int CARGO_CULTIST_SHORTS = 10636;
public static final int UNIVERSAL_SEASONING = 10640;
public static final int CHOCOLATE_CHIP_MUFFIN = 10643;
public static final int KNOCK_OFF_RETRO_SUPERHERO_CAPE = 10647;
public static final int SUBSCRIPTION_COCOA_DISPENSER = 10652;
public static final int OVERFLOWING_GIFT_BASKET = 10670;
public static final int FOOD_DRIVE_BUTTON = 10691;
public static final int BOOZE_DRIVE_BUTTON = 10692;
public static final int CANDY_DRIVE_BUTTON = 10693;
public static final int FOOD_MAILING_LIST = 10694;
public static final int BOOZE_MAILING_LIST = 10695;
public static final int CANDY_MAILING_LIST = 10696;
public static final int GOVERNMENT_FOOD_SHIPMENT = 10685;
public static final int GOVERNMENT_BOOZE_SHIPMENT = 10686;
public static final int GOVERNMENT_CANDY_SHIPMENT = 10687;
public static final int MINIATURE_CRYSTAL_BALL = 10730;
public static final int COAT_OF_PAINT = 10732;
public static final int SPINAL_FLUID_COVERED_EMOTION_CHIP = 10734;
public static final int BATTERY_9V = 10742;
public static final int BATTERY_LANTERN = 10743;
public static final int BATTERY_CAR = 10744;
public static final int GREEN_MARSHMALLOW = 10746;
public static final int MARSHMALLOW_BOMB = 10747;
public static final int BACKUP_CAMERA = 10749;
public static final int BLUE_PLATE = 10751;
public static final int FAMILIAR_SCRAPBOOK = 10759;
public static final int CLAN_UNDERGROUND_FIREWORKS_SHOP = 10761;
public static final int FEDORA_MOUNTED_FOUNTAIN = 10762;
public static final int PORKPIE_MOUNTED_POPPER = 10763;
public static final int SOMBRERO_MOUNTED_SPARKLER = 10764;
public static final int CATHERINE_WHEEL = 10770;
public static final int ROCKET_BOOTS = 10771;
public static final int OVERSIZED_SPARKLER = 10772;
public static final int EXTRA_WIDE_HEAD_CANDLE = 10783;
public static final int BLART = 10790;
public static final int RAINPROOF_BARREL_CAULK = 10794;
public static final int PUMP_GREASE = 10795;
public static final int INDUSTRIAL_FIRE_EXTINGUISHER = 10797;
public static final int VAMPIRE_VINTNER_WINE = 10800;
public static final int DAYLIGHT_SHAVINGS_HELMET = 10804;
public static final int COLD_MEDICINE_CABINET = 10815;
public static final int HOMEBODYL = 10828;
public static final int EXTROVERMECTIN = 10829;
public static final int BREATHITIN = 10830;
public static final int FLESHAZOLE = 10831;
public static final int GOOIFIED_ANIMAL_MATTER = 10844;
public static final int GOOIFIED_VEGETABLE_MATTER = 10845;
public static final int GOOIFIED_MINERAL_MATTER = 10846;
public static final int CARNIVOROUS_POTTED_PLANT = 10864;
public static final int MEATBALL_MACHINE = 10878;
public static final int REFURBISHED_AIR_FRYER = 10879;
public static final int ELEVEN_LEAF_CLOVER = 10881;
public static final int CURSED_MAGNIFYING_GLASS = 10885;
public static final int COSMIC_BOWLING_BALL = 10891;
public static final int COMBAT_LOVERS_LOCKET = 10893;
public static final int UNBREAKABLE_UMBRELLA = 10899;
public static final int MAYDAY_SUPPLY_PACKAGE = 10901;
public static final int SURVIVAL_KNIFE = 10903;
public static final int THE_BIG_BOOK_OF_EVERY_SKILL = 10917;
public static final int JUNE_CLEAVER = 10920;
public static final int MOTHERS_NECKLACE = 10925;
public static final int DESIGNER_SWEATPANTS = 10929;
public static final int STILLSUIT = 10932;
public static final int DINODOLLAR = 10944;
public static final int DINOSAUR_DROPPINGS = 10945;
public static final int JURASSIC_PARKA = 10952;
public static final int AUTUMNATON = 10954;
public static final int ROASTED_VEGETABLE_OF_JARLSBERG = 10972;
public static final int PETES_RICH_RICOTTA = 10975;
public static final int BORIS_BREAD = 10978;
public static final int ROBY_RATATOUILLE_DE_JARLSBERG = 10979;
public static final int ROBY_JARLSBERGS_VEGETABLE_SOUP = 10980;
public static final int ROBY_ROASTED_VEGETABLE_OF_J = 10981;
public static final int ROBY_PETES_SNEAKY_SMOOTHIE = 10982;
public static final int ROBY_PETES_WILY_WHEY_BAR = 10983;
public static final int ROBY_PETES_RICH_RICOTTA = 10984;
public static final int ROBY_BORIS_BEER = 10985;
public static final int ROBY_HONEY_BUN_OF_BORIS = 10986;
public static final int ROBY_BORIS_BREAD = 10987;
public static final int BAKED_VEGGIE_RICOTTA_CASSEROLE = 10988;
public static final int PLAIN_CALZONE = 10989;
public static final int ROASTED_VEGETABLE_FOCACCIA = 10990;
public static final int PIZZA_OF_LEGEND = 10991;
public static final int CALZONE_OF_LEGEND = 10992;
public static final int ROBY_CALZONE_OF_LEGEND = 10993;
public static final int ROBY_PIZZA_OF_LEGEND = 10994;
public static final int ROBY_ROASTED_VEGETABLE_FOCACCIA = 10995;
public static final int ROBY_PLAIN_CALZONE = 10996;
public static final int ROBY_BAKED_VEGGIE_RICOTTA = 10997;
public static final int ROBY_DEEP_DISH_OF_LEGEND = 10999;
public static final int DEEP_DISH_OF_LEGEND = 11000;
public static final int DEED_TO_OLIVERS_PLACE = 11001;
public static final int DRINK_CHIT = 11002;
public static final int GOVERNMENT_PER_DIEM = 11003;
public static final int MILK_CAP = 11012;
public static final int CHARLESTON_CHOO_CHOO = 11013;
public static final int VELVET_VEIL = 11014;
public static final int MARLTINI = 11015;
public static final int STRONG_SILENT_TYPE = 11016;
public static final int MYSTERIOUS_STRANGER = 11017;
public static final int CHAMPAGNE_SHIMMY = 11018;
public static final int THE_SOTS_PARCEL = 11019;
public static final int MODEL_TRAIN_SET = 11045;
public static final int CRIMBO_TRAINING_MANUAL = 11046;
public static final int PING_PONG_PADDLE = 11056;
public static final int PING_PONG_BALL = 11057;
public static final int TRAINBOT_HARNESS = 11058;
public static final int PING_PONG_TABLE = 11059;
public static final int TRAINBOT_AUTOASSEMBLY_MODULE = 11061;
public static final int CRIMBO_CRYSTAL_SHARDS = 11066;
public static final int LOST_ELF_LUGGAGE = 11068;
public static final int TRAINBOT_LUGGAGE_HOOK = 11069;
public static final int WHITE_ARM_TOWEL = 11073;
public static final int TRAINBOT_SLAG = 11076;
public static final int PORTABLE_STEAM_UNIT = 11081;
public static final int CRYSTAL_CRIMBO_GOBLET = 11082;
public static final int CRYSTAL_CRIMBO_PLATTER = 11083;
public static final int GRUBBY_WOOL = 11091;
public static final int GRUBBY_WOOL_HAT = 11092;
public static final int GRUBBY_WOOL_SCARF = 11093;
public static final int GRUBBY_WOOL_TROUSERS = 11094;
public static final int GRUBBY_WOOL_GLOVES = 11095;
public static final int GRUBBY_WOOL_BEERWARMER = 11096;
public static final int NICE_WARM_BEER = 11097;
public static final int GRUBBY_WOOLBALL = 11098;
public static final int ROCK_SEEDS = 11100;
public static final int GROVELING_GRAVEL = 11101;
public static final int FRUITY_PEBBLE = 11102;
public static final int LODESTONE = 11103;
public static final int MILESTONE = 11104;
public static final int BOLDER_BOULDER = 11105;
public static final int MOLEHILL_MOUNTAIN = 11106;
public static final int WHETSTONE = 11107;
public static final int HARD_ROCK = 11108;
public static final int STRANGE_STALAGMITE = 11109;
public static final int CHOCOLATE_COVERED_PING_PONG_BALL = 11110;
public static final int SIT_COURSE_COMPLETION_CERTIFICATE = 11116;
public static final int SHADOW_SAUSAGE = 11135;
public static final int SHADOW_SKIN = 11136;
public static final int SHADOW_FLAME = 11137;
public static final int SHADOW_BREAD = 11138;
public static final int SHADOW_ICE = 11139;
public static final int SHADOW_FLUID = 11140;
public static final int SHADOW_GLASS = 11141;
public static final int SHADOW_BRICK = 11142;
public static final int SHADOW_SINEW = 11143;
public static final int SHADOW_VENOM = 11144;
public static final int SHADOW_NECTAR = 11145;
public static final int SHADOW_STICK = 11146;
public static final int ADVANCED_PIG_SKINNING = 11163;
public static final int THE_CHEESE_WIZARDS_COMPANION = 11164;
public static final int JAZZ_AGENT_SHEET_MUSIC = 11165;
public static final int SHADOWY_CHEAT_SHEET = 11167;
public static final int CLOSED_CIRCUIT_PAY_PHONE = 11169;
public static final int SHADOW_LIGHTER = 11170;
public static final int SHADOW_HEPTAHEDRON = 11171;
public static final int SHADOW_SNOWFLAKE = 11172;
public static final int SHADOW_HEART = 11173;
public static final int SHADOW_BUCKET = 11174;
public static final int SHADOW_WAVE = 11175;
public static final int RUFUS_SHADOW_LODESTONE = 11176;
public static final int SHADOW_CHEFS_HAT = 11177;
public static final int SHADOW_TROUSERS = 11178;
public static final int SHADOW_HAMMER = 11179;
public static final int SHADOW_MONOCLE = 11180;
public static final int SHADOW_CANDLE = 11181;
public static final int SHADOW_HOT_DOG = 11182;
public static final int SHADOW_MARTINI = 11183;
public static final int SHADOW_PILL = 11184;
public static final int SHADOW_NEEDLE = 11185;
public static final int CURSED_MONKEY_PAW = 11186;
public static final int REPLICA_MR_ACCESSORY = 11189;
public static final int REPLICA_DARK_JILL = 11190;
public static final int REPLICA_HAND_TURKEY = 11191;
public static final int REPLICA_CRIMBO_ELF = 11192;
public static final int REPLICA_BUGBEAR_SHAMAN = 11193;
public static final int REPLICA_GRAVY_MAYPOLE = 11195;
public static final int REPLICA_WAX_LIPS = 11196;
public static final int REPLICA_SNOWCONE_BOOK = 11197;
public static final int REPLICA_JEWEL_EYED_WIZARD_HAT = 11199;
public static final int REPLICA_BOTTLE_ROCKET = 11200;
public static final int REPLICA_NAVEL_RING = 11201;
public static final int REPLICA_V_MASK = 11202;
public static final int REPLICA_HAIKU_KATANA = 11203;
public static final int REPLICA_FIREWORKS = 11204;
public static final int REPLICA_COTTON_CANDY_COCOON = 11205;
public static final int REPLICA_ELVISH_SUNGLASSES = 11206;
public static final int REPLICA_SQUAMOUS_POLYP = 11207;
public static final int REPLICA_GREAT_PANTS = 11209;
public static final int REPLICA_ORGAN_GRINDER = 11210;
public static final int REPLICA_JUJU_MOJO_MASK = 11211;
public static final int REPLICA_PATRIOT_SHIELD = 11212;
public static final int REPLICA_RESOLUTION_BOOK = 11213;
public static final int REPLICA_PLASTIC_VAMPIRE_FANGS = 11214;
public static final int REPLICA_CUTE_ANGEL = 11215;
public static final int REPLICA_CAMP_SCOUT_BACKPACK = 11216;
public static final int REPLICA_DEACTIVATED_NANOBOTS = 11217;
public static final int REPLICA_BANDERSNATCH = 11218;
public static final int REPLICA_SMITH_BOOK = 11219;
public static final int REPLICA_FOLDER_HOLDER = 11220;
public static final int REPLICA_GREEN_THUMB = 11221;
public static final int CINCHO_DE_MAYO = 11223;
public static final int REPLICA_GENE_SPLICING_LAB = 11225;
public static final int REPLICA_STILL_GRILL = 11226;
public static final int REPLICA_CRIMBO_SAPLING = 11227;
public static final int REPLICA_YELLOW_PUCK = 11228;
public static final int REPLICA_CHATEAU_ROOM_KEY = 11229;
public static final int REPLICA_DECK_OF_EVERY_CARD = 11230;
public static final int REPLICA_SOURCE_TERMINAL = 11231;
public static final int REPLICA_INTERGNAT = 11232;
public static final int REPLICA_WITCHESS_SET = 11233;
public static final int REPLICA_GENIE_BOTTLE = 11234;
public static final int REPLICA_SPACE_PLANULA = 11235;
public static final int REPLICA_ROBORTENDER = 11236;
public static final int REPLICA_NEVERENDING_PARTY_INVITE = 11237;
public static final int REPLICA_GARBAGE_TOTE = 11238;
public static final int REPLICA_GOD_LOBSTER = 11239;
public static final int REPLICA_FOURTH_SABER = 11240;
public static final int REPLICA_SAUSAGE_O_MATIC = 11241;
public static final int REPLICA_HEWN_MOON_RUNE_SPOON = 11242;
public static final int REPLICA_CAMELCALF = 11243;
public static final int REPLICA_POWERFUL_GLOVE = 11244;
public static final int REPLICA_CARGO_CULTIST_SHORTS = 11245;
public static final int REPLICA_INDUSTRIAL_FIRE_EXTINGUISHER = 11246;
public static final int REPLICA_MINIATURE_CRYSTAL_BALL = 11247;
public static final int REPLICA_EMOTION_CHIP = 11248;
public static final int REPLICA_JURASSIC_PARKA = 11249;
public static final int REPLICA_GREY_GOSLING = 11250;
public static final int REPLICA_DESIGNER_SWEATPANTS = 11251;
public static final int REPLICA_PUMPKIN_BUCKET = 11252;
public static final int REPLICA_TEN_DOLLARS = 11253;
public static final int REPLICA_CINCHO_DE_MAYO = 11254;
public static final int MR_STORE_2002_CATALOG = 11257;
public static final int PRO_SKATEBOARD = 11260;
public static final int MEAT_BUTLER = 11262;
public static final int LOATHING_IDOL_MICROPHONE = 11263;
public static final int CHARTER_NELLYVILLE = 11264;
public static final int FLASH_LIQUIDIZER_ULTRA_DOUSING_ACCESSORY = 11266;
public static final int GIANT_BLACK_MONOLITH = 11268;
public static final int SPOOKY_VHS_TAPE = 11270;
public static final int LOATHING_IDOL_MICROPHONE_75 = 11277;
public static final int LOATHING_IDOL_MICROPHONE_50 = 11278;
public static final int LOATHING_IDOL_MICROPHONE_25 = 11279;
public static final int REPLICA_MR_STORE_2002_CATALOG = 11280;
public static final int REPLICA_PATRIOTIC_EAGLE = 11304;
public static final int AUGUST_SCEPTER = 11306;
public static final int FIXODENT = 11312;
public static final int BAYWATCH = 11321;
public static final int POCKET_GUIDE_TO_MILD_EVIL = 11322;
public static final int POCKET_GUIDE_TO_MILD_EVIL_USED = 11323;
public static final int REPLICA_AUGUST_SCEPTER = 11325;
public static final int RESIDUAL_CHITIN_PASTE = 11327;
public static final int BOOK_OF_FACTS = 11333;
public static final int BOOK_OF_FACTS_DOG_EARED = 11334;
public static final int LED_CANDLE = 11336;
public static final int MAP_TO_A_CANDY_RICH_BLOCK = 11337;
public static final int FRANKEN_STEIN = 11339;
public static final int A_GUIDE_TO_BURNING_LEAVES = 11340;
public static final int INFLAMMABLE_LEAF = 11341;
public static final int AUTUMNIC_BOMB = 11344;
public static final int FOREST_CANOPY_BED = 11345;
public static final int DAY_SHORTENER = 11346;
public static final int EXTRA_TIME = 11347;
public static final int AUTUMNAL_AEGIS = 11348;
public static final int DISTILLED_RESIN = 11349;
public static final int SUPER_HEATED_LEAF = 11350;
public static final int LIT_LEAF_LASSO = 11351;
public static final int TIED_UP_LEAFLET = 11352;
public static final int TIED_UP_MONSTERA = 11353;
public static final int TIED_UP_LEAVIATHAN = 11354;
public static final int IMPROMPTU_TORCH = 11355;
public static final int FLAMING_FIG_LEAF = 11356;
public static final int SMOLDERING_DRAPE = 11357;
public static final int SMOLDERING_LEAFCUTTER_ANT_EGG = 11358;
public static final int AUTUMNIC_BALM = 11361;
public static final int COPING_JUICE = 11362;
private ItemPool() {}
public static final AdventureResult get(String itemName, int count) {
int itemId = ItemDatabase.getItemId(itemName, 1, false);
if (itemId != -1) {
return ItemPool.get(itemId, count);
}
return AdventureResult.tallyItem(itemName, count, false);
}
public static final AdventureResult get(int itemId, int count) {
return new AdventureResult(itemId, count, false);
}
public static final AdventureResult get(int itemId) {
return new AdventureResult(itemId, 1, false);
}
// Support for various classes of items:
// El Vibrato helmet
public static final String[] EV_HELMET_CONDUITS =
new String[] {
"ATTACK", "BUILD", "BUFF", "MODIFY", "REPAIR", "TARGET", "SELF", "DRONE", "WALL"
};
public static final List<String> EV_HELMET_LEVELS =
Arrays.asList(
"PA",
"ZERO",
"NOKGAGA",
"NEGLIGIBLE",
"GABUHO NO",
"EXTREMELY LOW",
"GA NO",
"VERY LOW",
"NO",
"LOW",
"FUZEVENI",
"MODERATE",
"PAPACHA",
"ELEVATED",
"FU",
"HIGH",
"GA FU",
"VERY HIGH",
"GABUHO FU",
"EXTREMELY HIGH",
"CHOSOM",
"MAXIMAL");
// BANG POTIONS and SLIME VIALS
public static final String[][] bangPotionStrings = {
// name, combat use mssage, inventory use message
{"inebriety", "wino", "liquid fire"},
{"healing", "better", "You gain"},
{"confusion", "confused", "Confused"},
{"blessing", "stylish", "Izchak's Blessing"},
{"detection", "blink", "Object Detection"},
{"sleepiness", "yawn", "Sleepy"},
{"mental acuity", "smarter", "Strange Mental Acuity"},
{"ettin strength", "stronger", "Strength of Ten Ettins"},
{"teleportitis", "disappearing", "Teleportitis"},
};
public static final String[][][] slimeVialStrings = {
// name, inventory use mssage
{ // primary
{"strong", "Slimily Strong"},
{"sagacious", "Slimily Sagacious"},
{"speedy", "Slimily Speedy"},
},
{ // secondary
{"brawn", "Bilious Brawn"},
{"brains", "Bilious Brains"},
{"briskness", "Bilious Briskness"},
},
{ // tertiary
{"slimeform", "Slimeform"},
{"eyesight", "Ichorous Eyesight"},
{"intensity", "Ichorous Intensity"},
{"muscle", "Mucilaginous Muscle"},
{"mentalism", "Mucilaginous Mentalism"},
{"moxiousness", "Mucilaginous Moxiousness"},
},
};
public static final boolean eliminationProcessor(
final String[][] strings,
final int index,
final int id,
final int minId,
final int maxId,
final String baseName,
final String joiner) {
String effect = strings[index][0];
Preferences.setString(baseName + id, effect);
String name = ItemDatabase.getItemName(id);
String testName = name + joiner + effect;
String testPlural = ItemDatabase.getPluralName(id) + joiner + effect;
ItemDatabase.registerItemAlias(id, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
HashSet<String> possibilities = new HashSet<>();
for (int i = 0; i < strings.length; ++i) {
possibilities.add(strings[i][0]);
}
int missing = 0;
for (int i = minId; i <= maxId; ++i) {
effect = Preferences.getString(baseName + i);
if (effect.equals("")) {
if (missing != 0) {
// more than one missing item in set
return false;
}
missing = i;
} else {
possibilities.remove(effect);
}
}
if (missing == 0) {
// no missing items
return false;
}
if (possibilities.size() != 1) {
// something's screwed up if this happens
return false;
}
effect = possibilities.iterator().next();
Preferences.setString(baseName + missing, effect);
name = ItemDatabase.getItemName(missing);
testName = name + joiner + effect;
testPlural = ItemDatabase.getPluralName(missing) + joiner + effect;
ItemDatabase.registerItemAlias(missing, testName, testPlural);
// Update generic alias too
testName = null;
if (id >= ItemPool.FIRST_BANG_POTION && id <= ItemPool.LAST_BANG_POTION) {
testName = "potion of " + effect;
} else if (id >= ItemPool.FIRST_SLIME_VIAL && id <= ItemPool.LAST_SLIME_VIAL) {
testName = "vial of slime: " + effect;
}
if (testName != null) {
ItemDatabase.registerItemAlias(id, testName, null);
}
return true;
}
// Suggest one or two items from a permutation group that need to be identified.
// Strategy: identify the items the player has the most of first,
// to maximize the usefulness of having identified them.
// If two items remain unidentified, only identify one, since
// eliminationProcessor will handle the other.
public static final void suggestIdentify(
final List<Integer> items, final int minId, final int maxId, final String baseName) {
// Can't autoidentify in G-Lover
if (KoLCharacter.inGLover()) {
return;
}
ArrayList<Integer> possible = new ArrayList<>();
int unknown = 0;
for (int i = minId; i <= maxId; ++i) {
if (!Preferences.getString(baseName + i).equals("")) {
continue; // already identified;
}
++unknown;
AdventureResult item = new AdventureResult(i, 1, false);
int count = item.getCount(KoLConstants.inventory);
if (count <= 0) {
continue; // can't identify yet
}
possible.add(i | Math.min(count, 127) << 24);
}
int count = possible.size();
// Nothing to do if we have no items that qualify
if (count == 0) {
return;
}
if (count > 1) {
possible.sort(Collections.reverseOrder());
}
// Identify the item we have the most of
items.add(possible.get(0) & 0x00FFFFFF);
// If only two items are unknown, that's enough, since the
// other will be identified by eliminationProcessor
if (unknown == 2) {
return;
}
// If we have three or more unknowns, try for a second
if (count > 1) {
items.add(possible.get(1) & 0x00FFFFFF);
}
}
}
| Shiverwarp/kolmafia | src/net/sourceforge/kolmafia/objectpool/ItemPool.java |
733 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.decrypter;
import java.util.ArrayList;
import java.util.HashMap;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporza\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" })
public class DeredactieBe extends PluginForDecrypt {
public DeredactieBe(PluginWrapper wrapper) {
super(wrapper);
}
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
String parameter = param.toString();
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(parameter);
// Link offline
if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {
try {
decryptedLinks.add(this.createOfflinelink(parameter));
} catch (final Throwable t) {
logger.info("Offline Link: " + parameter);
}
}
HashMap<String, String> mediaValue = new HashMap<String, String>();
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {
mediaValue.put(s[0], s[1]);
}
final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src");
if (finalurl == null) {
try {
decryptedLinks.add(this.createOfflinelink(parameter));
} catch (final Throwable t) {
logger.info("Offline Link: " + parameter);
}
return decryptedLinks;
}
if (finalurl.contains("youtube.com")) {
decryptedLinks.add(createDownloadlink(finalurl));
} else {
decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/")));
}
return decryptedLinks;
}
/* NO OVERRIDE!! */
public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) {
return false;
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/decrypter/DeredactieBe.java |
734 | import java.io.*;
import java.util.*;
class Result {
public long dfs(ArrayList<Integer>[] graph, boolean[] vis, int src) {
vis[src] = true;
long count = 0;
for (Integer e : graph[src]) {
if (!vis[e])
count += dfs(graph, vis, e);
}
return count + 1;
}
public long journeyToMoon(ArrayList<Integer>[] graph, int N) {
boolean[] vis = new boolean[N];
ArrayList<Long> population = new ArrayList<>();
for (int i = 0; i < N; i++) {
if (!vis[i]) {
population.add(dfs(graph, vis, i));
}
}
long ans = 0;
long ssf = 0; // sum so far
for (int i = population.size() - 1; i >= 0; i--) {
long ele = population.get(i);
ans += ssf * ele;
ssf += ele;
}
return ans;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
ArrayList<Integer>[] graph = new ArrayList[N];
for (int i = 0; i < N; i++)
graph[i] = new ArrayList<>();
int Edges = scn.nextInt();
for (int i = 0; i < Edges; i++) {
int a = scn.nextInt(), b = scn.nextInt();
graph[a].add(b);
graph[b].add(a);
}
Result obj = new Result();
long ans = obj.journeyToMoon(graph, N);
System.out.println(ans);
}
}
| pankajmahato/pepcoding-Batches | 2020/NIET/graph/journeyToMoon.java |
735 | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2016 Massachusetts Institute of Technology. All rights reserved.
/**
* @fileoverview Dutch (Flanders (Belgium)/the Netherlands) strings.
* @author [email protected] (volunteers from the Flemish Coderdojo Community)
*/
'use strict';
goog.require('Blockly.Msg.nl');
goog.provide('AI.Blockly.Msg.nl');
/**
* Due to the frequency of long strings, the 80-column wrap rule need not apply
* to message files.
*/
Blockly.Msg.nl.switch_language_to_dutch = {
// Switch language to Dutch.
category: '',
helpUrl: '',
init: function() {
Blockly.Msg.LANG_LISTS_LOOKUP_IN_PAIRS_INPUT = 'Zoek op per paar sleutel %1 paren %2 nietGevonden %3';
Blockly.MSG_VARIABLE_CATEGORY = 'Variabelen';
Blockly.Msg.ADD_COMMENT = 'Commentaar toevoegen';
Blockly.Msg.EXPAND_BLOCK = 'Blok uitbreiden';
Blockly.Msg.LANG_CONTROLS_IF_ELSE_TITLE_ELSE = 'anders';
Blockly.Msg.LANG_TEXT_SPLIT_TOOLTIP_SPLIT = 'Verdeelt tekst in stukken met de tekst \'op\' als splitspunt en levert een lijst van de resultaten. \n"één,twee,drie,vier" splitsen op "," (komma) geeft de lijst "(één twee drie vier)" terug. \n"één-aardappel,twee-aardappel,drie-aardappel,vier" splitsen op "-aardappel," geeft ook de lijst "(één twee drie vier)" terug.';
Blockly.Msg.LANG_LISTS_FROM_CSV_TABLE_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_CONTROLS_GET_START_VALUE_TOOLTIP = 'Geeft de waarde terug die was doorgegeven bij het openen van het scherm, meestal door een ander scherm in een app met meerdere schermen. Als er geen waarde was meegegeven, wordt er een lege tekst teruggegeven.';
Blockly.Msg.LANG_LISTS_CREATE_WITH_ITEM_TITLE = 'item';
Blockly.Msg.DELETE_BLOCK = 'Verwijder blok';
Blockly.Msg.LANG_MATH_FORMAT_AS_DECIMAL_TOOLTIP = 'Geeft het nummer terug in decimale notatie\nmet een bepaald aantal getallen achter de komma.';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_OPERATOR_WHILE = 'herhaal tot';
Blockly.Msg.LANG_COLOUR_PINK = 'roze';
Blockly.Msg.CONNECT_TO_DO_IT = 'U moet verbonden zijn met de AI Companion app of emulator om "Doe het" te gebruiken';
Blockly.Msg.LANG_VARIABLES_GET_COLLAPSED_TEXT = 'krijg';
Blockly.Msg.LANG_MATH_TRIG_SIN = 'sin';
Blockly.Msg.LANG_CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = 'ga verder met volgende iteratie';
Blockly.Msg.DISABLE_BLOCK = 'Schakel Blok uit';
Blockly.Msg.REPL_HELPER_Q = 'Helper?';
Blockly.Msg.LANG_TEXT_REPLACE_ALL_INPUT = 'Vervang alle tekst %1 stukje tekst %2 vervangingstekst %3';
Blockly.Msg.LANG_COMPONENT_BLOCK_TITLE_WHEN = 'wanneer';
Blockly.Msg.LANG_COLOUR_CYAN = 'Lichtblauw';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_VALUE_COLLAPSED_TEXT = 'sluit scherm met waarde';
Blockly.Msg.LANG_MATH_TRIG_ASIN = 'asin';
Blockly.Msg.LANG_LISTS_TO_CSV_TABLE_TITLE_TO_CSV = 'lijst naar .csv tabel';
Blockly.Msg.REPL_NOW_DOWNLOADING = 'We downloaden nu een update van de App Inventor server. Even geduld aub.';
Blockly.Msg.LANG_MATH_RANDOM_SEED_TOOLTIP = 'specificeert een numerieke seed waarde\nvoor de willekeurige nummer maker';
Blockly.Msg.LANG_MATH_CONVERT_ANGLES_TITLE_CONVERT = 'zet om';
Blockly.Msg.LANG_MATH_SINGLE_OP_EXP = 'e^';
Blockly.Msg.LANG_TEXT_COMPARE_EQUAL = ' =';
Blockly.Msg.LANG_MATH_SINGLE_TOOLTIP_ROOT = 'Geeft de vierkantswortel van een getal.';
Blockly.Msg.LANG_TEXT_REPLACE_ALL_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_TOOLTIP = 'Voeg items toe aan het einde van een lijst.';
Blockly.Msg.LANG_LISTS_SELECT_ITEM_INPUT_INDEX = 'index';
Blockly.Msg.LANG_TEXT_COMPARE_GT = ' >';
Blockly.Msg.REPL_USB_CONNECTED_WAIT = 'USB verbonden, effe wachten aub';
Blockly.Msg.LANG_VARIABLES_LOCAL_MUTATOR_CONTAINER_TITLE_LOCAL_NAMES = 'lokale namen';
Blockly.Msg.LANG_COLOUR_MAKE_COLOUR = 'maak kleur';
Blockly.Msg.LANG_MATH_DIVIDE = '÷';
Blockly.Msg.LANG_CONTROLS_DO_THEN_RETURN_TOOLTIP = 'Voert alle blokken uit in \'do\' en geeft een statement terug. Handig wanneer je een procedure wil uitvoeren voor een waarde terug te geven aan een variabele.';
Blockly.Msg.COPY_ALLBLOCKS = 'Kopieer alle blokken naar de rugzak';
Blockly.Msg.LANG_TEXT_SPLIT_INPUT_AT_LIST = 'op (lijst)';
Blockly.Msg.LANG_VARIABLES_GLOBAL_DECLARATION_COLLAPSED_TEXT = 'globaal';
Blockly.Msg.LANG_PROCEDURES_MUTATORARG_TITLE = 'invoer:';
Blockly.Msg.LANG_LISTS_LOOKUP_IN_PAIRS_INPUT_NOT_FOUND = 'nietGevonden';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_TOOLTIP = 'Laat je toe variabelen te maken die enkel toegankelijk zijn in het doe deel van dit blok.';
Blockly.Msg.REPL_PLUGGED_IN_Q = 'Aangesloten?';
Blockly.Msg.LANG_PROCEDURES_MUTATORCONTAINER_TOOLTIP = '';
Blockly.Msg.HORIZONTAL_PARAMETERS = 'Rangschik eigenschappen horizontaal';
Blockly.Msg.LANG_LISTS_IS_LIST_TITLE_IS_LIST = 'is een lijst?';
Blockly.Msg.LANG_PROCEDURES_MUTATORCONTAINER_TITLE = 'invoer';
Blockly.Msg.LANG_MATH_RANDOM_INT_INPUT_FROM = 'van';
Blockly.Msg.LANG_LISTS_APPEND_LIST_TITLE_APPEND = 'voeg toe aan lijst';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_COLLAPSED_SUFFIX = ' binnen bereik';
Blockly.MSG_NEW_VARIABLE_TITLE = 'Nieuwe variabelenaam:';
Blockly.Msg.VERTICAL_PARAMETERS = 'Rangschik eigenschappen horizontaal';
Blockly.Msg.LANG_TEXT_SEGMENT_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_PROCEDURES_DOTHENRETURN_RETURN = 'resultaat';
Blockly.Msg.LANG_LISTS_REPLACE_ITEM_TITLE_REPLACE = 'vervang element in de lijst';
Blockly.Msg.LANG_TEXT_SPLIT_TOOLTIP_SPLIT_AT_ANY = 'Verdeelt de gegeven tekst in een lijst, waarbij elk element in de lijst \'\'op\'\' als het\nverdeelpunt, en geeft een lijst terug van het resultaat. \nSplitsen van "sinaasappel,banaan,appel,hondenvoer" met als "op" een lijst van 2 elementen met als eerste \nelement een komma en als tweede element "pel" geeft een lijst van 4 elementen: \n"(sinaasap banaan ap hondenvoer)".';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_EXPRESSION_IN_RETURN = 'in';
Blockly.Msg.DO_IT = 'Voer uit';
Blockly.Msg.LANG_MATH_SINGLE_OP_ABSOLUTE = 'absoluut';
Blockly.Msg.LANG_TEXT_STARTS_AT_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_PROCEDURES_CALLNORETURN_TRANSLATED_NAME = 'functie die niets teruggeeft';
Blockly.Msg.LANG_TEXT_CONTAINS_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_CONTROLS_WHILE_TOOLTIP = 'Voert de blokken in het \'doe\'-gedeelte uit zolang de test waar is.';
Blockly.Msg.BACKPACK_DOCUMENTATION = 'De Rugzak is een knip/plak functie. Het laat toe om blokken te kopieren van een project of scherm en ze in een ander scherm of project te plakken. Om te kopieren sleep je de blokken in de rugzak. Om te plakken klik je op het Rugzak icoon en sleep je de blokken in de werkplaats.</p><p> De inhoud van de Rugzak blijft behouden tijdens de ganse App Inventor sessie. Als je de App Inventor dicht doet, of als je je browser herlaadt, wordt de Rugzak leeggemaakt.</p><p>Voor meer info en een video, bekijk:</p><p><a href="http://ai2.appinventor.mit.edu/reference/other/backpack.html" target="_blank">http://ai2.appinventor.mit.edu/reference/other/backpack.html</a>';
Blockly.Msg.LANG_MATH_TRIG_ATAN2 = 'atan2';
Blockly.Msg.LANG_PROCEDURES_CALLRETURN_COLLAPSED_PREFIX = 'aanroep ';
Blockly.Msg.LANG_CONTROLS_DO_THEN_RETURN_INPUT_DO = 'doe';
Blockly.Msg.LANG_CONTROLS_IF_MSG_ELSEIF = 'of als';
Blockly.Msg.LANG_CONTROLS_DO_THEN_RETURN_INPUT_RETURN = 'resultaat';
Blockly.Msg.LANG_PROCEDURES_CALLRETURN_CALL = 'roep aan';
Blockly.Msg.LANG_TEXT_SPLIT_AT_SPACES_TITLE = 'splits bij spaties';
Blockly.Msg.LANG_LISTS_FROM_CSV_ROW_TITLE_FROM_CSV = 'lijst van .csv rij';
Blockly.Msg.LANG_VARIABLES_LOCAL_MUTATOR_ARG_DEFAULT_VARIABLE = 'x';
Blockly.Msg.REPL_CONNECTION_FAILURE1 = 'Verbindingsfout';
Blockly.Msg.LANG_TEXT_SPLIT_TOOLTIP_SPLIT_AT_FIRST_OF_ANY = 'Splitst een gegeven tekst in een lijst met twee elementen. De eerste plaats van eender welk item in de lijst "aan" is het \'\'splitsingspunt\'\'. \n\nBijvoorbeeld als je "Ik hou van appels, bananen en ananas" splitst volgens de lijst "(ba,ap)", dan geeft dit \neen lijst van 2 elementen terug. Het eerste item is "Ik hou van" en het tweede item is \n"pels, bananen en ananas."';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_TITLE = 'open een ander scherm';
Blockly.Msg.LANG_LISTS_IS_LIST_INPUT_THING = 'ding';
Blockly.Msg.LANG_LISTS_CREATE_WITH_CONTAINER_TOOLTIP = 'Voeg toe, verwijder of verander de volgorde van de secties om dit lijst blok opnieuw te configureren. ';
Blockly.Msg.LANG_MATH_COMPARE_TOOLTIP_GTE = 'Geef waar terug als het eerste getal groter is\ndan of gelijk aan het tweede getal.';
Blockly.Msg.LANG_CONTROLS_FOR_TOOLTIP = 'Tel van een start- tot een eindnummer.\nZet het huidige nummer, voor iedere tel, op\nvariabele "%1", en doe erna een aantal dingen.';
Blockly.Msg.LANG_LISTS_REPLACE_ITEM_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_MATH_RANDOM_FLOAT_TOOLTIP = 'Geef een willekeurig getal tussen 0 en 1 terug.';
Blockly.Msg.LANG_MATH_RANDOM_INT_INPUT_TO = 'tot';
Blockly.Msg.LANG_VARIABLES_VARIABLE = ' variabele';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_CONTAINER_TITLE_ADD = 'lijst';
Blockly.Msg.WARNING_DELETE_X_BLOCKS = 'Weet u zeker dat u alle %1 van deze blokken wilt verwijderen?';
Blockly.Msg.LANG_TEXT_JOIN_ITEM_TOOLTIP = '';
Blockly.Msg.LANG_LISTS_INSERT_INPUT_ITEM = 'item';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_TITLE = 'sluit scherm';
Blockly.Msg.LANG_TEXT_COMPARE_TOOLTIP_EQUAL = 'Test of stukken tekst identiek zijn, of ze dezelfde karakters hebben\n in dezelfde volgorde. Dit verschilt van de normale=\nin het geval waarin de stukken tekst getallen zijn: 123 en 0123 zijn=\nmaar niet tekst =.';
Blockly.Msg.LANG_MATH_ROUND_TOOLTIP_ROUND = 'Rond een nummer af naar boven of beneden.';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_END = 'tot';
Blockly.Msg.LANG_COLOUR_ORANGE = 'oranje';
Blockly.Msg.REPL_STARTING_COMPANION_IN_EMULATOR = 'AI Companion App wordt opgestart in de emulator.';
Blockly.Msg.LANG_MATH_COMPARE_LT = '<';
Blockly.Msg.LANG_MATH_SINGLE_TOOLTIP_ABS = 'Geef de absolute waarde van een getal terug.';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_INPUT_ITEM = 'item';
Blockly.ERROR_SELECT_VALID_ITEM_FROM_DROPDOWN = 'Selecteer een geldig item uit de drop down.';
Blockly.Msg.LANG_MATH_ONLIST_OPERATOR_MAX = 'max';
Blockly.Msg.LANG_MATH_CONVERT_ANGLES_OP_DEG_TO_RAD = 'graden naar radialen';
Blockly.Msg.LANG_CONTROLS_GET_PLAIN_START_TEXT_TOOLTIP = 'Geeft de platte tekst terug die doorgegeven werd toen dit scherm werd gestart door een andere app. Als er geen waarde werd doorgegeven, geeft deze functie een lege tekst terug. Voor multischerm apps, gebruik dan neem start waarde in plaats van neem platte start tekst.';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_ITEM = 'voor elk';
Blockly.Msg.BACKPACK_DOC_TITLE = 'Rugzak informatie';
Blockly.Msg.LANG_TEXT_JOIN_TITLE_JOIN = 'samenvoegen';
Blockly.Msg.LANG_TEXT_LENGTH_TOOLTIP = 'Geeft het aantal letters (inclusief spaties)\nterug in de meegegeven tekst.';
Blockly.Msg.LANG_CONTROLS_IF_IF_TOOLTIP = 'Voeg toe, verwijder of verander de volgorde van de secties\nom dit blok opnieuw te configureren.';
Blockly.Msg.REPL_COMPANION_OUT_OF_DATE1 = 'De AI Companion die je op je smartphone gebruikt, is verouderd.<br/><br/>Deze versie van de App Inventor moet gebruikt worden met Companion versie';
Blockly.Msg.LANG_TEXT_CHANGECASE_OPERATOR_UPPERCASE = 'hoofdletters';
Blockly.Msg.LANG_MATH_ARITHMETIC_ADD = '+';
Blockly.Msg.REPL_COMPANION_VERSION_CHECK = 'Versie controle van de AI Companion';
Blockly.Msg.LANG_PROCEDURES_DEFRETURN_TOOLTIP = 'Een procedure die een resultaat teruggeeft.';
Blockly.Msg.LANG_MATH_TRIG_ATAN2_X = 'x';
Blockly.Msg.EXPAND_ALL = 'Blok uitbreiden';
Blockly.MSG_CHANGE_VALUE_TITLE = 'Wijzig waarde:';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_TOOLTIP = 'Opent een nieuw scherm in een app met meerdere schermen.';
Blockly.Msg.LANG_TEXT_ISEMPTY_TOOLTIP = 'Geeft waar terug als de lengte van de\ntekst gelijk is aan 0, anders wordt niet waar teruggegeven.';
Blockly.Msg.LANG_VARIABLES_SET_COLLAPSED_TEXT = 'ingesteld';
Blockly.Msg.LANG_MATH_RANDOM_FLOAT_TITLE_RANDOM = 'willekeurig deel';
Blockly.Msg.LANG_COLOUR_BLUE = 'blauw';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = 'tot';
Blockly.Msg.LANG_VARIABLES_GET_TITLE_GET = 'krijg';
Blockly.Msg.REPL_APPROVE_UPDATE = ' scherm omdat je gevraagd gaat worden om een update goed te keuren.';
Blockly.Msg.LANG_TEXT_TRIM_TOOLTIP = 'Geeft een kopie terug van de tekst argumenten met elke\nspatie vooraan en achteraan verwijderd.';
Blockly.Msg.REPL_EMULATORS = 'emulators';
Blockly.Msg.LANG_MATH_IS_A_NUMBER_INPUT_NUM = 'is een getal?';
Blockly.Msg.LANG_PROCEDURES_DEFRETURN_COLLAPSED_PREFIX = 'to ';
Blockly.Msg.LANG_LISTS_SELECT_ITEM_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_TEXT_COMPARE_INPUT_COMPARE = 'vergelijk teksten';
Blockly.Msg.LANG_MATH_NUMBER_TOOLTIP = 'Rapporteer het getoonde getal.';
Blockly.Msg.LANG_TEXT_COMPARE_LT = ' <';
Blockly.Msg.LANG_LISTS_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_LISTS_REMOVE_ITEM_TOOLTIP = 'Verwijdert het element op de gegeven positie uit de lijst.';
Blockly.Msg.LANG_LISTS_IS_IN_TITLE_IS_IN = 'staat in een lijst?';
Blockly.Msg.LANG_MATH_ROUND_TOOLTIP_CEILING = 'Rond de input af tot het kleinste\ngetal dat niet kleiner is dan de input';
Blockly.Msg.LANG_COLOUR_YELLOW = 'geel';
Blockly.Msg.LANG_MATH_ROUND_TOOLTIP_FLOOR = 'Rond de input af tot het grootste\ngetal dat niet groter is dan de input';
Blockly.Msg.LANG_MATH_DIVIDE_TOOLTIP_MODULO = 'Geeft de gehele deling terug.';
Blockly.Msg.LANG_TEXT_JOIN_ITEM_TITLE_ITEM = 'tekst';
Blockly.Msg.LANG_PROCEDURES_CALLNORETURN_PROCEDURE = 'procedure';
Blockly.Msg.LANG_CONTROLS_IF_MSG_ELSE = 'anders';
Blockly.Msg.LANG_TEXT_STARTS_AT_TOOLTIP = 'Geeft de beginpositie terug van het stukje in de tekst\nwaar index 1 het begin van de tekst aangeeft. Geeft 0 terug wanneer\nhet stuk tekst niet voorkomt.';
Blockly.Msg.SORT_W = 'Sorteer blokken op breedte';
Blockly.Msg.ENABLE_BLOCK = 'Schakel blok aan';
Blockly.Msg.LANG_CONTROLS_EVAL_BUT_COLLAPSED_TEXT = 'evalueer maar negeer';
Blockly.Msg.LANG_MATH_ARITHMETIC_TOOLTIP_ADD = 'Geeft de som van twee getallen terug.';
Blockly.Msg.LANG_LISTS_POSITION_IN_INPUT = 'index in lijst item %1 lijst %2';
Blockly.Msg.REPL_SECONDS_ENSURE_RUNNING = ' seconden om er zeker van te zijn dat alles draait.';
Blockly.Msg.REPL_NO_ERROR_FIVE_SECONDS = '<br/><i>Merk op:</i> ,Je zal geen andere foutmeldingen zien gedurende de volgende 5 seconden.';
Blockly.Msg.LANG_LOGIC_NEGATE_INPUT_NOT = 'niet';
Blockly.Msg.LANG_PROCEDURES_DEFRETURN_PROCEDURE = 'procedure';
Blockly.Msg.LANG_CATEGORY_CONTROLS = 'Bediening';
Blockly.Msg.LANG_COLOUR_MAGENTA = 'magenta';
Blockly.Msg.LANG_LISTS_IS_IN_TOOLTIP = 'Geeft waar terug als het ding een item is dat in de lijst zit, anders wordt onwaar teruggegeven.';
Blockly.Msg.LANG_LISTS_REPLACE_ITEM_INPUT = 'vervang lijst item lijst %1 index %2 vervanging %3';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_TOOLTIP_DEC_TO_BIN = 'Neemt een positief geheel decimaal getal en geeft de tekst weer die dat getal voorstelt in binair';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_OP_HEX_TO_DEC = 'hex naar dec';
Blockly.Msg.LANG_LOGIC_COMPARE_NEQ = '≠';
Blockly.Msg.LANG_VARIABLES_GLOBAL_DECLARATION_NAME = 'naam';
Blockly.MSG_NEW_VARIABLE = 'Nieuwe variabele ...';
Blockly.Msg.LANG_LOGIC_OPERATION_TOOLTIP_OR = 'Geef waar terug als de invoer waar is.';
Blockly.Msg.LANG_VARIABLES_LOCAL_MUTATOR_CONTAINER_TOOLTIP = '';
Blockly.Msg.LANG_TEXT_CONTAINS_INPUT_CONTAINS = 'bevat';
Blockly.Msg.LANG_LISTS_REMOVE_ITEM_INPUT = 'verwijder lijstitem lijst %1 index %2';
Blockly.Msg.LANG_TEXT_SEGMENT_INPUT = 'segment tekst %1 start %2 lengte %3';
Blockly.Msg.LANG_LISTS_LENGTH_INPUT = 'lengte van de lijst lijst %1';
Blockly.Msg.LANG_TEXT_CONTAINS_TOOLTIP = 'Test of het stukje voorkomt in de tekst.';
Blockly.Msg.LANG_MATH_CONVERT_ANGLES_TOOLTIP_RAD_TO_DEG = 'Geeft de graden terug tussen\n(0,360) die overeenkomt met het argument in radialen.';
Blockly.Msg.LANG_LISTS_REMOVE_ITEM_INPUT_INDEX = 'index';
Blockly.Msg.LANG_CONTROLS_GET_PLAIN_START_TEXT_COLLAPSED_TEXT = 'Neem platte start tekst';
Blockly.Msg.LANG_LISTS_POSITION_IN_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_TEXT_REPLACE_ALL_INPUT_SEGMENT = 'segment';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_INPUT_LIST = ' lijst';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_COLLAPSED_PREFIX = 'voor ';
Blockly.Msg.LANG_MATH_TRIG_TAN = 'tan';
Blockly.Msg.LANG_MATH_TRIG_ATAN = 'atan';
Blockly.Msg.LANG_MATH_RANDOM_SEED_INPUT_TO = 'tot';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_COLLAPSED_TEXT = 'lokaal';
Blockly.Msg.LANG_PROCEDURES_DOTHENRETURN_DO = 'doe';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = 'Terwijl een waarde onwaar is, doe enkele andere stappen.';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_VALUE_INPUT_RESULT = 'resultaat';
Blockly.Msg.LANG_MATH_CONVERT_ANGLES_OP_RAD_TO_DEG = 'radialen naar graden';
Blockly.Msg.LANG_LISTS_SELECT_ITEM_TITLE_SELECT = 'kies een item uit de lijst';
Blockly.Msg.LANG_CATEGORY_TEXT = 'Tekst';
Blockly.Msg.LANG_LISTS_APPEND_LIST_INPUT = 'voeg toe aan lijst lijst1 %1 lijst2 %2';
Blockly.Msg.LANG_COLOUR_SPLIT_COLOUR = 'splits kleur';
Blockly.Msg.LANG_CONTROLS_IF_MSG_IF = 'als';
Blockly.Msg.LANG_PROCEDURES_CALLRETURN_TOOLTIP = 'Roep een procedure op die iets teruggeeft.';
Blockly.Msg.LANG_MATH_ROUND_OPERATOR_ROUND = 'rond af';
Blockly.Msg.REPL_DISMISS = 'Negeer';
Blockly.Msg.LANG_LISTS_REPLACE_ITEM_TOOLTIP = 'Vervangt het n\'de item in een lijst.';
Blockly.Msg.LANG_TEXT_COMPARE_TOOLTIP_GT = 'Geeft aan of tekst1 lexicologisch groter is dan tekst2.\nAls een tekst het eerste deel is van de andere, dan wordt de kortere tekst aanzien als kleiner.\nHoofdletters hebben voorrang op kleine letters.';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_VAR = 'item';
Blockly.Msg.LANG_CONTROLS_FOR_INPUT_TO = 'tot';
Blockly.Msg.LANG_COLOUR_RED = 'rood';
Blockly.Msg.LANG_VARIABLES_SET_TITLE_TO = 'tot';
Blockly.Msg.LANG_LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = 'lijst';
Blockly.Msg.REPL_KEEP_TRYING = 'Blijf Proberen';
Blockly.Msg.LANG_LISTS_CREATE_WITH_TITLE_MAKE_LIST = 'maak een lijst';
Blockly.Msg.LANG_MATH_ROUND_OPERATOR_CEILING = 'afrondenNaarBoven';
Blockly.Msg.LANG_COMPONENT_BLOCK_GENERIC_SETTER_TITLE_SET = 'zet';
Blockly.Msg.EXTERNAL_INPUTS = 'Externe ingangen';
Blockly.Msg.LANG_LISTS_LOOKUP_IN_PAIRS_INPUT_PAIRS = 'paren';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_WITH_START_VALUE_TITLE = 'open ander scherm met startwaarde';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_TOOLTIP_HEX_TO_DEC = 'Neemt een tekst die een hexadecimaal getal voorstelt en geeft een tekst terug die dat nummer voorstelt als decimaal getal.';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_SIN = 'Geeft de sinus van de gegeven hoek (in graden).';
Blockly.Msg.REPL_GIVE_UP = 'Opgeven';
Blockly.Msg.LANG_CATEGORY_LOGIC = 'Logica';
Blockly.Msg.LANG_LISTS_COPY_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_LISTS_INSERT_INPUT = 'voeg lijstitem toe lijst %1 index %2 item %3';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_TOOLTIP_DEC_TO_HEX = 'Neemt een positief decimaal getal en geeft een tekst terug die dat getal voorstelt in hexadecimale notatie.';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_START = 'van';
Blockly.Msg.LANG_CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = 'breek uit';
Blockly.Msg.LANG_LISTS_FROM_CSV_ROW_TOOLTIP = 'Ontleedt een tekst als een CSV (d.i. door komma\'s gescheiden waarde) opgemaakte rij om een lijst met velden te produceren. Als de rij tekst meerdere onbeschermde nieuwe regels (meerdere lijnen) bevat in de velden, krijg je een foutmelding. Je moet de rij tekst laten eindigen in een nieuwe regel of CRLF.';
Blockly.Msg.LANG_MATH_ARITHMETIC_TOOLTIP_POWER = 'Geeft het eerste getal verheven tot\nde macht van het tweede getal.';
Blockly.Msg.LANG_LISTS_FROM_CSV_ROW_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_VARIABLES_SET_TITLE_SET = 'zet';
Blockly.Msg.LANG_COMPONENT_BLOCK_TITLE_DO = 'doe';
Blockly.Msg.LANG_TEXT_SPLIT_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_COLOUR_GRAY = 'grijs';
Blockly.Msg.REPL_NETWORK_ERROR_RESTART = 'Netwerk Communicatie Fout met de AI Companion. <br />Probeer eens de smartphone te herstarten en opnieuw te connecteren.';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_DO = 'doe';
Blockly.Msg.LANG_LISTS_PICK_RANDOM_TITLE_PICK_RANDOM = 'kies een willekeurig item';
Blockly.Msg.LANG_TEXT_COMPARE_TOOLTIP_LT = 'Controleert of tekst1 lexicografisch kleiner is dan text2. \ NAls een stuk tekst het voorvoegsel is van de andere, dan wordt de kortere tekst \ nals kleiner beschouwd. Kleine letters worden voorafgegaan door hoofdletters.';
Blockly.Msg.LANG_TEXT_APPEND_APPENDTEXT = 'voeg tekst toe';
Blockly.Msg.REPL_CANCEL = 'Annuleren';
Blockly.Msg.LANG_CATEGORY_MATH = 'Wiskunde';
Blockly.Msg.LANG_TEXT_TEXT_OBSFUCATE_TOOLTIP = 'Produceert tekst, zoals een tekstblok. Het verschil is dat de \ntekst niet gemakkelijk te detecteren is door de APK van de app te onderzoeken. Gebruik deze functie daarom bij het maken van apps \n die vertrouwelijke informatie bevatten, zoals API sleutels. \nWaarschuwing: tegen complexe security-aanvallen biedt deze functie slechts een zeer lage bescherming.';
Blockly.Msg.SORT_C = 'Sorteer blokken op categorie';
Blockly.Msg.LANG_CONTROLS_WHILE_INPUT_DO = 'doe';
Blockly.Msg.LANG_LISTS_SELECT_ITEM_TOOLTIP = 'Geeft het item op positie index in de lijst.';
Blockly.Msg.LANG_LISTS_IS_IN_INPUT_THING = 'ding';
Blockly.Msg.LANG_LISTS_LENGTH_INPUT_LENGTH = 'lengte van de lijst';
Blockly.Msg.LANG_VARIABLES_LOCAL_MUTATOR_ARG_TITLE_NAME = 'naam';
Blockly.Msg.LANG_MATH_FORMAT_AS_DECIMAL_TITLE = 'maak op als decimaal';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = 'Zolang een waarde waar is, do dan enkele regels code.';
Blockly.Msg.LANG_LISTS_CREATE_EMPTY_TITLE = 'maak lege lijst';
Blockly.Msg.LANG_MATH_ARITHMETIC_POWER = '^';
Blockly.Msg.LANG_LISTS_IS_IN_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_CONTROLS_EVAL_BUT_IGNORE_TOOLTIP = 'Voert het aangesloten blok code uit en negeert de return waarde (indien aanwezig). Deze functie is handig wanneer je een procedure wil aanroepen die een return waarde heeft, zonder dat je die waarde zelf nodig hebt.';
Blockly.Msg.LANG_LISTS_CREATE_WITH_TOOLTIP = 'Maak een lijst met een bepaald aantal items.';
Blockly.ERROR_DUPLICATE_EVENT_HANDLER = 'Dit een een copy van een signaalafhandelaar voor deze component.';
Blockly.Msg.LANG_MATH_TRIG_COS = 'cos';
Blockly.Msg.BACKPACK_CONFIRM_EMPTY = 'Weet u zeker dat u de rugzak wil ledigen?';
Blockly.Msg.LANG_LISTS_IS_EMPTY_TOOLTIP = 'Geeft \'waar\' terug als de lijst leeg is.';
Blockly.Msg.LANG_PROCEDURES_CALLRETURN_TRANSLATED_NAME = 'oproep weergave';
Blockly.Msg.LANG_LISTS_REMOVE_ITEM_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_MATH_SINGLE_TOOLTIP_LN = 'Teruggave van het natuurlijke logaritme van een getal, d.w.z. het logaritme met het grondtal e (2,71828 ...)';
Blockly.Msg.LANG_TEXT_CHANGECASE_TOOLTIP_UPPERCASE = 'Geeft een kopie van de meegegeven tekst omgezet in hoofdletters.';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_CONTAINER_TOOLTIP = 'Toevoegen, verwijderen of herschikken van secties om dit lijstblok te herconfigureren.';
Blockly.Msg.LANG_COLOUR_DARK_GRAY = 'donkergrijs';
Blockly.Msg.ARRANGE_H = 'Rangschik blokken horizontaal';
Blockly.Msg.LANG_CONTROLS_IF_ELSEIF_TITLE_ELSEIF = 'anders als';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_VALUE_TOOLTIP = 'Sluit het huidig scherm en geeft een resultaat terug aan het scherm dat deze opende.';
Blockly.Msg.LANG_CONTROLS_IF_TOOLTIP_4 = 'Als de eerste waarde \'waar\' is, voer dan het eerste blok met opdrachten uit.\nAnders, als de tweede waarde \'waar\' is, voer dan het tweede blok met opdrachten uit.\nAls geen van de waarden \'waar\' is, voer dan het laatste blok met opdrachten uit.';
Blockly.Msg.REPL_NETWORK_CONNECTION_ERROR = 'Fout netwerkverbinding';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_COLLAPSED_SUFFIX = ' in lijst';
Blockly.Msg.LANG_LISTS_IS_IN_INPUT = 'is in lijst? item %1 lijst %2';
Blockly.Msg.LANG_COMPONENT_BLOCK_GENERIC_METHOD_TITLE_CALL = 'aanroep ';
Blockly.Msg.LANG_CONTROLS_FOR_INPUT_VAR = 'x';
Blockly.Msg.LANG_MATH_IS_A_DECIMAL_INPUT_NUM = 'is decimaal?';
Blockly.Msg.LANG_COLOUR_SPLIT_COLOUR_TOOLTIP = 'Een lijst van vier elementen, elk op een schaal van 0 tot 255, die de rode, groene, blauwe en alfa componenten voorstellen.';
Blockly.Msg.LANG_CONTROLS_EVAL_BUT_IGNORE_TITLE = 'evalueer maar negeer het resultaat';
Blockly.Msg.LANG_LISTS_TO_CSV_ROW_INPUT_LIST = 'lijst';
Blockly.Msg.CAN_NOT_DO_IT = 'Kan dit niet doen';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_TRANSLATED_NAME = 'initialiseer lokale variable in doe';
Blockly.Msg.LANG_TEXT_TEXT_LEFT_QUOTE = '“';
Blockly.Msg.LANG_CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = 'Sla de rest van deze loop over en \n begin met de volgende iteratie.';
Blockly.Msg.LANG_CONTROLS_FOR_INPUT_FROM = 'van';
Blockly.Msg.COPY_TO_BACKPACK = 'Voeg toe aan rugzak';
Blockly.Msg.LANG_CONTROLS_GET_START_VALUE_INPUT_SCREENNAME = 'schermNaam';
Blockly.Msg.LANG_TEXT_ISEMPTY_INPUT_ISEMPTY = 'is leeg';
Blockly.Msg.LANG_TEXT_SPLIT_OPERATOR_SPLIT_AT_ANY = 'splits bij elk';
Blockly.Msg.EXPORT_IMAGE = 'Download blokken als afbeelding';
Blockly.Msg.REPL_GOT_IT = 'Begrepen';
Blockly.Msg.LANG_COLOUR_MAKE_COLOUR_TOOLTIP = 'Een kleur met de gegeven rood, groen, blauw en optionele alfa componenten.';
Blockly.Msg.LANG_LISTS_TITLE_IS_EMPTY = 'is de lijst leeg?';
Blockly.Msg.LANG_MATH_SINGLE_OP_NEG = 'negatief';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_WITH_START_VALUE_INPUT_SCREENNAME = 'schermNaam';
Blockly.Msg.LANG_COMPONENT_BLOCK_SETTER_TITLE_SET = 'stel in';
Blockly.Msg.INLINE_INPUTS = 'Inlijn invulveld';
Blockly.Msg.LANG_LISTS_INSERT_TOOLTIP = 'Voeg een element toe op een specifieke plaats in een lijst.';
Blockly.Msg.REPL_CONNECTING = 'Verbinden ...';
Blockly.Msg.LANG_LISTS_LOOKUP_IN_PAIRS_TOOLTIP = 'Geeft de waarde terug die hoort bij de sleutel in een lijst van paren';
Blockly.Msg.LANG_MATH_SINGLE_TOOLTIP_NEG = 'Geeft het negatief van een getal.';
Blockly.Msg.REPL_UNABLE_TO_LOAD = 'Opladen naar de App Inventor server mislukt';
Blockly.Msg.LANG_LISTS_COPY_TOOLTIP = 'Maakt een kopie van een lijst. Sublijsten worden ook gekopieerd';
Blockly.Msg.LANG_LOGIC_BOOLEAN_TOOLTIP_TRUE = 'Geeft de booleaanse waar terug.';
Blockly.Msg.LANG_TEXT_TEXT_OBSFUCATE = 'Onleesbaar gemaakte Tekst';
Blockly.Msg.LANG_TEXT_TEXT_TOOLTIP = 'Een tekst.';
Blockly.Msg.LANG_LISTS_SELECT_ITEM_INPUT = 'Selecteer een element uit lijst %1 index %2';
Blockly.Msg.REPL_DO_YOU_REALLY_Q = 'Wil Je Dit Echt? Echt echt?';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_EXPRESSION_TOOLTIP = 'Laat je toe om variabelen te maken die je alleen kan gebruiken in het deel van dit blok dat iets teruggeeft.';
Blockly.Msg.LANG_VARIABLES_GLOBAL_DECLARATION_TITLE_INIT = 'Initializeer globaal';
Blockly.Msg.LANG_MATH_IS_A_HEXADECIMAL_INPUT_NUM = 'is hexadecimaal?';
Blockly.Msg.LANG_MATH_DIVIDE_TOOLTIP_QUOTIENT = 'Berekent het quotient.';
Blockly.Msg.LANG_MATH_IS_A_BINARY_INPUT_NUM = 'is binair?';
Blockly.Msg.LANG_CONTROLS_FOREACH_TOOLTIP = 'Voert de blokken in het \'doe\' deel uit voor elk element van de lijst. Gebruik de opgegeven naam van de variabele om te verwijzen naar het huidige element.';
Blockly.Msg.LANG_TEXT_REPLACE_ALL_INPUT_REPLACEMENT = 'vervanging';
Blockly.Msg.LANG_TEXT_TEXT_RIGHT_QUOTE = '”';
Blockly.Msg.LANG_CONTROLS_IF_MSG_THEN = 'dan';
Blockly.Msg.LANG_CONTROLS_WHILE_TITLE = 'herhaal tot';
Blockly.Msg.LANG_MATH_COMPARE_GT = '>';
Blockly.Msg.LANG_MATH_IS_A_DECIMAL_TOOLTIP = 'Test of iets een string is die een positief integraal grondgetal 10 voorstelt.';
Blockly.Msg.LANG_MATH_MUTATOR_ITEM_INPUT_NUMBER = 'getal';
Blockly.Msg.LANG_LISTS_ADD_ITEM_TOOLTIP = 'Voeg een item toe aan de lijst.';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_IN_DO = 'in';
Blockly.Msg.LANG_MATH_COMPARE_TOOLTIP_LT = 'Geeft Waar terug als het eerste nummer\nkleiner is dan het tweede nummer.';
Blockly.Msg.LANG_COLOUR_BLACK = 'zwart';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_PLAIN_TEXT_TOOLTIP = 'Sluit het huidige scherm af en geeft de tekst terug aan de app die dit scherm geopend heeft. Deze functie is bedoeld om tekst te retourneren aan activiteiten die niet gerelateerd zijn aan App Inventor en niet om naar App Inventor schermen terug te keren. Voor App Inventor apps met meerdere schermen, gebruik de functie Sluit Scherm met Waarde, niet Sluit Scherm met Gewone Tekst.';
Blockly.Msg.REPL_COMPANION_OUT_OF_DATE = 'Jouw Companion App is te oud. Klik "OK" om bijwerken te starten. Bekijk jouw ';
Blockly.Msg.LANG_LOGIC_OPERATION_TOOLTIP_AND = 'Geef Waar terug als alle invoer Waar is.';
Blockly.Msg.REPL_NO_START_EMULATOR = 'Het is niet gelukt de MIT AI Companion te starten in de Emulator';
Blockly.Msg.LANG_CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = 'Breek uit de omliggende lus.';
Blockly.Msg.LANG_MATH_COMPARE_TOOLTIP_EQ = 'Geef Waar terug als beide getallen gelijk zijn aan elkaar.';
Blockly.Msg.LANG_LOGIC_OPERATION_AND = 'en';
Blockly.Msg.LANG_TEXT_SPLIT_TOOLTIP_SPLIT_AT_FIRST = 'Verdeelt de opgegeven tekst in twee delen en gebruikt hiervoor de plaats het eerste voorkomen \nvan de tekst \'aan\' als splitser, en geeft een lijst met twee elementen terug. Deze lijst bestaat \nuit het deel voor de splitser en het deel achter de splitser. \nHet splitsen van "appel,banaan,kers,hondeneten" met als een komma als splitser geeft een lijst \nterug met twee elementen: het eerste is de tekst "appel" en het tweede is de tekst \n"banaan,kers,hondeneten". \nMerk op de de komma achter "appel\' niet in het resultaat voorkomt, omdat dit de splitser is.';
Blockly.Msg.LANG_PROCEDURES_DOTHENRETURN_COLLAPSED_TEXT = 'doe/resultaat';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_OP_BIN_TO_DEC = 'binair naar decimaal';
Blockly.Msg.LANG_CONTROLS_IF_ELSE_TOOLTIP = 'Voeg een finaal, vang-alles-op conditie toe aan het als blok.';
Blockly.Msg.GENERATE_YAIL = 'Genereer Yail';
Blockly.Msg.LANG_LOGIC_COMPARE_TRANSLATED_NAME = 'logische is gelijk';
Blockly.Msg.LANG_TEXT_CHANGECASE_TOOLTIP_DOWNCASE = 'Geeft een kopie terug van de tekst in kleine letters.';
Blockly.Msg.LANG_TEXT_LENGTH_INPUT_LENGTH = 'lengte';
Blockly.Msg.LANG_LISTS_POSITION_IN_INPUT_THING = 'ding';
Blockly.Msg.LANG_MATH_DIVIDE_OPERATOR_QUOTIENT = 'quotiënt van';
Blockly.Msg.LANG_MATH_COMPARE_TOOLTIP_NEQ = 'Geef Waar terug als beide getallen niet gelijk zijn aan elkaar.';
Blockly.Msg.DELETE_X_BLOCKS = 'Verwijder %1 blokken';
Blockly.Msg.LANG_MATH_DIVIDE_OPERATOR_MODULO = 'rest van';
Blockly.Msg.LANG_TEXT_STARTS_AT_INPUT = 'start op tekst %1 stuk %2';
Blockly.Msg.BACKPACK_EMPTY = 'Maak de Rugzak leeg';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_INLIST = 'in lijst';
Blockly.Msg.LANG_PROCEDURES_DOTHENRETURN_TOOLTIP = 'Voert de blokken in \'\'doe\'\' uit en geeft een statement terug. Handig als je een procedure wil uitvoeren alvorens een waarde terug te geven aan een variabele.';
Blockly.Msg.LANG_CONTROLS_FORRANGE_TOOLTIP = 'Voert de blokken in de \'doe\' sectie uit voor elke numerieke waarde van begin tot eind, telkens verdergaand met de volgende waarde. Gebruik de gegeven naam van de variabele om te verwijzen naar de actuele waarde.';
Blockly.Msg.LANG_LISTS_REMOVE_ITEM_TITLE_REMOVE = 'verwijder lijst item';
Blockly.Msg.REPL_STARTING_COMPANION_ON_PHONE = 'Bezig het opstarten van de Companion App op de aangesloten telefoon.';
Blockly.Msg.ARRANGE_S = 'Rangschik blokken diagonaal';
Blockly.ERROR_COMPONENT_DOES_NOT_EXIST = 'Component bestaat niet';
Blockly.Msg.LANG_MATH_COMPARE_LTE = '≤';
Blockly.Msg.LANG_TEXT_CONTAINS_INPUT = 'bevat tekst %1 stuk %2';
Blockly.Msg.LANG_MATH_ONLIST_OPERATOR_MIN = 'min';
Blockly.Msg.LANG_MATH_FORMAT_AS_DECIMAL_INPUT = 'Formatteer als decimaal getal %1 plaatsen %2';
Blockly.Msg.LANG_CONTROLS_CHOOSE_INPUT_TEST = '';
Blockly.Msg.LANG_PROCEDURES_MUTATORARG_TOOLTIP = '';
Blockly.Msg.LANG_PROCEDURES_CALLNORETURN_CALL = 'aanroep ';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_TAN = 'Geeft de tangens van de gegeven hoek in graden.';
Blockly.Msg.LANG_VARIABLES_GLOBAL_DECLARATION_TO = 'tot';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_INPUT_SCREENNAME = 'schermNaam';
Blockly.Msg.HELP = 'Hulp';
Blockly.Msg.LANG_LISTS_POSITION_IN_TITLE_POSITION = 'positie in lijst';
Blockly.Msg.LANG_CONTROLS_CLOSE_APPLICATION_TITLE = 'toepassing sluiten';
Blockly.Msg.LANG_COLOUR_GREEN = 'groen';
Blockly.Msg.LANG_PROCEDURES_HIGHLIGHT_DEF = 'Markeer Procedure';
Blockly.Msg.LANG_CONTROLS_GET_START_VALUE_TITLE = 'krijg startwaarde';
Blockly.Msg.LANG_CONTROLS_FLOW_STATEMENTS_INPUT_OFLOOP = 'van lus';
Blockly.Msg.LANG_PROCEDURES_CALLNORETURN_COLLAPSED_PREFIX = 'roep op ';
Blockly.Msg.LANG_CONTROLS_GET_PLAIN_START_TEXT_TITLE = 'Verkrijg gewone starttekst';
Blockly.Msg.LANG_PROCEDURES_CALLNORETURN_TOOLTIP = 'Roep een procedure op die geen waarde teruggeeft.';
Blockly.Msg.LANG_LISTS_FROM_CSV_TABLE_TITLE_FROM_CSV = 'lijst van een csv tabel';
Blockly.Msg.LANG_LISTS_INSERT_TITLE_INSERT_LIST = 'voeg een lijst element toe';
Blockly.Msg.LANG_LISTS_TO_CSV_TABLE_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_LISTS_APPEND_LIST_INPUT_LIST1 = 'lijst1';
Blockly.Msg.LANG_LISTS_APPEND_LIST_INPUT_LIST2 = 'lijst2';
Blockly.Msg.REPL_UPDATE_INFO = 'De update wordt nu geïnstalleerd op je toestel. Hou je scherm (of emulator) in het oog en keur de installatie goed wanneer je dat gevraagd wordt.<br /><br />BELANGRIJK: Wanneer de update afloopt, kies "VOLTOOID" (klik niet op "open"). Ga dan naar App Inventor in je web browser, klik op het "Connecteer" menu en kies "Herstart Verbinding". Verbind dan het toestel.';
Blockly.Msg.LANG_MATH_COMPARE_TOOLTIP_LTE = 'Geeft waar terug als het eerste getal kleiner is\nof gelijk aan het tweede getal.';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_PLAIN_TEXT_COLLAPSED_TEXT = 'sluit scherm met platte tekst';
Blockly.Msg.LANG_CONTROLS_WHILE_COLLAPSED_TEXT = 'herhaal tot';
Blockly.Msg.LANG_LISTS_LOOKUP_IN_PAIRS_INPUT_KEY = 'sleutel';
Blockly.Msg.LANG_TEXT_JOIN_TITLE_CREATEWITH = 'maak tekst met';
Blockly.Msg.LANG_LISTS_TO_CSV_ROW_TOOLTIP = 'Interpreteert de lijst als een rij van een tabel en geeft een CSV (door komma\'s gescheiden waarden) tekst terug die de rij representeert. Elk item in de rij lijst wordt beschouwd als een veld, er wordt naar verwezen met dubbele aanhalingstekens in de CSV tekst. Items worden gescheiden door een komma. De geretourneerde rij tekst heeft geen lijn separator aan het einde.';
Blockly.Msg.LANG_TEXT_JOIN_TOOLTIP = 'Voegt alle inputs samen tot 1 enkele tekst.\nAls er geen inputs zijn, wordt een lege tekst gemaakt.';
Blockly.Msg.LANG_COLOUR_WHITE = 'Wit';
Blockly.Msg.LANG_MATH_ARITHMETIC_TOOLTIP_DIVIDE = 'Geeft het quotiënt van twee getallen.';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_INPUT = 'voeg items to lijst lijst %1 item %2';
Blockly.Msg.LANG_LOGIC_BOOLEAN_FALSE = 'onwaar';
Blockly.Msg.LANG_LISTS_INSERT_INPUT_INDEX = 'index';
Blockly.Msg.LANG_LISTS_FROM_CSV_TABLE_TOOLTIP = 'Ontleedt een tekst als een CSV (d.i. een door komma\'s gescheiden waarde) opgemaakte tabel om een lijst van rijen te produceren, elke rij is een lijst van velden. Rijen kunnen worden gescheiden door nieuwe lijnen (n) of CRLF (rn).';
Blockly.Msg.LANG_CONTROLS_CHOOSE_INPUT_ELSE_RETURN = 'anders';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_WITH_START_VALUE_TOOLTIP = 'Opent een nieuw scherm in een meer-schermen app en geeft de startwaarde mee aan dat scherm.';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_ASIN = 'Geeft een hoek tussen [-90,+90]\ngraden met de gegeven sinus waarde.';
Blockly.Msg.LANG_COMPONENT_BLOCK_GENERIC_GETTER_TITLE_OF_COMPONENT = 'van component';
Blockly.Msg.LANG_MATH_RANDOM_SEED_TITLE_RANDOM = 'stel willekeurige seed in';
Blockly.Msg.LANG_PROCEDURES_DEFNORETURN_DO = 'doe';
Blockly.Msg.LANG_LISTS_LOOKUP_IN_PAIRS_TITLE_LOOKUP_IN_PAIRS = 'zoek op in paren';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_EXPRESSION_COLLAPSED_TEXT = 'lokaal';
Blockly.Msg.LANG_TEXT_CONTAINS_INPUT_PIECE = 'stukje';
Blockly.Msg.LANG_TEXT_STARTS_AT_INPUT_STARTS_AT = 'begint bij';
Blockly.Msg.REPL_NOT_NOW = 'Niet Nu. Later, misschien ...';
Blockly.Msg.LANG_TEXT_STARTS_AT_INPUT_PIECE = 'stukje';
Blockly.Msg.LANG_COMPONENT_BLOCK_GENERIC_METHOD_TITLE_FOR_COMPONENT = 'voor component';
Blockly.Msg.HIDE_WARNINGS = 'Waarschuwingen Verbergen';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_OP_DEC_TO_HEX = 'decimaal naar hexadecimaal';
Blockly.Msg.REPL_CONNECT_TO_COMPANION = 'Connecteer met de Companion';
Blockly.Msg.LANG_COLOUR_PICKER_TOOLTIP = 'Klik op de rechthoek om een kleur te kiezen.';
Blockly.Msg.LANG_COMPONENT_BLOCK_GENERIC_SETTER_TITLE_TO = ' tot';
Blockly.Msg.REPL_SOFTWARE_UPDATE = 'Software bijwerken';
Blockly.Msg.LANG_LISTS_PICK_RANDOM_ITEM_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_CONTROLS_CHOOSE_TOOLTIP = 'Als de voorwaarde die wordt getest waar is,retourneer dan het resultaat verbonden aan het \'dan-teruggave\' veld, indien niet, geef dan het resultaat terug van het \'zoneen-teruggave\' veld, op zijn minst een van de resultaten verbonden aan beide teruggave velden wordt weergegeven.';
Blockly.MSG_RENAME_VARIABLE_TITLE = 'Hernoem alle "%1" variabelen naar:';
Blockly.Msg.LANG_LOGIC_BOOLEAN_TOOLTIP_FALSE = 'Geeft booleaanse niet waar terug.';
Blockly.Msg.REPL_TRY_AGAIN1 = 'Connecteren met de AI2 Companion is mislukt, probeer het eens opnieuw.';
Blockly.Msg.REPL_VERIFYING_COMPANION = 'Kijken of de Companion gestart is...';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_WITH_START_VALUE_INPUT_STARTVALUE = 'startWaarde';
Blockly.Msg.LANG_LISTS_POSITION_IN_TOOLTIP = 'Zoek de positie van het ding op in de lijst. Als het ding niet in de lijst zit, geef 0 terug.';
Blockly.Msg.LANG_LISTS_INSERT_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_PLAIN_TEXT_INPUT_TEXT = 'tekst';
Blockly.Msg.LANG_CONTROLS_FLOW_STATEMENTS_WARNING = 'Waarschuwing:\nDit blok mag alleen\ngebruikt worden in een lus.';
Blockly.Msg.REPL_AI_NO_SEE_DEVICE = 'AI2 ziet je toestel niet, zorg ervoor dat de kabel is aangesloten en dat de besturingsprogramma\'s juist zijn.';
Blockly.Msg.LANG_LISTS_REPLACE_ITEM_INPUT_INDEX = 'index';
Blockly.Msg.LANG_MATH_CONVERT_ANGLES_TOOLTIP_DEG_TO_RAD = 'Geeft de waarde in radialen terug volgens een schaal van\n[-π, +π) overeenkomstig met de graden.';
Blockly.Msg.REPL_STARTING_EMULATOR = 'Bezig met opstarten van de Android Emulator<br/>Even geduld: Dit kan een minuutje of twee duren (of koop snellere computer, grapke Pol! :p).';
Blockly.Msg.REPL_RUNTIME_ERROR = 'Uitvoeringsfout';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_COLLAPSED_TEXT = 'open scherm';
Blockly.Msg.REPL_FACTORY_RESET = 'Deze probeert jouw Emulator te herstellen in zijn initiële staat. Als je eerder je AI Companion had geupdate in de emulator, ga je dit waarschijnlijk op nieuw moeten doen. ';
Blockly.Msg.LANG_LISTS_ADD_ITEM_TITLE = 'item';
Blockly.Msg.LANG_CONTROLS_CHOOSE_TITLE = 'als';
Blockly.Msg.LANG_CATEGORY_LISTS = 'Lijsten';
Blockly.Msg.LANG_MATH_COMPARE_TOOLTIP_GT = 'Geeft waar terug als het eerste getal groter is\ndan het tweede getal.';
Blockly.Msg.LANG_CONTROLS_CLOSE_APPLICATION_COLLAPSED_TEXT = 'sluit toepassing';
Blockly.Msg.LANG_CONTROLS_GET_START_VALUE_COLLAPSED_TEXT = 'Krijg start waarde';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_COLLAPSED_TEXT = 'sluit scherm';
Blockly.Msg.REMOVE_COMMENT = 'Commentaar Verwijderen';
Blockly.Msg.LANG_PROCEDURES_DEFNORETURN_PROCEDURE = 'procedure';
Blockly.Msg.REPL_OK_LOWER = 'OK';
Blockly.Msg.LANG_MATH_SINGLE_OP_LN = 'log';
Blockly.Msg.LANG_MATH_IS_A_BINARY_TOOLTIP = 'Test of iets een tekst is die een binair getal voorstelt.';
Blockly.Msg.REPL_UNABLE_TO_UPDATE = 'Het is niet gelukt een update naar het toestel/emulator te sturen.';
Blockly.Msg.LANG_LISTS_LENGTH_INPUT_LIST = 'lijst';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_INPUT_TO = 'tot';
Blockly.Msg.LANG_MATH_COMPARE_NEQ = '≠';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_STEP = 'bij';
Blockly.Msg.LANG_MATH_COMPARE_GTE = '≥';
Blockly.Msg.LANG_COMPONENT_BLOCK_METHOD_TITLE_CALL = 'aanroep ';
Blockly.Msg.LANG_MATH_TRIG_ACOS = 'acos';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_ATAN = 'Geeft een hoek tussen [-90, +90]\ngraden met de gegeven tangens.';
Blockly.Msg.LANG_PROCEDURES_DEFRETURN_DEFINE = 'tot';
Blockly.Msg.LANG_MATH_ARITHMETIC_MINUS = '-';
Blockly.Msg.LANG_PROCEDURES_DEFRETURN_RETURN = 'resultaat';
Blockly.Msg.LANG_CONTROLS_IF_TOOLTIP_1 = 'Als een waarde waar is, voer dan enkele stappen uit.';
Blockly.Msg.LANG_CONTROLS_IF_TOOLTIP_3 = 'Als de eerste waarde waar is, voer dan het eerste codeblok uit.\nAnders, als de tweede waarde waar is, voer het tweede codeblok uit.';
Blockly.Msg.LANG_CONTROLS_IF_TOOLTIP_2 = 'Als de waarde waar is, voer dan het eerste codeblok uit.\nAnders, voer het tweede codeblok uit.';
Blockly.Msg.LANG_MATH_ROUND_OPERATOR_FLOOR = 'naar beneden afgerond';
Blockly.Msg.LANG_TEXT_APPEND_TO = 'naar';
Blockly.Msg.LANG_CONTROLS_IF_ELSEIF_TOOLTIP = 'Voeg een test toe aan het als blok.';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_TITLE_REPEAT = 'herhaal';
Blockly.Msg.LANG_CONTROLS_FOR_INPUT_WITH = 'tel met';
Blockly.Msg.LANG_VARIABLES_GLOBAL_DECLARATION_TOOLTIP = 'Maakt een globale variabele en geeft die de waarde van de geconnecteerde blokken';
Blockly.Msg.CLEAR_DO_IT_ERROR = 'Wis Fout';
Blockly.Msg.LANG_LISTS_TO_CSV_ROW_TITLE_TO_CSV = 'lijst to csv rij';
Blockly.Msg.LANG_MATH_SINGLE_TOOLTIP_EXP = 'Geef e (2.71828...) tot de macht terug';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_DEFAULT_NAME = 'naam';
Blockly.Msg.LANG_MATH_ARITHMETIC_MULTIPLY = '*';
Blockly.Msg.LANG_CONTROLS_CLOSE_APPLICATION_TOOLTIP = 'Sluit al de schermen af in deze app en stopt de app.';
Blockly.Msg.MISSING_SOCKETS_WARNINGS = 'Je moet alle connecties opvullen met blokken';
Blockly.Msg.LANG_MATH_ARITHMETIC_DIVIDE = '/';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_TOOLTIP = 'Sluit het huidige scherm';
Blockly.Msg.LANG_LISTS_TO_CSV_TABLE_TOOLTIP = 'Interpreteert de lijst als een tabel in rij-eerst formaat en geeft een CSV (door komma\'s gescheiden waarden) tekst terug die de tabel voorstelt. Elk element in de lijst zou op zijn beurt zelf een lijst moeten zijn die een rij van de CSV tabel voorstelt. Elk element in de rij lijst wordt beschouwd als een veld, waarvan de uiteindelijke CSV tekst zich binnen dubbele aanhalingstekens bevindt. In de teruggegeven tekst worden de elementen in de rijen gescheiden door komma\'s en worden de rijen zelf gescheiden door CRLF (\\r\\n).';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_VALUE_TITLE = 'sluit venster met waarde';
Blockly.Msg.LANG_TEXT_SPLIT_AT_TOOLTIP = 'Splitst de tekst in stukjes bij elke spatie.';
Blockly.Msg.LANG_MATH_IS_A_NUMBER_TOOLTIP = 'Test of iets een getal is.';
Blockly.Msg.LANG_LISTS_IS_LIST_TOOLTIP = 'Test of iets in een lijst zit.';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_ACOS = 'Geeft een hoek tussen [0, 180]\ngraden met de gegeven cosinus waarde.';
Blockly.Msg.LANG_MATH_RANDOM_INT_TITLE_RANDOM = 'willekeurig getal';
Blockly.ERROR_BLOCK_CANNOT_BE_IN_DEFINTION = 'Dit blok kan niet in een definitie';
Blockly.Msg.LANG_MATH_DIVIDE_TOOLTIP_REMAINDER = 'Geef de rest terug.';
Blockly.Msg.REPL_CONNECTING_USB_CABLE = 'Aan het connecteren via USB kabel';
Blockly.Msg.LANG_MATH_FORMAT_AS_DECIMAL_INPUT_PLACES = 'plaatsen';
Blockly.Msg.LANG_CONTROLS_FOR_INPUT_DO = 'doe';
Blockly.Msg.LANG_CONTROLS_OPEN_ANOTHER_SCREEN_WITH_START_VALUE_COLLAPSED_TEXT = 'open scherm met waarde';
Blockly.Msg.LANG_LISTS_APPEND_LIST_TOOLTIP = 'Voeg alle elementen van list2 achteraan toe bij lijst1. Na deze toevoegoperatie zal lijst1 de toegevoegde elementen bevatten, lijst2 zal niet gewijzigd zijn.';
Blockly.Msg.REPL_COMPANION_OUT_OF_DATE_IMMEDIATE = 'Je gebrukt een oude Companion. Je zou zo snel mogelijk moeten upgraden naar MIT AI2 Companion. Als je automatisch updaten hebt ingesteld in de store, gebeurt de update binnenkort vanzelf.';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_COS = 'Geeft de cosinus van een gegeven hoek in graden.';
Blockly.Msg.LANG_TEXT_SEGMENT_TITLE_SEGMENT = 'segment';
Blockly.Msg.BACKPACK_GET = 'Plak Alle Blokken van Rugzak';
Blockly.MSG_PROCEDURE_CATEGORY = 'Procedures';
Blockly.Msg.LANG_TEXT_SEGMENT_INPUT_LENGTH = 'lengte';
Blockly.Msg.LANG_COMPONENT_BLOCK_SETTER_TITLE_TO = ' tot';
Blockly.Msg.LANG_LISTS_COPY_TITLE_COPY = 'copieer lijst';
Blockly.Msg.LANG_LISTS_LENGTH_TOOLTIP = 'Telt het aantal elementen van een lijst';
Blockly.Msg.LANG_VARIABLES_GET_TOOLTIP = 'Geeft de waarde van deze variabele terug.';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_INPUT_DO = 'doe';
Blockly.Msg.LANG_TEXT_APPEND_VARIABLE = 'item';
Blockly.Msg.LANG_MATH_ARITHMETIC_TOOLTIP_MULTIPLY = 'Geeft het product van twee getallen terug.';
Blockly.Msg.REPL_OK = 'OK';
Blockly.Msg.LANG_PROCEDURES_DOTHENRETURN_THEN_RETURN = 'resultaat';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_COLLAPSED_PREFIX = 'voor ';
Blockly.Msg.LANG_MATH_TRIG_ATAN2_Y = 'j';
Blockly.Msg.LANG_PROCEDURES_CALLRETURN_PROCEDURE = 'procedure';
Blockly.Msg.LANG_PROCEDURES_DEFRETURN_DO = 'doe';
Blockly.Msg.REPL_HELPER_NOT_RUNNING = 'De aiStarter helper lijkt niet opgestart<br /><a href="http://appinventor.mit.edu" target="_blank">hulp nodig?</a>';
Blockly.Msg.LANG_TEXT_SEGMENT_AT_TOOLTIP = 'Haalt een deel van gegeven lengte uit de gegeven tekst\nstartend van de gegeven tekst op de gegeven positie. Positie \n1 betekent het begin van de tekst.';
Blockly.Msg.LANG_LOGIC_OPERATION_OR = 'of';
Blockly.Msg.WRONG_TYPE_BLOCK_WARINGS = 'Dit blok moet worden geconnecteerd met een gebeurtenisblok of de definitie van een procedure';
Blockly.Msg.LANG_MATH_ARITHMETIC_TOOLTIP_MINUS = 'Geeft het verschil tussen twee getallen terug.';
Blockly.Msg.LANG_TEXT_APPEND_TOOLTIP = 'Voeg wat tekst toe aan variabele "%1".';
Blockly.Msg.LANG_TEXT_REPLACE_ALL_TITLE_REPLACE_ALL = 'vervang allemaal';
Blockly.Msg.LANG_CONTROLS_WHILE_INPUT_TEST = 'Tekst';
Blockly.Msg.LANG_PROCEDURES_DEFNORETURN_COLLAPSED_PREFIX = 'tot ';
Blockly.Msg.LANG_TEXT_TRIM_TITLE_TRIM = 'trim';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_VAR = 'getal';
Blockly.Msg.LANG_CONTROLS_GET_START_VALUE_INPUT_STARTVALUE = 'startWaarde';
Blockly.Msg.LANG_MATH_FORMAT_AS_DECIMAL_INPUT_NUM = 'getal';
Blockly.Msg.LANG_MATH_TRIG_TOOLTIP_ATAN2 = 'Geeft een hoek in tussen [-180, +180]\ngraden met de gegeven rechthoekcoordinaten.';
Blockly.Msg.REPL_YOUR_CODE_IS = 'Jouw code is';
Blockly.Msg.LANG_TEXT_SPLIT_OPERATOR_SPLIT = 'splits';
Blockly.Msg.LANG_CONTROLS_IF_IF_TITLE_IF = 'als';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_DO = 'doe';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_EXPRESSION_TRANSLATED_NAME = 'initializeer lokaal in return';
Blockly.Msg.REPL_EMULATOR_STARTED = 'Emulator gestart, wachten ';
Blockly.Msg.LANG_TEXT_SPLIT_OPERATOR_SPLIT_AT_FIRST = 'splits aan de eerste';
Blockly.Msg.LANG_COLOUR_LIGHT_GRAY = 'lichtgrijs';
Blockly.Msg.LANG_CONTROLS_WHILEUNTIL_TOOLTIP_1 = 'Voert de blokken in het \'doe\'-gedeelte uit zolang de test waar is.';
Blockly.Msg.DUPLICATE_BLOCK = 'Dupliceer';
Blockly.Msg.SORT_H = 'Soorteer Blokken op Hoogte';
Blockly.Msg.ARRANGE_V = 'Organizeer Blokken Vertikaal';
Blockly.Msg.LANG_PROCEDURES_DEFNORETURN_DEFINE = 'tot';
Blockly.Msg.LANG_MATH_RANDOM_INT_INPUT = 'willekeurig getal tussen %1 en %2';
Blockly.Msg.LANG_LOGIC_COMPARE_TOOLTIP_EQ = 'Test of twee dingen gelijk zijn. \nDe dingen die worden vergeleken kunnen vanalles zijn, niet enkel getallen. \nGetallen worden als gelijk beschouwd aan hun tekstvorm, \nbijvoorbeeld, het getal 0 is gelijk aan de tekst "0". Ook two tekstvelden \ndie getallen voorstellen zijn gelijk aan elkaar als de getallen gelijk zijn aan mekaar. \n"1" is gelijk aan "01".';
Blockly.Msg.LANG_LOGIC_COMPARE_EQ = '=';
Blockly.MSG_RENAME_VARIABLE = 'Geef variabele een andere naam...';
Blockly.Msg.LANG_MATH_RANDOM_INT_TOOLTIP = 'Geeft een willekeurige geheel getal tussen de boven en de\nondergrens. De grenzen worden afgerond tot getallen kleiner\ndan 2**30.';
Blockly.Msg.LANG_LOGIC_BOOLEAN_TRUE = 'waar';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_ITEM = 'voor elk';
Blockly.Msg.LANG_LISTS_PICK_RANDOM_TOOLTIP = 'Neem een willekeurig element van de lijst.';
Blockly.Msg.LANG_LISTS_REPLACE_ITEM_INPUT_REPLACEMENT = 'vervanging';
Blockly.Msg.LANG_CONTROLS_CLOSE_SCREEN_WITH_PLAIN_TEXT_TITLE = 'Sluit het venster met gewone tekst';
Blockly.Msg.REPL_UNABLE_TO_LOAD_NO_RESPOND = 'Kan geen update laden van de App Inventor server (de server antwoordt niet)';
Blockly.Msg.LANG_TEXT_SEGMENT_INPUT_START = 'start';
Blockly.Msg.LANG_CONTROLS_DO_THEN_RETURN_TITLE = 'doe resultaat';
Blockly.Msg.LANG_PROCEDURES_DEFNORETURN_TOOLTIP = 'Een procedure die geen waarde teruggeeft.';
Blockly.Msg.LANG_MATH_IS_A_HEXADECIMAL_TOOLTIP = 'Tests of iets een tekst is die een hexadecimaal getal voorstelt.';
Blockly.Msg.LANG_TEXT_REPLACE_ALL_TOOLTIP = 'Geeft een nieuwe tekst terug door alle stukjes tekst zoals het segment\nte vervangen door de vervangtekst.';
Blockly.Msg.LANG_VARIABLES_SET_TOOLTIP = 'Zet deze variabele gelijk aan de input.';
Blockly.Msg.REPL_ERROR_FROM_COMPANION = 'Fout van de Companion';
Blockly.Msg.LANG_LOGIC_COMPARE_TOOLTIP_NEQ = 'Geef waar terug als beide inputs niet gelijk zijn aan elkaar.';
Blockly.Msg.LANG_COMPONENT_BLOCK_GENERIC_SETTER_TITLE_OF_COMPONENT = 'van de component';
Blockly.Msg.LANG_CONTROLS_DO_THEN_RETURN_COLLAPSED_TEXT = 'doe/resultaat';
Blockly.Msg.LANG_LISTS_CREATE_WITH_ITEM_TOOLTIP = 'Voeg een element toe aan de lijst.';
Blockly.Msg.LANG_TEXT_CHANGECASE_OPERATOR_DOWNCASE = 'naar kleine letters';
Blockly.Msg.LANG_CONTROLS_FOREACH_INPUT_COLLAPSED_TEXT = 'voor element in lijst';
Blockly.Msg.COLLAPSE_ALL = 'Klap blokken dicht';
Blockly.Msg.LANG_PROCEDURES_DEF_DUPLICATE_WARNING = 'Waarschuwing:\nDeze procedure heeft\ndubbele inputs.';
Blockly.Msg.LANG_CONTROLS_CHOOSE_COLLAPSED_TEXT = 'als';
Blockly.Msg.REPL_NETWORK_ERROR = 'Netwerkfout';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_TITLE_CONVERT = 'zet getal om';
Blockly.Msg.COLLAPSE_BLOCK = 'Klap blok dicht';
Blockly.Msg.LANG_LISTS_ADD_ITEMS_TITLE_ADD = 'voeg dingen toe aan lijst';
Blockly.Msg.REPL_COMPANION_STARTED_WAITING = 'Companion start op, effe wachten ...';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_TOOLTIP_BIN_TO_DEC = 'Neemt een tekst die een binair getal voorstelt en geeft de tekst terug die dat getal decimaal voorstelt';
Blockly.Msg.LANG_LOGIC_NEGATE_TOOLTIP = 'Geeft waar terug wanneer de input niet waar is.\nGeeft niet waar terug waneer de input waar is.';
Blockly.Msg.LANG_MATH_DIVIDE_OPERATOR_REMAINDER = 'de rest van';
Blockly.Msg.LANG_TEXT_SPLIT_OPERATOR_SPLIT_AT_FIRST_OF_ANY = 'splits bij de eerste van';
Blockly.Msg.SHOW_WARNINGS = 'Toon Waarschuwingen';
Blockly.Msg.LANG_MATH_CONVERT_NUMBER_OP_DEC_TO_BIN = 'decimaal naar binair';
Blockly.Msg.LANG_VARIABLES_LOCAL_DECLARATION_TITLE_INIT = 'initializeer lokaal';
Blockly.Msg.REPL_DEVICES = 'apparaten';
Blockly.Msg.LANG_CONTROLS_CHOOSE_INPUT_THEN_RETURN = 'dan';
Blockly.Msg.LANG_TEXT_SPLIT_INPUT_AT = 'op';
Blockly.Msg.LANG_CONTROLS_FORRANGE_INPUT_COLLAPSED_TEXT = 'voor getal in een zeker bereik';
Blockly.Msg.LANG_MATH_SINGLE_OP_ROOT = 'vierkantswortel';
Blockly.Msg.LANG_MATH_COMPARE_EQ = '=';
Blockly.Msg.LANG_MATH_ONLIST_TOOLTIP_MIN = 'Geeft het kleinste van zijn argumenten terug..';
Blockly.Msg.LANG_MATH_ONLIST_TOOLTIP_MAX = 'Geeft het grootste van zijn argumenten terug..';
Blockly.Msg.TIME_YEARS = "Jaren";
Blockly.Msg.TIME_MONTHS = "Maanden";
Blockly.Msg.TIME_WEEKS = "Weken";
Blockly.Msg.TIME_DAYS = "Dagen";
Blockly.Msg.TIME_HOURS = "Uren";
Blockly.Msg.TIME_MINUTES = "Minuten";
Blockly.Msg.TIME_SECONDS = "Seconden";
Blockly.Msg.TIME_DURATION = "Duurtijd";
Blockly.Msg.SHOW_BACKPACK_DOCUMENTATION = "Toon Rugzak informatie";
Blockly.Msg.ENABLE_GRID = 'Toon Werkruimte raster';
Blockly.Msg.DISABLE_GRID = 'Werkruimte raster verbergen';
Blockly.Msg.ENABLE_SNAPPING = 'Uitlijnen op raster aanzetten';
Blockly.Msg.DISABLE_SNAPPING = 'Uitlijnen op raster uitzetten';
}
};
// Initalize language definition to Dutch
Blockly.Msg.nl.switch_blockly_language_to_nl.init();
Blockly.Msg.nl.switch_language_to_dutch.init();
| LaboratoryForPlayfulComputation/appinventor-extensions | appinventor/blocklyeditor/src/msg/nl/_messages.js |
736 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.db;
import java.util.ListResourceBundle;
/**
* Connection Resource Strings
*
* @author Eldir Tomassen
* @version $Id: DBRes_nl.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $
*/
public class DBRes_nl extends ListResourceBundle
{
/** Data */
static final Object[][] contents = new String[][]
{
{ "CConnectionDialog", "Verbinding met Adempiere" },
{ "Name", "Naam" },
{ "AppsHost", "Applicatie Server" },
{ "AppsPort", "Applicatie Poort" },
{ "TestApps", "Test Applicatie" },
{ "DBHost", "Database Server" },
{ "DBPort", "Database Poort" },
{ "DBName", "Database Naam" },
{ "DBUidPwd", "Gebruikersnaam / Wachtwoord" },
{ "ViaFirewall", "via Firewall" },
{ "FWHost", "Firewall" },
{ "FWPort", "Firewall Poort" },
{ "TestConnection", "Test Database" },
{ "Type", "Database Type" },
{ "BequeathConnection", "Lokale Connectie" },
{ "Overwrite", "Overschrijven" },
{ "ConnectionProfile", "Connection" },
{ "LAN", "LAN" },
{ "TerminalServer", "Terminal Server" },
{ "VPN", "VPN" },
{ "WAN", "WAN" },
{ "ConnectionError", "Fout bij verbinden" },
{ "ServerNotActive", "Server Niet Actief" }
};
/**
* Get Contsnts
* @return contents
*/
public Object[][] getContents()
{
return contents;
} // getContent
} // Res
| alhudaghifari/adempiere | base/src/org/compiere/db/DBRes_nl.java |
737 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.decrypter;
import java.util.ArrayList;
import java.util.Random;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.nutils.encoding.Encoding;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://(www\\.)?cobra(?:\\.canvas)?\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|cobra)([^/]+)?/(mediatheek|videozone).+)" })
public class CobraBeDecrypter extends PluginForDecrypt {
public CobraBeDecrypter(PluginWrapper wrapper) {
super(wrapper);
}
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
String parameter = param.toString();
parameter = parameter.replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1");
parameter = parameter.replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3");
final DownloadLink mainlink = createDownloadlink("http://cobradecrypted.be/" + System.currentTimeMillis() + new Random().nextInt(1000000));
this.br.setFollowRedirects(true);
br.getPage(parameter);
mainlink.setProperty("mainlink", this.br.getURL());
final String externID = br.getRegex("data\\-video\\-src=\"(https?://(www\\.)?youtube\\.com/[^<>\"]*?)\"").getMatch(0);
if (externID != null) {
decryptedLinks.add(createDownloadlink(externID));
return decryptedLinks;
}
if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || this.br.getHttpConnection().getResponseCode() == 404) {
final DownloadLink offline = this.createOfflinelink(parameter);
decryptedLinks.add(offline);
return decryptedLinks;
}
final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0);
if (filename != null) {
mainlink.setLinkID(filename);
mainlink.setName(Encoding.htmlDecode(filename.trim()));
}
decryptedLinks.add(mainlink);
return decryptedLinks;
}
}
| substanc3-dev/jdownloader2 | src/jd/plugins/decrypter/CobraBeDecrypter.java |
738 | package binnie.core.gui.resource.textures;
import binnie.core.api.gui.Alignment;
import binnie.core.api.gui.IBorder;
import binnie.core.api.gui.ITexture;
import binnie.core.gui.geometry.Area;
import binnie.core.gui.geometry.Border;
import binnie.core.resource.IBinnieTexture;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class Texture implements ITexture {
private final Area area;
private final Border padding;
private final Border border;
private final IBinnieTexture binnieTexture;
public Texture(final Area area, final Border padding, final Border border, final IBinnieTexture binnieTexture) {
this.area = new Area(area);
this.padding = new Border(padding);
this.border = new Border(border);
this.binnieTexture = binnieTexture;
}
@Override
public Area getArea() {
return this.area;
}
@Override
public IBorder getBorder() {
return this.border;
}
@Override
@SideOnly(Side.CLIENT)
public ResourceLocation getResourceLocation() {
return this.binnieTexture.getTexture().getResourceLocation();
}
@Override
public IBorder getTotalPadding() {
return this.padding.add(this.border);
}
@Override
public int width() {
return this.getArea().width();
}
@Override
public int height() {
return this.getArea().height();
}
@Override
public ITexture crop(final Alignment anchor, final int dist) {
return this.crop(new Border(anchor.opposite(), dist));
}
@Override
public ITexture crop(final IBorder crop) {
final Texture copy = new Texture(this.area, this.padding, this.border, this.binnieTexture);
if (crop.getBottom() > 0) {
copy.border.setBottom(0);
copy.padding.setBottom(copy.padding.getBottom() - Math.min(crop.getBottom(), copy.padding.getBottom()));
copy.area.setHeight(copy.area.height() - crop.getBottom());
}
if (crop.getTop() > 0) {
copy.border.setTop(0);
copy.padding.setTop(copy.padding.getTop() - Math.min(crop.getTop(), copy.padding.getTop()));
copy.area.setHeight(copy.area.height() - crop.getTop());
copy.area.setYPos(copy.area.yPos() + crop.getTop());
}
if (crop.getRight() > 0) {
copy.border.setRight(0);
copy.padding.setRight(copy.padding.getRight() - Math.min(crop.getRight(), copy.padding.getRight()));
copy.area.setWidth(copy.area.width() - crop.getRight());
}
if (crop.getLeft() > 0) {
copy.border.setLeft(0);
copy.padding.setLeft(copy.padding.getLeft() - Math.min(crop.getLeft(), copy.padding.getLeft()));
copy.area.setWidth(copy.area.width() - crop.getLeft());
copy.area.setXPos(copy.area.xPos() + crop.getLeft());
}
return copy;
}
@Override
public String toString() {
String out = "Texture[";
out += this.area.toString();
if (!this.padding.isNonZero()) {
out = out + " padding:" + this.padding.toString();
}
if (!this.border.isNonZero()) {
out = out + " border:" + this.border.toString();
}
return out + ']';
}
}
| ForestryMC/Binnie | core/src/main/java/binnie/core/gui/resource/textures/Texture.java |
739 | //### This file created by BYACC 1.8(/Java extension 1.13)
//### Java capabilities added 7 Jan 97, Bob Jamison
//### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten
//### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor
//### 01 Jun 99 -- Bob Jamison -- added Runnable support
//### 06 Aug 00 -- Bob Jamison -- made state variables class-global
//### 03 Jan 01 -- Bob Jamison -- improved flags, tracing
//### 16 May 01 -- Bob Jamison -- added custom stack sizing
//### 04 Mar 02 -- Yuval Oren -- improved java performance, added options
//### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround
//### 14 Sep 06 -- Keltin Leung-- ReduceListener support, eliminate underflow report in error recovery
//### Please send bug reports to [email protected]
//### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90";
//#line 11 "Parser.y"
package decaf.frontend;
import decaf.tree.Tree;
import decaf.tree.Tree.*;
import decaf.error.*;
import java.util.*;
//#line 25 "Parser.java"
interface ReduceListener {
public boolean onReduce(String rule);
}
public class Parser
extends BaseParser
implements ReduceListener
{
boolean yydebug; //do I want debug output?
int yynerrs; //number of errors so far
int yyerrflag; //was there an error?
int yychar; //the current working character
ReduceListener reduceListener = null;
void yyclearin () {yychar = (-1);}
void yyerrok () {yyerrflag=0;}
void addReduceListener(ReduceListener l) {
reduceListener = l;}
//########## MESSAGES ##########
//###############################################################
// method: debug
//###############################################################
void debug(String msg)
{
if (yydebug)
System.out.println(msg);
}
//########## STATE STACK ##########
final static int YYSTACKSIZE = 500; //maximum stack size
int statestk[] = new int[YYSTACKSIZE]; //state stack
int stateptr;
int stateptrmax; //highest index of stackptr
int statemax; //state when highest index reached
//###############################################################
// methods: state stack push,pop,drop,peek
//###############################################################
final void state_push(int state)
{
try {
stateptr++;
statestk[stateptr]=state;
}
catch (ArrayIndexOutOfBoundsException e) {
int oldsize = statestk.length;
int newsize = oldsize * 2;
int[] newstack = new int[newsize];
System.arraycopy(statestk,0,newstack,0,oldsize);
statestk = newstack;
statestk[stateptr]=state;
}
}
final int state_pop()
{
return statestk[stateptr--];
}
final void state_drop(int cnt)
{
stateptr -= cnt;
}
final int state_peek(int relative)
{
return statestk[stateptr-relative];
}
//###############################################################
// method: init_stacks : allocate and prepare stacks
//###############################################################
final boolean init_stacks()
{
stateptr = -1;
val_init();
return true;
}
//###############################################################
// method: dump_stacks : show n levels of the stacks
//###############################################################
void dump_stacks(int count)
{
int i;
System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr);
for (i=0;i<count;i++)
System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]);
System.out.println("======================");
}
//########## SEMANTIC VALUES ##########
//## **user defined:SemValue
String yytext;//user variable to return contextual strings
SemValue yyval; //used to return semantic vals from action routines
SemValue yylval;//the 'lval' (result) I got from yylex()
SemValue valstk[] = new SemValue[YYSTACKSIZE];
int valptr;
//###############################################################
// methods: value stack push,pop,drop,peek.
//###############################################################
final void val_init()
{
yyval=new SemValue();
yylval=new SemValue();
valptr=-1;
}
final void val_push(SemValue val)
{
try {
valptr++;
valstk[valptr]=val;
}
catch (ArrayIndexOutOfBoundsException e) {
int oldsize = valstk.length;
int newsize = oldsize*2;
SemValue[] newstack = new SemValue[newsize];
System.arraycopy(valstk,0,newstack,0,oldsize);
valstk = newstack;
valstk[valptr]=val;
}
}
final SemValue val_pop()
{
return valstk[valptr--];
}
final void val_drop(int cnt)
{
valptr -= cnt;
}
final SemValue val_peek(int relative)
{
return valstk[valptr-relative];
}
//#### end semantic value section ####
public final static short VOID=257;
public final static short BOOL=258;
public final static short INT=259;
public final static short STRING=260;
public final static short CLASS=261;
public final static short NULL=262;
public final static short EXTENDS=263;
public final static short THIS=264;
public final static short WHILE=265;
public final static short FOR=266;
public final static short IF=267;
public final static short ELSE=268;
public final static short RETURN=269;
public final static short BREAK=270;
public final static short NEW=271;
public final static short PRINT=272;
public final static short READ_INTEGER=273;
public final static short READ_LINE=274;
public final static short LITERAL=275;
public final static short IDENTIFIER=276;
public final static short AND=277;
public final static short OR=278;
public final static short STATIC=279;
public final static short INSTANCEOF=280;
public final static short LESS_EQUAL=281;
public final static short GREATER_EQUAL=282;
public final static short EQUAL=283;
public final static short NOT_EQUAL=284;
public final static short MIN_CP=285;
public final static short SWITCH=286;
public final static short CASE=287;
public final static short DEFAULT=288;
public final static short REPEAT=289;
public final static short UNTIL=290;
public final static short CONTINUE=291;
public final static short PCLONE=292;
public final static short UMINUS=293;
public final static short EMPTY=294;
public final static short YYERRCODE=256;
final static short yylhs[] = { -1,
0, 1, 1, 3, 4, 5, 5, 5, 5, 5,
5, 2, 6, 6, 7, 7, 7, 9, 9, 10,
10, 8, 8, 11, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14,
14, 27, 27, 24, 24, 26, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 29, 29, 28, 28, 30, 30,
16, 17, 22, 23, 15, 18, 32, 32, 34, 33,
33, 19, 31, 31, 20, 20, 21,
};
final static short yylen[] = { 2,
1, 2, 1, 2, 2, 1, 1, 1, 1, 2,
3, 6, 2, 0, 2, 2, 0, 1, 0, 3,
1, 7, 6, 3, 2, 0, 1, 2, 1, 1,
1, 1, 2, 2, 2, 2, 2, 1, 3, 1,
0, 2, 0, 2, 4, 5, 1, 1, 1, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 2, 2, 3, 3, 1, 4, 5,
6, 5, 5, 3, 1, 1, 1, 0, 3, 1,
5, 9, 1, 1, 6, 8, 2, 0, 4, 3,
0, 6, 2, 0, 2, 1, 4,
};
final static short yydefred[] = { 0,
0, 0, 0, 3, 0, 2, 0, 0, 13, 17,
0, 7, 8, 6, 9, 0, 0, 12, 15, 0,
0, 16, 10, 0, 4, 0, 0, 0, 0, 11,
0, 21, 0, 0, 0, 0, 5, 0, 0, 0,
26, 23, 20, 22, 0, 76, 68, 0, 0, 0,
0, 83, 0, 0, 0, 0, 75, 0, 0, 26,
84, 0, 0, 0, 24, 27, 38, 25, 0, 29,
30, 31, 32, 0, 0, 0, 0, 0, 0, 0,
0, 0, 49, 0, 0, 0, 47, 0, 48, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 28, 33, 34, 35, 36, 37, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 42, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 66, 67, 0, 0, 0, 0, 63,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 69, 0, 0, 97, 0, 0, 0, 0, 45,
0, 0, 0, 81, 0, 0, 70, 0, 0, 88,
0, 72, 0, 46, 0, 0, 85, 71, 0, 92,
0, 93, 0, 0, 0, 87, 0, 0, 26, 86,
82, 26, 0, 0,
};
final static short yydgoto[] = { 2,
3, 4, 66, 20, 33, 8, 11, 22, 34, 35,
67, 45, 68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 87, 80, 89, 82, 172, 83, 133,
187, 189, 195, 196,
};
final static short yysindex[] = { -228,
-224, 0, -228, 0, -219, 0, -214, -66, 0, 0,
-91, 0, 0, 0, 0, -209, -120, 0, 0, 12,
-85, 0, 0, -83, 0, 41, -10, 46, -120, 0,
-120, 0, -80, 47, 45, 50, 0, -28, -120, -28,
0, 0, 0, 0, 2, 0, 0, 53, 57, 58,
871, 0, -46, 59, 60, 63, 0, 64, 67, 0,
0, 871, 871, 810, 0, 0, 0, 0, 52, 0,
0, 0, 0, 55, 62, 76, 83, 84, 48, 740,
0, -154, 0, 871, 871, 871, 0, 740, 0, 86,
32, 871, 103, 111, 871, 871, 37, -30, -30, -123,
477, 0, 0, 0, 0, 0, 0, 871, 871, 871,
871, 871, 871, 871, 871, 871, 871, 871, 871, 871,
871, 0, 871, 871, 871, 122, 489, 95, 513, 124,
1022, 740, -3, 0, 0, 540, 552, 123, 130, 0,
740, 998, 948, 73, 73, 1049, 1049, -22, -22, -30,
-30, -30, 73, 73, 564, 576, 3, 871, 72, 871,
72, 0, 650, 871, 0, -95, 69, 871, 871, 0,
871, 134, 138, 0, 674, -78, 0, 740, 157, 0,
824, 0, 740, 0, 871, 72, 0, 0, -208, 0,
158, 0, -232, 145, 81, 0, 72, 150, 0, 0,
0, 0, 72, 72,
};
final static short yyrindex[] = { 0,
0, 0, 209, 0, 93, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 151, 0, 0, 176, 0,
176, 0, 0, 0, 177, 0, 0, 0, 0, 0,
0, 0, 0, 0, -56, 0, 0, 0, 0, 0,
-54, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -55, -55, -55, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 846, 0,
447, 0, 0, -55, -56, -55, 0, 164, 0, 0,
0, -55, 0, 0, -55, -55, -56, 114, 142, 0,
0, 0, 0, 0, 0, 0, 0, -55, -55, -55,
-55, -55, -55, -55, -55, -55, -55, -55, -55, -55,
-55, 0, -55, -55, -55, 87, 0, 0, 0, 0,
-55, 10, 0, 0, 0, 0, 0, 0, 0, 0,
-20, -27, 975, 705, 918, 43, 625, 881, 905, 370,
394, 423, 943, 968, 0, 0, -40, -32, -56, -55,
-56, 0, 0, -55, 0, 0, 0, -55, -55, 0,
-55, 0, 205, 0, 0, -33, 0, 31, 0, 0,
0, 0, 15, 0, -31, -56, 0, 0, 153, 0,
0, 0, 0, 0, 0, 0, -56, 0, 0, 0,
0, 0, -57, 224,
};
final static short yygindex[] = { 0,
0, 245, 238, -2, 11, 0, 0, 0, 239, 0,
38, -5, -101, -72, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1052, 1241, 1115, 0, 0, 96, 121,
0, 0, 0, 0,
};
final static int YYTABLESIZE=1412;
static short yytable[];
static { yytable();}
static void yytable(){
yytable = new short[]{ 94,
74, 41, 41, 74, 96, 27, 94, 27, 78, 41,
27, 94, 128, 61, 119, 122, 61, 74, 74, 117,
39, 21, 74, 122, 118, 94, 32, 24, 32, 46,
61, 61, 1, 18, 63, 61, 43, 165, 39, 119,
164, 64, 57, 7, 117, 115, 62, 116, 122, 118,
80, 5, 74, 80, 97, 73, 10, 174, 73, 176,
123, 9, 121, 91, 120, 61, 23, 90, 123, 63,
25, 79, 73, 73, 79, 42, 64, 44, 193, 194,
29, 62, 30, 55, 192, 31, 55, 38, 39, 94,
40, 94, 84, 123, 41, 201, 85, 86, 92, 93,
55, 55, 94, 95, 63, 55, 96, 73, 108, 119,
102, 64, 191, 103, 117, 115, 62, 116, 122, 118,
104, 126, 131, 44, 41, 130, 65, 44, 44, 44,
44, 44, 44, 44, 105, 55, 12, 13, 14, 15,
16, 106, 107, 134, 44, 44, 44, 44, 44, 44,
64, 135, 139, 160, 64, 64, 64, 64, 64, 41,
64, 158, 168, 123, 162, 12, 13, 14, 15, 16,
169, 64, 64, 64, 184, 64, 64, 44, 65, 44,
179, 164, 65, 65, 65, 65, 65, 17, 65, 186,
26, 180, 28, 203, 41, 37, 204, 188, 197, 65,
65, 65, 199, 65, 65, 200, 64, 202, 1, 5,
12, 13, 14, 15, 16, 14, 19, 18, 43, 43,
43, 43, 95, 94, 94, 94, 94, 94, 94, 90,
94, 94, 94, 94, 65, 94, 94, 94, 94, 94,
94, 94, 94, 43, 43, 77, 94, 6, 19, 61,
61, 74, 94, 94, 94, 94, 94, 94, 12, 13,
14, 15, 16, 46, 61, 47, 48, 49, 50, 36,
51, 52, 53, 54, 55, 56, 57, 91, 173, 109,
110, 58, 41, 111, 112, 113, 114, 59, 198, 0,
60, 0, 61, 12, 13, 14, 15, 16, 46, 0,
47, 48, 49, 50, 0, 51, 52, 53, 54, 55,
56, 57, 0, 0, 0, 0, 58, 0, 0, 55,
55, 0, 59, 0, 0, 60, 138, 61, 12, 13,
14, 15, 16, 46, 55, 47, 48, 49, 50, 0,
51, 52, 53, 54, 55, 56, 57, 0, 89, 0,
0, 58, 0, 0, 0, 0, 0, 59, 0, 0,
60, 0, 61, 44, 44, 0, 0, 44, 44, 44,
44, 0, 0, 0, 0, 0, 0, 0, 44, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64, 64, 0, 0, 64, 64, 64, 64, 0, 0,
0, 0, 0, 0, 0, 64, 52, 0, 0, 0,
52, 52, 52, 52, 52, 0, 52, 0, 65, 65,
0, 0, 65, 65, 65, 65, 0, 52, 52, 52,
53, 52, 52, 65, 53, 53, 53, 53, 53, 0,
53, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 53, 53, 53, 0, 53, 53, 0, 0, 54,
0, 0, 52, 54, 54, 54, 54, 54, 0, 54,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
54, 54, 54, 48, 54, 54, 53, 40, 48, 48,
0, 48, 48, 48, 0, 0, 0, 0, 0, 43,
0, 0, 0, 0, 0, 40, 48, 0, 48, 48,
89, 89, 0, 119, 0, 54, 0, 140, 117, 115,
0, 116, 122, 118, 0, 119, 0, 0, 0, 159,
117, 115, 0, 116, 122, 118, 121, 48, 120, 124,
0, 0, 0, 0, 0, 0, 0, 0, 121, 119,
120, 124, 0, 161, 117, 115, 0, 116, 122, 118,
0, 0, 0, 0, 0, 0, 0, 123, 0, 0,
0, 0, 121, 0, 120, 124, 119, 0, 0, 123,
0, 117, 115, 166, 116, 122, 118, 0, 119, 0,
0, 0, 167, 117, 115, 0, 116, 122, 118, 121,
119, 120, 124, 123, 0, 117, 115, 0, 116, 122,
118, 121, 119, 120, 124, 0, 0, 117, 115, 0,
116, 122, 118, 121, 0, 120, 124, 0, 0, 0,
123, 0, 0, 171, 0, 121, 0, 120, 124, 0,
0, 0, 123, 0, 0, 0, 52, 52, 0, 0,
52, 52, 52, 52, 123, 0, 170, 0, 0, 0,
0, 52, 0, 0, 0, 56, 123, 0, 56, 0,
53, 53, 0, 0, 53, 53, 53, 53, 0, 0,
0, 0, 56, 56, 0, 53, 119, 56, 0, 0,
0, 117, 115, 0, 116, 122, 118, 0, 0, 54,
54, 0, 0, 54, 54, 54, 54, 0, 0, 121,
119, 120, 124, 0, 54, 117, 115, 56, 116, 122,
118, 0, 0, 48, 48, 0, 0, 48, 48, 48,
48, 0, 185, 121, 0, 120, 124, 0, 48, 0,
123, 0, 177, 0, 0, 59, 0, 0, 59, 0,
0, 0, 0, 109, 110, 0, 0, 111, 112, 113,
114, 0, 59, 59, 123, 109, 110, 59, 125, 111,
112, 113, 114, 0, 0, 0, 119, 0, 0, 0,
125, 117, 115, 0, 116, 122, 118, 0, 0, 109,
110, 0, 0, 111, 112, 113, 114, 59, 0, 121,
0, 120, 124, 0, 125, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 109, 110, 0, 0,
111, 112, 113, 114, 0, 0, 0, 0, 109, 110,
123, 125, 111, 112, 113, 114, 0, 0, 0, 0,
109, 110, 63, 125, 111, 112, 113, 114, 0, 64,
0, 0, 109, 110, 62, 125, 111, 112, 113, 114,
119, 0, 0, 0, 190, 117, 115, 125, 116, 122,
118, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 47, 121, 0, 120, 124, 47, 47, 0,
47, 47, 47, 0, 0, 0, 0, 0, 0, 0,
0, 56, 56, 63, 0, 47, 0, 47, 47, 0,
64, 0, 0, 0, 123, 62, 56, 0, 0, 0,
0, 50, 0, 50, 50, 50, 109, 110, 0, 0,
111, 112, 113, 114, 0, 0, 47, 0, 50, 50,
50, 125, 50, 50, 0, 51, 0, 51, 51, 51,
109, 110, 0, 0, 111, 112, 113, 114, 60, 0,
0, 60, 51, 51, 51, 125, 51, 51, 0, 0,
0, 0, 0, 50, 0, 60, 60, 0, 0, 0,
60, 59, 59, 58, 119, 0, 58, 59, 59, 117,
115, 0, 116, 122, 118, 0, 59, 51, 0, 0,
58, 58, 0, 0, 0, 58, 0, 121, 57, 120,
60, 57, 0, 0, 0, 62, 109, 110, 62, 0,
111, 112, 113, 114, 0, 57, 57, 0, 0, 0,
57, 125, 62, 62, 119, 58, 0, 62, 123, 117,
115, 0, 116, 122, 118, 0, 0, 0, 0, 0,
0, 0, 0, 0, 63, 0, 0, 121, 0, 120,
57, 64, 0, 0, 0, 0, 62, 62, 0, 0,
100, 46, 0, 47, 0, 0, 0, 0, 0, 0,
53, 0, 55, 56, 57, 119, 0, 0, 123, 58,
117, 115, 0, 116, 122, 118, 79, 0, 0, 0,
109, 110, 0, 0, 111, 112, 113, 114, 121, 0,
120, 0, 0, 0, 30, 125, 0, 0, 0, 0,
0, 0, 47, 47, 0, 0, 47, 47, 47, 47,
0, 0, 46, 0, 47, 0, 79, 47, 0, 123,
0, 53, 0, 55, 56, 57, 0, 0, 79, 0,
58, 0, 0, 0, 0, 0, 0, 50, 50, 81,
0, 50, 50, 50, 50, 0, 0, 0, 0, 0,
0, 0, 50, 0, 0, 0, 0, 0, 0, 0,
0, 51, 51, 0, 0, 51, 51, 51, 51, 0,
0, 0, 0, 0, 60, 60, 51, 0, 0, 81,
60, 60, 0, 0, 0, 0, 0, 0, 0, 60,
79, 81, 79, 0, 0, 0, 0, 0, 0, 58,
58, 0, 0, 0, 109, 58, 58, 0, 111, 112,
113, 114, 0, 0, 58, 0, 79, 79, 0, 0,
0, 0, 0, 0, 57, 57, 0, 0, 79, 0,
57, 57, 62, 0, 79, 79, 0, 0, 0, 57,
0, 0, 0, 0, 0, 0, 62, 0, 0, 0,
0, 0, 0, 81, 0, 81, 0, 0, 111, 112,
113, 114, 0, 46, 0, 47, 0, 0, 0, 0,
0, 88, 53, 0, 55, 56, 57, 0, 0, 81,
81, 58, 98, 99, 101, 0, 0, 0, 0, 0,
0, 81, 0, 0, 0, 0, 0, 81, 81, 0,
0, 0, 0, 0, 127, 0, 129, 0, 0, 111,
112, 0, 132, 0, 0, 136, 137, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
153, 154, 0, 155, 156, 157, 0, 0, 0, 0,
0, 163, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 132, 0,
175, 0, 0, 0, 178, 0, 0, 0, 181, 182,
0, 183,
};
}
static short yycheck[];
static { yycheck(); }
static void yycheck() {
yycheck = new short[] { 33,
41, 59, 59, 44, 59, 91, 40, 91, 41, 41,
91, 45, 85, 41, 37, 46, 44, 58, 59, 42,
41, 11, 63, 46, 47, 59, 29, 17, 31, 262,
58, 59, 261, 125, 33, 63, 39, 41, 59, 37,
44, 40, 275, 263, 42, 43, 45, 45, 46, 47,
41, 276, 93, 44, 60, 41, 123, 159, 44, 161,
91, 276, 60, 53, 62, 93, 276, 125, 91, 33,
59, 41, 58, 59, 44, 38, 40, 40, 287, 288,
40, 45, 93, 41, 186, 40, 44, 41, 44, 123,
41, 125, 40, 91, 123, 197, 40, 40, 40, 40,
58, 59, 40, 40, 33, 63, 40, 93, 61, 37,
59, 40, 185, 59, 42, 43, 45, 45, 46, 47,
59, 276, 91, 37, 123, 40, 125, 41, 42, 43,
44, 45, 46, 47, 59, 93, 257, 258, 259, 260,
261, 59, 59, 41, 58, 59, 60, 61, 62, 63,
37, 41, 276, 59, 41, 42, 43, 44, 45, 123,
47, 40, 40, 91, 41, 257, 258, 259, 260, 261,
41, 58, 59, 60, 41, 62, 63, 91, 37, 93,
276, 44, 41, 42, 43, 44, 45, 279, 47, 268,
276, 123, 276, 199, 123, 276, 202, 41, 41, 58,
59, 60, 58, 62, 63, 125, 93, 58, 0, 59,
257, 258, 259, 260, 261, 123, 41, 41, 276, 276,
276, 276, 59, 257, 258, 259, 260, 261, 262, 276,
264, 265, 266, 267, 93, 269, 270, 271, 272, 273,
274, 275, 276, 276, 276, 41, 280, 3, 11, 277,
278, 292, 286, 287, 288, 289, 290, 291, 257, 258,
259, 260, 261, 262, 292, 264, 265, 266, 267, 31,
269, 270, 271, 272, 273, 274, 275, 125, 158, 277,
278, 280, 59, 281, 282, 283, 284, 286, 193, -1,
289, -1, 291, 257, 258, 259, 260, 261, 262, -1,
264, 265, 266, 267, -1, 269, 270, 271, 272, 273,
274, 275, -1, -1, -1, -1, 280, -1, -1, 277,
278, -1, 286, -1, -1, 289, 290, 291, 257, 258,
259, 260, 261, 262, 292, 264, 265, 266, 267, -1,
269, 270, 271, 272, 273, 274, 275, -1, 125, -1,
-1, 280, -1, -1, -1, -1, -1, 286, -1, -1,
289, -1, 291, 277, 278, -1, -1, 281, 282, 283,
284, -1, -1, -1, -1, -1, -1, -1, 292, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
277, 278, -1, -1, 281, 282, 283, 284, -1, -1,
-1, -1, -1, -1, -1, 292, 37, -1, -1, -1,
41, 42, 43, 44, 45, -1, 47, -1, 277, 278,
-1, -1, 281, 282, 283, 284, -1, 58, 59, 60,
37, 62, 63, 292, 41, 42, 43, 44, 45, -1,
47, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 58, 59, 60, -1, 62, 63, -1, -1, 37,
-1, -1, 93, 41, 42, 43, 44, 45, -1, 47,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
58, 59, 60, 37, 62, 63, 93, 41, 42, 43,
-1, 45, 46, 47, -1, -1, -1, -1, -1, 276,
-1, -1, -1, -1, -1, 59, 60, -1, 62, 63,
287, 288, -1, 37, -1, 93, -1, 41, 42, 43,
-1, 45, 46, 47, -1, 37, -1, -1, -1, 41,
42, 43, -1, 45, 46, 47, 60, 91, 62, 63,
-1, -1, -1, -1, -1, -1, -1, -1, 60, 37,
62, 63, -1, 41, 42, 43, -1, 45, 46, 47,
-1, -1, -1, -1, -1, -1, -1, 91, -1, -1,
-1, -1, 60, -1, 62, 63, 37, -1, -1, 91,
-1, 42, 43, 44, 45, 46, 47, -1, 37, -1,
-1, -1, 41, 42, 43, -1, 45, 46, 47, 60,
37, 62, 63, 91, -1, 42, 43, -1, 45, 46,
47, 60, 37, 62, 63, -1, -1, 42, 43, -1,
45, 46, 47, 60, -1, 62, 63, -1, -1, -1,
91, -1, -1, 58, -1, 60, -1, 62, 63, -1,
-1, -1, 91, -1, -1, -1, 277, 278, -1, -1,
281, 282, 283, 284, 91, -1, 93, -1, -1, -1,
-1, 292, -1, -1, -1, 41, 91, -1, 44, -1,
277, 278, -1, -1, 281, 282, 283, 284, -1, -1,
-1, -1, 58, 59, -1, 292, 37, 63, -1, -1,
-1, 42, 43, -1, 45, 46, 47, -1, -1, 277,
278, -1, -1, 281, 282, 283, 284, -1, -1, 60,
37, 62, 63, -1, 292, 42, 43, 93, 45, 46,
47, -1, -1, 277, 278, -1, -1, 281, 282, 283,
284, -1, 59, 60, -1, 62, 63, -1, 292, -1,
91, -1, 93, -1, -1, 41, -1, -1, 44, -1,
-1, -1, -1, 277, 278, -1, -1, 281, 282, 283,
284, -1, 58, 59, 91, 277, 278, 63, 292, 281,
282, 283, 284, -1, -1, -1, 37, -1, -1, -1,
292, 42, 43, -1, 45, 46, 47, -1, -1, 277,
278, -1, -1, 281, 282, 283, 284, 93, -1, 60,
-1, 62, 63, -1, 292, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 277, 278, -1, -1,
281, 282, 283, 284, -1, -1, -1, -1, 277, 278,
91, 292, 281, 282, 283, 284, -1, -1, -1, -1,
277, 278, 33, 292, 281, 282, 283, 284, -1, 40,
-1, -1, 277, 278, 45, 292, 281, 282, 283, 284,
37, -1, -1, -1, 41, 42, 43, 292, 45, 46,
47, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 37, 60, -1, 62, 63, 42, 43, -1,
45, 46, 47, -1, -1, -1, -1, -1, -1, -1,
-1, 277, 278, 33, -1, 60, -1, 62, 63, -1,
40, -1, -1, -1, 91, 45, 292, -1, -1, -1,
-1, 41, -1, 43, 44, 45, 277, 278, -1, -1,
281, 282, 283, 284, -1, -1, 91, -1, 58, 59,
60, 292, 62, 63, -1, 41, -1, 43, 44, 45,
277, 278, -1, -1, 281, 282, 283, 284, 41, -1,
-1, 44, 58, 59, 60, 292, 62, 63, -1, -1,
-1, -1, -1, 93, -1, 58, 59, -1, -1, -1,
63, 277, 278, 41, 37, -1, 44, 283, 284, 42,
43, -1, 45, 46, 47, -1, 292, 93, -1, -1,
58, 59, -1, -1, -1, 63, -1, 60, 41, 62,
93, 44, -1, -1, -1, 41, 277, 278, 44, -1,
281, 282, 283, 284, -1, 58, 59, -1, -1, -1,
63, 292, 58, 59, 37, 93, -1, 63, 91, 42,
43, -1, 45, 46, 47, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 33, -1, -1, 60, -1, 62,
93, 40, -1, -1, -1, -1, 45, 93, -1, -1,
261, 262, -1, 264, -1, -1, -1, -1, -1, -1,
271, -1, 273, 274, 275, 37, -1, -1, 91, 280,
42, 43, -1, 45, 46, 47, 45, -1, -1, -1,
277, 278, -1, -1, 281, 282, 283, 284, 60, -1,
62, -1, -1, -1, 93, 292, -1, -1, -1, -1,
-1, -1, 277, 278, -1, -1, 281, 282, 283, 284,
-1, -1, 262, -1, 264, -1, 85, 292, -1, 91,
-1, 271, -1, 273, 274, 275, -1, -1, 97, -1,
280, -1, -1, -1, -1, -1, -1, 277, 278, 45,
-1, 281, 282, 283, 284, -1, -1, -1, -1, -1,
-1, -1, 292, -1, -1, -1, -1, -1, -1, -1,
-1, 277, 278, -1, -1, 281, 282, 283, 284, -1,
-1, -1, -1, -1, 277, 278, 292, -1, -1, 85,
283, 284, -1, -1, -1, -1, -1, -1, -1, 292,
159, 97, 161, -1, -1, -1, -1, -1, -1, 277,
278, -1, -1, -1, 277, 283, 284, -1, 281, 282,
283, 284, -1, -1, 292, -1, 185, 186, -1, -1,
-1, -1, -1, -1, 277, 278, -1, -1, 197, -1,
283, 284, 278, -1, 203, 204, -1, -1, -1, 292,
-1, -1, -1, -1, -1, -1, 292, -1, -1, -1,
-1, -1, -1, 159, -1, 161, -1, -1, 281, 282,
283, 284, -1, 262, -1, 264, -1, -1, -1, -1,
-1, 51, 271, -1, 273, 274, 275, -1, -1, 185,
186, 280, 62, 63, 64, -1, -1, -1, -1, -1,
-1, 197, -1, -1, -1, -1, -1, 203, 204, -1,
-1, -1, -1, -1, 84, -1, 86, -1, -1, 281,
282, -1, 92, -1, -1, 95, 96, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, -1, 123, 124, 125, -1, -1, -1, -1,
-1, 131, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 158, -1,
160, -1, -1, -1, 164, -1, -1, -1, 168, 169,
-1, 171,
};
}
final static short YYFINAL=2;
final static short YYMAXTOKEN=294;
final static String yyname[] = {
"end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,"'!'",null,null,null,"'%'",null,null,"'('","')'","'*'","'+'",
"','","'-'","'.'","'/'",null,null,null,null,null,null,null,null,null,null,"':'",
"';'","'<'","'='","'>'","'?'",null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,"'['",null,"']'",null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,"'{'",null,"'}'",null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,"VOID","BOOL","INT","STRING",
"CLASS","NULL","EXTENDS","THIS","WHILE","FOR","IF","ELSE","RETURN","BREAK",
"NEW","PRINT","READ_INTEGER","READ_LINE","LITERAL","IDENTIFIER","AND","OR",
"STATIC","INSTANCEOF","LESS_EQUAL","GREATER_EQUAL","EQUAL","NOT_EQUAL","MIN_CP",
"SWITCH","CASE","DEFAULT","REPEAT","UNTIL","CONTINUE","PCLONE","UMINUS","EMPTY",
};
final static String yyrule[] = {
"$accept : Program",
"Program : ClassList",
"ClassList : ClassList ClassDef",
"ClassList : ClassDef",
"VariableDef : Variable ';'",
"Variable : Type IDENTIFIER",
"Type : INT",
"Type : VOID",
"Type : BOOL",
"Type : STRING",
"Type : CLASS IDENTIFIER",
"Type : Type '[' ']'",
"ClassDef : CLASS IDENTIFIER ExtendsClause '{' FieldList '}'",
"ExtendsClause : EXTENDS IDENTIFIER",
"ExtendsClause :",
"FieldList : FieldList VariableDef",
"FieldList : FieldList FunctionDef",
"FieldList :",
"Formals : VariableList",
"Formals :",
"VariableList : VariableList ',' Variable",
"VariableList : Variable",
"FunctionDef : STATIC Type IDENTIFIER '(' Formals ')' StmtBlock",
"FunctionDef : Type IDENTIFIER '(' Formals ')' StmtBlock",
"StmtBlock : '{' StmtList '}'",
"StmtList : StmtList Stmt",
"StmtList :",
"Stmt : VariableDef",
"Stmt : SimpleStmt ';'",
"Stmt : IfStmt",
"Stmt : WhileStmt",
"Stmt : ForStmt",
"Stmt : SwitchStmt",
"Stmt : RepeatStmt ';'",
"Stmt : ReturnStmt ';'",
"Stmt : PrintStmt ';'",
"Stmt : BreakStmt ';'",
"Stmt : ContinueStmt ';'",
"Stmt : StmtBlock",
"SimpleStmt : LValue '=' Expr",
"SimpleStmt : Call",
"SimpleStmt :",
"Receiver : Expr '.'",
"Receiver :",
"LValue : Receiver IDENTIFIER",
"LValue : Expr '[' Expr ']'",
"Call : Receiver IDENTIFIER '(' Actuals ')'",
"Expr : LValue",
"Expr : Call",
"Expr : Constant",
"Expr : Expr '+' Expr",
"Expr : Expr '-' Expr",
"Expr : Expr '*' Expr",
"Expr : Expr '/' Expr",
"Expr : Expr '%' Expr",
"Expr : Expr EQUAL Expr",
"Expr : Expr NOT_EQUAL Expr",
"Expr : Expr '<' Expr",
"Expr : Expr '>' Expr",
"Expr : Expr LESS_EQUAL Expr",
"Expr : Expr GREATER_EQUAL Expr",
"Expr : Expr AND Expr",
"Expr : Expr OR Expr",
"Expr : '(' Expr ')'",
"Expr : '-' Expr",
"Expr : '!' Expr",
"Expr : READ_INTEGER '(' ')'",
"Expr : READ_LINE '(' ')'",
"Expr : THIS",
"Expr : NEW IDENTIFIER '(' ')'",
"Expr : NEW Type '[' Expr ']'",
"Expr : INSTANCEOF '(' Expr ',' IDENTIFIER ')'",
"Expr : '(' CLASS IDENTIFIER ')' Expr",
"Expr : Expr '?' Expr ':' Expr",
"Expr : Expr PCLONE Expr",
"Constant : LITERAL",
"Constant : NULL",
"Actuals : ExprList",
"Actuals :",
"ExprList : ExprList ',' Expr",
"ExprList : Expr",
"WhileStmt : WHILE '(' Expr ')' Stmt",
"ForStmt : FOR '(' SimpleStmt ';' Expr ';' SimpleStmt ')' Stmt",
"BreakStmt : BREAK",
"ContinueStmt : CONTINUE",
"IfStmt : IF '(' Expr ')' Stmt ElseClause",
"SwitchStmt : SWITCH '(' Expr ')' '{' CaseStmtList DefaultStmt '}'",
"CaseStmtList : CaseStmtList CaseStmt",
"CaseStmtList :",
"CaseStmt : CASE Constant ':' StmtList",
"DefaultStmt : DEFAULT ':' StmtList",
"DefaultStmt :",
"RepeatStmt : REPEAT StmtList UNTIL '(' Expr ')'",
"ElseClause : ELSE Stmt",
"ElseClause :",
"ReturnStmt : RETURN Expr",
"ReturnStmt : RETURN",
"PrintStmt : PRINT '(' ExprList ')'",
};
//#line 486 "Parser.y"
/**
* 打印当前归约所用的语法规则<br>
* 请勿修改。
*/
public boolean onReduce(String rule) {
if (rule.startsWith("$$"))
return false;
else
rule = rule.replaceAll(" \\$\\$\\d+", "");
if (rule.endsWith(":"))
System.out.println(rule + " <empty>");
else
System.out.println(rule);
return false;
}
public void diagnose() {
addReduceListener(this);
yyparse();
}
//#line 694 "Parser.java"
//###############################################################
// method: yylexdebug : check lexer state
//###############################################################
void yylexdebug(int state,int ch)
{
String s=null;
if (ch < 0) ch=0;
if (ch <= YYMAXTOKEN) //check index bounds
s = yyname[ch]; //now get it
if (s==null)
s = "illegal-symbol";
debug("state "+state+", reading "+ch+" ("+s+")");
}
//The following are now global, to aid in error reporting
int yyn; //next next thing to do
int yym; //
int yystate; //current parsing state from state table
String yys; //current token string
//###############################################################
// method: yyparse : parse input and execute indicated items
//###############################################################
int yyparse()
{
boolean doaction;
init_stacks();
yynerrs = 0;
yyerrflag = 0;
yychar = -1; //impossible char forces a read
yystate=0; //initial state
state_push(yystate); //save it
while (true) //until parsing is done, either correctly, or w/error
{
doaction=true;
//if (yydebug) debug("loop");
//#### NEXT ACTION (from reduction table)
for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate])
{
//if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar);
if (yychar < 0) //we want a char?
{
yychar = yylex(); //get next token
//if (yydebug) debug(" next yychar:"+yychar);
//#### ERROR CHECK ####
//if (yychar < 0) //it it didn't work/error
// {
// yychar = 0; //change it to default string (no -1!)
//if (yydebug)
// yylexdebug(yystate,yychar);
// }
}//yychar<0
yyn = yysindex[yystate]; //get amount to shift by (shift index)
if ((yyn != 0) && (yyn += yychar) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yychar)
{
//if (yydebug)
//debug("state "+yystate+", shifting to state "+yytable[yyn]);
//#### NEXT STATE ####
yystate = yytable[yyn];//we are in a new state
state_push(yystate); //save it
val_push(yylval); //push our lval as the input for next rule
yychar = -1; //since we have 'eaten' a token, say we need another
if (yyerrflag > 0) //have we recovered an error?
--yyerrflag; //give ourselves credit
doaction=false; //but don't process yet
break; //quit the yyn=0 loop
}
yyn = yyrindex[yystate]; //reduce
if ((yyn !=0 ) && (yyn += yychar) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yychar)
{ //we reduced!
//if (yydebug) debug("reduce");
yyn = yytable[yyn];
doaction=true; //get ready to execute
break; //drop down to actions
}
else //ERROR RECOVERY
{
if (yyerrflag==0)
{
yyerror("syntax error");
yynerrs++;
}
if (yyerrflag < 3) //low error count?
{
yyerrflag = 3;
while (true) //do until break
{
if (stateptr<0 || valptr<0) //check for under & overflow here
{
return 1;
}
yyn = yysindex[state_peek(0)];
if ((yyn != 0) && (yyn += YYERRCODE) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE)
{
//if (yydebug)
//debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" ");
yystate = yytable[yyn];
state_push(yystate);
val_push(yylval);
doaction=false;
break;
}
else
{
//if (yydebug)
//debug("error recovery discarding state "+state_peek(0)+" ");
if (stateptr<0 || valptr<0) //check for under & overflow here
{
return 1;
}
state_pop();
val_pop();
}
}
}
else //discard this token
{
if (yychar == 0)
return 1; //yyabort
//if (yydebug)
//{
//yys = null;
//if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
//if (yys == null) yys = "illegal-symbol";
//debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")");
//}
yychar = -1; //read another
}
}//end error recovery
}//yyn=0 loop
if (!doaction) //any reason not to proceed?
continue; //skip action
yym = yylen[yyn]; //get count of terminals on rhs
//if (yydebug)
//debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")");
if (yym>0) //if count of rhs not 'nil'
yyval = val_peek(yym-1); //get current semantic value
if (reduceListener == null || reduceListener.onReduce(yyrule[yyn])) // if intercepted!
switch(yyn)
{
//########## USER-SUPPLIED ACTIONS ##########
case 1:
//#line 59 "Parser.y"
{
tree = new Tree.TopLevel(val_peek(0).clist, val_peek(0).loc);
}
break;
case 2:
//#line 65 "Parser.y"
{
yyval.clist.add(val_peek(0).cdef);
}
break;
case 3:
//#line 69 "Parser.y"
{
yyval.clist = new ArrayList<Tree.ClassDef>();
yyval.clist.add(val_peek(0).cdef);
}
break;
case 5:
//#line 79 "Parser.y"
{
yyval.vdef = new Tree.VarDef(val_peek(0).ident, val_peek(1).type, val_peek(0).loc);
}
break;
case 6:
//#line 85 "Parser.y"
{
yyval.type = new Tree.TypeIdent(Tree.INT, val_peek(0).loc);
}
break;
case 7:
//#line 89 "Parser.y"
{
yyval.type = new Tree.TypeIdent(Tree.VOID, val_peek(0).loc);
}
break;
case 8:
//#line 93 "Parser.y"
{
yyval.type = new Tree.TypeIdent(Tree.BOOL, val_peek(0).loc);
}
break;
case 9:
//#line 97 "Parser.y"
{
yyval.type = new Tree.TypeIdent(Tree.STRING, val_peek(0).loc);
}
break;
case 10:
//#line 101 "Parser.y"
{
yyval.type = new Tree.TypeClass(val_peek(0).ident, val_peek(1).loc);
}
break;
case 11:
//#line 105 "Parser.y"
{
yyval.type = new Tree.TypeArray(val_peek(2).type, val_peek(2).loc);
}
break;
case 12:
//#line 111 "Parser.y"
{
yyval.cdef = new Tree.ClassDef(val_peek(4).ident, val_peek(3).ident, val_peek(1).flist, val_peek(5).loc);
}
break;
case 13:
//#line 117 "Parser.y"
{
yyval.ident = val_peek(0).ident;
}
break;
case 14:
//#line 121 "Parser.y"
{
yyval = new SemValue();
}
break;
case 15:
//#line 127 "Parser.y"
{
yyval.flist.add(val_peek(0).vdef);
}
break;
case 16:
//#line 131 "Parser.y"
{
yyval.flist.add(val_peek(0).fdef);
}
break;
case 17:
//#line 135 "Parser.y"
{
yyval = new SemValue();
yyval.flist = new ArrayList<Tree>();
}
break;
case 19:
//#line 143 "Parser.y"
{
yyval = new SemValue();
yyval.vlist = new ArrayList<Tree.VarDef>();
}
break;
case 20:
//#line 150 "Parser.y"
{
yyval.vlist.add(val_peek(0).vdef);
}
break;
case 21:
//#line 154 "Parser.y"
{
yyval.vlist = new ArrayList<Tree.VarDef>();
yyval.vlist.add(val_peek(0).vdef);
}
break;
case 22:
//#line 161 "Parser.y"
{
yyval.fdef = new MethodDef(true, val_peek(4).ident, val_peek(5).type, val_peek(2).vlist, (Block) val_peek(0).stmt, val_peek(4).loc);
}
break;
case 23:
//#line 165 "Parser.y"
{
yyval.fdef = new MethodDef(false, val_peek(4).ident, val_peek(5).type, val_peek(2).vlist, (Block) val_peek(0).stmt, val_peek(4).loc);
}
break;
case 24:
//#line 171 "Parser.y"
{
yyval.stmt = new Block(val_peek(1).slist, val_peek(2).loc);
}
break;
case 25:
//#line 177 "Parser.y"
{
yyval.slist.add(val_peek(0).stmt);
}
break;
case 26:
//#line 181 "Parser.y"
{
yyval = new SemValue();
yyval.slist = new ArrayList<Tree>();
}
break;
case 27:
//#line 188 "Parser.y"
{
yyval.stmt = val_peek(0).vdef;
}
break;
case 28:
//#line 193 "Parser.y"
{
if (yyval.stmt == null) {
yyval.stmt = new Tree.Skip(val_peek(0).loc);
}
}
break;
case 39:
//#line 211 "Parser.y"
{
yyval.stmt = new Tree.Assign(val_peek(2).lvalue, val_peek(0).expr, val_peek(1).loc);
}
break;
case 40:
//#line 215 "Parser.y"
{
yyval.stmt = new Tree.Exec(val_peek(0).expr, val_peek(0).loc);
}
break;
case 41:
//#line 219 "Parser.y"
{
yyval = new SemValue();
}
break;
case 43:
//#line 226 "Parser.y"
{
yyval = new SemValue();
}
break;
case 44:
//#line 232 "Parser.y"
{
yyval.lvalue = new Tree.Ident(val_peek(1).expr, val_peek(0).ident, val_peek(0).loc);
if (val_peek(1).loc == null) {
yyval.loc = val_peek(0).loc;
}
}
break;
case 45:
//#line 239 "Parser.y"
{
yyval.lvalue = new Tree.Indexed(val_peek(3).expr, val_peek(1).expr, val_peek(3).loc);
}
break;
case 46:
//#line 245 "Parser.y"
{
yyval.expr = new Tree.CallExpr(val_peek(4).expr, val_peek(3).ident, val_peek(1).elist, val_peek(3).loc);
if (val_peek(4).loc == null) {
yyval.loc = val_peek(3).loc;
}
}
break;
case 47:
//#line 254 "Parser.y"
{
yyval.expr = val_peek(0).lvalue;
}
break;
case 50:
//#line 260 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.PLUS, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 51:
//#line 264 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.MINUS, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 52:
//#line 268 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.MUL, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 53:
//#line 272 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.DIV, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 54:
//#line 276 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.MOD, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 55:
//#line 280 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.EQ, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 56:
//#line 284 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.NE, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 57:
//#line 288 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.LT, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 58:
//#line 292 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.GT, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 59:
//#line 296 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.LE, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 60:
//#line 300 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.GE, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 61:
//#line 304 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.AND, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 62:
//#line 308 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.OR, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 63:
//#line 312 "Parser.y"
{
yyval = val_peek(1);
}
break;
case 64:
//#line 316 "Parser.y"
{
yyval.expr = new Tree.Unary(Tree.NEG, val_peek(0).expr, val_peek(1).loc);
}
break;
case 65:
//#line 320 "Parser.y"
{
yyval.expr = new Tree.Unary(Tree.NOT, val_peek(0).expr, val_peek(1).loc);
}
break;
case 66:
//#line 324 "Parser.y"
{
yyval.expr = new Tree.ReadIntExpr(val_peek(2).loc);
}
break;
case 67:
//#line 328 "Parser.y"
{
yyval.expr = new Tree.ReadLineExpr(val_peek(2).loc);
}
break;
case 68:
//#line 332 "Parser.y"
{
yyval.expr = new Tree.ThisExpr(val_peek(0).loc);
}
break;
case 69:
//#line 336 "Parser.y"
{
yyval.expr = new Tree.NewClass(val_peek(2).ident, val_peek(3).loc);
}
break;
case 70:
//#line 340 "Parser.y"
{
yyval.expr = new Tree.NewArray(val_peek(3).type, val_peek(1).expr, val_peek(4).loc);
}
break;
case 71:
//#line 344 "Parser.y"
{
yyval.expr = new Tree.TypeTest(val_peek(3).expr, val_peek(1).ident, val_peek(5).loc);
}
break;
case 72:
//#line 348 "Parser.y"
{
yyval.expr = new Tree.TypeCast(val_peek(2).ident, val_peek(0).expr, val_peek(0).loc);
}
break;
case 73:
//#line 352 "Parser.y"
{
yyval.expr = new Tree.Ternary(Tree.CONDEXPR, val_peek(4).expr, val_peek(2).expr, val_peek(0).expr, val_peek(3).loc);
}
break;
case 74:
//#line 356 "Parser.y"
{
yyval.expr = new Tree.Binary(Tree.PCLONE, val_peek(2).expr, val_peek(0).expr, val_peek(1).loc);
}
break;
case 75:
//#line 362 "Parser.y"
{
yyval.expr = new Tree.Literal(val_peek(0).typeTag, val_peek(0).literal, val_peek(0).loc);
}
break;
case 76:
//#line 366 "Parser.y"
{
yyval.expr = new Null(val_peek(0).loc);
}
break;
case 78:
//#line 373 "Parser.y"
{
yyval = new SemValue();
yyval.elist = new ArrayList<Tree.Expr>();
}
break;
case 79:
//#line 380 "Parser.y"
{
yyval.elist.add(val_peek(0).expr);
}
break;
case 80:
//#line 384 "Parser.y"
{
yyval.elist = new ArrayList<Tree.Expr>();
yyval.elist.add(val_peek(0).expr);
}
break;
case 81:
//#line 391 "Parser.y"
{
yyval.stmt = new Tree.WhileLoop(val_peek(2).expr, val_peek(0).stmt, val_peek(4).loc);
}
break;
case 82:
//#line 397 "Parser.y"
{
yyval.stmt = new Tree.ForLoop(val_peek(6).stmt, val_peek(4).expr, val_peek(2).stmt, val_peek(0).stmt, val_peek(8).loc);
}
break;
case 83:
//#line 403 "Parser.y"
{
yyval.stmt = new Tree.Break(val_peek(0).loc);
}
break;
case 84:
//#line 409 "Parser.y"
{
yyval.stmt = new Tree.Continue(val_peek(0).loc);
}
break;
case 85:
//#line 415 "Parser.y"
{
yyval.stmt = new Tree.If(val_peek(3).expr, val_peek(1).stmt, val_peek(0).stmt, val_peek(5).loc);
}
break;
case 86:
//#line 421 "Parser.y"
{
yyval.stmt = new Tree.Switch(val_peek(5).expr, val_peek(2).caselist, val_peek(1).slist, val_peek(7).loc);
}
break;
case 87:
//#line 427 "Parser.y"
{
yyval.caselist.add(val_peek(0).casedef);
}
break;
case 88:
//#line 431 "Parser.y"
{
yyval = new SemValue();
yyval.caselist = new ArrayList<Case>();
}
break;
case 89:
//#line 438 "Parser.y"
{
yyval.casedef = new Tree.Case(val_peek(2).expr, val_peek(0).slist, val_peek(3).loc);
}
break;
case 90:
//#line 444 "Parser.y"
{
yyval.slist = val_peek(0).slist;
}
break;
case 91:
//#line 448 "Parser.y"
{
yyval = new SemValue();
}
break;
case 92:
//#line 454 "Parser.y"
{
yyval.stmt = new Tree.Repeat(val_peek(1).expr, val_peek(4).slist, val_peek(5).loc);
}
break;
case 93:
//#line 460 "Parser.y"
{
yyval.stmt = val_peek(0).stmt;
}
break;
case 94:
//#line 464 "Parser.y"
{
yyval = new SemValue();
}
break;
case 95:
//#line 470 "Parser.y"
{
yyval.stmt = new Tree.Return(val_peek(0).expr, val_peek(1).loc);
}
break;
case 96:
//#line 474 "Parser.y"
{
yyval.stmt = new Tree.Return(null, val_peek(0).loc);
}
break;
case 97:
//#line 480 "Parser.y"
{
yyval.stmt = new Print(val_peek(1).elist, val_peek(3).loc);
}
break;
//#line 1342 "Parser.java"
//########## END OF USER-SUPPLIED ACTIONS ##########
}//switch
//#### Now let's reduce... ####
//if (yydebug) debug("reduce");
state_drop(yym); //we just reduced yylen states
yystate = state_peek(0); //get new state
val_drop(yym); //corresponding value drop
yym = yylhs[yyn]; //select next TERMINAL(on lhs)
if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL
{
//if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+"");
yystate = YYFINAL; //explicitly say we're done
state_push(YYFINAL); //and save it
val_push(yyval); //also save the semantic value of parsing
if (yychar < 0) //we want another character?
{
yychar = yylex(); //get next character
//if (yychar<0) yychar=0; //clean, if necessary
//if (yydebug)
//yylexdebug(yystate,yychar);
}
if (yychar == 0) //Good exit (if lex returns 0 ;-)
break; //quit the loop--all DONE
}//if yystate
else //else not done yet
{ //get next state and push, for next yydefred[]
yyn = yygindex[yym]; //find out where to go
if ((yyn != 0) && (yyn += yystate) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yystate)
yystate = yytable[yyn]; //get new state
else
yystate = yydgoto[yym]; //else go to new defred
//if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+"");
state_push(yystate); //going again, so push state & val...
val_push(yyval); //for next action
}
}//main loop
return 0;//yyaccept!!
}
//## end of method parse() ######################################
//## run() --- for Thread #######################################
//## The -Jnorun option was used ##
//## end of method run() ########################################
//## Constructors ###############################################
//## The -Jnoconstruct option was used ##
//###############################################################
}
//################### END OF CLASS ##############################
| PKUanonym/REKCARC-TSC-UHT | 大三上/编译原理/hw/2016_黄家晖_PA/698609556_1_decaf_PA1A/src/decaf/frontend/Parser.java |
740 | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package routing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import routing.util.RoutingInfo;
import util.Tuple;
import core.Connection;
import core.DTNHost;
import core.Message;
import core.Settings;
import core.SimClock;
/**
* Implementation of PRoPHET router as described in
* <I>Probabilistic routing in intermittently connected networks</I> by
* Anders Lindgren et al.
*
*
* This version tries to estimate a good value of protocol parameters from
* a timescale parameter given by the user, and from the encounters the node
* sees during simulation.
* Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing
* Protocols</I> Chants, 2008
*
*/
public class ProphetRouterWithEstimation extends ActiveRouter {
/** delivery predictability initialization constant*/
public static final double P_INIT = 0.75;
/** delivery predictability transitivity scaling constant default value */
public static final double DEFAULT_BETA = 0.25;
/** delivery predictability aging constant */
public static final double GAMMA = 0.98;
/** default P target */
public static final double DEFAULT_PTARGET = .2;
/** Prophet router's setting namespace ({@value})*/
public static final String PROPHET_NS = "ProphetRouterWithEstimation";
/**
* Number of seconds in time scale.*/
public static final String TIME_SCALE_S ="timeScale";
/**
* Target P_avg
*
*/
public static final String P_AVG_TARGET_S = "targetPavg";
/**
* Transitivity scaling constant (beta) -setting id ({@value}).
* Default value for setting is {@link #DEFAULT_BETA}.
*/
public static final String BETA_S = "beta";
/** values of parameter settings */
private double beta;
private double gamma;
private double pinit;
/** value of time scale variable */
private int timescale;
private double ptavg;
/** delivery predictabilities */
private Map<DTNHost, Double> preds;
/** last meeting time with a node */
private Map<DTNHost, Double> meetings;
private int nrofSamples;
private double meanIET;
/** last delivery predictability update (sim)time */
private double lastAgeUpdate;
/**
* Constructor. Creates a new message router based on the settings in
* the given Settings object.
* @param s The settings object
*/
public ProphetRouterWithEstimation(Settings s) {
super(s);
Settings prophetSettings = new Settings(PROPHET_NS);
timescale = prophetSettings.getInt(TIME_SCALE_S);
if (prophetSettings.contains(P_AVG_TARGET_S)) {
ptavg = prophetSettings.getDouble(P_AVG_TARGET_S);
} else {
ptavg = DEFAULT_PTARGET;
}
if (prophetSettings.contains(BETA_S)) {
beta = prophetSettings.getDouble(BETA_S);
} else {
beta = DEFAULT_BETA;
}
gamma = GAMMA;
pinit = P_INIT;
initPreds();
initMeetings();
}
/**
* Copyconstructor.
* @param r The router prototype where setting values are copied from
*/
protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) {
super(r);
this.timescale = r.timescale;
this.ptavg = r.ptavg;
this.beta = r.beta;
initPreds();
initMeetings();
}
/**
* Initializes predictability hash
*/
private void initPreds() {
this.preds = new HashMap<DTNHost, Double>();
}
/**
* Initializes inter-encounter time estimator
*/
private void initMeetings() {
this.meetings = new HashMap<DTNHost, Double>();
this.meanIET = 0;
this.nrofSamples = 0;
}
@Override
public void changedConnection(Connection con) {
super.changedConnection(con);
if (con.isUp()) {
DTNHost otherHost = con.getOtherNode(getHost());
if (updateIET(otherHost)) {
updateParams();
}
updateDeliveryPredFor(otherHost);
updateTransitivePreds(otherHost);
}
}
/**
* Updates the interencounter time estimates
* @param host
*/
private boolean updateIET(DTNHost host) {
/* First estimate the mean InterEncounter Time */
double currentTime = SimClock.getTime();
if (meetings.containsKey(host)) {
double timeDiff = currentTime - meetings.get(host);
// System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host));
nrofSamples++;
meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET
+ (1 / (double)nrofSamples) * timeDiff;
meetings.put(host, currentTime);
return true;
} else {
/* nothing to update */
meetings.put(host,currentTime);
return false;
}
}
/**
* update PROPHET parameters
*
*/
private void updateParams()
{
double b;
double zeta;
double err;
boolean cond;
int ntarg;
double zetadiff;
int ozeta;
double pstable;
double pavg;
double ee;
double bdiff;
int ob;
int zcount;
boolean bcheck;
double pnzero;
double pnone;
double eezero;
double eeone;
/*
* the estimation algorith does not work for timescales
* shorter than the mean IET - so use defaults
*/
if (meanIET > (double)timescale) {
System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale);
return;
}
if (meanIET == 0) {
System.out.printf("Mean IET == 0\n");
return;
}
System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET);
b = 1e-5;
zeta = .9;
err = 0.005;
zetadiff = .1;
ozeta = 0;
cond = false;
ntarg = (int)Math.ceil((double)timescale/(double)meanIET);
while (cond == false) {
pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta);
pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) *
(1- Math.exp( -b*meanIET));
if (Double.isNaN(pavg)) {
pavg = 1;
}
if (pavg > ptavg) {
//System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg);
if (ozeta == 2) {
zetadiff = zetadiff / 2.0;
}
ozeta = 1;
zeta = zeta + zetadiff;
if (zeta >= 1) {
zeta = 1-zetadiff;
zetadiff = zetadiff / 2.0;
ozeta = 0;
}
} else {
if (pavg < ptavg * (1-err)) {
// System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg);
if (ozeta == 1) {
zetadiff = zetadiff / 2.0;
}
ozeta = 2;
zeta = zeta-zetadiff;
if (zeta <= 0) {
zeta = 0 + zetadiff;
zetadiff = zetadiff / 2.0;
ozeta = 0;
}
} else {
cond = true;
}
}
//System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff);
ee = 1;
bdiff = .1;
ob = 0;
zcount = 0; // if 100 iterations won't help, lets increase zeta...
bcheck = false;
while (bcheck == false) {
pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta);
pnzero = Math.exp(-b*meanIET) * (1-zeta) *
((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/
(1-zeta*Math.exp(-b*meanIET)));
pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero;
eezero = Math.abs(pnzero-pstable);
eeone = Math.abs(pnone -pstable);
ee = Math.max(eezero,eeone);
// System.out.printf("Zeta: %f\n", zeta);
// System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable);
// System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone);
// System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone);
if (ee > err) {
if (ob == 2) {
bdiff = bdiff / 2.0;
}
ob = 1;
b = b+bdiff;
} else {
if (ee < (err*(1-err))) {
if (ob == 1) {
bdiff = bdiff / 2.0;
}
ob = 2;
b = b-bdiff;
if (b <= 0) {
b = 0 + bdiff;
bdiff = bdiff / 1.5;
ob = 0;
}
} else {
bcheck = true;
// System.out.println("******");
}
}
// System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff);
zcount = zcount + 1;
if (zcount > 100) {
bcheck = true;
ozeta = 0;
}
}
}
gamma = Math.exp(-b);
pinit = 1-zeta;
}
/**
* Updates delivery predictions for a host.
* <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE>
* @param host The host we just met
*/
private void updateDeliveryPredFor(DTNHost host) {
double oldValue = getPredFor(host);
double newValue = oldValue + (1 - oldValue) * pinit;
preds.put(host, newValue);
}
/**
* Returns the current prediction (P) value for a host or 0 if entry for
* the host doesn't exist.
* @param host The host to look the P for
* @return the current P value
*/
public double getPredFor(DTNHost host) {
ageDeliveryPreds(); // make sure preds are updated before getting
if (preds.containsKey(host)) {
return preds.get(host);
}
else {
return 0;
}
}
/**
* Updates transitive (A->B->C) delivery predictions.
* <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA
* </CODE>
* @param host The B host who we just met
*/
private void updateTransitivePreds(DTNHost host) {
MessageRouter otherRouter = host.getRouter();
assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " +
" with other routers of same type";
double pForHost = getPredFor(host); // P(a,b)
Map<DTNHost, Double> othersPreds =
((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds();
for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) {
if (e.getKey() == getHost()) {
continue; // don't add yourself
}
double pOld = getPredFor(e.getKey()); // P(a,c)_old
double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta;
preds.put(e.getKey(), pNew);
}
}
/**
* Ages all entries in the delivery predictions.
* <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of
* time units that have elapsed since the last time the metric was aged.
*/
private void ageDeliveryPreds() {
double timeDiff = (SimClock.getTime() - this.lastAgeUpdate);
if (timeDiff == 0) {
return;
}
double mult = Math.pow(gamma, timeDiff);
for (Map.Entry<DTNHost, Double> e : preds.entrySet()) {
e.setValue(e.getValue()*mult);
}
this.lastAgeUpdate = SimClock.getTime();
}
/**
* Returns a map of this router's delivery predictions
* @return a map of this router's delivery predictions
*/
private Map<DTNHost, Double> getDeliveryPreds() {
ageDeliveryPreds(); // make sure the aging is done
return this.preds;
}
@Override
public void update() {
super.update();
if (!canStartTransfer() ||isTransferring()) {
return; // nothing to transfer or is currently transferring
}
// try messages that could be delivered to final recipient
if (exchangeDeliverableMessages() != null) {
return;
}
tryOtherMessages();
}
/**
* Tries to send all other messages to all connected hosts ordered by
* their delivery probability
* @return The return value of {@link #tryMessagesForConnected(List)}
*/
private Tuple<Message, Connection> tryOtherMessages() {
List<Tuple<Message, Connection>> messages =
new ArrayList<Tuple<Message, Connection>>();
Collection<Message> msgCollection = getMessageCollection();
/* for all connected hosts collect all messages that have a higher
probability of delivery by the other host */
for (Connection con : getConnections()) {
DTNHost other = con.getOtherNode(getHost());
ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter();
if (othRouter.isTransferring()) {
continue; // skip hosts that are transferring
}
for (Message m : msgCollection) {
if (othRouter.hasMessage(m.getId())) {
continue; // skip messages that the other one has
}
if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) {
// the other node has higher probability of delivery
messages.add(new Tuple<Message, Connection>(m,con));
}
}
}
if (messages.size() == 0) {
return null;
}
// sort the message-connection tuples
Collections.sort(messages, new TupleComparator());
return tryMessagesForConnected(messages); // try to send messages
}
/**
* Comparator for Message-Connection-Tuples that orders the tuples by
* their delivery probability by the host on the other side of the
* connection (GRTRMax)
*/
private class TupleComparator implements Comparator
<Tuple<Message, Connection>> {
public int compare(Tuple<Message, Connection> tuple1,
Tuple<Message, Connection> tuple2) {
// delivery probability of tuple1's message with tuple1's connection
double p1 = ((ProphetRouterWithEstimation)tuple1.getValue().
getOtherNode(getHost()).getRouter()).getPredFor(
tuple1.getKey().getTo());
// -"- tuple2...
double p2 = ((ProphetRouterWithEstimation)tuple2.getValue().
getOtherNode(getHost()).getRouter()).getPredFor(
tuple2.getKey().getTo());
// bigger probability should come first
if (p2-p1 == 0) {
/* equal probabilities -> let queue mode decide */
return compareByQueueMode(tuple1.getKey(), tuple2.getKey());
}
else if (p2-p1 < 0) {
return -1;
}
else {
return 1;
}
}
}
@Override
public RoutingInfo getRoutingInfo() {
ageDeliveryPreds();
RoutingInfo top = super.getRoutingInfo();
RoutingInfo ri = new RoutingInfo(preds.size() +
" delivery prediction(s)");
for (Map.Entry<DTNHost, Double> e : preds.entrySet()) {
DTNHost host = e.getKey();
Double value = e.getValue();
ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f",
host, value)));
}
ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples)));
ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma)));
ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit)));
top.addMoreInfo(ri);
return top;
}
@Override
public MessageRouter replicate() {
ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this);
return r;
}
}
| aunroel/the-one | src/routing/ProphetRouterWithEstimation.java |
741 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.doris.load;
import org.apache.doris.common.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class MiniEtlTaskInfo implements Writable {
private long id;
private long backendId;
private long tableId;
private final EtlStatus taskStatus;
public MiniEtlTaskInfo() {
this(-1L, -1L, -1L);
}
public MiniEtlTaskInfo(long id, long backendId, long tableId) {
this.id = id;
this.backendId = backendId;
this.tableId = tableId;
this.taskStatus = new EtlStatus();
}
public long getId() {
return id;
}
public long getBackendId() {
return backendId;
}
public long getTableId() {
return tableId;
}
public EtlStatus getTaskStatus() {
return taskStatus;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeLong(id);
out.writeLong(backendId);
out.writeLong(tableId);
}
public void readFields(DataInput in) throws IOException {
id = in.readLong();
backendId = in.readLong();
tableId = in.readLong();
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof MiniEtlTaskInfo)) {
return false;
}
MiniEtlTaskInfo taskInfo = (MiniEtlTaskInfo) obj;
return id == taskInfo.id
&& backendId == taskInfo.backendId
&& tableId == taskInfo.tableId;
}
}
| apache/doris | fe/fe-core/src/main/java/org/apache/doris/load/MiniEtlTaskInfo.java |