file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
2,307
/* * Copyright (c) 2010-2021 Haifeng Li. All rights reserved. * * Smile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Smile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Smile. If not, see <https://www.gnu.org/licenses/>. */ package smile.math.special; import static java.lang.Math.*; /** * The error function. The error function (or the Gauss error function) * is a special function of sigmoid shape which occurs in probability, * statistics, materials science, and partial differential equations. * It is defined as: * <p> * erf(x) = <i>&#8747;<sub><small>0</small></sub><sup><small>x</small></sup> e<sup>-t^2</sup>dt</i> * <p> * The complementary error function, denoted erfc, is defined as * <code>erfc(x) = 1 - erf(x)</code>. The error function and complementary * error function are special cases of the incomplete gamma function. * * @author Haifeng Li */ public class Erf { /** Utility classes should not have public constructors. */ private Erf() { } private static final double[] cof = { -1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2, -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4, 4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6, 1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8, 6.529054439e-9, 5.059343495e-9, -9.91364156e-10, -2.27365122e-10, 9.6467911e-11, 2.394038e-12, -6.886027e-12, 8.94487e-13, 3.13092e-13, -1.12708e-13, 3.81e-16, 7.106e-15, -1.523e-15, -9.4e-17, 1.21e-16, -2.8e-17 }; /** * The Gauss error function. * @param x a real number. * @return the function value. */ public static double erf(double x) { if (x >= 0.) { return 1.0 - erfccheb(x); } else { return erfccheb(-x) - 1.0; } } /** * The complementary error function. * @param x a real number. * @return the function value. */ public static double erfc(double x) { if (x >= 0.) { return erfccheb(x); } else { return 2.0 - erfccheb(-x); } } /** * The complementary error function with fractional error everywhere less * than 1.2 &times; 10<sup>-7</sup>. This concise routine is faster than erfc. * @param x a real number. * @return the function value. */ public static double erfcc(double x) { double z = abs(x); double t = 2.0 / (2.0 + z); double ans = t * exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))))); return (x >= 0.0 ? ans : 2.0 - ans); } private static double erfccheb(double z) { double t, ty, tmp, d = 0., dd = 0.; if (z < 0.) { throw new IllegalArgumentException("erfccheb requires non-negative argument"); } t = 2. / (2. + z); ty = 4. * t - 2.; for (int j = cof.length - 1; j > 0; j--) { tmp = d; d = ty * d - dd + cof[j]; dd = tmp; } return t * exp(-z * z + 0.5 * (cof[0] + ty * d) - dd); } /** * The inverse complementary error function. * @param p a real number. * @return the function value. */ public static double inverfc(double p) { double x, err, t, pp; if (p >= 2.0) { return -100.; } if (p <= 0.0) { return 100.; } pp = (p < 1.0) ? p : 2. - p; t = sqrt(-2. * log(pp / 2.)); x = -0.70711 * ((2.30753 + t * 0.27061) / (1. + t * (0.99229 + t * 0.04481)) - t); for (int j = 0; j < 2; j++) { err = erfc(x) - pp; x += err / (1.12837916709551257 * exp(-x * x) - x * err); } return (p < 1.0 ? x : -x); } /** * The inverse error function. * @param p a real number. * @return the function value. */ public static double inverf(double p) { return inverfc(1. - p); } }
haifengl/smile
base/src/main/java/smile/math/special/Erf.java
2,308
/* * Copyright 2002-2022 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.util; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.Function; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; /** * Benchmarks for {@link ConcurrentLruCache}. * @author Brian Clozel */ @BenchmarkMode(Mode.Throughput) public class ConcurrentLruCacheBenchmark { @Benchmark public void lruCache(BenchmarkData data, Blackhole bh) { for (String element : data.elements) { String value = data.lruCache.get(element); bh.consume(value); } } @State(Scope.Benchmark) public static class BenchmarkData { ConcurrentLruCache<String, String> lruCache; @Param({"100"}) public int capacity; @Param({"0.1"}) public float cacheMissRate; public List<String> elements; public Function<String, String> generator; @Setup(Level.Iteration) public void setup() { this.generator = key -> key + "value"; this.lruCache = new ConcurrentLruCache<>(this.capacity, this.generator); Assert.isTrue(this.cacheMissRate < 1, "cache miss rate should be < 1"); Random random = new Random(); int elementsCount = Math.round(this.capacity * (1 + this.cacheMissRate)); this.elements = new ArrayList<>(elementsCount); random.ints(elementsCount).forEach(value -> this.elements.add(String.valueOf(value))); this.elements.sort(String::compareTo); } } }
spring-projects/spring-framework
spring-core/src/jmh/java/org/springframework/util/ConcurrentLruCacheBenchmark.java
2,309
package com.baeldung.i; public interface BearKeeper { void washTheBear(); void feedTheBear(); void petTheBear(); }
eugenp/tutorials
patterns-modules/solid/src/main/java/com/baeldung/i/BearKeeper.java
2,310
package mindustry.world.modules; import arc.math.*; import arc.struct.*; import arc.util.*; import arc.util.io.*; import mindustry.type.*; import java.util.*; import static mindustry.Vars.*; public class ItemModule extends BlockModule{ public static final ItemModule empty = new ItemModule(); private static final int windowSize = 6; private static WindowedMean[] cacheFlow; private static float[] cacheSums; private static float[] displayFlow; private static final Bits cacheBits = new Bits(); private static final Interval flowTimer = new Interval(2); private static final float pollScl = 20f; protected int[] items = new int[content.items().size]; protected int total; protected int takeRotation; private @Nullable WindowedMean[] flow; public ItemModule copy(){ ItemModule out = new ItemModule(); out.set(this); return out; } public void set(ItemModule other){ total = other.total; takeRotation = other.takeRotation; System.arraycopy(other.items, 0, items, 0, items.length); } public void updateFlow(){ //update the flow at N fps at most if(flowTimer.get(1, pollScl)){ if(flow == null){ if(cacheFlow == null || cacheFlow.length != items.length){ cacheFlow = new WindowedMean[items.length]; for(int i = 0; i < items.length; i++){ cacheFlow[i] = new WindowedMean(windowSize); } cacheSums = new float[items.length]; displayFlow = new float[items.length]; }else{ for(int i = 0; i < items.length; i++){ cacheFlow[i].reset(); } Arrays.fill(cacheSums, 0); cacheBits.clear(); } Arrays.fill(displayFlow, -1); flow = cacheFlow; } boolean updateFlow = flowTimer.get(30); for(int i = 0; i < items.length; i++){ flow[i].add(cacheSums[i]); if(cacheSums[i] > 0){ cacheBits.set(i); } cacheSums[i] = 0; if(updateFlow){ displayFlow[i] = flow[i].hasEnoughData() ? flow[i].mean() / pollScl : -1; } } } } public void stopFlow(){ flow = null; } public int length(){ return items.length; } /** @return a specific item's flow rate in items/s; any value < 0 means not ready.*/ public float getFlowRate(Item item){ return flow == null ? -1f : displayFlow[item.id] * 60; } public boolean hasFlowItem(Item item){ return flow != null && cacheBits.get(item.id); } public void each(ItemConsumer cons){ for(int i = 0; i < items.length; i++){ if(items[i] != 0){ cons.accept(content.item(i), items[i]); } } } public float sum(ItemCalculator calc){ float sum = 0f; for(int i = 0; i < items.length; i++){ if(items[i] > 0){ sum += calc.get(content.item(i), items[i]); } } return sum; } public boolean has(int id){ return items[id] > 0; } public boolean has(Item item){ return get(item) > 0; } public boolean has(Item item, int amount){ return get(item) >= amount; } public boolean has(ItemStack[] stacks){ for(ItemStack stack : stacks){ if(!has(stack.item, stack.amount)) return false; } return true; } public boolean has(ItemSeq items){ for(Item item : content.items()){ if(!has(item, items.get(item))){ return false; } } return true; } public boolean has(Iterable<ItemStack> stacks){ for(ItemStack stack : stacks){ if(!has(stack.item, stack.amount)) return false; } return true; } public boolean has(ItemStack[] stacks, float multiplier){ for(ItemStack stack : stacks){ if(!has(stack.item, Math.round(stack.amount * multiplier))) return false; } return true; } /** * Returns true if this entity has at least one of each item in each stack. */ public boolean hasOne(ItemStack[] stacks){ for(ItemStack stack : stacks){ if(!has(stack.item, 1)) return false; } return true; } public boolean empty(){ return total == 0; } public int total(){ return total; } public boolean any(){ return total > 0; } @Nullable public Item first(){ for(int i = 0; i < items.length; i++){ if(items[i] > 0){ return content.item(i); } } return null; } @Nullable public Item take(){ for(int i = 0; i < items.length; i++){ int index = (i + takeRotation); if(index >= items.length) index -= items.length; if(items[index] > 0){ items[index] --; total --; takeRotation = index + 1; return content.item(index); } } return null; } /** Begins a speculative take operation. This returns the item that would be returned by #take(), but does not change state. */ @Nullable public Item takeIndex(int takeRotation){ for(int i = 0; i < items.length; i++){ int index = (i + takeRotation); if(index >= items.length) index -= items.length; if(items[index] > 0){ return content.item(index); } } return null; } public int nextIndex(int takeRotation){ for(int i = 1; i < items.length; i++){ int index = (i + takeRotation); if(index >= items.length) index -= items.length; if(items[index] > 0){ return (takeRotation + i) % items.length; } } return takeRotation; } public int get(int id){ return items[id]; } public int get(Item item){ return items[item.id]; } public void set(Item item, int amount){ total += (amount - items[item.id]); items[item.id] = amount; } public void add(Iterable<ItemStack> stacks){ for(ItemStack stack : stacks){ add(stack.item, stack.amount); } } public void add(ItemSeq stacks){ stacks.each(this::add); } public void add(ItemModule items){ for(int i = 0; i < items.items.length; i++){ add(i, items.items[i]); } } public void add(Item item, int amount){ add(item.id, amount); } private void add(int item, int amount){ items[item] += amount; total += amount; if(flow != null){ cacheSums[item] += amount; } } public void handleFlow(Item item, int amount){ if(flow != null){ cacheSums[item.id] += amount; } } public void undoFlow(Item item){ if(flow != null){ cacheSums[item.id] -= 1; } } public void remove(Item item, int amount){ amount = Math.min(amount, items[item.id]); items[item.id] -= amount; total -= amount; } public void remove(ItemStack[] stacks){ for(ItemStack stack : stacks) remove(stack.item, stack.amount); } public void remove(ItemSeq stacks){ stacks.each(this::remove); } public void remove(Iterable<ItemStack> stacks){ for(ItemStack stack : stacks) remove(stack.item, stack.amount); } public void remove(ItemStack stack){ remove(stack.item, stack.amount); } public void clear(){ Arrays.fill(items, 0); total = 0; } @Override public void write(Writes write){ int amount = 0; for(int item : items){ if(item > 0) amount++; } write.s(amount); for(int i = 0; i < items.length; i++){ if(items[i] > 0){ write.s(i); //item ID write.i(items[i]); //item amount } } } @Override public void read(Reads read, boolean legacy){ //just in case, reset items Arrays.fill(items, 0); int count = legacy ? read.ub() : read.s(); total = 0; for(int j = 0; j < count; j++){ int itemid = legacy ? read.ub() : read.s(); int itemamount = read.i(); Item item = content.item(itemid); if(item != null){ items[item.id] = itemamount; total += itemamount; } } } public interface ItemConsumer{ void accept(Item item, int amount); } public interface ItemCalculator{ float get(Item item, int amount); } @Override public String toString(){ var res = new StringBuilder(); res.append("ItemModule{"); boolean any = false; for(int i = 0; i < items.length; i++){ if(items[i] != 0){ res.append(content.items().get(i).name).append(":").append(items[i]).append(","); any = true; } } if(any){ res.setLength(res.length() - 1); } res.append("}"); return res.toString(); } }
Anuken/Mindustry
core/src/mindustry/world/modules/ItemModule.java
2,311
package org.opencv.android; import java.util.List; import org.opencv.BuildConfig; import org.opencv.R; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; /** * This is a basic class, implementing the interaction with Camera and OpenCV library. * The main responsibility of it - is to control when camera can be enabled, process the frame, * call external listener to make any adjustments to the frame and then draw the resulting * frame to the screen. * The clients shall implement CvCameraViewListener. */ public abstract class CameraBridgeViewBase extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = "CameraBridge"; protected static final int MAX_UNSPECIFIED = -1; private static final int STOPPED = 0; private static final int STARTED = 1; private int mState = STOPPED; private Bitmap mCacheBitmap; private CvCameraViewListener2 mListener; private boolean mSurfaceExist; private final Object mSyncObject = new Object(); protected int mFrameWidth; protected int mFrameHeight; protected int mMaxHeight; protected int mMaxWidth; protected float mScale = 0; protected int mPreviewFormat = RGBA; protected int mCameraIndex = CAMERA_ID_ANY; protected boolean mEnabled; protected boolean mCameraPermissionGranted = false; protected FpsMeter mFpsMeter = null; public static final int CAMERA_ID_ANY = -1; public static final int CAMERA_ID_BACK = 99; public static final int CAMERA_ID_FRONT = 98; public static final int RGBA = 1; public static final int GRAY = 2; public CameraBridgeViewBase(Context context, int cameraId) { super(context); mCameraIndex = cameraId; getHolder().addCallback(this); mMaxWidth = MAX_UNSPECIFIED; mMaxHeight = MAX_UNSPECIFIED; } public CameraBridgeViewBase(Context context, AttributeSet attrs) { super(context, attrs); int count = attrs.getAttributeCount(); Log.d(TAG, "Attr count: " + Integer.valueOf(count)); TypedArray styledAttrs = getContext().obtainStyledAttributes(attrs, R.styleable.CameraBridgeViewBase); if (styledAttrs.getBoolean(R.styleable.CameraBridgeViewBase_show_fps, false)) enableFpsMeter(); mCameraIndex = styledAttrs.getInt(R.styleable.CameraBridgeViewBase_camera_id, -1); getHolder().addCallback(this); mMaxWidth = MAX_UNSPECIFIED; mMaxHeight = MAX_UNSPECIFIED; styledAttrs.recycle(); } /** * Sets the camera index * @param cameraIndex new camera index */ public void setCameraIndex(int cameraIndex) { this.mCameraIndex = cameraIndex; } public interface CvCameraViewListener { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when delivery of the frame needs to be done. * The returned values - is a modified frame which needs to be displayed on the screen. * TODO: pass the parameters specifying the format of the frame (BPP, YUV or RGB and etc) */ public Mat onCameraFrame(Mat inputFrame); } public interface CvCameraViewListener2 { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when delivery of the frame needs to be done. * The returned values - is a modified frame which needs to be displayed on the screen. * TODO: pass the parameters specifying the format of the frame (BPP, YUV or RGB and etc) */ public Mat onCameraFrame(CvCameraViewFrame inputFrame); }; protected class CvCameraViewListenerAdapter implements CvCameraViewListener2 { public CvCameraViewListenerAdapter(CvCameraViewListener oldStypeListener) { mOldStyleListener = oldStypeListener; } public void onCameraViewStarted(int width, int height) { mOldStyleListener.onCameraViewStarted(width, height); } public void onCameraViewStopped() { mOldStyleListener.onCameraViewStopped(); } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { Mat result = null; switch (mPreviewFormat) { case RGBA: result = mOldStyleListener.onCameraFrame(inputFrame.rgba()); break; case GRAY: result = mOldStyleListener.onCameraFrame(inputFrame.gray()); break; default: Log.e(TAG, "Invalid frame format! Only RGBA and Gray Scale are supported!"); }; return result; } public void setFrameFormat(int format) { mPreviewFormat = format; } private int mPreviewFormat = RGBA; private CvCameraViewListener mOldStyleListener; }; /** * This class interface is abstract representation of single frame from camera for onCameraFrame callback * Attention: Do not use objects, that represents this interface out of onCameraFrame callback! */ public interface CvCameraViewFrame { /** * This method returns RGBA Mat with frame */ public Mat rgba(); /** * This method returns single channel gray scale Mat with frame */ public Mat gray(); public void release(); }; public class RotatedCameraFrame implements CvCameraViewFrame { @Override public Mat gray() { if (mRotation != 0) { Core.rotate(mFrame.gray(), mGrayRotated, getCvRotationCode(mRotation)); return mGrayRotated; } else { return mFrame.gray(); } } @Override public Mat rgba() { if (mRotation != 0) { Core.rotate(mFrame.rgba(), mRgbaRotated, getCvRotationCode(mRotation)); return mRgbaRotated; } else { return mFrame.rgba(); } } private int getCvRotationCode(int degrees) { if (degrees == 90) { return Core.ROTATE_90_CLOCKWISE; } else if (degrees == 180) { return Core.ROTATE_180; } else { return Core.ROTATE_90_COUNTERCLOCKWISE; } } public RotatedCameraFrame(CvCameraViewFrame frame, int rotation) { super(); mFrame = frame; mRgbaRotated = new Mat(); mGrayRotated = new Mat(); mRotation = rotation; } @Override public void release() { mRgbaRotated.release(); mGrayRotated.release(); } public CvCameraViewFrame mFrame; private Mat mRgbaRotated; private Mat mGrayRotated; private int mRotation; }; /** * Calculates how to rotate camera frame to match current screen orientation */ protected int getFrameRotation(boolean cameraFacingFront, int cameraSensorOrientation) { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); int screenOrientation = windowManager.getDefaultDisplay().getRotation(); int screenRotation = 0; switch (screenOrientation) { case Surface.ROTATION_0: screenRotation = 0; break; case Surface.ROTATION_90: screenRotation = 90; break; case Surface.ROTATION_180: screenRotation = 180; break; case Surface.ROTATION_270: screenRotation = 270; break; } int frameRotation; if (cameraFacingFront) { frameRotation = (cameraSensorOrientation + screenRotation) % 360; } else { frameRotation = (cameraSensorOrientation - screenRotation + 360) % 360; } return frameRotation; } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { Log.d(TAG, "call surfaceChanged event"); synchronized(mSyncObject) { if (!mSurfaceExist) { mSurfaceExist = true; checkCurrentState(); } else { /** Surface changed. We need to stop camera and restart with new parameters */ /* Pretend that old surface has been destroyed */ mSurfaceExist = false; checkCurrentState(); /* Now use new surface. Say we have it now */ mSurfaceExist = true; checkCurrentState(); } } } public void surfaceCreated(SurfaceHolder holder) { /* Do nothing. Wait until surfaceChanged delivered */ } public void surfaceDestroyed(SurfaceHolder holder) { synchronized(mSyncObject) { mSurfaceExist = false; checkCurrentState(); } } /** * This method is provided for clients, so they can signal camera permission has been granted. * The actual onCameraViewStarted callback will be delivered only after setCameraPermissionGranted * and enableView have been called and surface is available */ public void setCameraPermissionGranted() { synchronized(mSyncObject) { mCameraPermissionGranted = true; checkCurrentState(); } } /** * This method is provided for clients, so they can enable the camera connection. * The actual onCameraViewStarted callback will be delivered only after setCameraPermissionGranted * and enableView have been called and surface is available */ public void enableView() { synchronized(mSyncObject) { mEnabled = true; checkCurrentState(); } } /** * This method is provided for clients, so they can disable camera connection and stop * the delivery of frames even though the surface view itself is not destroyed and still stays on the screen */ public void disableView() { synchronized(mSyncObject) { mEnabled = false; checkCurrentState(); } } /** * This method enables label with fps value on the screen */ public void enableFpsMeter() { if (mFpsMeter == null) { mFpsMeter = new FpsMeter(); mFpsMeter.setResolution(mFrameWidth, mFrameHeight); } } public void disableFpsMeter() { mFpsMeter = null; } /** * * @param listener */ public void setCvCameraViewListener(CvCameraViewListener2 listener) { mListener = listener; } public void setCvCameraViewListener(CvCameraViewListener listener) { CvCameraViewListenerAdapter adapter = new CvCameraViewListenerAdapter(listener); adapter.setFrameFormat(mPreviewFormat); mListener = adapter; } /** * This method sets the maximum size that camera frame is allowed to be. When selecting * size - the biggest size which less or equal the size set will be selected. * As an example - we set setMaxFrameSize(200,200) and we have 176x152 and 320x240 sizes. The * preview frame will be selected with 176x152 size. * This method is useful when need to restrict the size of preview frame for some reason (for example for video recording) * @param maxWidth - the maximum width allowed for camera frame. * @param maxHeight - the maximum height allowed for camera frame */ public void setMaxFrameSize(int maxWidth, int maxHeight) { mMaxWidth = maxWidth; mMaxHeight = maxHeight; } public void SetCaptureFormat(int format) { mPreviewFormat = format; if (mListener instanceof CvCameraViewListenerAdapter) { CvCameraViewListenerAdapter adapter = (CvCameraViewListenerAdapter) mListener; adapter.setFrameFormat(mPreviewFormat); } } /** * Called when mSyncObject lock is held */ private void checkCurrentState() { Log.d(TAG, "call checkCurrentState"); int targetState; if (mEnabled && mCameraPermissionGranted && mSurfaceExist && getVisibility() == VISIBLE) { targetState = STARTED; } else { targetState = STOPPED; } if (targetState != mState) { /* The state change detected. Need to exit the current state and enter target state */ processExitState(mState); mState = targetState; processEnterState(mState); } } private void processEnterState(int state) { Log.d(TAG, "call processEnterState: " + state); switch(state) { case STARTED: onEnterStartedState(); if (mListener != null) { mListener.onCameraViewStarted(mFrameWidth, mFrameHeight); } break; case STOPPED: onEnterStoppedState(); if (mListener != null) { mListener.onCameraViewStopped(); } break; }; } private void processExitState(int state) { Log.d(TAG, "call processExitState: " + state); switch(state) { case STARTED: onExitStartedState(); break; case STOPPED: onExitStoppedState(); break; }; } private void onEnterStoppedState() { /* nothing to do */ } private void onExitStoppedState() { /* nothing to do */ } // NOTE: The order of bitmap constructor and camera connection is important for android 4.1.x // Bitmap must be constructed before surface private void onEnterStartedState() { Log.d(TAG, "call onEnterStartedState"); /* Connect camera */ if (!connectCamera(getWidth(), getHeight())) { AlertDialog ad = new AlertDialog.Builder(getContext()).create(); ad.setCancelable(false); // This blocks the 'BACK' button ad.setMessage("It seems that your device does not support camera (or it is locked). Application will be closed."); ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ((Activity) getContext()).finish(); } }); ad.show(); } } private void onExitStartedState() { disconnectCamera(); if (mCacheBitmap != null) { mCacheBitmap.recycle(); } } /** * This method shall be called by the subclasses when they have valid * object and want it to be delivered to external client (via callback) and * then displayed on the screen. * @param frame - the current frame to be delivered */ protected void deliverAndDrawFrame(CvCameraViewFrame frame) { Mat modified; if (mListener != null) { modified = mListener.onCameraFrame(frame); } else { modified = frame.rgba(); } boolean bmpValid = true; if (modified != null) { try { Utils.matToBitmap(modified, mCacheBitmap); } catch(Exception e) { Log.e(TAG, "Mat type: " + modified); Log.e(TAG, "Bitmap type: " + mCacheBitmap.getWidth() + "*" + mCacheBitmap.getHeight()); Log.e(TAG, "Utils.matToBitmap() throws an exception: " + e.getMessage()); bmpValid = false; } } if (bmpValid && mCacheBitmap != null) { Canvas canvas = getHolder().lockCanvas(); if (canvas != null) { canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR); if (BuildConfig.DEBUG) Log.d(TAG, "mStretch value: " + mScale); if (mScale != 0) { canvas.drawBitmap(mCacheBitmap, new Rect(0,0,mCacheBitmap.getWidth(), mCacheBitmap.getHeight()), new Rect((int)((canvas.getWidth() - mScale*mCacheBitmap.getWidth()) / 2), (int)((canvas.getHeight() - mScale*mCacheBitmap.getHeight()) / 2), (int)((canvas.getWidth() - mScale*mCacheBitmap.getWidth()) / 2 + mScale*mCacheBitmap.getWidth()), (int)((canvas.getHeight() - mScale*mCacheBitmap.getHeight()) / 2 + mScale*mCacheBitmap.getHeight())), null); } else { canvas.drawBitmap(mCacheBitmap, new Rect(0,0,mCacheBitmap.getWidth(), mCacheBitmap.getHeight()), new Rect((canvas.getWidth() - mCacheBitmap.getWidth()) / 2, (canvas.getHeight() - mCacheBitmap.getHeight()) / 2, (canvas.getWidth() - mCacheBitmap.getWidth()) / 2 + mCacheBitmap.getWidth(), (canvas.getHeight() - mCacheBitmap.getHeight()) / 2 + mCacheBitmap.getHeight()), null); } if (mFpsMeter != null) { mFpsMeter.measure(); mFpsMeter.draw(canvas, 20, 30); } getHolder().unlockCanvasAndPost(canvas); } } } /** * This method is invoked shall perform concrete operation to initialize the camera. * CONTRACT: as a result of this method variables mFrameWidth and mFrameHeight MUST be * initialized with the size of the Camera frames that will be delivered to external processor. * @param width - the width of this SurfaceView * @param height - the height of this SurfaceView */ protected abstract boolean connectCamera(int width, int height); /** * Disconnects and release the particular camera object being connected to this surface view. * Called when syncObject lock is held */ protected abstract void disconnectCamera(); // NOTE: On Android 4.1.x the function must be called before SurfaceTexture constructor! protected void AllocateCache() { mCacheBitmap = Bitmap.createBitmap(mFrameWidth, mFrameHeight, Bitmap.Config.ARGB_8888); } public interface ListItemAccessor { public int getWidth(Object obj); public int getHeight(Object obj); }; /** * This helper method can be called by subclasses to select camera preview size. * It goes over the list of the supported preview sizes and selects the maximum one which * fits both values set via setMaxFrameSize() and surface frame allocated for this view * @param supportedSizes * @param surfaceWidth * @param surfaceHeight * @return optimal frame size */ protected Size calculateCameraFrameSize(List<?> supportedSizes, ListItemAccessor accessor, int surfaceWidth, int surfaceHeight) { int calcWidth = 0; int calcHeight = 0; int maxAllowedWidth = (mMaxWidth != MAX_UNSPECIFIED && mMaxWidth < surfaceWidth)? mMaxWidth : surfaceWidth; int maxAllowedHeight = (mMaxHeight != MAX_UNSPECIFIED && mMaxHeight < surfaceHeight)? mMaxHeight : surfaceHeight; for (Object size : supportedSizes) { int width = accessor.getWidth(size); int height = accessor.getHeight(size); Log.d(TAG, "trying size: " + width + "x" + height); if (width <= maxAllowedWidth && height <= maxAllowedHeight) { if (width >= calcWidth && height >= calcHeight) { calcWidth = (int) width; calcHeight = (int) height; } } } if ((calcWidth == 0 || calcHeight == 0) && supportedSizes.size() > 0) { Log.i(TAG, "fallback to the first frame size"); Object size = supportedSizes.get(0); calcWidth = accessor.getWidth(size); calcHeight = accessor.getHeight(size); } return new Size(calcWidth, calcHeight); } }
opencv/opencv
modules/java/generator/android/java/org/opencv/android/CameraBridgeViewBase.java
2,312
/* ### * 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.macosx.plugins; import java.io.IOException; import java.util.List; import docking.action.builder.ActionBuilder; import ghidra.app.CorePluginPackage; import ghidra.app.context.ProgramLocationActionContext; import ghidra.app.plugin.PluginCategoryNames; import ghidra.app.util.bin.ByteProvider; import ghidra.app.util.bin.format.macho.MachException; import ghidra.app.util.bin.format.macho.MachHeader; import ghidra.app.util.bin.format.macho.commands.SegmentCommand; import ghidra.app.util.bin.format.macho.dyld.*; import ghidra.app.util.opinion.DyldCacheExtractLoader; import ghidra.app.util.opinion.DyldCacheUtils.SplitDyldCache; import ghidra.file.formats.ios.dyldcache.DyldCacheFileSystem; import ghidra.formats.gfilesystem.*; import ghidra.framework.plugintool.*; import ghidra.framework.plugintool.util.PluginStatus; import ghidra.plugin.importer.ImporterUtilities; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; import ghidra.program.util.ProgramLocation; import ghidra.util.HelpLocation; import ghidra.util.Msg; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskLauncher; import ghidra.util.task.TaskMonitor; /** * A {@link Plugin} that adds an action to build up a DYLD Cache from extracted components */ //@formatter:off @PluginInfo( status = PluginStatus.RELEASED, packageName = CorePluginPackage.NAME, category = PluginCategoryNames.COMMON, shortDescription = "DYLD Cache Builder", description = "This plugin provides actions for adding DYLD Cache components to the program" ) //@formatter:on public class DyldCacheBuilderPlugin extends Plugin { /** * Creates a new {@link DyldCacheBuilderPlugin} * * @param tool The {@link PluginTool} that will host/contain this {@link Plugin} */ public DyldCacheBuilderPlugin(PluginTool tool) { super(tool); } @Override protected void init() { super.init(); String actionName = "Add To Program"; new ActionBuilder(actionName, getName()) .withContext(ProgramLocationActionContext.class) .enabledWhen(p -> p.getProgram() .getExecutableFormat() .equals(DyldCacheExtractLoader.DYLD_CACHE_EXTRACT_NAME)) .onAction(plac -> TaskLauncher.launchModal(actionName, monitor -> addMissingDyldCacheComponent(plac.getLocation(), monitor))) .popupMenuPath("References", actionName) .popupMenuGroup("Add") .helpLocation(new HelpLocation("ImporterPlugin", "Add_To_Program")) .buildAndInstall(tool); } /** * Attempts to add the DYLD Cache component that resides at the given {@link ProgramLocation}'s * "referred to" address * * @param location The {@link ProgramLocation} where the action took place * @param monitor A {@link TaskMonitor} */ private void addMissingDyldCacheComponent(ProgramLocation location, TaskMonitor monitor) { Program program = location.getProgram(); Address refAddress = location.getRefAddress(); if (refAddress == null) { Msg.showInfo(this, null, name, "No referenced address selected"); return; } if (refAddress.getAddressSpace().isExternalSpace()) { Msg.showInfo(this, null, name, "External locations are not currently supported"); return; } if (program.getMemory().contains(refAddress)) { Msg.showInfo(this, null, name, "Referenced address already exists in memory"); return; } try (FileSystemRef fsRef = openDyldCache(program, monitor)) { DyldCacheFileSystem fs = (DyldCacheFileSystem) fsRef.getFilesystem(); SplitDyldCache splitDyldCache = fs.getSplitDyldCache(); long refAddr = refAddress.getOffset(); String fsPath = findInDylibSegment(refAddr, splitDyldCache); if (fsPath == null) { fsPath = findInStubs(refAddr, splitDyldCache); } if (fsPath == null) { fsPath = findInDyldData(refAddr, splitDyldCache); } if (fsPath != null) { ImporterUtilities.showAddToProgramDialog(fs.getFSRL().appendPath(fsPath), program, tool, monitor); } else { Msg.showInfo(this, null, name, "Address %s not found in %s".formatted(refAddress, fs.toString())); } } catch (CancelledException e) { // Do nothing } catch (MachException | IOException e) { Msg.showError(this, null, name, e.getMessage(), e); } } /** * Attempts to open the given {@link Program}'s originating {@link DyldCacheFileSystem} * * @param program The {@link Program} * @param monitor A {@link TaskMonitor} * @return A {@link FileSystemRef file system reference} to the open {@link DyldCacheFileSystem} * @throws IOException if an FSRL or IO-related error occurred * @throws CancelledException if the user cancelled the operation */ private FileSystemRef openDyldCache(Program program, TaskMonitor monitor) throws IOException, CancelledException { FSRL fsrl = FSRL.fromProgram(program); if (fsrl == null) { throw new IOException("The program does not have an FSRL property"); } String requiredProtocol = DyldCacheFileSystem.DYLD_CACHE_FSTYPE; if (!fsrl.getFS().getProtocol().equals(requiredProtocol)) { throw new IOException("The program's FSRL protocol is '%s' but '%s' is required" .formatted(fsrl.getFS().getProtocol(), requiredProtocol)); } FSRLRoot fsrlRoot = fsrl.getFS(); return FileSystemService.getInstance().getFilesystem(fsrlRoot, monitor); } /** * Attempts to find the given address in the DYLD Cache's DYLIB segments * * @param addr The address to find * @param splitDyldCache The {@link SplitDyldCache} * @return The path of the DYLIB within the {@link DyldCacheFileSystem} that contains the given * address, or null if the address was not found * @throws MachException if there was an error parsing a DYLIB header * @throws IOException if an IO-related error occurred */ private String findInDylibSegment(long addr, SplitDyldCache splitDyldCache) throws MachException, IOException { for (int i = 0; i < splitDyldCache.size(); i++) { DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i); ByteProvider provider = splitDyldCache.getProvider(i); for (DyldCacheImage mappedImage : dyldCacheHeader.getMappedImages()) { MachHeader machHeader = new MachHeader(provider, mappedImage.getAddress() - dyldCacheHeader.getBaseAddress()); for (SegmentCommand segment : machHeader.parseSegments()) { if (segment.contains(addr)) { return mappedImage.getPath(); } } } } return null; } /** * Attempts to find the given address in the DYLD Cache's text stubs * * @param addr The address to find * @param splitDyldCache The {@link SplitDyldCache} * @return The path of the text stub within the {@link DyldCacheFileSystem} that contains the * given address, or null if the address was not found */ private String findInStubs(long addr, SplitDyldCache splitDyldCache) { for (int i = 0; i < splitDyldCache.size(); i++) { String dyldCacheName = splitDyldCache.getName(i); DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i); for (DyldCacheMappingAndSlideInfo mappingInfo : dyldCacheHeader .getCacheMappingAndSlideInfos()) { if (mappingInfo.contains(addr) && mappingInfo.isTextStubs()) { return DyldCacheFileSystem.getStubPath(dyldCacheName); } } } return null; } /** * Attempts to find the given address in the DYLD data * * @param addr The address to find * @param splitDyldCache The {@link SplitDyldCache} * @return The path of the Dyld data within the {@link DyldCacheFileSystem} that contains the * given address, or null if the address was not found */ private String findInDyldData(long addr, SplitDyldCache splitDyldCache) { for (int i = 0; i < splitDyldCache.size(); i++) { String dyldCacheName = splitDyldCache.getName(i); if (dyldCacheName.endsWith(".dylddata")) { DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i); List<DyldCacheMappingAndSlideInfo> mappingInfos = dyldCacheHeader.getCacheMappingAndSlideInfos(); for (int j = 0; j < mappingInfos.size(); j++) { DyldCacheMappingAndSlideInfo mappingInfo = mappingInfos.get(j); if (mappingInfo.contains(addr)) { return DyldCacheFileSystem.getDyldDataPath(dyldCacheName, j); } } } } return null; } }
NationalSecurityAgency/ghidra
Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/plugins/DyldCacheBuilderPlugin.java
2,313
class Solution { public char[][] rotateTheBox(char[][] box) { int m = box.length, n = box[0].length; char[][] ans = new char[n][m]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { ans[j][m - i - 1] = box[i][j]; } } for (int j = 0; j < m; ++j) { Deque<Integer> q = new ArrayDeque<>(); for (int i = n - 1; i >= 0; --i) { if (ans[i][j] == '*') { q.clear(); } else if (ans[i][j] == '.') { q.offer(i); } else if (!q.isEmpty()) { ans[q.pollFirst()][j] = '#'; ans[i][j] = '.'; q.offer(i); } } } return ans; } }
doocs/leetcode
solution/1800-1899/1861.Rotating the Box/Solution.java
2,314
/* * 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.flink.optimizer; import org.apache.flink.api.common.io.statistics.BaseStatistics; import java.util.HashMap; import java.util.Map; /** * The collection of access methods that can be used to retrieve statistical information about the * data processed in a job. Currently this method acts as an entry point only for obtaining cached * statistics. */ public class DataStatistics { private final Map<String, BaseStatistics> baseStatisticsCache; // -------------------------------------------------------------------------------------------- /** Creates a new statistics object, with an empty cache. */ public DataStatistics() { this.baseStatisticsCache = new HashMap<String, BaseStatistics>(); } // -------------------------------------------------------------------------------------------- /** * Gets the base statistics for the input identified by the given identifier. * * @param inputIdentifier The identifier for the input. * @return The statistics that were cached for this input. */ public BaseStatistics getBaseStatistics(String inputIdentifier) { synchronized (this.baseStatisticsCache) { return this.baseStatisticsCache.get(inputIdentifier); } } /** * Caches the given statistics. They are later retrievable under the given identifier. * * @param statistics The statistics to cache. * @param identifier The identifier which may be later used to retrieve the statistics. */ public void cacheBaseStatistics(BaseStatistics statistics, String identifier) { synchronized (this.baseStatisticsCache) { this.baseStatisticsCache.put(identifier, statistics); } } }
apache/flink
flink-optimizer/src/main/java/org/apache/flink/optimizer/DataStatistics.java
2,315
package com.bumptech.glide.load.engine.executor; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.text.TextUtils; import android.util.Log; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.bumptech.glide.util.Synthetic; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; /** A prioritized {@link ThreadPoolExecutor} for running jobs in Glide. */ public final class GlideExecutor implements ExecutorService { /** * The default thread name prefix for executors used to load/decode/transform data not found in * cache. */ static final String DEFAULT_SOURCE_EXECUTOR_NAME = "source"; /** * The default thread name prefix for executors used to load/decode/transform data found in * Glide's cache. */ static final String DEFAULT_DISK_CACHE_EXECUTOR_NAME = "disk-cache"; /** * The default thread count for executors used to load/decode/transform data found in Glide's * cache. */ static final int DEFAULT_DISK_CACHE_EXECUTOR_THREADS = 1; private static final String TAG = "GlideExecutor"; /** * The default thread name prefix for executors from unlimited thread pool used to * load/decode/transform data not found in cache. */ private static final String DEFAULT_SOURCE_UNLIMITED_EXECUTOR_NAME = "source-unlimited"; static final String DEFAULT_ANIMATION_EXECUTOR_NAME = "animation"; /** The default keep alive time for threads in our cached thread pools in milliseconds. */ private static final long KEEP_ALIVE_TIME_MS = TimeUnit.SECONDS.toMillis(10); // Don't use more than four threads when automatically determining thread count.. private static final int MAXIMUM_AUTOMATIC_THREAD_COUNT = 4; // May be accessed on other threads, but this is an optimization only so it's ok if we set its // value more than once. private static volatile int bestThreadCount; private final ExecutorService delegate; /** * Returns a new {@link Builder} with the {@link #DEFAULT_DISK_CACHE_EXECUTOR_THREADS} threads, * {@link #DEFAULT_DISK_CACHE_EXECUTOR_NAME} name and {@link UncaughtThrowableStrategy#DEFAULT} * uncaught throwable strategy. * * <p>Disk cache executors do not allow network operations on their threads. */ public static GlideExecutor.Builder newDiskCacheBuilder() { return new GlideExecutor.Builder(/* preventNetworkOperations= */ true) .setThreadCount(DEFAULT_DISK_CACHE_EXECUTOR_THREADS) .setName(DEFAULT_DISK_CACHE_EXECUTOR_NAME); } /** Shortcut for calling {@link Builder#build()} on {@link #newDiskCacheBuilder()}. */ public static GlideExecutor newDiskCacheExecutor() { return newDiskCacheBuilder().build(); } /** * @deprecated Use {@link #newDiskCacheBuilder()} and {@link * Builder#setUncaughtThrowableStrategy(UncaughtThrowableStrategy)} instead. */ // Public API. @SuppressWarnings("unused") @Deprecated public static GlideExecutor newDiskCacheExecutor( UncaughtThrowableStrategy uncaughtThrowableStrategy) { return newDiskCacheBuilder().setUncaughtThrowableStrategy(uncaughtThrowableStrategy).build(); } /** * @deprecated Use {@link #newDiskCacheBuilder()} instead. */ // Public API. @SuppressWarnings("WeakerAccess") @Deprecated public static GlideExecutor newDiskCacheExecutor( int threadCount, String name, UncaughtThrowableStrategy uncaughtThrowableStrategy) { return newDiskCacheBuilder() .setThreadCount(threadCount) .setName(name) .setUncaughtThrowableStrategy(uncaughtThrowableStrategy) .build(); } /** * Returns a new {@link Builder} with the default thread count returned from {@link * #calculateBestThreadCount()}, the {@link #DEFAULT_SOURCE_EXECUTOR_NAME} thread name prefix, and * the {@link * com.bumptech.glide.load.engine.executor.GlideExecutor.UncaughtThrowableStrategy#DEFAULT} * uncaught throwable strategy. * * <p>Source executors allow network operations on their threads. */ public static GlideExecutor.Builder newSourceBuilder() { return new GlideExecutor.Builder(/* preventNetworkOperations= */ false) .setThreadCount(calculateBestThreadCount()) .setName(DEFAULT_SOURCE_EXECUTOR_NAME); } /** Shortcut for calling {@link Builder#build()} on {@link #newSourceBuilder()}. */ public static GlideExecutor newSourceExecutor() { return newSourceBuilder().build(); } /** * @deprecated Use {@link #newSourceBuilder()} instead. */ // Public API. @SuppressWarnings("unused") @Deprecated public static GlideExecutor newSourceExecutor( UncaughtThrowableStrategy uncaughtThrowableStrategy) { return newSourceBuilder().setUncaughtThrowableStrategy(uncaughtThrowableStrategy).build(); } /** * @deprecated Use {@link #newSourceBuilder()} instead. */ // Public API. @SuppressWarnings("WeakerAccess") @Deprecated public static GlideExecutor newSourceExecutor( int threadCount, String name, UncaughtThrowableStrategy uncaughtThrowableStrategy) { return newSourceBuilder() .setThreadCount(threadCount) .setName(name) .setUncaughtThrowableStrategy(uncaughtThrowableStrategy) .build(); } /** * Returns a new unlimited thread pool with zero core thread count to make sure no threads are * created by default, {@link #KEEP_ALIVE_TIME_MS} keep alive time, the {@link * #DEFAULT_SOURCE_UNLIMITED_EXECUTOR_NAME} thread name prefix, the {@link * com.bumptech.glide.load.engine.executor.GlideExecutor.UncaughtThrowableStrategy#DEFAULT} * uncaught throwable strategy, and the {@link SynchronousQueue} since using default unbounded * blocking queue, for example, {@link PriorityBlockingQueue} effectively won't create more than * {@code corePoolSize} threads. See <a href= * "http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html"> * ThreadPoolExecutor documentation</a>. * * <p>Source executors allow network operations on their threads. */ public static GlideExecutor newUnlimitedSourceExecutor() { return new GlideExecutor( new ThreadPoolExecutor( 0, Integer.MAX_VALUE, KEEP_ALIVE_TIME_MS, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new DefaultThreadFactory( new DefaultPriorityThreadFactory(), DEFAULT_SOURCE_UNLIMITED_EXECUTOR_NAME, UncaughtThrowableStrategy.DEFAULT, false))); } /** * Returns a new fixed thread pool that defaults to either one or two threads depending on the * number of available cores to use when loading frames of animations. * * <p>Animation executors do not allow network operations on their threads. */ public static GlideExecutor.Builder newAnimationBuilder() { int maximumPoolSize = calculateAnimationExecutorThreadCount(); return new GlideExecutor.Builder(/* preventNetworkOperations= */ true) .setThreadCount(maximumPoolSize) .setName(DEFAULT_ANIMATION_EXECUTOR_NAME); } static int calculateAnimationExecutorThreadCount() { int bestThreadCount = calculateBestThreadCount(); // We don't want to add a ton of threads running animations in parallel with our source and // disk cache executors. Doing so adds unnecessary CPU load and can also dramatically increase // our maximum memory usage. Typically one thread is sufficient here, but for higher end devices // with more cores, two threads can provide better performance if lots of GIFs are showing at // once. return bestThreadCount >= 4 ? 2 : 1; } /** Shortcut for calling {@link Builder#build()} on {@link #newAnimationBuilder()}. */ public static GlideExecutor newAnimationExecutor() { return newAnimationBuilder().build(); } /** * @deprecated Use {@link #newAnimationBuilder()} instead. */ // Public API. @SuppressWarnings("WeakerAccess") @Deprecated public static GlideExecutor newAnimationExecutor( int threadCount, UncaughtThrowableStrategy uncaughtThrowableStrategy) { return newAnimationBuilder() .setThreadCount(threadCount) .setUncaughtThrowableStrategy(uncaughtThrowableStrategy) .build(); } @VisibleForTesting GlideExecutor(ExecutorService delegate) { this.delegate = delegate; } @Override public void execute(@NonNull Runnable command) { delegate.execute(command); } @NonNull @Override public Future<?> submit(@NonNull Runnable task) { return delegate.submit(task); } @NonNull @Override public <T> List<Future<T>> invokeAll(@NonNull Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(tasks); } @NonNull @Override public <T> List<Future<T>> invokeAll( @NonNull Collection<? extends Callable<T>> tasks, long timeout, @NonNull TimeUnit unit) throws InterruptedException { return delegate.invokeAll(tasks, timeout, unit); } @NonNull @Override public <T> T invokeAny(@NonNull Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(tasks); } @Override public <T> T invokeAny( @NonNull Collection<? extends Callable<T>> tasks, long timeout, @NonNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(tasks, timeout, unit); } @NonNull @Override public <T> Future<T> submit(@NonNull Runnable task, T result) { return delegate.submit(task, result); } @Override public <T> Future<T> submit(@NonNull Callable<T> task) { return delegate.submit(task); } @Override public void shutdown() { delegate.shutdown(); } @NonNull @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, @NonNull TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public String toString() { return delegate.toString(); } /** Determines the number of cores available on the device. */ // Public API. @SuppressWarnings("WeakerAccess") public static int calculateBestThreadCount() { if (bestThreadCount == 0) { bestThreadCount = Math.min(MAXIMUM_AUTOMATIC_THREAD_COUNT, RuntimeCompat.availableProcessors()); } return bestThreadCount; } /** * A strategy for handling unexpected and uncaught {@link Throwable}s thrown by futures run on the * pool. */ public interface UncaughtThrowableStrategy { /** Silently catches and ignores the uncaught {@link Throwable}s. */ // Public API. @SuppressWarnings("unused") UncaughtThrowableStrategy IGNORE = new UncaughtThrowableStrategy() { @Override public void handle(Throwable t) { // ignore } }; /** Logs the uncaught {@link Throwable}s using {@link #TAG} and {@link Log}. */ UncaughtThrowableStrategy LOG = new UncaughtThrowableStrategy() { @Override public void handle(Throwable t) { if (t != null && Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "Request threw uncaught throwable", t); } } }; /** Rethrows the uncaught {@link Throwable}s to crash the app. */ // Public API. @SuppressWarnings("unused") UncaughtThrowableStrategy THROW = new UncaughtThrowableStrategy() { @Override public void handle(Throwable t) { if (t != null) { throw new RuntimeException("Request threw uncaught throwable", t); } } }; /** The default strategy, currently {@link #LOG}. */ UncaughtThrowableStrategy DEFAULT = LOG; void handle(Throwable t); } private static final class DefaultPriorityThreadFactory implements ThreadFactory { private static final int DEFAULT_PRIORITY = android.os.Process.THREAD_PRIORITY_BACKGROUND + android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE; @Override public Thread newThread(@NonNull Runnable runnable) { return new Thread(runnable) { @Override public void run() { // why PMD suppression is needed: https://github.com/pmd/pmd/issues/808 android.os.Process.setThreadPriority(DEFAULT_PRIORITY); // NOPMD AccessorMethodGeneration super.run(); } }; } } /** * A {@link java.util.concurrent.ThreadFactory} that builds threads slightly above priority {@link * android.os.Process#THREAD_PRIORITY_BACKGROUND}. */ private static final class DefaultThreadFactory implements ThreadFactory { private final ThreadFactory delegate; private final String name; @Synthetic final UncaughtThrowableStrategy uncaughtThrowableStrategy; @Synthetic final boolean preventNetworkOperations; private final AtomicInteger threadNum = new AtomicInteger(); DefaultThreadFactory( ThreadFactory delegate, String name, UncaughtThrowableStrategy uncaughtThrowableStrategy, boolean preventNetworkOperations) { this.delegate = delegate; this.name = name; this.uncaughtThrowableStrategy = uncaughtThrowableStrategy; this.preventNetworkOperations = preventNetworkOperations; } @Override public Thread newThread(@NonNull final Runnable runnable) { Thread newThread = delegate.newThread( new Runnable() { @Override public void run() { if (preventNetworkOperations) { StrictMode.setThreadPolicy( new ThreadPolicy.Builder().detectNetwork().penaltyDeath().build()); } try { runnable.run(); } catch (Throwable t) { uncaughtThrowableStrategy.handle(t); } } }); newThread.setName("glide-" + name + "-thread-" + threadNum.getAndIncrement()); return newThread; } } /** A builder for {@link GlideExecutor}s. */ public static final class Builder { /** * Prevents core and non-core threads from timing out ever if provided to {@link * #setThreadTimeoutMillis(long)}. */ public static final long NO_THREAD_TIMEOUT = 0L; private final boolean preventNetworkOperations; private int corePoolSize; private int maximumPoolSize; @NonNull private ThreadFactory threadFactory = new DefaultPriorityThreadFactory(); @NonNull private UncaughtThrowableStrategy uncaughtThrowableStrategy = UncaughtThrowableStrategy.DEFAULT; private String name; private long threadTimeoutMillis; @Synthetic Builder(boolean preventNetworkOperations) { this.preventNetworkOperations = preventNetworkOperations; } /** * Allows both core and non-core threads in the executor to be terminated if no tasks arrive for * at least the given timeout milliseconds. * * <p>Use {@link #NO_THREAD_TIMEOUT} to remove a previously set timeout. */ public Builder setThreadTimeoutMillis(long threadTimeoutMillis) { this.threadTimeoutMillis = threadTimeoutMillis; return this; } /** Sets the maximum number of threads to use. */ public Builder setThreadCount(@IntRange(from = 1) int threadCount) { corePoolSize = threadCount; maximumPoolSize = threadCount; return this; } /** * Sets the {@link ThreadFactory} responsible for creating threads and setting their priority. * * <p>Usage of this method may override other options on this builder. No guarantees are * provided with regards to the behavior of this method or how it interacts with other methods * on the builder. Use at your own risk. * * @deprecated This is an experimental method that may be removed without warning in a future * version. */ @Deprecated public Builder setThreadFactory(@NonNull ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } /** * Sets the {@link UncaughtThrowableStrategy} to use for unexpected exceptions thrown by tasks * on {@link GlideExecutor}s built by this {@code Builder}. */ public Builder setUncaughtThrowableStrategy(@NonNull UncaughtThrowableStrategy strategy) { this.uncaughtThrowableStrategy = strategy; return this; } /** * Sets the prefix to use for each thread name created by any {@link GlideExecutor}s built by * this {@code Builder}. */ public Builder setName(String name) { this.name = name; return this; } /** Builds a new {@link GlideExecutor} with any previously specified options. */ public GlideExecutor build() { if (TextUtils.isEmpty(name)) { throw new IllegalArgumentException( "Name must be non-null and non-empty, but given: " + name); } ThreadPoolExecutor executor = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, /* keepAliveTime= */ threadTimeoutMillis, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), new DefaultThreadFactory( threadFactory, name, uncaughtThrowableStrategy, preventNetworkOperations)); if (threadTimeoutMillis != NO_THREAD_TIMEOUT) { executor.allowCoreThreadTimeOut(true); } return new GlideExecutor(executor); } } }
bumptech/glide
library/src/main/java/com/bumptech/glide/load/engine/executor/GlideExecutor.java
2,316
package com.taobao.rigel.rap.common.utils; import com.taobao.rigel.rap.project.bo.Action; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.io.IOException; /** * Created by Bosn on 14/11/28. * Basic cache, need weight for string length. */ public class CacheUtils { private static final int DEFAULT_CACHE_EXPIRE_SECS = 600; private static final Logger logger = LogManager.getLogger(CacheUtils.class); public static final String KEY_MOCK_RULE = "KEY_MOCK_RULE:"; public static final String KEY_MOCK_DATA = "KEY_MOCK_DATA"; public static final String KEY_PROJECT_LIST = "KEY_PROJECT_LIST"; public static final String KEY_CORP_LIST = "KEY_CORP_LIST"; public static final String KEY_CORP_LIST_TOP_ITEMS = "KEY_CORP_LIST_TOP_ITEMS"; public static final String KEY_WORKSPACE = "KEY_WORKSPACE"; public static final String KEY_ACCESS_USER_TO_PROJECT = "KEY_ACCESS_USER_TO_PROJECT"; public static final String KEY_NOTIFICATION = "KEY_NOTIFICATION"; public static final String KEY_STATISTICS = "KEY_STATISTICS"; public static final String KEY_STATISTICS_OF_TEAM = "KEY_STATISTICS_OF_TEAM"; private static JedisPool jedisPool; private static Jedis jedis; public CacheUtils() {} private static Jedis getJedis() { try { jedisPool = JedisFactory.getInstance().getJedisPool(); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); } jedis = jedisPool.getResource(); return jedis; } private static void returnJedis() { jedisPool.returnResourceObject(jedis); } /** * get cached Mock rule * * @param action * @param pattern * @return */ public static String getRuleCache(Action action, String pattern, boolean isMockData) { int actionId = action.getId(); String requestUrl = action.getRequestUrl(); if (requestUrl == null) { requestUrl = ""; } if (pattern.contains("noCache=true") || requestUrl.contains("{") || requestUrl.contains("noCache=true")) { return null; } String [] cacheKey = new String[]{isMockData ? KEY_MOCK_DATA : KEY_MOCK_RULE, new Integer(actionId).toString()}; return get(cacheKey); } /** * set Mock rule cache * * @param actionId * @param result */ public static void setRuleCache(int actionId, String result, boolean isMockData) { String[] cacheKey = new String[]{isMockData ? KEY_MOCK_DATA : KEY_MOCK_RULE, new Integer(actionId).toString()}; put(cacheKey, result); } public static void removeCacheByActionId(int id) { String[] cacheKey1 = new String[]{KEY_MOCK_RULE, new Integer(id).toString()}; String[] cacheKey2 = new String[]{KEY_MOCK_DATA, new Integer(id).toString()}; getJedis(); jedis.del(StringUtils.join(cacheKey1, "|")); jedis.del(StringUtils.join(cacheKey2, "|")); returnJedis(); } public static void put(String [] keys, String value, int expireInSecs) { Jedis jedis = getJedis(); String cacheKey = StringUtils.join(keys, "|"); jedis.set(cacheKey, value); if (expireInSecs > 0) jedis.expire(cacheKey, expireInSecs); returnJedis(); } public static void put(String [] keys, String value) { put(keys, value, DEFAULT_CACHE_EXPIRE_SECS); } public static String get(String []keys) { String cache = getJedis().get(StringUtils.join(keys, "|")); returnJedis(); return cache; } public static void del(String[] keys) { String cacheKey = StringUtils.join(keys, "|"); getJedis().del(cacheKey); returnJedis(); } public static void init() { getJedis(); jedis.flushAll(); returnJedis(); } }
thx/RAP
src/main/java/com/taobao/rigel/rap/common/utils/CacheUtils.java
2,317
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.python; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import static net.starlark.java.eval.Starlark.NONE; import com.google.common.annotations.VisibleForTesting; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.Depset; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.packages.Info; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.StarlarkInfo; import com.google.devtools.build.lib.packages.StarlarkProviderWrapper; import com.google.devtools.build.lib.skyframe.BzlLoadValue; import com.google.devtools.build.lib.starlarkbuildapi.python.PyRuntimeInfoApi; import javax.annotation.Nullable; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Starlark; /** * Instance of the provider type that describes Python runtimes. * * <p>Invariant: Exactly one of {@link #interpreterPath} and {@link #interpreter} is non-null. The * former corresponds to a platform runtime, and the latter to an in-build runtime; these two cases * are mutually exclusive. In addition, {@link #files} is non-null if and only if {@link * #interpreter} is non-null; in other words files are only used for in-build runtimes. These * invariants mirror the user-visible API on {@link PyRuntimeInfoApi} except that {@code None} is * replaced by null. */ @VisibleForTesting public final class PyRuntimeInfo { private static final BuiltinProvider BUILTIN_PROVIDER = new BuiltinProvider(); private static final RulesPythonProvider RULES_PYTHON_PROVIDER = new RulesPythonProvider(); // Only present so PyRuntimeRule can reference it as a default. static final String DEFAULT_STUB_SHEBANG = "#!/usr/bin/env python3"; // Only present so PyRuntimeRule can reference it as a default. // Must call getToolsLabel() when using this. static final String DEFAULT_BOOTSTRAP_TEMPLATE = "//tools/python:python_bootstrap_template.txt"; private final StarlarkInfo info; private PyRuntimeInfo(StarlarkInfo info) { this.info = info; } public static PyRuntimeInfo fromTarget(ConfiguredTarget target) throws RuleErrorException { var provider = fromTargetNullable(target); if (provider == null) { throw new IllegalStateException( String.format("Unable to find PyRuntimeInfo provider in %s", target)); } else { return provider; } } @Nullable public static PyRuntimeInfo fromTargetNullable(ConfiguredTarget target) throws RuleErrorException { PyRuntimeInfo provider = target.get(RULES_PYTHON_PROVIDER); if (provider != null) { return provider; } provider = target.get(BUILTIN_PROVIDER); if (provider != null) { return provider; } return null; } @Nullable public String getInterpreterPathString() { Object value = info.getValue("interpreter_path"); return value == Starlark.NONE ? null : (String) value; } @Nullable public Artifact getInterpreter() { Object value = info.getValue("interpreter"); return value == Starlark.NONE ? null : (Artifact) value; } public String getStubShebang() throws EvalException { return info.getValue("stub_shebang", String.class); } @Nullable public Artifact getBootstrapTemplate() { Object value = info.getValue("bootstrap_template"); return value == Starlark.NONE ? null : (Artifact) value; } @Nullable public NestedSet<Artifact> getFiles() throws EvalException { Object value = info.getValue("files"); if (value == NONE) { return null; } else { return Depset.cast(value, Artifact.class, "files"); } } public PythonVersion getPythonVersion() throws EvalException { return PythonVersion.parseTargetValue(info.getValue("python_version", String.class)); } private static class BaseProvider extends StarlarkProviderWrapper<PyRuntimeInfo> { private BaseProvider(BzlLoadValue.Key bzlKey) { super(bzlKey, "PyRuntimeInfo"); } @Override public PyRuntimeInfo wrap(Info value) { return new PyRuntimeInfo((StarlarkInfo) value); } } /** Provider instance for the builtin PyRuntimeInfo provider. */ private static class BuiltinProvider extends BaseProvider { private BuiltinProvider() { super( keyForBuiltins( Label.parseCanonicalUnchecked("@_builtins//:common/python/providers.bzl"))); } } /** Provider instance for the rules_python PyRuntimeInfo provider. */ private static class RulesPythonProvider extends BaseProvider { private RulesPythonProvider() { super( keyForBuild( Label.parseCanonicalUnchecked( "//third_party/bazel_rules/rules_python/python/private/common:providers.bzl"))); } } }
bazelbuild/bazel
src/main/java/com/google/devtools/build/lib/rules/python/PyRuntimeInfo.java
2,318
404: Not Found
sohutv/cachecloud
cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/CacheBaseJob.java
2,319
/* * Copyright 2012-2023 The Feign 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 feign.benchmark; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import feign.Client; import feign.Contract; import feign.Feign; import feign.MethodMetadata; import feign.Request; import feign.Response; import feign.Target.HardCodedTarget; @Measurement(iterations = 5, time = 1) @Warmup(iterations = 10, time = 1) @Fork(3) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @State(Scope.Thread) public class WhatShouldWeCacheBenchmarks { private Contract feignContract; private Contract cachedContact; private Client fakeClient; private Feign cachedFakeFeign; private FeignTestInterface cachedFakeApi; @Setup public void setup() { feignContract = new Contract.Default(); cachedContact = new Contract() { private final List<MethodMetadata> cached = new Default().parseAndValidateMetadata(FeignTestInterface.class); public List<MethodMetadata> parseAndValidateMetadata(Class<?> declaring) { return cached; } }; fakeClient = (request, options) -> { Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>(); return Response.builder() .body((byte[]) null) .status(200) .headers(headers) .reason("ok") .request(request) .build(); }; cachedFakeFeign = Feign.builder().client(fakeClient).build(); cachedFakeApi = cachedFakeFeign.newInstance( new HardCodedTarget<FeignTestInterface>(FeignTestInterface.class, "http://localhost")); } /** * How fast is parsing an api interface? */ @Benchmark public List<MethodMetadata> parseFeignContract() { return feignContract.parseAndValidateMetadata(FeignTestInterface.class); } /** * How fast is creating a feign instance for each http request, without considering network? */ @Benchmark public Response buildAndQuery_fake() { return Feign.builder().client(fakeClient) .target(FeignTestInterface.class, "http://localhost").query(); } /** * How fast is creating a feign instance for each http request, without considering network, and * without re-parsing the annotated http api? */ @Benchmark public Response buildAndQuery_fake_cachedContract() { return Feign.builder().contract(cachedContact).client(fakeClient) .target(FeignTestInterface.class, "http://localhost").query(); } /** * How fast re-parsing the annotated http api for each http request, without considering network? */ @Benchmark public Response buildAndQuery_fake_cachedFeign() { return cachedFakeFeign.newInstance( new HardCodedTarget<FeignTestInterface>(FeignTestInterface.class, "http://localhost")) .query(); } /** * How fast is our advice to use a cached api for each http request, without considering network? */ @Benchmark public Response buildAndQuery_fake_cachedApi() { return cachedFakeApi.query(); } }
OpenFeign/feign
benchmark/src/main/java/feign/benchmark/WhatShouldWeCacheBenchmarks.java
2,320
package edu.stanford.nlp.trees.international.hebrew; import edu.stanford.nlp.util.logging.Redwood; import java.io.*; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreeReader; import edu.stanford.nlp.trees.TreeReaderFactory; import edu.stanford.nlp.trees.TreebankLanguagePack; /** * Makes Tsarfaty's canonical split of HTBv2 (see her PhD thesis). This is also * the split that appears in Yoav Goldberg's work. * * @author Spence Green * */ public class SplitMaker { /** A logger for this class */ private static Redwood.RedwoodChannels log = Redwood.channels(SplitMaker.class); /** * @param args */ public static void main(String[] args) { if(args.length != 1) { System.err.printf("Usage: java %s tree_file%n", SplitMaker.class.getName()); System.exit(-1); } TreebankLanguagePack tlp = new HebrewTreebankLanguagePack(); String inputFile = args[0]; File treeFile = new File(inputFile); try { TreeReaderFactory trf = new HebrewTreeReaderFactory(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(treeFile), tlp.getEncoding())); TreeReader tr = trf.newTreeReader(br); PrintWriter pwDev = new PrintWriter(new PrintStream(new FileOutputStream(inputFile + ".clean.dev"),false,tlp.getEncoding())); PrintWriter pwTrain = new PrintWriter(new PrintStream(new FileOutputStream(inputFile + ".clean.train"),false,tlp.getEncoding())); PrintWriter pwTest = new PrintWriter(new PrintStream(new FileOutputStream(inputFile + ".clean.test"),false,tlp.getEncoding())); int numTrees = 0; for(Tree t; ((t = tr.readTree()) != null); numTrees++) { if(numTrees < 483) pwDev.println(t.toString()); else if(numTrees >= 483 && numTrees < 5724) pwTrain.println(t.toString()); else pwTest.println(t.toString()); } tr.close(); pwDev.close(); pwTrain.close(); pwTest.close(); System.err.printf("Processed %d trees.%n",numTrees); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/trees/international/hebrew/SplitMaker.java
2,321
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.io; import com.intellij.util.BitUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.SystemProperties; import com.intellij.util.io.stats.BTreeStatistics; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import org.jetbrains.annotations.ApiStatus.Internal; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; @Internal public final class IntToIntBtree extends AbstractIntToIntBtree { private static final boolean CACHE_ROOT_NODE_BUFFER = SystemProperties.getBooleanProperty("idea.btree.cache.root.node.buffer", true); private static final int HAS_ZERO_KEY_MASK = 0xFF000000; static final boolean doSanityCheck = false; static final boolean doDump = false; final int pageSize; private final short maxInteriorNodes; private final short maxLeafNodes; private final short maxLeafNodesInHash; final BtreeRootNode root; private int height; private int maxStepsSearchedInHash; private int totalHashStepsSearched; private int hashSearchRequests; private int pagesCount; private int hashedPagesCount; private int count; private int movedMembersCount; private boolean hasZeroKey; private int zeroKeyValue; private final ResizeableMappedFile storage; private final int metaDataLeafPageLength; private final int hashPageCapacity; private static final int UNDEFINED_ADDRESS = -1; private static final int DEFAULT_PAGE_SIZE = 1024 * 1024; public IntToIntBtree(int pageSize, @NotNull Path file, @NotNull StorageLockContext storageLockContext, boolean initial) throws IOException { this.pageSize = pageSize; if (initial) { Files.deleteIfExists(file); } storage = new ResizeableMappedFile(file, pageSize, storageLockContext, SystemProperties.getIntProperty("idea.IntToIntBtree.page.size", DEFAULT_PAGE_SIZE), true, IOUtil.useNativeByteOrderForByteBuffers()); storage.setRoundFactor(pageSize); root = new BtreeRootNode(); if (initial) { root.setAddress(UNDEFINED_ADDRESS); } int i = (this.pageSize - BtreeIndexNodeView.RESERVED_META_PAGE_LEN) / BtreeIndexNodeView.INTERIOR_SIZE - 1; assert i < Short.MAX_VALUE && i % 2 == 0; maxInteriorNodes = (short)i; maxLeafNodes = (short)i; ++i; while (!isPrime(i)) { i -= 2; } hashPageCapacity = i; int metaPageLen = BtreeIndexNodeView.RESERVED_META_PAGE_LEN; i = (int)(hashPageCapacity * 0.9); if ((i & 1) == 1) { ++i; } metaDataLeafPageLength = metaPageLen; assert i > 0 && i % 2 == 0; maxLeafNodesInHash = (short)i; } private void doAllocateRoot() throws IOException { nextPage(); // allocate root root.setAddress(0); root.getNodeView().setIndexLeaf(true); } // return total number of bytes needed for storing information @Override public void persistVars(@NotNull BtreeDataStorage storage, boolean toDisk) throws IOException { int i = storage.persistInt(0, height | (hasZeroKey ? HAS_ZERO_KEY_MASK : 0), toDisk); hasZeroKey = (i & HAS_ZERO_KEY_MASK) != 0; height = i & ~HAS_ZERO_KEY_MASK; pagesCount = storage.persistInt(4, pagesCount, toDisk); movedMembersCount = storage.persistInt(8, movedMembersCount, toDisk); maxStepsSearchedInHash = storage.persistInt(12, maxStepsSearchedInHash, toDisk); count = storage.persistInt(16, count, toDisk); hashSearchRequests = storage.persistInt(20, hashSearchRequests, toDisk); totalHashStepsSearched = storage.persistInt(24, totalHashStepsSearched, toDisk); hashedPagesCount = storage.persistInt(28, hashedPagesCount, toDisk); root.setAddress(storage.persistInt(32, root.address, toDisk)); zeroKeyValue = storage.persistInt(36, zeroKeyValue, toDisk); } private final class BtreeRootNode { int address; final BtreeIndexNodeView nodeView = new BtreeIndexNodeView(false); boolean initialized; void setAddress(int _address) { address = _address; initialized = false; } void syncWithStore() throws IOException { nodeView.setAddress(address); initialized = true; } BtreeIndexNodeView getNodeView() throws IOException { if (!initialized) syncWithStore(); return nodeView; } } private static boolean isPrime(int val) { if (val % 2 == 0) return false; int maxDivisor = (int)Math.sqrt(val); for (int i = 3; i <= maxDivisor; i += 2) { if (val % i == 0) return false; } return true; } private int nextPage() throws IOException { int pageStart = (int)storage.length(); storage.putInt(pageStart + pageSize - 4, 0); ++pagesCount; return pageStart; } private BtreeIndexNodeView myAccessNodeView; private int myLastGetKey; private int myOptimizedInserts; private boolean myCanUseLastKey; /** * Lookup given key in BTree, and return true if key is exist in the Tree (associated value is returned * in result[0]), false if there is no such key in the Tree (result is untouched then) * * @return true if key was found, false otherwise */ @Override public boolean get(int key, int @NotNull [] result) throws IOException { assert result.length > 0 : "result.length must be >0"; if (key == 0) { if (hasZeroKey) { result[0] = zeroKeyValue; return true; } return false; } if (root.address == UNDEFINED_ADDRESS) return false; DirectBufferWrapper root = initAccessNodeView(); try { int index = myAccessNodeView.locate(key, false); if (index < 0) { myCanUseLastKey = true; myLastGetKey = key; return false; } else { myCanUseLastKey = false; } result[0] = myAccessNodeView.addressAt(index); } finally { myAccessNodeView.disposeBuffer(); if (root != null) { root.unlock(); } } return true; } private DirectBufferWrapper initAccessNodeView() throws IOException { int rootAddress = root.address; DirectBufferWrapper wrapper; if (CACHE_ROOT_NODE_BUFFER) { BtreeIndexNodeView node = root.getNodeView(); node.lockBuffer(); wrapper = node.bufferWrapper; } else { wrapper = null; } if (myAccessNodeView == null) { myAccessNodeView = new BtreeIndexNodeView(rootAddress, true, wrapper); } else { myAccessNodeView.initTraversal(rootAddress, wrapper); } return wrapper; } @Override public void put(int key, int value) throws IOException { if (key == 0) { hasZeroKey = true; zeroKeyValue = value; return; } boolean canUseLastKey = myCanUseLastKey; if (canUseLastKey) { myCanUseLastKey = false; if (key == myLastGetKey && !myAccessNodeView.myHasFullPagesAlongPath) { ++myOptimizedInserts; ++count; try { myAccessNodeView.insert(key, value); } finally { myAccessNodeView.disposeBuffer(); } return; } } doPut(key, value); } private void doPut(int key, int value) throws IOException { if (root.address == UNDEFINED_ADDRESS) doAllocateRoot(); DirectBufferWrapper root = initAccessNodeView(); try { int index = myAccessNodeView.locate(key, true); if (index < 0) { ++count; myAccessNodeView.insert(key, value); } else { myAccessNodeView.setAddressAt(index, value); } } finally { myAccessNodeView.disposeBuffer(); if (root != null) { root.unlock(); } } } @Override @NotNull public BTreeStatistics getStatistics() throws IOException { int leafPages = height == 3 ? pagesCount - (1 + root.getNodeView().getChildrenCount() + 1) : height == 2 ? pagesCount - 1 : 1; return new BTreeStatistics( pagesCount, count, height, movedMembersCount, leafPages, maxStepsSearchedInHash, hashSearchRequests, totalHashStepsSearched, pageSize, storage.length() ); } @Override public void doClose() throws IOException { storage.close(); } @Override public void doFlush() throws IOException { storage.force(); } @FunctionalInterface private interface NodeOp<T> { T operate(@NotNull DirectBufferWrapper buffer) throws IOException; } // Leaf index node // (value_address {<0 if address in duplicates segment}, hash key) {getChildrenCount()} // (|next_node {<0} , hash key|) {getChildrenCount()} , next_node {<0} // next_node[i] is pointer to all less than hash_key[i] except for the last @SuppressWarnings("UseOfSystemOutOrSystemErr") private final class BtreeIndexNodeView implements Closeable { static final int INTERIOR_SIZE = 8; static final int KEY_OFFSET = 4; private boolean isIndexLeaf; private boolean isHashedLeaf; private static final int LARGE_MOVE_THRESHOLD = 5; static final int RESERVED_META_PAGE_LEN = 8; static final int FLAGS_SHIFT = 24; static final int LENGTH_SHIFT = 8; static final int LENGTH_MASK = 0xFFFF; private int address = -1; private int addressInBuffer; private short myChildrenCount = -1; private DirectBufferWrapper bufferWrapper; private boolean isSharedBuffer; private boolean myHasFullPagesAlongPath; /** * Do not unlock buffer in {@link #unlockBuffer()}: keep it locked after first {@link #lockBuffer()} call * and until {@link #disposeBuffer()} */ private final boolean cacheBuffer; private void setFlag(int mask, boolean flag) throws IOException { mask <<= FLAGS_SHIFT; lockBuffer(); try { int anInt = bufferWrapper.getInt(addressInBuffer); if (flag) { anInt |= mask; } else { anInt &= ~mask; } bufferWrapper.putInt(addressInBuffer, anInt); } finally { unlockBuffer(); } } BtreeIndexNodeView(boolean cacheBuffer) { this.cacheBuffer = cacheBuffer; } BtreeIndexNodeView(int address, boolean cacheBuffer, DirectBufferWrapper sharedBuffer) throws IOException { this.cacheBuffer = cacheBuffer; initTraversal(address, sharedBuffer); } private short getChildrenCount() { return myChildrenCount; } private void setChildrenCount(short value) throws IOException { myChildrenCount = value; lockBuffer(); try { int myValue = bufferWrapper.getInt(addressInBuffer); myValue &= ~LENGTH_MASK << LENGTH_SHIFT; myValue |= value << LENGTH_SHIFT; bufferWrapper.putInt(addressInBuffer, myValue); } finally { unlockBuffer(); } } private void setNextPage(int nextPage) throws IOException { putInt(4, nextPage); } private int getNextPage() throws IOException { lockBuffer(); try { return getInt(4); } finally { unlockBuffer(); } } private int getInt(int address) throws IOException { lockBuffer(); try { return bufferWrapper.getInt(addressInBuffer + address); } finally { unlockBuffer(); } } private void putInt(int offset, int value) throws IOException { lockBuffer(); try { bufferWrapper.putInt(addressInBuffer + offset, value); } finally { unlockBuffer(); } } private ByteBuffer getBytes(int address, int length) throws IOException { lockBuffer(); try { ByteBuffer duplicate = bufferWrapper.copy(); int newPosition = address + addressInBuffer; duplicate.position(newPosition); duplicate.limit(newPosition + length); return duplicate; } finally { unlockBuffer(); } } private void putBytes(int address, ByteBuffer buffer) throws IOException { lockBuffer(); try { bufferWrapper.position(address + addressInBuffer); bufferWrapper.put(buffer); } finally { unlockBuffer(); } } private static final int HASH_FREE = 0; void setAddress(int _address) throws IOException { setAddress(_address, null); } void setAddress(int _address, DirectBufferWrapper sharedBuffer) throws IOException { if (doSanityCheck) assert _address % pageSize == 0; address = _address; addressInBuffer = getStorage().getOffsetInPage(address); disposeBuffer(); if (sharedBuffer != null) { bufferWrapper = sharedBuffer; isSharedBuffer = true; } syncWithStore(); } private void syncWithStore() throws IOException { lockBuffer(); try { doInitFlags(bufferWrapper.getInt(addressInBuffer)); } finally { unlockBuffer(); } } private void lockBuffer() throws IOException { if (isSharedBuffer) { return; } if (bufferWrapper == null) { bufferWrapper = getStorage().getByteBuffer(address, false); } else { if (!cacheBuffer) { if (!bufferWrapper.tryLock()) { bufferWrapper = getStorage().getByteBuffer(address, false); } } } } private void unlockBuffer() { if (isSharedBuffer) { return; } if (!cacheBuffer) { bufferWrapper.unlock(); } } private void disposeBuffer() { if (bufferWrapper != null && cacheBuffer) { if (isSharedBuffer) { isSharedBuffer = false; } else { bufferWrapper.unlock(); } } bufferWrapper = null; } private @NotNull PagedFileStorage getStorage() { return storage.getPagedFileStorage(); } private int search(final int value) throws IOException { if (isIndexLeaf() && isHashedLeaf()) { return hashIndex(value); } return ObjectUtils.binarySearch(0, getChildrenCount(), mid -> { return Integer.compare(keyAt(mid), value); }); } int addressAt(int i) throws IOException { if (doSanityCheck) { short childrenCount = getChildrenCount(); if (isHashedLeaf()) { assert i < hashPageCapacity; } else { boolean b = i < childrenCount || (!isIndexLeaf() && i == childrenCount); assert b; } } return getInt(indexToOffset(i)); } private void setAddressAt(int i, int value) throws IOException { int offset = indexToOffset(i); if (doSanityCheck) { short childrenCount = getChildrenCount(); final int metaPageLen; if (isHashedLeaf()) { assert i < hashPageCapacity; metaPageLen = metaDataLeafPageLength; } else { boolean b = i < childrenCount || (!isIndexLeaf() && i == childrenCount); assert b; metaPageLen = RESERVED_META_PAGE_LEN; } assert offset + 4 <= pageSize; assert offset >= metaPageLen; } putInt(offset, value); } private int indexToOffset(int i) { return i * INTERIOR_SIZE + (isHashedLeaf() ? metaDataLeafPageLength : RESERVED_META_PAGE_LEN); } private int keyAt(int i) { try { if (doSanityCheck) { if (isHashedLeaf()) { assert i < hashPageCapacity; } else { assert i < getChildrenCount(); } } return getInt(indexToOffset(i) + KEY_OFFSET); } catch (IOException e) { throw new RuntimeException(e); } } private void setKeyAt(int i, int value) throws IOException { final int offset = indexToOffset(i) + KEY_OFFSET; if (doSanityCheck) { final int metaPageLen; if (isHashedLeaf()) { assert i < hashPageCapacity; metaPageLen = metaDataLeafPageLength; } else { assert i < getChildrenCount(); metaPageLen = RESERVED_META_PAGE_LEN; } assert offset + 4 <= pageSize; assert offset >= metaPageLen; } putInt(offset, value); } static final int INDEX_LEAF_MASK = 0x1; static final int HASHED_LEAF_MASK = 0x2; boolean isIndexLeaf() { return isIndexLeaf; } private void doInitFlags(int flags) { myChildrenCount = (short)((flags >>> LENGTH_SHIFT) & LENGTH_MASK); flags = (flags >> FLAGS_SHIFT) & 0xFF; isHashedLeaf = BitUtil.isSet(flags, HASHED_LEAF_MASK); isIndexLeaf = BitUtil.isSet(flags, INDEX_LEAF_MASK); } void setIndexLeaf(boolean value) throws IOException { isIndexLeaf = value; setFlag(INDEX_LEAF_MASK, value); } private boolean isHashedLeaf() { return isHashedLeaf; } void setHashedLeaf() throws IOException { isHashedLeaf = true; setFlag(HASHED_LEAF_MASK, true); } short getMaxChildrenCount() { return isIndexLeaf() ? isHashedLeaf() ? maxLeafNodesInHash : maxLeafNodes : maxInteriorNodes; } boolean isFull() { short childrenCount = getChildrenCount(); if (!isIndexLeaf()) { ++childrenCount; } return childrenCount == getMaxChildrenCount(); } boolean processMappings(KeyValueProcessor processor) throws IOException { assert isIndexLeaf(); if (isHashedLeaf()) { int offset = addressInBuffer + indexToOffset(0); for (int i = 0; i < hashPageCapacity; ++i) { int finalOffset = offset; Boolean result; lockBuffer(); try { result = ((NodeOp<Boolean>)b -> { int key = b.getInt(finalOffset + KEY_OFFSET); if (key != HASH_FREE) { if (!processor.process(key, b.getInt(finalOffset))) return false; } return true; }).operate(bufferWrapper); } finally { unlockBuffer(); } if (!result) { return false; } offset += INTERIOR_SIZE; } } else { final int childrenCount = getChildrenCount(); for (int i = 0; i < childrenCount; ++i) { if (!processor.process(keyAt(i), addressAt(i))) return false; } } return true; } public void initTraversal(int address, DirectBufferWrapper sharedBuffer) throws IOException { myHasFullPagesAlongPath = false; setAddress(address, sharedBuffer); } @Override public void close() { disposeBuffer(); } private final class HashLeafData { final BtreeIndexNodeView nodeView; final int[] keys; final Int2IntMap values; HashLeafData(BtreeIndexNodeView _nodeView, int recordCount) throws IOException { nodeView = _nodeView; int offset = nodeView.addressInBuffer + nodeView.indexToOffset(0); keys = new int[recordCount]; values = new Int2IntOpenHashMap(recordCount); final int[] keyNumber = {0}; for (int i = 0; i < hashPageCapacity; ++i) { nodeView.lockBuffer(); try { int key = nodeView.bufferWrapper.getInt(offset + KEY_OFFSET); if (key != HASH_FREE) { int value = nodeView.bufferWrapper.getInt(offset); if (keyNumber[0] == keys.length) throw new CorruptedException(storage.getPagedFileStorage().getFile()); keys[keyNumber[0]++] = key; values.put(key, value); } } finally { nodeView.unlockBuffer(); } offset += INTERIOR_SIZE; } Arrays.sort(keys); } private void clean() throws IOException { for (int i = 0; i < hashPageCapacity; ++i) { nodeView.setKeyAt(i, HASH_FREE); } } } private int splitNode(int parentAddress) throws IOException { final boolean indexLeaf = isIndexLeaf(); if (doSanityCheck) { assert isFull(); dump("before split:" + indexLeaf); } final boolean hashedLeaf = isHashedLeaf(); final short recordCount = getChildrenCount(); BtreeIndexNodeView parent = null; HashLeafData hashLeafData; try { if (parentAddress != 0) { parent = new BtreeIndexNodeView(parentAddress, true, null); } short maxIndex = (short)(getMaxChildrenCount() / 2); try (BtreeIndexNodeView newIndexNode = new BtreeIndexNodeView(nextPage(), true, null)) { syncWithStore(); // next page can cause ByteBuffer to be invalidated! if (parent != null) parent.syncWithStore(); root.syncWithStore(); newIndexNode.setIndexLeaf(indexLeaf); // newIndexNode becomes dirty int nextPage = getNextPage(); setNextPage(newIndexNode.address); newIndexNode.setNextPage(nextPage); int medianKey; if (indexLeaf && hashedLeaf) { hashLeafData = new HashLeafData(this, recordCount); final int[] keys = hashLeafData.keys; hashLeafData.clean(); final Int2IntMap map = hashLeafData.values; final int avg = keys.length / 2; medianKey = keys[avg]; --hashedPagesCount; setChildrenCount((short)0); // this node becomes dirty newIndexNode.setChildrenCount((short)0); for (int i = 0; i < avg; ++i) { int key = keys[i]; insert(key, map.get(key)); key = keys[avg + i]; newIndexNode.insert(key, map.get(key)); } } else { short recordCountInNewNode = (short)(recordCount - maxIndex); newIndexNode.setChildrenCount(recordCountInNewNode); // newIndexNode node becomes dirty ByteBuffer buffer = getBytes(indexToOffset(maxIndex), recordCountInNewNode * INTERIOR_SIZE); newIndexNode.putBytes(newIndexNode.indexToOffset(0), buffer); if (indexLeaf) { medianKey = newIndexNode.keyAt(0); } else { newIndexNode.setAddressAt(recordCountInNewNode, addressAt(recordCount)); --maxIndex; medianKey = keyAt(maxIndex); // key count is odd (since children count is even) and middle key goes to parent } setChildrenCount(maxIndex); // "this" node becomes dirty } if (parent != null) { if (doSanityCheck) { int medianKeyInParent = parent.search(medianKey); int ourKey = keyAt(0); int ourKeyInParent = parent.search(ourKey); parent.dump("About to insert " + medianKey + "," + newIndexNode.address + "," + medianKeyInParent + " our key " + ourKey + ", " + ourKeyInParent); assert medianKeyInParent < 0; boolean b = !parent.isFull(); assert b; } parent.insert(medianKey, -newIndexNode.address); if (doSanityCheck) { parent.dump("After modifying parent"); int search = parent.search(medianKey); assert search >= 0; boolean b = parent.addressAt(search + 1) == -newIndexNode.address; assert b; dump("old node after split:"); newIndexNode.dump("new node after split:"); } } else { if (doSanityCheck) { root.getNodeView().dump("Splitting root:" + medianKey); } int newRootAddress = nextPage(); newIndexNode.syncWithStore(); syncWithStore(); if (doSanityCheck) { System.out.println("Pages:" + pagesCount + ", elements:" + count + ", average:" + (height + 1)); } root.setAddress(newRootAddress); parentAddress = newRootAddress; BtreeIndexNodeView rootNodeView = root.getNodeView(); rootNodeView.setChildrenCount((short)1); // root becomes dirty rootNodeView.setKeyAt(0, medianKey); rootNodeView.setAddressAt(0, -address); rootNodeView.setAddressAt(1, -newIndexNode.address); if (doSanityCheck) { rootNodeView.dump("New root"); dump("First child"); newIndexNode.dump("Second child"); } } } } finally { if (parent != null) { parent.close(); } } return parentAddress; } void dump(String s) throws IOException { if (doDump) { immediateDump(s); } } private void immediateDump(String s) throws IOException { short maxIndex = getChildrenCount(); System.out.println(s + " @" + address); for (int i = 0; i < maxIndex; ++i) { System.out.print(addressAt(i) + " " + keyAt(i) + " "); } if (!isIndexLeaf()) { System.out.println(addressAt(maxIndex)); } else { System.out.println(); } } private int locate(int valueHC, boolean split) throws IOException { int searched = 0; int parentAddress = 0; final int maxHeight = height + 1; while (true) { if (isFull()) { if (split) { parentAddress = splitNode(parentAddress); if (parentAddress != 0) setAddress(parentAddress); --searched; } else { myHasFullPagesAlongPath = true; } } int i = search(valueHC); ++searched; if (searched > maxHeight) throw new CorruptedException(storage.getPagedFileStorage().getFile()); if (isIndexLeaf()) { height = Math.max(height, searched); return i; } int address = i < 0 ? addressAt(-i - 1) : addressAt(i + 1); parentAddress = this.address; setAddress(-address); } } private void insert(int valueHC, int newValueId) throws IOException { if (doSanityCheck) { boolean b = !isFull(); assert b; } short recordCount = getChildrenCount(); if (doSanityCheck) assert recordCount < getMaxChildrenCount(); final boolean indexLeaf = isIndexLeaf(); if (indexLeaf) { if (recordCount == 0) { setHashedLeaf(); ++hashedPagesCount; } if (isHashedLeaf()) { int index = hashIndex(valueHC); if (index < 0) { index = -index - 1; } setKeyAt(index, valueHC); setAddressAt(index, newValueId); setChildrenCount((short)(recordCount + 1)); // "this" node becomes dirty return; } } int medianKeyInParent = search(valueHC); if (doSanityCheck) assert medianKeyInParent < 0; int index = -medianKeyInParent - 1; setChildrenCount((short)(recordCount + 1)); // "this" node becomes dirty final int itemsToMove = recordCount - index; movedMembersCount += itemsToMove; if (indexLeaf) { if (itemsToMove > LARGE_MOVE_THRESHOLD) { ByteBuffer buffer = getBytes(indexToOffset(index), itemsToMove * INTERIOR_SIZE); putBytes(indexToOffset(index + 1), buffer); } else { for (int i = recordCount - 1; i >= index; --i) { setKeyAt(i + 1, keyAt(i)); setAddressAt(i + 1, addressAt(i)); } } setKeyAt(index, valueHC); setAddressAt(index, newValueId); } else { // <address> (<key><address>) {record_count - 1} // setAddressAt(recordCount + 1, addressAt(recordCount)); if (itemsToMove > LARGE_MOVE_THRESHOLD) { int elementsAfterIndex = recordCount - index - 1; if (elementsAfterIndex > 0) { ByteBuffer buffer = getBytes(indexToOffset(index + 1), elementsAfterIndex * INTERIOR_SIZE); putBytes(indexToOffset(index + 2), buffer); } } else { for (int i = recordCount - 1; i > index; --i) { setKeyAt(i + 1, keyAt(i)); setAddressAt(i + 1, addressAt(i)); } } if (index < recordCount) setKeyAt(index + 1, keyAt(index)); setKeyAt(index, valueHC); setAddressAt(index + 1, newValueId); } if (doSanityCheck) { if (index > 0) assert keyAt(index - 1) < keyAt(index); if (index < recordCount) assert keyAt(index) < keyAt(index + 1); } } private static final boolean useDoubleHash = true; private int hashIndex(int value) throws IOException { final int length = hashPageCapacity; int hash = value & 0x7fffffff; int index = hash % length; int keyAtIndex = keyAt(index); hashSearchRequests++; int total = 0; if (useDoubleHash) { if (keyAtIndex != value && keyAtIndex != HASH_FREE) { // see Knuth, p. 529 final int probe = 1 + (hash % (length - 2)); do { index -= probe; if (index < 0) index += length; keyAtIndex = keyAt(index); ++total; if (total > length) { throw new CorruptedException(storage.getPagedFileStorage().getFile()); // violation of Euler's theorem } } while (keyAtIndex != value && keyAtIndex != HASH_FREE); } } else { while (keyAtIndex != value && keyAtIndex != HASH_FREE) { if (index == 0) index = length; --index; keyAtIndex = keyAt(index); ++total; if (total > length) throw new CorruptedException(storage.getPagedFileStorage().getFile()); // violation of Euler's theorem } } maxStepsSearchedInHash = Math.max(maxStepsSearchedInHash, total); totalHashStepsSearched += total; return keyAtIndex == HASH_FREE ? -index - 1 : index; } } @Override public boolean processMappings(@NotNull KeyValueProcessor processor) throws IOException { doFlush(); if (hasZeroKey) { if (!processor.process(0, zeroKeyValue)) return false; } if (root.address == UNDEFINED_ADDRESS) return true; root.syncWithStore(); return processLeafPages(root.getNodeView(), processor); } private boolean processLeafPages(@NotNull BtreeIndexNodeView node, @NotNull KeyValueProcessor processor) throws IOException { if (node.isIndexLeaf()) { return node.processMappings(processor); } // Copy children addresses first to avoid node's ByteBuffer invalidation final int[] childrenAddresses = new int[node.getChildrenCount() + 1]; for (int i = 0; i < childrenAddresses.length; ++i) { childrenAddresses[i] = -node.addressAt(i); } if (childrenAddresses.length > 0) { try (BtreeIndexNodeView child = new BtreeIndexNodeView(true)) { for (int childrenAddress : childrenAddresses) { child.setAddress(childrenAddress); if (!processLeafPages(child, processor)) return false; } } } return true; } }
JetBrains/intellij-community
platform/util/src/com/intellij/util/io/IntToIntBtree.java
2,322
package com.u9porn.data; import com.u9porn.data.db.DbHelper; import com.u9porn.data.model.User; import com.u9porn.data.network.ApiHelper; import com.u9porn.data.prefs.PreferencesHelper; /** * @author flymegoc * @date 2018/3/4 */ public interface DataManager extends DbHelper, ApiHelper, PreferencesHelper { String getVideoCacheProxyUrl(String originalVideoUrl); boolean isVideoCacheByProxy(String originalVideoUrl); void existLogin(); void resetPorn91VideoWatchTime(boolean reset); User getUser(); boolean isUserLogin(); }
techGay/v9porn
app/src/main/java/com/u9porn/data/DataManager.java
2,323
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.committed; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.CachingCommittedChangesProvider; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.RepositoryLocation; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.CommonProcessors.CollectProcessor; import com.intellij.util.Processor; import com.intellij.util.io.DigestUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static com.intellij.util.containers.ContainerUtil.find; import static com.intellij.util.io.DigestUtilKt.hashToHexString; public final class CachesHolder { @NonNls private static final String VCS_CACHE_PATH = "vcsCache"; private final @NotNull Project myProject; private final @NotNull Map<String, ChangesCacheFile> cacheFiles = new ConcurrentHashMap<>(); private final @NotNull RepositoryLocationCache myLocationCache; public CachesHolder(@NotNull Project project, @NotNull RepositoryLocationCache locationCache) { myProject = project; myLocationCache = locationCache; } /** * Returns all paths that will be used to collect committed changes about. Ideally, for one checkout, there should be one file */ public @NotNull Map<VirtualFile, RepositoryLocation> getAllRootsUnderVcs(@NotNull AbstractVcs vcs) { return new RootsCalculator(myProject, vcs, myLocationCache).getRoots(); } public void iterateAllCaches(@NotNull Processor<? super ChangesCacheFile> processor) { for (AbstractVcs vcs : ProjectLevelVcsManager.getInstance(myProject).getAllActiveVcss()) { if (vcs.getCommittedChangesProvider() instanceof CachingCommittedChangesProvider) { for (Map.Entry<VirtualFile, RepositoryLocation> entry : getAllRootsUnderVcs(vcs).entrySet()) { ChangesCacheFile cacheFile = getCacheFile(vcs, entry.getKey(), entry.getValue()); if (!processor.process(cacheFile)) { return; } } } } } public void reset() { cacheFiles.clear(); } public void clearAllCaches() { cacheFiles.values().forEach(ChangesCacheFile::delete); reset(); } public @NotNull Collection<ChangesCacheFile> getAllCaches() { CollectProcessor<ChangesCacheFile> processor = new CollectProcessor<>(); iterateAllCaches(processor); return processor.getResults(); } public @NotNull ChangesCacheFile getCacheFile(@NotNull AbstractVcs vcs, @NotNull VirtualFile root, @NotNull RepositoryLocation location) { return cacheFiles .computeIfAbsent(location.getKey(), key -> new ChangesCacheFile(myProject, getCachePath(location), vcs, root, location)); } public @NotNull Path getCacheBasePath() { return Path.of(PathManager.getSystemPath(), VCS_CACHE_PATH, myProject.getLocationHash()); } private @NotNull Path getCachePath(@NotNull RepositoryLocation location) { Path file = getCacheBasePath(); try { Files.createDirectories(file); } catch (IOException e) { throw new UncheckedIOException(e); } return file.resolve(hashToHexString(location.getKey(), DigestUtil.md5())); } public @Nullable ChangesCacheFile haveCache(@NotNull RepositoryLocation location) { String key = location.getKey(); ChangesCacheFile result = cacheFiles.get(key); if (result == null) { String keyWithSlash = key.endsWith("/") ? key : key + "/"; String cachedSimilarKey = find(cacheFiles.keySet(), s -> keyWithSlash.startsWith(s) || s.startsWith(keyWithSlash)); result = cachedSimilarKey != null ? cacheFiles.get(cachedSimilarKey) : null; } return result; } }
JetBrains/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CachesHolder.java
2,324
/* * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang; import java.util.Arrays; import java.util.Map; import java.util.HashMap; import java.util.Locale; /** * The {@code Character} class wraps a value of the primitive * type {@code char} in an object. An object of class * {@code Character} contains a single field whose type is * {@code char}. * <p> * In addition, this class provides a large number of static methods for * determining a character's category (lowercase letter, digit, etc.) * and for converting characters from uppercase to lowercase and vice * versa. * * <h3><a id="conformance">Unicode Conformance</a></h3> * <p> * The fields and methods of class {@code Character} are defined in terms * of character information from the Unicode Standard, specifically the * <i>UnicodeData</i> file that is part of the Unicode Character Database. * This file specifies properties including name and category for every * assigned Unicode code point or character range. The file is available * from the Unicode Consortium at * <a href="http://www.unicode.org">http://www.unicode.org</a>. * <p> * The Java SE 8 Platform uses character information from version 6.2 * of the Unicode Standard, with three extensions. First, in recognition of the fact * that new currencies appear frequently, the Java SE 8 Platform allows an * implementation of class {@code Character} to use the Currency Symbols * block from version 10.0 of the Unicode Standard. Second, the Java SE 8 Platform * allows an implementation of class {@code Character} to use the code points * in the range of {@code U+9FCD} to {@code U+9FEF} from version 11.0 of the * Unicode Standard and in the {@code CJK Unified Ideographs Extension E} block * from version 8.0 of the Unicode Standard, in order for the class to allow the * "Implementation Level 2" of the Chinese GB18030-2022 standard. * Third, the Java SE 8 Platform * allows an implementation of class {@code Character} to use the Japanese Era * code point, {@code U+32FF}, from the Unicode Standard version 12.1. * Consequently, the * behavior of fields and methods of class {@code Character} may vary across * implementations of the Java SE 8 Platform when processing the aforementioned * code points ( outside of version 6.2 ), except for the following methods * that define Java identifiers: * {@link #isJavaIdentifierStart(int)}, {@link #isJavaIdentifierStart(char)}, * {@link #isJavaIdentifierPart(int)}, and {@link #isJavaIdentifierPart(char)}. * Code points in Java identifiers must be drawn from version 6.2 of * the Unicode Standard. * * <h3><a name="unicode">Unicode Character Representations</a></h3> * * <p>The {@code char} data type (and therefore the value that a * {@code Character} object encapsulates) are based on the * original Unicode specification, which defined characters as * fixed-width 16-bit entities. The Unicode Standard has since been * changed to allow for characters whose representation requires more * than 16 bits. The range of legal <em>code point</em>s is now * U+0000 to U+10FFFF, known as <em>Unicode scalar value</em>. * (Refer to the <a * href="http://www.unicode.org/reports/tr27/#notation"><i> * definition</i></a> of the U+<i>n</i> notation in the Unicode * Standard.) * * <p><a name="BMP">The set of characters from U+0000 to U+FFFF</a> is * sometimes referred to as the <em>Basic Multilingual Plane (BMP)</em>. * <a name="supplementary">Characters</a> whose code points are greater * than U+FFFF are called <em>supplementary character</em>s. The Java * platform uses the UTF-16 representation in {@code char} arrays and * in the {@code String} and {@code StringBuffer} classes. In * this representation, supplementary characters are represented as a pair * of {@code char} values, the first from the <em>high-surrogates</em> * range, (&#92;uD800-&#92;uDBFF), the second from the * <em>low-surrogates</em> range (&#92;uDC00-&#92;uDFFF). * * <p>A {@code char} value, therefore, represents Basic * Multilingual Plane (BMP) code points, including the surrogate * code points, or code units of the UTF-16 encoding. An * {@code int} value represents all Unicode code points, * including supplementary code points. The lower (least significant) * 21 bits of {@code int} are used to represent Unicode code * points and the upper (most significant) 11 bits must be zero. * Unless otherwise specified, the behavior with respect to * supplementary characters and surrogate {@code char} values is * as follows: * * <ul> * <li>The methods that only accept a {@code char} value cannot support * supplementary characters. They treat {@code char} values from the * surrogate ranges as undefined characters. For example, * {@code Character.isLetter('\u005CuD840')} returns {@code false}, even though * this specific value if followed by any low-surrogate value in a string * would represent a letter. * * <li>The methods that accept an {@code int} value support all * Unicode characters, including supplementary characters. For * example, {@code Character.isLetter(0x2F81A)} returns * {@code true} because the code point value represents a letter * (a CJK ideograph). * </ul> * * <p>In the Java SE API documentation, <em>Unicode code point</em> is * used for character values in the range between U+0000 and U+10FFFF, * and <em>Unicode code unit</em> is used for 16-bit * {@code char} values that are code units of the <em>UTF-16</em> * encoding. For more information on Unicode terminology, refer to the * <a href="http://www.unicode.org/glossary/">Unicode Glossary</a>. * * @author Lee Boynton * @author Guy Steele * @author Akira Tanaka * @author Martin Buchholz * @author Ulf Zibis * @since 1.0 */ public final class Character implements java.io.Serializable, Comparable<Character> { /** * The minimum radix available for conversion to and from strings. * The constant value of this field is the smallest value permitted * for the radix argument in radix-conversion methods such as the * {@code digit} method, the {@code forDigit} method, and the * {@code toString} method of class {@code Integer}. * * @see Character#digit(char, int) * @see Character#forDigit(int, int) * @see Integer#toString(int, int) * @see Integer#valueOf(String) */ public static final int MIN_RADIX = 2; /** * The maximum radix available for conversion to and from strings. * The constant value of this field is the largest value permitted * for the radix argument in radix-conversion methods such as the * {@code digit} method, the {@code forDigit} method, and the * {@code toString} method of class {@code Integer}. * * @see Character#digit(char, int) * @see Character#forDigit(int, int) * @see Integer#toString(int, int) * @see Integer#valueOf(String) */ public static final int MAX_RADIX = 36; /** * The constant value of this field is the smallest value of type * {@code char}, {@code '\u005Cu0000'}. * * @since 1.0.2 */ public static final char MIN_VALUE = '\u0000'; /** * The constant value of this field is the largest value of type * {@code char}, {@code '\u005CuFFFF'}. * * @since 1.0.2 */ public static final char MAX_VALUE = '\uFFFF'; /** * The {@code Class} instance representing the primitive type * {@code char}. * * @since 1.1 */ @SuppressWarnings("unchecked") public static final Class<Character> TYPE = (Class<Character>) Class.getPrimitiveClass("char"); /* * Normative general types */ /* * General character types */ /** * General category "Cn" in the Unicode specification. * @since 1.1 */ public static final byte UNASSIGNED = 0; /** * General category "Lu" in the Unicode specification. * @since 1.1 */ public static final byte UPPERCASE_LETTER = 1; /** * General category "Ll" in the Unicode specification. * @since 1.1 */ public static final byte LOWERCASE_LETTER = 2; /** * General category "Lt" in the Unicode specification. * @since 1.1 */ public static final byte TITLECASE_LETTER = 3; /** * General category "Lm" in the Unicode specification. * @since 1.1 */ public static final byte MODIFIER_LETTER = 4; /** * General category "Lo" in the Unicode specification. * @since 1.1 */ public static final byte OTHER_LETTER = 5; /** * General category "Mn" in the Unicode specification. * @since 1.1 */ public static final byte NON_SPACING_MARK = 6; /** * General category "Me" in the Unicode specification. * @since 1.1 */ public static final byte ENCLOSING_MARK = 7; /** * General category "Mc" in the Unicode specification. * @since 1.1 */ public static final byte COMBINING_SPACING_MARK = 8; /** * General category "Nd" in the Unicode specification. * @since 1.1 */ public static final byte DECIMAL_DIGIT_NUMBER = 9; /** * General category "Nl" in the Unicode specification. * @since 1.1 */ public static final byte LETTER_NUMBER = 10; /** * General category "No" in the Unicode specification. * @since 1.1 */ public static final byte OTHER_NUMBER = 11; /** * General category "Zs" in the Unicode specification. * @since 1.1 */ public static final byte SPACE_SEPARATOR = 12; /** * General category "Zl" in the Unicode specification. * @since 1.1 */ public static final byte LINE_SEPARATOR = 13; /** * General category "Zp" in the Unicode specification. * @since 1.1 */ public static final byte PARAGRAPH_SEPARATOR = 14; /** * General category "Cc" in the Unicode specification. * @since 1.1 */ public static final byte CONTROL = 15; /** * General category "Cf" in the Unicode specification. * @since 1.1 */ public static final byte FORMAT = 16; /** * General category "Co" in the Unicode specification. * @since 1.1 */ public static final byte PRIVATE_USE = 18; /** * General category "Cs" in the Unicode specification. * @since 1.1 */ public static final byte SURROGATE = 19; /** * General category "Pd" in the Unicode specification. * @since 1.1 */ public static final byte DASH_PUNCTUATION = 20; /** * General category "Ps" in the Unicode specification. * @since 1.1 */ public static final byte START_PUNCTUATION = 21; /** * General category "Pe" in the Unicode specification. * @since 1.1 */ public static final byte END_PUNCTUATION = 22; /** * General category "Pc" in the Unicode specification. * @since 1.1 */ public static final byte CONNECTOR_PUNCTUATION = 23; /** * General category "Po" in the Unicode specification. * @since 1.1 */ public static final byte OTHER_PUNCTUATION = 24; /** * General category "Sm" in the Unicode specification. * @since 1.1 */ public static final byte MATH_SYMBOL = 25; /** * General category "Sc" in the Unicode specification. * @since 1.1 */ public static final byte CURRENCY_SYMBOL = 26; /** * General category "Sk" in the Unicode specification. * @since 1.1 */ public static final byte MODIFIER_SYMBOL = 27; /** * General category "So" in the Unicode specification. * @since 1.1 */ public static final byte OTHER_SYMBOL = 28; /** * General category "Pi" in the Unicode specification. * @since 1.4 */ public static final byte INITIAL_QUOTE_PUNCTUATION = 29; /** * General category "Pf" in the Unicode specification. * @since 1.4 */ public static final byte FINAL_QUOTE_PUNCTUATION = 30; /** * Error flag. Use int (code point) to avoid confusion with U+FFFF. */ static final int ERROR = 0xFFFFFFFF; /** * Undefined bidirectional character type. Undefined {@code char} * values have undefined directionality in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_UNDEFINED = -1; /** * Strong bidirectional character type "L" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_LEFT_TO_RIGHT = 0; /** * Strong bidirectional character type "R" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_RIGHT_TO_LEFT = 1; /** * Strong bidirectional character type "AL" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC = 2; /** * Weak bidirectional character type "EN" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_EUROPEAN_NUMBER = 3; /** * Weak bidirectional character type "ES" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR = 4; /** * Weak bidirectional character type "ET" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR = 5; /** * Weak bidirectional character type "AN" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_ARABIC_NUMBER = 6; /** * Weak bidirectional character type "CS" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_COMMON_NUMBER_SEPARATOR = 7; /** * Weak bidirectional character type "NSM" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_NONSPACING_MARK = 8; /** * Weak bidirectional character type "BN" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_BOUNDARY_NEUTRAL = 9; /** * Neutral bidirectional character type "B" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_PARAGRAPH_SEPARATOR = 10; /** * Neutral bidirectional character type "S" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_SEGMENT_SEPARATOR = 11; /** * Neutral bidirectional character type "WS" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_WHITESPACE = 12; /** * Neutral bidirectional character type "ON" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_OTHER_NEUTRALS = 13; /** * Strong bidirectional character type "LRE" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING = 14; /** * Strong bidirectional character type "LRO" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE = 15; /** * Strong bidirectional character type "RLE" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING = 16; /** * Strong bidirectional character type "RLO" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE = 17; /** * Weak bidirectional character type "PDF" in the Unicode specification. * @since 1.4 */ public static final byte DIRECTIONALITY_POP_DIRECTIONAL_FORMAT = 18; /** * The minimum value of a * <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit"> * Unicode high-surrogate code unit</a> * in the UTF-16 encoding, constant {@code '\u005CuD800'}. * A high-surrogate is also known as a <i>leading-surrogate</i>. * * @since 1.5 */ public static final char MIN_HIGH_SURROGATE = '\uD800'; /** * The maximum value of a * <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit"> * Unicode high-surrogate code unit</a> * in the UTF-16 encoding, constant {@code '\u005CuDBFF'}. * A high-surrogate is also known as a <i>leading-surrogate</i>. * * @since 1.5 */ public static final char MAX_HIGH_SURROGATE = '\uDBFF'; /** * The minimum value of a * <a href="http://www.unicode.org/glossary/#low_surrogate_code_unit"> * Unicode low-surrogate code unit</a> * in the UTF-16 encoding, constant {@code '\u005CuDC00'}. * A low-surrogate is also known as a <i>trailing-surrogate</i>. * * @since 1.5 */ public static final char MIN_LOW_SURROGATE = '\uDC00'; /** * The maximum value of a * <a href="http://www.unicode.org/glossary/#low_surrogate_code_unit"> * Unicode low-surrogate code unit</a> * in the UTF-16 encoding, constant {@code '\u005CuDFFF'}. * A low-surrogate is also known as a <i>trailing-surrogate</i>. * * @since 1.5 */ public static final char MAX_LOW_SURROGATE = '\uDFFF'; /** * The minimum value of a Unicode surrogate code unit in the * UTF-16 encoding, constant {@code '\u005CuD800'}. * * @since 1.5 */ public static final char MIN_SURROGATE = MIN_HIGH_SURROGATE; /** * The maximum value of a Unicode surrogate code unit in the * UTF-16 encoding, constant {@code '\u005CuDFFF'}. * * @since 1.5 */ public static final char MAX_SURROGATE = MAX_LOW_SURROGATE; /** * The minimum value of a * <a href="http://www.unicode.org/glossary/#supplementary_code_point"> * Unicode supplementary code point</a>, constant {@code U+10000}. * * @since 1.5 */ public static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000; /** * The minimum value of a * <a href="http://www.unicode.org/glossary/#code_point"> * Unicode code point</a>, constant {@code U+0000}. * * @since 1.5 */ public static final int MIN_CODE_POINT = 0x000000; /** * The maximum value of a * <a href="http://www.unicode.org/glossary/#code_point"> * Unicode code point</a>, constant {@code U+10FFFF}. * * @since 1.5 */ public static final int MAX_CODE_POINT = 0X10FFFF; /** * Instances of this class represent particular subsets of the Unicode * character set. The only family of subsets defined in the * {@code Character} class is {@link Character.UnicodeBlock}. * Other portions of the Java API may define other subsets for their * own purposes. * * @since 1.2 */ public static class Subset { private String name; /** * Constructs a new {@code Subset} instance. * * @param name The name of this subset * @exception NullPointerException if name is {@code null} */ protected Subset(String name) { if (name == null) { throw new NullPointerException("name"); } this.name = name; } /** * Compares two {@code Subset} objects for equality. * This method returns {@code true} if and only if * {@code this} and the argument refer to the same * object; since this method is {@code final}, this * guarantee holds for all subclasses. */ public final boolean equals(Object obj) { return (this == obj); } /** * Returns the standard hash code as defined by the * {@link Object#hashCode} method. This method * is {@code final} in order to ensure that the * {@code equals} and {@code hashCode} methods will * be consistent in all subclasses. */ public final int hashCode() { return super.hashCode(); } /** * Returns the name of this subset. */ public final String toString() { return name; } } // See http://www.unicode.org/Public/UNIDATA/Blocks.txt // for the latest specification of Unicode Blocks. /** * A family of character subsets representing the character blocks in the * Unicode specification. Character blocks generally define characters * used for a specific script or purpose. A character is contained by * at most one Unicode block. * * @since 1.2 */ public static final class UnicodeBlock extends Subset { private static Map<String, UnicodeBlock> map = new HashMap<>(256); /** * Creates a UnicodeBlock with the given identifier name. * This name must be the same as the block identifier. */ private UnicodeBlock(String idName) { super(idName); map.put(idName, this); } /** * Creates a UnicodeBlock with the given identifier name and * alias name. */ private UnicodeBlock(String idName, String alias) { this(idName); map.put(alias, this); } /** * Creates a UnicodeBlock with the given identifier name and * alias names. */ private UnicodeBlock(String idName, String... aliases) { this(idName); for (String alias : aliases) map.put(alias, this); } /** * Constant for the "Basic Latin" Unicode character block. * @since 1.2 */ public static final UnicodeBlock BASIC_LATIN = new UnicodeBlock("BASIC_LATIN", "BASIC LATIN", "BASICLATIN"); /** * Constant for the "Latin-1 Supplement" Unicode character block. * @since 1.2 */ public static final UnicodeBlock LATIN_1_SUPPLEMENT = new UnicodeBlock("LATIN_1_SUPPLEMENT", "LATIN-1 SUPPLEMENT", "LATIN-1SUPPLEMENT"); /** * Constant for the "Latin Extended-A" Unicode character block. * @since 1.2 */ public static final UnicodeBlock LATIN_EXTENDED_A = new UnicodeBlock("LATIN_EXTENDED_A", "LATIN EXTENDED-A", "LATINEXTENDED-A"); /** * Constant for the "Latin Extended-B" Unicode character block. * @since 1.2 */ public static final UnicodeBlock LATIN_EXTENDED_B = new UnicodeBlock("LATIN_EXTENDED_B", "LATIN EXTENDED-B", "LATINEXTENDED-B"); /** * Constant for the "IPA Extensions" Unicode character block. * @since 1.2 */ public static final UnicodeBlock IPA_EXTENSIONS = new UnicodeBlock("IPA_EXTENSIONS", "IPA EXTENSIONS", "IPAEXTENSIONS"); /** * Constant for the "Spacing Modifier Letters" Unicode character block. * @since 1.2 */ public static final UnicodeBlock SPACING_MODIFIER_LETTERS = new UnicodeBlock("SPACING_MODIFIER_LETTERS", "SPACING MODIFIER LETTERS", "SPACINGMODIFIERLETTERS"); /** * Constant for the "Combining Diacritical Marks" Unicode character block. * @since 1.2 */ public static final UnicodeBlock COMBINING_DIACRITICAL_MARKS = new UnicodeBlock("COMBINING_DIACRITICAL_MARKS", "COMBINING DIACRITICAL MARKS", "COMBININGDIACRITICALMARKS"); /** * Constant for the "Greek and Coptic" Unicode character block. * <p> * This block was previously known as the "Greek" block. * * @since 1.2 */ public static final UnicodeBlock GREEK = new UnicodeBlock("GREEK", "GREEK AND COPTIC", "GREEKANDCOPTIC"); /** * Constant for the "Cyrillic" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CYRILLIC = new UnicodeBlock("CYRILLIC"); /** * Constant for the "Armenian" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ARMENIAN = new UnicodeBlock("ARMENIAN"); /** * Constant for the "Hebrew" Unicode character block. * @since 1.2 */ public static final UnicodeBlock HEBREW = new UnicodeBlock("HEBREW"); /** * Constant for the "Arabic" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ARABIC = new UnicodeBlock("ARABIC"); /** * Constant for the "Devanagari" Unicode character block. * @since 1.2 */ public static final UnicodeBlock DEVANAGARI = new UnicodeBlock("DEVANAGARI"); /** * Constant for the "Bengali" Unicode character block. * @since 1.2 */ public static final UnicodeBlock BENGALI = new UnicodeBlock("BENGALI"); /** * Constant for the "Gurmukhi" Unicode character block. * @since 1.2 */ public static final UnicodeBlock GURMUKHI = new UnicodeBlock("GURMUKHI"); /** * Constant for the "Gujarati" Unicode character block. * @since 1.2 */ public static final UnicodeBlock GUJARATI = new UnicodeBlock("GUJARATI"); /** * Constant for the "Oriya" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ORIYA = new UnicodeBlock("ORIYA"); /** * Constant for the "Tamil" Unicode character block. * @since 1.2 */ public static final UnicodeBlock TAMIL = new UnicodeBlock("TAMIL"); /** * Constant for the "Telugu" Unicode character block. * @since 1.2 */ public static final UnicodeBlock TELUGU = new UnicodeBlock("TELUGU"); /** * Constant for the "Kannada" Unicode character block. * @since 1.2 */ public static final UnicodeBlock KANNADA = new UnicodeBlock("KANNADA"); /** * Constant for the "Malayalam" Unicode character block. * @since 1.2 */ public static final UnicodeBlock MALAYALAM = new UnicodeBlock("MALAYALAM"); /** * Constant for the "Thai" Unicode character block. * @since 1.2 */ public static final UnicodeBlock THAI = new UnicodeBlock("THAI"); /** * Constant for the "Lao" Unicode character block. * @since 1.2 */ public static final UnicodeBlock LAO = new UnicodeBlock("LAO"); /** * Constant for the "Tibetan" Unicode character block. * @since 1.2 */ public static final UnicodeBlock TIBETAN = new UnicodeBlock("TIBETAN"); /** * Constant for the "Georgian" Unicode character block. * @since 1.2 */ public static final UnicodeBlock GEORGIAN = new UnicodeBlock("GEORGIAN"); /** * Constant for the "Hangul Jamo" Unicode character block. * @since 1.2 */ public static final UnicodeBlock HANGUL_JAMO = new UnicodeBlock("HANGUL_JAMO", "HANGUL JAMO", "HANGULJAMO"); /** * Constant for the "Latin Extended Additional" Unicode character block. * @since 1.2 */ public static final UnicodeBlock LATIN_EXTENDED_ADDITIONAL = new UnicodeBlock("LATIN_EXTENDED_ADDITIONAL", "LATIN EXTENDED ADDITIONAL", "LATINEXTENDEDADDITIONAL"); /** * Constant for the "Greek Extended" Unicode character block. * @since 1.2 */ public static final UnicodeBlock GREEK_EXTENDED = new UnicodeBlock("GREEK_EXTENDED", "GREEK EXTENDED", "GREEKEXTENDED"); /** * Constant for the "General Punctuation" Unicode character block. * @since 1.2 */ public static final UnicodeBlock GENERAL_PUNCTUATION = new UnicodeBlock("GENERAL_PUNCTUATION", "GENERAL PUNCTUATION", "GENERALPUNCTUATION"); /** * Constant for the "Superscripts and Subscripts" Unicode character * block. * @since 1.2 */ public static final UnicodeBlock SUPERSCRIPTS_AND_SUBSCRIPTS = new UnicodeBlock("SUPERSCRIPTS_AND_SUBSCRIPTS", "SUPERSCRIPTS AND SUBSCRIPTS", "SUPERSCRIPTSANDSUBSCRIPTS"); /** * Constant for the "Currency Symbols" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CURRENCY_SYMBOLS = new UnicodeBlock("CURRENCY_SYMBOLS", "CURRENCY SYMBOLS", "CURRENCYSYMBOLS"); /** * Constant for the "Combining Diacritical Marks for Symbols" Unicode * character block. * <p> * This block was previously known as "Combining Marks for Symbols". * @since 1.2 */ public static final UnicodeBlock COMBINING_MARKS_FOR_SYMBOLS = new UnicodeBlock("COMBINING_MARKS_FOR_SYMBOLS", "COMBINING DIACRITICAL MARKS FOR SYMBOLS", "COMBININGDIACRITICALMARKSFORSYMBOLS", "COMBINING MARKS FOR SYMBOLS", "COMBININGMARKSFORSYMBOLS"); /** * Constant for the "Letterlike Symbols" Unicode character block. * @since 1.2 */ public static final UnicodeBlock LETTERLIKE_SYMBOLS = new UnicodeBlock("LETTERLIKE_SYMBOLS", "LETTERLIKE SYMBOLS", "LETTERLIKESYMBOLS"); /** * Constant for the "Number Forms" Unicode character block. * @since 1.2 */ public static final UnicodeBlock NUMBER_FORMS = new UnicodeBlock("NUMBER_FORMS", "NUMBER FORMS", "NUMBERFORMS"); /** * Constant for the "Arrows" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ARROWS = new UnicodeBlock("ARROWS"); /** * Constant for the "Mathematical Operators" Unicode character block. * @since 1.2 */ public static final UnicodeBlock MATHEMATICAL_OPERATORS = new UnicodeBlock("MATHEMATICAL_OPERATORS", "MATHEMATICAL OPERATORS", "MATHEMATICALOPERATORS"); /** * Constant for the "Miscellaneous Technical" Unicode character block. * @since 1.2 */ public static final UnicodeBlock MISCELLANEOUS_TECHNICAL = new UnicodeBlock("MISCELLANEOUS_TECHNICAL", "MISCELLANEOUS TECHNICAL", "MISCELLANEOUSTECHNICAL"); /** * Constant for the "Control Pictures" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CONTROL_PICTURES = new UnicodeBlock("CONTROL_PICTURES", "CONTROL PICTURES", "CONTROLPICTURES"); /** * Constant for the "Optical Character Recognition" Unicode character block. * @since 1.2 */ public static final UnicodeBlock OPTICAL_CHARACTER_RECOGNITION = new UnicodeBlock("OPTICAL_CHARACTER_RECOGNITION", "OPTICAL CHARACTER RECOGNITION", "OPTICALCHARACTERRECOGNITION"); /** * Constant for the "Enclosed Alphanumerics" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ENCLOSED_ALPHANUMERICS = new UnicodeBlock("ENCLOSED_ALPHANUMERICS", "ENCLOSED ALPHANUMERICS", "ENCLOSEDALPHANUMERICS"); /** * Constant for the "Box Drawing" Unicode character block. * @since 1.2 */ public static final UnicodeBlock BOX_DRAWING = new UnicodeBlock("BOX_DRAWING", "BOX DRAWING", "BOXDRAWING"); /** * Constant for the "Block Elements" Unicode character block. * @since 1.2 */ public static final UnicodeBlock BLOCK_ELEMENTS = new UnicodeBlock("BLOCK_ELEMENTS", "BLOCK ELEMENTS", "BLOCKELEMENTS"); /** * Constant for the "Geometric Shapes" Unicode character block. * @since 1.2 */ public static final UnicodeBlock GEOMETRIC_SHAPES = new UnicodeBlock("GEOMETRIC_SHAPES", "GEOMETRIC SHAPES", "GEOMETRICSHAPES"); /** * Constant for the "Miscellaneous Symbols" Unicode character block. * @since 1.2 */ public static final UnicodeBlock MISCELLANEOUS_SYMBOLS = new UnicodeBlock("MISCELLANEOUS_SYMBOLS", "MISCELLANEOUS SYMBOLS", "MISCELLANEOUSSYMBOLS"); /** * Constant for the "Dingbats" Unicode character block. * @since 1.2 */ public static final UnicodeBlock DINGBATS = new UnicodeBlock("DINGBATS"); /** * Constant for the "CJK Symbols and Punctuation" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CJK_SYMBOLS_AND_PUNCTUATION = new UnicodeBlock("CJK_SYMBOLS_AND_PUNCTUATION", "CJK SYMBOLS AND PUNCTUATION", "CJKSYMBOLSANDPUNCTUATION"); /** * Constant for the "Hiragana" Unicode character block. * @since 1.2 */ public static final UnicodeBlock HIRAGANA = new UnicodeBlock("HIRAGANA"); /** * Constant for the "Katakana" Unicode character block. * @since 1.2 */ public static final UnicodeBlock KATAKANA = new UnicodeBlock("KATAKANA"); /** * Constant for the "Bopomofo" Unicode character block. * @since 1.2 */ public static final UnicodeBlock BOPOMOFO = new UnicodeBlock("BOPOMOFO"); /** * Constant for the "Hangul Compatibility Jamo" Unicode character block. * @since 1.2 */ public static final UnicodeBlock HANGUL_COMPATIBILITY_JAMO = new UnicodeBlock("HANGUL_COMPATIBILITY_JAMO", "HANGUL COMPATIBILITY JAMO", "HANGULCOMPATIBILITYJAMO"); /** * Constant for the "Kanbun" Unicode character block. * @since 1.2 */ public static final UnicodeBlock KANBUN = new UnicodeBlock("KANBUN"); /** * Constant for the "Enclosed CJK Letters and Months" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ENCLOSED_CJK_LETTERS_AND_MONTHS = new UnicodeBlock("ENCLOSED_CJK_LETTERS_AND_MONTHS", "ENCLOSED CJK LETTERS AND MONTHS", "ENCLOSEDCJKLETTERSANDMONTHS"); /** * Constant for the "CJK Compatibility" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CJK_COMPATIBILITY = new UnicodeBlock("CJK_COMPATIBILITY", "CJK COMPATIBILITY", "CJKCOMPATIBILITY"); /** * Constant for the "CJK Unified Ideographs" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS = new UnicodeBlock("CJK_UNIFIED_IDEOGRAPHS", "CJK UNIFIED IDEOGRAPHS", "CJKUNIFIEDIDEOGRAPHS"); /** * Constant for the "Hangul Syllables" Unicode character block. * @since 1.2 */ public static final UnicodeBlock HANGUL_SYLLABLES = new UnicodeBlock("HANGUL_SYLLABLES", "HANGUL SYLLABLES", "HANGULSYLLABLES"); /** * Constant for the "Private Use Area" Unicode character block. * @since 1.2 */ public static final UnicodeBlock PRIVATE_USE_AREA = new UnicodeBlock("PRIVATE_USE_AREA", "PRIVATE USE AREA", "PRIVATEUSEAREA"); /** * Constant for the "CJK Compatibility Ideographs" Unicode character * block. * @since 1.2 */ public static final UnicodeBlock CJK_COMPATIBILITY_IDEOGRAPHS = new UnicodeBlock("CJK_COMPATIBILITY_IDEOGRAPHS", "CJK COMPATIBILITY IDEOGRAPHS", "CJKCOMPATIBILITYIDEOGRAPHS"); /** * Constant for the "Alphabetic Presentation Forms" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ALPHABETIC_PRESENTATION_FORMS = new UnicodeBlock("ALPHABETIC_PRESENTATION_FORMS", "ALPHABETIC PRESENTATION FORMS", "ALPHABETICPRESENTATIONFORMS"); /** * Constant for the "Arabic Presentation Forms-A" Unicode character * block. * @since 1.2 */ public static final UnicodeBlock ARABIC_PRESENTATION_FORMS_A = new UnicodeBlock("ARABIC_PRESENTATION_FORMS_A", "ARABIC PRESENTATION FORMS-A", "ARABICPRESENTATIONFORMS-A"); /** * Constant for the "Combining Half Marks" Unicode character block. * @since 1.2 */ public static final UnicodeBlock COMBINING_HALF_MARKS = new UnicodeBlock("COMBINING_HALF_MARKS", "COMBINING HALF MARKS", "COMBININGHALFMARKS"); /** * Constant for the "CJK Compatibility Forms" Unicode character block. * @since 1.2 */ public static final UnicodeBlock CJK_COMPATIBILITY_FORMS = new UnicodeBlock("CJK_COMPATIBILITY_FORMS", "CJK COMPATIBILITY FORMS", "CJKCOMPATIBILITYFORMS"); /** * Constant for the "Small Form Variants" Unicode character block. * @since 1.2 */ public static final UnicodeBlock SMALL_FORM_VARIANTS = new UnicodeBlock("SMALL_FORM_VARIANTS", "SMALL FORM VARIANTS", "SMALLFORMVARIANTS"); /** * Constant for the "Arabic Presentation Forms-B" Unicode character block. * @since 1.2 */ public static final UnicodeBlock ARABIC_PRESENTATION_FORMS_B = new UnicodeBlock("ARABIC_PRESENTATION_FORMS_B", "ARABIC PRESENTATION FORMS-B", "ARABICPRESENTATIONFORMS-B"); /** * Constant for the "Halfwidth and Fullwidth Forms" Unicode character * block. * @since 1.2 */ public static final UnicodeBlock HALFWIDTH_AND_FULLWIDTH_FORMS = new UnicodeBlock("HALFWIDTH_AND_FULLWIDTH_FORMS", "HALFWIDTH AND FULLWIDTH FORMS", "HALFWIDTHANDFULLWIDTHFORMS"); /** * Constant for the "Specials" Unicode character block. * @since 1.2 */ public static final UnicodeBlock SPECIALS = new UnicodeBlock("SPECIALS"); /** * @deprecated As of J2SE 5, use {@link #HIGH_SURROGATES}, * {@link #HIGH_PRIVATE_USE_SURROGATES}, and * {@link #LOW_SURROGATES}. These new constants match * the block definitions of the Unicode Standard. * The {@link #of(char)} and {@link #of(int)} methods * return the new constants, not SURROGATES_AREA. */ @Deprecated public static final UnicodeBlock SURROGATES_AREA = new UnicodeBlock("SURROGATES_AREA"); /** * Constant for the "Syriac" Unicode character block. * @since 1.4 */ public static final UnicodeBlock SYRIAC = new UnicodeBlock("SYRIAC"); /** * Constant for the "Thaana" Unicode character block. * @since 1.4 */ public static final UnicodeBlock THAANA = new UnicodeBlock("THAANA"); /** * Constant for the "Sinhala" Unicode character block. * @since 1.4 */ public static final UnicodeBlock SINHALA = new UnicodeBlock("SINHALA"); /** * Constant for the "Myanmar" Unicode character block. * @since 1.4 */ public static final UnicodeBlock MYANMAR = new UnicodeBlock("MYANMAR"); /** * Constant for the "Ethiopic" Unicode character block. * @since 1.4 */ public static final UnicodeBlock ETHIOPIC = new UnicodeBlock("ETHIOPIC"); /** * Constant for the "Cherokee" Unicode character block. * @since 1.4 */ public static final UnicodeBlock CHEROKEE = new UnicodeBlock("CHEROKEE"); /** * Constant for the "Unified Canadian Aboriginal Syllabics" Unicode character block. * @since 1.4 */ public static final UnicodeBlock UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS = new UnicodeBlock("UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS", "UNIFIED CANADIAN ABORIGINAL SYLLABICS", "UNIFIEDCANADIANABORIGINALSYLLABICS"); /** * Constant for the "Ogham" Unicode character block. * @since 1.4 */ public static final UnicodeBlock OGHAM = new UnicodeBlock("OGHAM"); /** * Constant for the "Runic" Unicode character block. * @since 1.4 */ public static final UnicodeBlock RUNIC = new UnicodeBlock("RUNIC"); /** * Constant for the "Khmer" Unicode character block. * @since 1.4 */ public static final UnicodeBlock KHMER = new UnicodeBlock("KHMER"); /** * Constant for the "Mongolian" Unicode character block. * @since 1.4 */ public static final UnicodeBlock MONGOLIAN = new UnicodeBlock("MONGOLIAN"); /** * Constant for the "Braille Patterns" Unicode character block. * @since 1.4 */ public static final UnicodeBlock BRAILLE_PATTERNS = new UnicodeBlock("BRAILLE_PATTERNS", "BRAILLE PATTERNS", "BRAILLEPATTERNS"); /** * Constant for the "CJK Radicals Supplement" Unicode character block. * @since 1.4 */ public static final UnicodeBlock CJK_RADICALS_SUPPLEMENT = new UnicodeBlock("CJK_RADICALS_SUPPLEMENT", "CJK RADICALS SUPPLEMENT", "CJKRADICALSSUPPLEMENT"); /** * Constant for the "Kangxi Radicals" Unicode character block. * @since 1.4 */ public static final UnicodeBlock KANGXI_RADICALS = new UnicodeBlock("KANGXI_RADICALS", "KANGXI RADICALS", "KANGXIRADICALS"); /** * Constant for the "Ideographic Description Characters" Unicode character block. * @since 1.4 */ public static final UnicodeBlock IDEOGRAPHIC_DESCRIPTION_CHARACTERS = new UnicodeBlock("IDEOGRAPHIC_DESCRIPTION_CHARACTERS", "IDEOGRAPHIC DESCRIPTION CHARACTERS", "IDEOGRAPHICDESCRIPTIONCHARACTERS"); /** * Constant for the "Bopomofo Extended" Unicode character block. * @since 1.4 */ public static final UnicodeBlock BOPOMOFO_EXTENDED = new UnicodeBlock("BOPOMOFO_EXTENDED", "BOPOMOFO EXTENDED", "BOPOMOFOEXTENDED"); /** * Constant for the "CJK Unified Ideographs Extension A" Unicode character block. * @since 1.4 */ public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A = new UnicodeBlock("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A", "CJK UNIFIED IDEOGRAPHS EXTENSION A", "CJKUNIFIEDIDEOGRAPHSEXTENSIONA"); /** * Constant for the "Yi Syllables" Unicode character block. * @since 1.4 */ public static final UnicodeBlock YI_SYLLABLES = new UnicodeBlock("YI_SYLLABLES", "YI SYLLABLES", "YISYLLABLES"); /** * Constant for the "Yi Radicals" Unicode character block. * @since 1.4 */ public static final UnicodeBlock YI_RADICALS = new UnicodeBlock("YI_RADICALS", "YI RADICALS", "YIRADICALS"); /** * Constant for the "Cyrillic Supplementary" Unicode character block. * @since 1.5 */ public static final UnicodeBlock CYRILLIC_SUPPLEMENTARY = new UnicodeBlock("CYRILLIC_SUPPLEMENTARY", "CYRILLIC SUPPLEMENTARY", "CYRILLICSUPPLEMENTARY", "CYRILLIC SUPPLEMENT", "CYRILLICSUPPLEMENT"); /** * Constant for the "Tagalog" Unicode character block. * @since 1.5 */ public static final UnicodeBlock TAGALOG = new UnicodeBlock("TAGALOG"); /** * Constant for the "Hanunoo" Unicode character block. * @since 1.5 */ public static final UnicodeBlock HANUNOO = new UnicodeBlock("HANUNOO"); /** * Constant for the "Buhid" Unicode character block. * @since 1.5 */ public static final UnicodeBlock BUHID = new UnicodeBlock("BUHID"); /** * Constant for the "Tagbanwa" Unicode character block. * @since 1.5 */ public static final UnicodeBlock TAGBANWA = new UnicodeBlock("TAGBANWA"); /** * Constant for the "Limbu" Unicode character block. * @since 1.5 */ public static final UnicodeBlock LIMBU = new UnicodeBlock("LIMBU"); /** * Constant for the "Tai Le" Unicode character block. * @since 1.5 */ public static final UnicodeBlock TAI_LE = new UnicodeBlock("TAI_LE", "TAI LE", "TAILE"); /** * Constant for the "Khmer Symbols" Unicode character block. * @since 1.5 */ public static final UnicodeBlock KHMER_SYMBOLS = new UnicodeBlock("KHMER_SYMBOLS", "KHMER SYMBOLS", "KHMERSYMBOLS"); /** * Constant for the "Phonetic Extensions" Unicode character block. * @since 1.5 */ public static final UnicodeBlock PHONETIC_EXTENSIONS = new UnicodeBlock("PHONETIC_EXTENSIONS", "PHONETIC EXTENSIONS", "PHONETICEXTENSIONS"); /** * Constant for the "Miscellaneous Mathematical Symbols-A" Unicode character block. * @since 1.5 */ public static final UnicodeBlock MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = new UnicodeBlock("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A", "MISCELLANEOUS MATHEMATICAL SYMBOLS-A", "MISCELLANEOUSMATHEMATICALSYMBOLS-A"); /** * Constant for the "Supplemental Arrows-A" Unicode character block. * @since 1.5 */ public static final UnicodeBlock SUPPLEMENTAL_ARROWS_A = new UnicodeBlock("SUPPLEMENTAL_ARROWS_A", "SUPPLEMENTAL ARROWS-A", "SUPPLEMENTALARROWS-A"); /** * Constant for the "Supplemental Arrows-B" Unicode character block. * @since 1.5 */ public static final UnicodeBlock SUPPLEMENTAL_ARROWS_B = new UnicodeBlock("SUPPLEMENTAL_ARROWS_B", "SUPPLEMENTAL ARROWS-B", "SUPPLEMENTALARROWS-B"); /** * Constant for the "Miscellaneous Mathematical Symbols-B" Unicode * character block. * @since 1.5 */ public static final UnicodeBlock MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = new UnicodeBlock("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B", "MISCELLANEOUS MATHEMATICAL SYMBOLS-B", "MISCELLANEOUSMATHEMATICALSYMBOLS-B"); /** * Constant for the "Supplemental Mathematical Operators" Unicode * character block. * @since 1.5 */ public static final UnicodeBlock SUPPLEMENTAL_MATHEMATICAL_OPERATORS = new UnicodeBlock("SUPPLEMENTAL_MATHEMATICAL_OPERATORS", "SUPPLEMENTAL MATHEMATICAL OPERATORS", "SUPPLEMENTALMATHEMATICALOPERATORS"); /** * Constant for the "Miscellaneous Symbols and Arrows" Unicode character * block. * @since 1.5 */ public static final UnicodeBlock MISCELLANEOUS_SYMBOLS_AND_ARROWS = new UnicodeBlock("MISCELLANEOUS_SYMBOLS_AND_ARROWS", "MISCELLANEOUS SYMBOLS AND ARROWS", "MISCELLANEOUSSYMBOLSANDARROWS"); /** * Constant for the "Katakana Phonetic Extensions" Unicode character * block. * @since 1.5 */ public static final UnicodeBlock KATAKANA_PHONETIC_EXTENSIONS = new UnicodeBlock("KATAKANA_PHONETIC_EXTENSIONS", "KATAKANA PHONETIC EXTENSIONS", "KATAKANAPHONETICEXTENSIONS"); /** * Constant for the "Yijing Hexagram Symbols" Unicode character block. * @since 1.5 */ public static final UnicodeBlock YIJING_HEXAGRAM_SYMBOLS = new UnicodeBlock("YIJING_HEXAGRAM_SYMBOLS", "YIJING HEXAGRAM SYMBOLS", "YIJINGHEXAGRAMSYMBOLS"); /** * Constant for the "Variation Selectors" Unicode character block. * @since 1.5 */ public static final UnicodeBlock VARIATION_SELECTORS = new UnicodeBlock("VARIATION_SELECTORS", "VARIATION SELECTORS", "VARIATIONSELECTORS"); /** * Constant for the "Linear B Syllabary" Unicode character block. * @since 1.5 */ public static final UnicodeBlock LINEAR_B_SYLLABARY = new UnicodeBlock("LINEAR_B_SYLLABARY", "LINEAR B SYLLABARY", "LINEARBSYLLABARY"); /** * Constant for the "Linear B Ideograms" Unicode character block. * @since 1.5 */ public static final UnicodeBlock LINEAR_B_IDEOGRAMS = new UnicodeBlock("LINEAR_B_IDEOGRAMS", "LINEAR B IDEOGRAMS", "LINEARBIDEOGRAMS"); /** * Constant for the "Aegean Numbers" Unicode character block. * @since 1.5 */ public static final UnicodeBlock AEGEAN_NUMBERS = new UnicodeBlock("AEGEAN_NUMBERS", "AEGEAN NUMBERS", "AEGEANNUMBERS"); /** * Constant for the "Old Italic" Unicode character block. * @since 1.5 */ public static final UnicodeBlock OLD_ITALIC = new UnicodeBlock("OLD_ITALIC", "OLD ITALIC", "OLDITALIC"); /** * Constant for the "Gothic" Unicode character block. * @since 1.5 */ public static final UnicodeBlock GOTHIC = new UnicodeBlock("GOTHIC"); /** * Constant for the "Ugaritic" Unicode character block. * @since 1.5 */ public static final UnicodeBlock UGARITIC = new UnicodeBlock("UGARITIC"); /** * Constant for the "Deseret" Unicode character block. * @since 1.5 */ public static final UnicodeBlock DESERET = new UnicodeBlock("DESERET"); /** * Constant for the "Shavian" Unicode character block. * @since 1.5 */ public static final UnicodeBlock SHAVIAN = new UnicodeBlock("SHAVIAN"); /** * Constant for the "Osmanya" Unicode character block. * @since 1.5 */ public static final UnicodeBlock OSMANYA = new UnicodeBlock("OSMANYA"); /** * Constant for the "Cypriot Syllabary" Unicode character block. * @since 1.5 */ public static final UnicodeBlock CYPRIOT_SYLLABARY = new UnicodeBlock("CYPRIOT_SYLLABARY", "CYPRIOT SYLLABARY", "CYPRIOTSYLLABARY"); /** * Constant for the "Byzantine Musical Symbols" Unicode character block. * @since 1.5 */ public static final UnicodeBlock BYZANTINE_MUSICAL_SYMBOLS = new UnicodeBlock("BYZANTINE_MUSICAL_SYMBOLS", "BYZANTINE MUSICAL SYMBOLS", "BYZANTINEMUSICALSYMBOLS"); /** * Constant for the "Musical Symbols" Unicode character block. * @since 1.5 */ public static final UnicodeBlock MUSICAL_SYMBOLS = new UnicodeBlock("MUSICAL_SYMBOLS", "MUSICAL SYMBOLS", "MUSICALSYMBOLS"); /** * Constant for the "Tai Xuan Jing Symbols" Unicode character block. * @since 1.5 */ public static final UnicodeBlock TAI_XUAN_JING_SYMBOLS = new UnicodeBlock("TAI_XUAN_JING_SYMBOLS", "TAI XUAN JING SYMBOLS", "TAIXUANJINGSYMBOLS"); /** * Constant for the "Mathematical Alphanumeric Symbols" Unicode * character block. * @since 1.5 */ public static final UnicodeBlock MATHEMATICAL_ALPHANUMERIC_SYMBOLS = new UnicodeBlock("MATHEMATICAL_ALPHANUMERIC_SYMBOLS", "MATHEMATICAL ALPHANUMERIC SYMBOLS", "MATHEMATICALALPHANUMERICSYMBOLS"); /** * Constant for the "CJK Unified Ideographs Extension B" Unicode * character block. * @since 1.5 */ public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B = new UnicodeBlock("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B", "CJK UNIFIED IDEOGRAPHS EXTENSION B", "CJKUNIFIEDIDEOGRAPHSEXTENSIONB"); /** * Constant for the "CJK Compatibility Ideographs Supplement" Unicode character block. * @since 1.5 */ public static final UnicodeBlock CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = new UnicodeBlock("CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT", "CJK COMPATIBILITY IDEOGRAPHS SUPPLEMENT", "CJKCOMPATIBILITYIDEOGRAPHSSUPPLEMENT"); /** * Constant for the "Tags" Unicode character block. * @since 1.5 */ public static final UnicodeBlock TAGS = new UnicodeBlock("TAGS"); /** * Constant for the "Variation Selectors Supplement" Unicode character * block. * @since 1.5 */ public static final UnicodeBlock VARIATION_SELECTORS_SUPPLEMENT = new UnicodeBlock("VARIATION_SELECTORS_SUPPLEMENT", "VARIATION SELECTORS SUPPLEMENT", "VARIATIONSELECTORSSUPPLEMENT"); /** * Constant for the "Supplementary Private Use Area-A" Unicode character * block. * @since 1.5 */ public static final UnicodeBlock SUPPLEMENTARY_PRIVATE_USE_AREA_A = new UnicodeBlock("SUPPLEMENTARY_PRIVATE_USE_AREA_A", "SUPPLEMENTARY PRIVATE USE AREA-A", "SUPPLEMENTARYPRIVATEUSEAREA-A"); /** * Constant for the "Supplementary Private Use Area-B" Unicode character * block. * @since 1.5 */ public static final UnicodeBlock SUPPLEMENTARY_PRIVATE_USE_AREA_B = new UnicodeBlock("SUPPLEMENTARY_PRIVATE_USE_AREA_B", "SUPPLEMENTARY PRIVATE USE AREA-B", "SUPPLEMENTARYPRIVATEUSEAREA-B"); /** * Constant for the "High Surrogates" Unicode character block. * This block represents codepoint values in the high surrogate * range: U+D800 through U+DB7F * * @since 1.5 */ public static final UnicodeBlock HIGH_SURROGATES = new UnicodeBlock("HIGH_SURROGATES", "HIGH SURROGATES", "HIGHSURROGATES"); /** * Constant for the "High Private Use Surrogates" Unicode character * block. * This block represents codepoint values in the private use high * surrogate range: U+DB80 through U+DBFF * * @since 1.5 */ public static final UnicodeBlock HIGH_PRIVATE_USE_SURROGATES = new UnicodeBlock("HIGH_PRIVATE_USE_SURROGATES", "HIGH PRIVATE USE SURROGATES", "HIGHPRIVATEUSESURROGATES"); /** * Constant for the "Low Surrogates" Unicode character block. * This block represents codepoint values in the low surrogate * range: U+DC00 through U+DFFF * * @since 1.5 */ public static final UnicodeBlock LOW_SURROGATES = new UnicodeBlock("LOW_SURROGATES", "LOW SURROGATES", "LOWSURROGATES"); /** * Constant for the "Arabic Supplement" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ARABIC_SUPPLEMENT = new UnicodeBlock("ARABIC_SUPPLEMENT", "ARABIC SUPPLEMENT", "ARABICSUPPLEMENT"); /** * Constant for the "NKo" Unicode character block. * @since 1.7 */ public static final UnicodeBlock NKO = new UnicodeBlock("NKO"); /** * Constant for the "Samaritan" Unicode character block. * @since 1.7 */ public static final UnicodeBlock SAMARITAN = new UnicodeBlock("SAMARITAN"); /** * Constant for the "Mandaic" Unicode character block. * @since 1.7 */ public static final UnicodeBlock MANDAIC = new UnicodeBlock("MANDAIC"); /** * Constant for the "Ethiopic Supplement" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ETHIOPIC_SUPPLEMENT = new UnicodeBlock("ETHIOPIC_SUPPLEMENT", "ETHIOPIC SUPPLEMENT", "ETHIOPICSUPPLEMENT"); /** * Constant for the "Unified Canadian Aboriginal Syllabics Extended" * Unicode character block. * @since 1.7 */ public static final UnicodeBlock UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED = new UnicodeBlock("UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED", "UNIFIED CANADIAN ABORIGINAL SYLLABICS EXTENDED", "UNIFIEDCANADIANABORIGINALSYLLABICSEXTENDED"); /** * Constant for the "New Tai Lue" Unicode character block. * @since 1.7 */ public static final UnicodeBlock NEW_TAI_LUE = new UnicodeBlock("NEW_TAI_LUE", "NEW TAI LUE", "NEWTAILUE"); /** * Constant for the "Buginese" Unicode character block. * @since 1.7 */ public static final UnicodeBlock BUGINESE = new UnicodeBlock("BUGINESE"); /** * Constant for the "Tai Tham" Unicode character block. * @since 1.7 */ public static final UnicodeBlock TAI_THAM = new UnicodeBlock("TAI_THAM", "TAI THAM", "TAITHAM"); /** * Constant for the "Balinese" Unicode character block. * @since 1.7 */ public static final UnicodeBlock BALINESE = new UnicodeBlock("BALINESE"); /** * Constant for the "Sundanese" Unicode character block. * @since 1.7 */ public static final UnicodeBlock SUNDANESE = new UnicodeBlock("SUNDANESE"); /** * Constant for the "Batak" Unicode character block. * @since 1.7 */ public static final UnicodeBlock BATAK = new UnicodeBlock("BATAK"); /** * Constant for the "Lepcha" Unicode character block. * @since 1.7 */ public static final UnicodeBlock LEPCHA = new UnicodeBlock("LEPCHA"); /** * Constant for the "Ol Chiki" Unicode character block. * @since 1.7 */ public static final UnicodeBlock OL_CHIKI = new UnicodeBlock("OL_CHIKI", "OL CHIKI", "OLCHIKI"); /** * Constant for the "Vedic Extensions" Unicode character block. * @since 1.7 */ public static final UnicodeBlock VEDIC_EXTENSIONS = new UnicodeBlock("VEDIC_EXTENSIONS", "VEDIC EXTENSIONS", "VEDICEXTENSIONS"); /** * Constant for the "Phonetic Extensions Supplement" Unicode character * block. * @since 1.7 */ public static final UnicodeBlock PHONETIC_EXTENSIONS_SUPPLEMENT = new UnicodeBlock("PHONETIC_EXTENSIONS_SUPPLEMENT", "PHONETIC EXTENSIONS SUPPLEMENT", "PHONETICEXTENSIONSSUPPLEMENT"); /** * Constant for the "Combining Diacritical Marks Supplement" Unicode * character block. * @since 1.7 */ public static final UnicodeBlock COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = new UnicodeBlock("COMBINING_DIACRITICAL_MARKS_SUPPLEMENT", "COMBINING DIACRITICAL MARKS SUPPLEMENT", "COMBININGDIACRITICALMARKSSUPPLEMENT"); /** * Constant for the "Glagolitic" Unicode character block. * @since 1.7 */ public static final UnicodeBlock GLAGOLITIC = new UnicodeBlock("GLAGOLITIC"); /** * Constant for the "Latin Extended-C" Unicode character block. * @since 1.7 */ public static final UnicodeBlock LATIN_EXTENDED_C = new UnicodeBlock("LATIN_EXTENDED_C", "LATIN EXTENDED-C", "LATINEXTENDED-C"); /** * Constant for the "Coptic" Unicode character block. * @since 1.7 */ public static final UnicodeBlock COPTIC = new UnicodeBlock("COPTIC"); /** * Constant for the "Georgian Supplement" Unicode character block. * @since 1.7 */ public static final UnicodeBlock GEORGIAN_SUPPLEMENT = new UnicodeBlock("GEORGIAN_SUPPLEMENT", "GEORGIAN SUPPLEMENT", "GEORGIANSUPPLEMENT"); /** * Constant for the "Tifinagh" Unicode character block. * @since 1.7 */ public static final UnicodeBlock TIFINAGH = new UnicodeBlock("TIFINAGH"); /** * Constant for the "Ethiopic Extended" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ETHIOPIC_EXTENDED = new UnicodeBlock("ETHIOPIC_EXTENDED", "ETHIOPIC EXTENDED", "ETHIOPICEXTENDED"); /** * Constant for the "Cyrillic Extended-A" Unicode character block. * @since 1.7 */ public static final UnicodeBlock CYRILLIC_EXTENDED_A = new UnicodeBlock("CYRILLIC_EXTENDED_A", "CYRILLIC EXTENDED-A", "CYRILLICEXTENDED-A"); /** * Constant for the "Supplemental Punctuation" Unicode character block. * @since 1.7 */ public static final UnicodeBlock SUPPLEMENTAL_PUNCTUATION = new UnicodeBlock("SUPPLEMENTAL_PUNCTUATION", "SUPPLEMENTAL PUNCTUATION", "SUPPLEMENTALPUNCTUATION"); /** * Constant for the "CJK Strokes" Unicode character block. * @since 1.7 */ public static final UnicodeBlock CJK_STROKES = new UnicodeBlock("CJK_STROKES", "CJK STROKES", "CJKSTROKES"); /** * Constant for the "Lisu" Unicode character block. * @since 1.7 */ public static final UnicodeBlock LISU = new UnicodeBlock("LISU"); /** * Constant for the "Vai" Unicode character block. * @since 1.7 */ public static final UnicodeBlock VAI = new UnicodeBlock("VAI"); /** * Constant for the "Cyrillic Extended-B" Unicode character block. * @since 1.7 */ public static final UnicodeBlock CYRILLIC_EXTENDED_B = new UnicodeBlock("CYRILLIC_EXTENDED_B", "CYRILLIC EXTENDED-B", "CYRILLICEXTENDED-B"); /** * Constant for the "Bamum" Unicode character block. * @since 1.7 */ public static final UnicodeBlock BAMUM = new UnicodeBlock("BAMUM"); /** * Constant for the "Modifier Tone Letters" Unicode character block. * @since 1.7 */ public static final UnicodeBlock MODIFIER_TONE_LETTERS = new UnicodeBlock("MODIFIER_TONE_LETTERS", "MODIFIER TONE LETTERS", "MODIFIERTONELETTERS"); /** * Constant for the "Latin Extended-D" Unicode character block. * @since 1.7 */ public static final UnicodeBlock LATIN_EXTENDED_D = new UnicodeBlock("LATIN_EXTENDED_D", "LATIN EXTENDED-D", "LATINEXTENDED-D"); /** * Constant for the "Syloti Nagri" Unicode character block. * @since 1.7 */ public static final UnicodeBlock SYLOTI_NAGRI = new UnicodeBlock("SYLOTI_NAGRI", "SYLOTI NAGRI", "SYLOTINAGRI"); /** * Constant for the "Common Indic Number Forms" Unicode character block. * @since 1.7 */ public static final UnicodeBlock COMMON_INDIC_NUMBER_FORMS = new UnicodeBlock("COMMON_INDIC_NUMBER_FORMS", "COMMON INDIC NUMBER FORMS", "COMMONINDICNUMBERFORMS"); /** * Constant for the "Phags-pa" Unicode character block. * @since 1.7 */ public static final UnicodeBlock PHAGS_PA = new UnicodeBlock("PHAGS_PA", "PHAGS-PA"); /** * Constant for the "Saurashtra" Unicode character block. * @since 1.7 */ public static final UnicodeBlock SAURASHTRA = new UnicodeBlock("SAURASHTRA"); /** * Constant for the "Devanagari Extended" Unicode character block. * @since 1.7 */ public static final UnicodeBlock DEVANAGARI_EXTENDED = new UnicodeBlock("DEVANAGARI_EXTENDED", "DEVANAGARI EXTENDED", "DEVANAGARIEXTENDED"); /** * Constant for the "Kayah Li" Unicode character block. * @since 1.7 */ public static final UnicodeBlock KAYAH_LI = new UnicodeBlock("KAYAH_LI", "KAYAH LI", "KAYAHLI"); /** * Constant for the "Rejang" Unicode character block. * @since 1.7 */ public static final UnicodeBlock REJANG = new UnicodeBlock("REJANG"); /** * Constant for the "Hangul Jamo Extended-A" Unicode character block. * @since 1.7 */ public static final UnicodeBlock HANGUL_JAMO_EXTENDED_A = new UnicodeBlock("HANGUL_JAMO_EXTENDED_A", "HANGUL JAMO EXTENDED-A", "HANGULJAMOEXTENDED-A"); /** * Constant for the "Javanese" Unicode character block. * @since 1.7 */ public static final UnicodeBlock JAVANESE = new UnicodeBlock("JAVANESE"); /** * Constant for the "Cham" Unicode character block. * @since 1.7 */ public static final UnicodeBlock CHAM = new UnicodeBlock("CHAM"); /** * Constant for the "Myanmar Extended-A" Unicode character block. * @since 1.7 */ public static final UnicodeBlock MYANMAR_EXTENDED_A = new UnicodeBlock("MYANMAR_EXTENDED_A", "MYANMAR EXTENDED-A", "MYANMAREXTENDED-A"); /** * Constant for the "Tai Viet" Unicode character block. * @since 1.7 */ public static final UnicodeBlock TAI_VIET = new UnicodeBlock("TAI_VIET", "TAI VIET", "TAIVIET"); /** * Constant for the "Ethiopic Extended-A" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ETHIOPIC_EXTENDED_A = new UnicodeBlock("ETHIOPIC_EXTENDED_A", "ETHIOPIC EXTENDED-A", "ETHIOPICEXTENDED-A"); /** * Constant for the "Meetei Mayek" Unicode character block. * @since 1.7 */ public static final UnicodeBlock MEETEI_MAYEK = new UnicodeBlock("MEETEI_MAYEK", "MEETEI MAYEK", "MEETEIMAYEK"); /** * Constant for the "Hangul Jamo Extended-B" Unicode character block. * @since 1.7 */ public static final UnicodeBlock HANGUL_JAMO_EXTENDED_B = new UnicodeBlock("HANGUL_JAMO_EXTENDED_B", "HANGUL JAMO EXTENDED-B", "HANGULJAMOEXTENDED-B"); /** * Constant for the "Vertical Forms" Unicode character block. * @since 1.7 */ public static final UnicodeBlock VERTICAL_FORMS = new UnicodeBlock("VERTICAL_FORMS", "VERTICAL FORMS", "VERTICALFORMS"); /** * Constant for the "Ancient Greek Numbers" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ANCIENT_GREEK_NUMBERS = new UnicodeBlock("ANCIENT_GREEK_NUMBERS", "ANCIENT GREEK NUMBERS", "ANCIENTGREEKNUMBERS"); /** * Constant for the "Ancient Symbols" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ANCIENT_SYMBOLS = new UnicodeBlock("ANCIENT_SYMBOLS", "ANCIENT SYMBOLS", "ANCIENTSYMBOLS"); /** * Constant for the "Phaistos Disc" Unicode character block. * @since 1.7 */ public static final UnicodeBlock PHAISTOS_DISC = new UnicodeBlock("PHAISTOS_DISC", "PHAISTOS DISC", "PHAISTOSDISC"); /** * Constant for the "Lycian" Unicode character block. * @since 1.7 */ public static final UnicodeBlock LYCIAN = new UnicodeBlock("LYCIAN"); /** * Constant for the "Carian" Unicode character block. * @since 1.7 */ public static final UnicodeBlock CARIAN = new UnicodeBlock("CARIAN"); /** * Constant for the "Old Persian" Unicode character block. * @since 1.7 */ public static final UnicodeBlock OLD_PERSIAN = new UnicodeBlock("OLD_PERSIAN", "OLD PERSIAN", "OLDPERSIAN"); /** * Constant for the "Imperial Aramaic" Unicode character block. * @since 1.7 */ public static final UnicodeBlock IMPERIAL_ARAMAIC = new UnicodeBlock("IMPERIAL_ARAMAIC", "IMPERIAL ARAMAIC", "IMPERIALARAMAIC"); /** * Constant for the "Phoenician" Unicode character block. * @since 1.7 */ public static final UnicodeBlock PHOENICIAN = new UnicodeBlock("PHOENICIAN"); /** * Constant for the "Lydian" Unicode character block. * @since 1.7 */ public static final UnicodeBlock LYDIAN = new UnicodeBlock("LYDIAN"); /** * Constant for the "Kharoshthi" Unicode character block. * @since 1.7 */ public static final UnicodeBlock KHAROSHTHI = new UnicodeBlock("KHAROSHTHI"); /** * Constant for the "Old South Arabian" Unicode character block. * @since 1.7 */ public static final UnicodeBlock OLD_SOUTH_ARABIAN = new UnicodeBlock("OLD_SOUTH_ARABIAN", "OLD SOUTH ARABIAN", "OLDSOUTHARABIAN"); /** * Constant for the "Avestan" Unicode character block. * @since 1.7 */ public static final UnicodeBlock AVESTAN = new UnicodeBlock("AVESTAN"); /** * Constant for the "Inscriptional Parthian" Unicode character block. * @since 1.7 */ public static final UnicodeBlock INSCRIPTIONAL_PARTHIAN = new UnicodeBlock("INSCRIPTIONAL_PARTHIAN", "INSCRIPTIONAL PARTHIAN", "INSCRIPTIONALPARTHIAN"); /** * Constant for the "Inscriptional Pahlavi" Unicode character block. * @since 1.7 */ public static final UnicodeBlock INSCRIPTIONAL_PAHLAVI = new UnicodeBlock("INSCRIPTIONAL_PAHLAVI", "INSCRIPTIONAL PAHLAVI", "INSCRIPTIONALPAHLAVI"); /** * Constant for the "Old Turkic" Unicode character block. * @since 1.7 */ public static final UnicodeBlock OLD_TURKIC = new UnicodeBlock("OLD_TURKIC", "OLD TURKIC", "OLDTURKIC"); /** * Constant for the "Rumi Numeral Symbols" Unicode character block. * @since 1.7 */ public static final UnicodeBlock RUMI_NUMERAL_SYMBOLS = new UnicodeBlock("RUMI_NUMERAL_SYMBOLS", "RUMI NUMERAL SYMBOLS", "RUMINUMERALSYMBOLS"); /** * Constant for the "Brahmi" Unicode character block. * @since 1.7 */ public static final UnicodeBlock BRAHMI = new UnicodeBlock("BRAHMI"); /** * Constant for the "Kaithi" Unicode character block. * @since 1.7 */ public static final UnicodeBlock KAITHI = new UnicodeBlock("KAITHI"); /** * Constant for the "Cuneiform" Unicode character block. * @since 1.7 */ public static final UnicodeBlock CUNEIFORM = new UnicodeBlock("CUNEIFORM"); /** * Constant for the "Cuneiform Numbers and Punctuation" Unicode * character block. * @since 1.7 */ public static final UnicodeBlock CUNEIFORM_NUMBERS_AND_PUNCTUATION = new UnicodeBlock("CUNEIFORM_NUMBERS_AND_PUNCTUATION", "CUNEIFORM NUMBERS AND PUNCTUATION", "CUNEIFORMNUMBERSANDPUNCTUATION"); /** * Constant for the "Egyptian Hieroglyphs" Unicode character block. * @since 1.7 */ public static final UnicodeBlock EGYPTIAN_HIEROGLYPHS = new UnicodeBlock("EGYPTIAN_HIEROGLYPHS", "EGYPTIAN HIEROGLYPHS", "EGYPTIANHIEROGLYPHS"); /** * Constant for the "Bamum Supplement" Unicode character block. * @since 1.7 */ public static final UnicodeBlock BAMUM_SUPPLEMENT = new UnicodeBlock("BAMUM_SUPPLEMENT", "BAMUM SUPPLEMENT", "BAMUMSUPPLEMENT"); /** * Constant for the "Kana Supplement" Unicode character block. * @since 1.7 */ public static final UnicodeBlock KANA_SUPPLEMENT = new UnicodeBlock("KANA_SUPPLEMENT", "KANA SUPPLEMENT", "KANASUPPLEMENT"); /** * Constant for the "Ancient Greek Musical Notation" Unicode character * block. * @since 1.7 */ public static final UnicodeBlock ANCIENT_GREEK_MUSICAL_NOTATION = new UnicodeBlock("ANCIENT_GREEK_MUSICAL_NOTATION", "ANCIENT GREEK MUSICAL NOTATION", "ANCIENTGREEKMUSICALNOTATION"); /** * Constant for the "Counting Rod Numerals" Unicode character block. * @since 1.7 */ public static final UnicodeBlock COUNTING_ROD_NUMERALS = new UnicodeBlock("COUNTING_ROD_NUMERALS", "COUNTING ROD NUMERALS", "COUNTINGRODNUMERALS"); /** * Constant for the "Mahjong Tiles" Unicode character block. * @since 1.7 */ public static final UnicodeBlock MAHJONG_TILES = new UnicodeBlock("MAHJONG_TILES", "MAHJONG TILES", "MAHJONGTILES"); /** * Constant for the "Domino Tiles" Unicode character block. * @since 1.7 */ public static final UnicodeBlock DOMINO_TILES = new UnicodeBlock("DOMINO_TILES", "DOMINO TILES", "DOMINOTILES"); /** * Constant for the "Playing Cards" Unicode character block. * @since 1.7 */ public static final UnicodeBlock PLAYING_CARDS = new UnicodeBlock("PLAYING_CARDS", "PLAYING CARDS", "PLAYINGCARDS"); /** * Constant for the "Enclosed Alphanumeric Supplement" Unicode character * block. * @since 1.7 */ public static final UnicodeBlock ENCLOSED_ALPHANUMERIC_SUPPLEMENT = new UnicodeBlock("ENCLOSED_ALPHANUMERIC_SUPPLEMENT", "ENCLOSED ALPHANUMERIC SUPPLEMENT", "ENCLOSEDALPHANUMERICSUPPLEMENT"); /** * Constant for the "Enclosed Ideographic Supplement" Unicode character * block. * @since 1.7 */ public static final UnicodeBlock ENCLOSED_IDEOGRAPHIC_SUPPLEMENT = new UnicodeBlock("ENCLOSED_IDEOGRAPHIC_SUPPLEMENT", "ENCLOSED IDEOGRAPHIC SUPPLEMENT", "ENCLOSEDIDEOGRAPHICSUPPLEMENT"); /** * Constant for the "Miscellaneous Symbols And Pictographs" Unicode * character block. * @since 1.7 */ public static final UnicodeBlock MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS = new UnicodeBlock("MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS", "MISCELLANEOUS SYMBOLS AND PICTOGRAPHS", "MISCELLANEOUSSYMBOLSANDPICTOGRAPHS"); /** * Constant for the "Emoticons" Unicode character block. * @since 1.7 */ public static final UnicodeBlock EMOTICONS = new UnicodeBlock("EMOTICONS"); /** * Constant for the "Transport And Map Symbols" Unicode character block. * @since 1.7 */ public static final UnicodeBlock TRANSPORT_AND_MAP_SYMBOLS = new UnicodeBlock("TRANSPORT_AND_MAP_SYMBOLS", "TRANSPORT AND MAP SYMBOLS", "TRANSPORTANDMAPSYMBOLS"); /** * Constant for the "Alchemical Symbols" Unicode character block. * @since 1.7 */ public static final UnicodeBlock ALCHEMICAL_SYMBOLS = new UnicodeBlock("ALCHEMICAL_SYMBOLS", "ALCHEMICAL SYMBOLS", "ALCHEMICALSYMBOLS"); /** * Constant for the "CJK Unified Ideographs Extension C" Unicode * character block. * @since 1.7 */ public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C = new UnicodeBlock("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C", "CJK UNIFIED IDEOGRAPHS EXTENSION C", "CJKUNIFIEDIDEOGRAPHSEXTENSIONC"); /** * Constant for the "CJK Unified Ideographs Extension D" Unicode * character block. * @since 1.7 */ public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D = new UnicodeBlock("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D", "CJK UNIFIED IDEOGRAPHS EXTENSION D", "CJKUNIFIEDIDEOGRAPHSEXTENSIOND"); /** * Constant for the "Arabic Extended-A" Unicode character block. * @since 1.8 */ public static final UnicodeBlock ARABIC_EXTENDED_A = new UnicodeBlock("ARABIC_EXTENDED_A", "ARABIC EXTENDED-A", "ARABICEXTENDED-A"); /** * Constant for the "Sundanese Supplement" Unicode character block. * @since 1.8 */ public static final UnicodeBlock SUNDANESE_SUPPLEMENT = new UnicodeBlock("SUNDANESE_SUPPLEMENT", "SUNDANESE SUPPLEMENT", "SUNDANESESUPPLEMENT"); /** * Constant for the "Meetei Mayek Extensions" Unicode character block. * @since 1.8 */ public static final UnicodeBlock MEETEI_MAYEK_EXTENSIONS = new UnicodeBlock("MEETEI_MAYEK_EXTENSIONS", "MEETEI MAYEK EXTENSIONS", "MEETEIMAYEKEXTENSIONS"); /** * Constant for the "Meroitic Hieroglyphs" Unicode character block. * @since 1.8 */ public static final UnicodeBlock MEROITIC_HIEROGLYPHS = new UnicodeBlock("MEROITIC_HIEROGLYPHS", "MEROITIC HIEROGLYPHS", "MEROITICHIEROGLYPHS"); /** * Constant for the "Meroitic Cursive" Unicode character block. * @since 1.8 */ public static final UnicodeBlock MEROITIC_CURSIVE = new UnicodeBlock("MEROITIC_CURSIVE", "MEROITIC CURSIVE", "MEROITICCURSIVE"); /** * Constant for the "Sora Sompeng" Unicode character block. * @since 1.8 */ public static final UnicodeBlock SORA_SOMPENG = new UnicodeBlock("SORA_SOMPENG", "SORA SOMPENG", "SORASOMPENG"); /** * Constant for the "Chakma" Unicode character block. * @since 1.8 */ public static final UnicodeBlock CHAKMA = new UnicodeBlock("CHAKMA"); /** * Constant for the "Sharada" Unicode character block. * @since 1.8 */ public static final UnicodeBlock SHARADA = new UnicodeBlock("SHARADA"); /** * Constant for the "Takri" Unicode character block. * @since 1.8 */ public static final UnicodeBlock TAKRI = new UnicodeBlock("TAKRI"); /** * Constant for the "Miao" Unicode character block. * @since 1.8 */ public static final UnicodeBlock MIAO = new UnicodeBlock("MIAO"); /** * Constant for the "Arabic Mathematical Alphabetic Symbols" Unicode * character block. * @since 1.8 */ public static final UnicodeBlock ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS = new UnicodeBlock("ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS", "ARABIC MATHEMATICAL ALPHABETIC SYMBOLS", "ARABICMATHEMATICALALPHABETICSYMBOLS"); /** * Constant for the "CJK Unified Ideographs Extension E" Unicode * character block. * @apiNote This field is defined in Java SE 8 Maintenance Release 5. * @since 1.8 */ public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E = new UnicodeBlock("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E", "CJK UNIFIED IDEOGRAPHS EXTENSION E", "CJKUNIFIEDIDEOGRAPHSEXTENSIONE"); private static final int blockStarts[] = { 0x0000, // 0000..007F; Basic Latin 0x0080, // 0080..00FF; Latin-1 Supplement 0x0100, // 0100..017F; Latin Extended-A 0x0180, // 0180..024F; Latin Extended-B 0x0250, // 0250..02AF; IPA Extensions 0x02B0, // 02B0..02FF; Spacing Modifier Letters 0x0300, // 0300..036F; Combining Diacritical Marks 0x0370, // 0370..03FF; Greek and Coptic 0x0400, // 0400..04FF; Cyrillic 0x0500, // 0500..052F; Cyrillic Supplement 0x0530, // 0530..058F; Armenian 0x0590, // 0590..05FF; Hebrew 0x0600, // 0600..06FF; Arabic 0x0700, // 0700..074F; Syriac 0x0750, // 0750..077F; Arabic Supplement 0x0780, // 0780..07BF; Thaana 0x07C0, // 07C0..07FF; NKo 0x0800, // 0800..083F; Samaritan 0x0840, // 0840..085F; Mandaic 0x0860, // unassigned 0x08A0, // 08A0..08FF; Arabic Extended-A 0x0900, // 0900..097F; Devanagari 0x0980, // 0980..09FF; Bengali 0x0A00, // 0A00..0A7F; Gurmukhi 0x0A80, // 0A80..0AFF; Gujarati 0x0B00, // 0B00..0B7F; Oriya 0x0B80, // 0B80..0BFF; Tamil 0x0C00, // 0C00..0C7F; Telugu 0x0C80, // 0C80..0CFF; Kannada 0x0D00, // 0D00..0D7F; Malayalam 0x0D80, // 0D80..0DFF; Sinhala 0x0E00, // 0E00..0E7F; Thai 0x0E80, // 0E80..0EFF; Lao 0x0F00, // 0F00..0FFF; Tibetan 0x1000, // 1000..109F; Myanmar 0x10A0, // 10A0..10FF; Georgian 0x1100, // 1100..11FF; Hangul Jamo 0x1200, // 1200..137F; Ethiopic 0x1380, // 1380..139F; Ethiopic Supplement 0x13A0, // 13A0..13FF; Cherokee 0x1400, // 1400..167F; Unified Canadian Aboriginal Syllabics 0x1680, // 1680..169F; Ogham 0x16A0, // 16A0..16FF; Runic 0x1700, // 1700..171F; Tagalog 0x1720, // 1720..173F; Hanunoo 0x1740, // 1740..175F; Buhid 0x1760, // 1760..177F; Tagbanwa 0x1780, // 1780..17FF; Khmer 0x1800, // 1800..18AF; Mongolian 0x18B0, // 18B0..18FF; Unified Canadian Aboriginal Syllabics Extended 0x1900, // 1900..194F; Limbu 0x1950, // 1950..197F; Tai Le 0x1980, // 1980..19DF; New Tai Lue 0x19E0, // 19E0..19FF; Khmer Symbols 0x1A00, // 1A00..1A1F; Buginese 0x1A20, // 1A20..1AAF; Tai Tham 0x1AB0, // unassigned 0x1B00, // 1B00..1B7F; Balinese 0x1B80, // 1B80..1BBF; Sundanese 0x1BC0, // 1BC0..1BFF; Batak 0x1C00, // 1C00..1C4F; Lepcha 0x1C50, // 1C50..1C7F; Ol Chiki 0x1C80, // unassigned 0x1CC0, // 1CC0..1CCF; Sundanese Supplement 0x1CD0, // 1CD0..1CFF; Vedic Extensions 0x1D00, // 1D00..1D7F; Phonetic Extensions 0x1D80, // 1D80..1DBF; Phonetic Extensions Supplement 0x1DC0, // 1DC0..1DFF; Combining Diacritical Marks Supplement 0x1E00, // 1E00..1EFF; Latin Extended Additional 0x1F00, // 1F00..1FFF; Greek Extended 0x2000, // 2000..206F; General Punctuation 0x2070, // 2070..209F; Superscripts and Subscripts 0x20A0, // 20A0..20CF; Currency Symbols 0x20D0, // 20D0..20FF; Combining Diacritical Marks for Symbols 0x2100, // 2100..214F; Letterlike Symbols 0x2150, // 2150..218F; Number Forms 0x2190, // 2190..21FF; Arrows 0x2200, // 2200..22FF; Mathematical Operators 0x2300, // 2300..23FF; Miscellaneous Technical 0x2400, // 2400..243F; Control Pictures 0x2440, // 2440..245F; Optical Character Recognition 0x2460, // 2460..24FF; Enclosed Alphanumerics 0x2500, // 2500..257F; Box Drawing 0x2580, // 2580..259F; Block Elements 0x25A0, // 25A0..25FF; Geometric Shapes 0x2600, // 2600..26FF; Miscellaneous Symbols 0x2700, // 2700..27BF; Dingbats 0x27C0, // 27C0..27EF; Miscellaneous Mathematical Symbols-A 0x27F0, // 27F0..27FF; Supplemental Arrows-A 0x2800, // 2800..28FF; Braille Patterns 0x2900, // 2900..297F; Supplemental Arrows-B 0x2980, // 2980..29FF; Miscellaneous Mathematical Symbols-B 0x2A00, // 2A00..2AFF; Supplemental Mathematical Operators 0x2B00, // 2B00..2BFF; Miscellaneous Symbols and Arrows 0x2C00, // 2C00..2C5F; Glagolitic 0x2C60, // 2C60..2C7F; Latin Extended-C 0x2C80, // 2C80..2CFF; Coptic 0x2D00, // 2D00..2D2F; Georgian Supplement 0x2D30, // 2D30..2D7F; Tifinagh 0x2D80, // 2D80..2DDF; Ethiopic Extended 0x2DE0, // 2DE0..2DFF; Cyrillic Extended-A 0x2E00, // 2E00..2E7F; Supplemental Punctuation 0x2E80, // 2E80..2EFF; CJK Radicals Supplement 0x2F00, // 2F00..2FDF; Kangxi Radicals 0x2FE0, // unassigned 0x2FF0, // 2FF0..2FFF; Ideographic Description Characters 0x3000, // 3000..303F; CJK Symbols and Punctuation 0x3040, // 3040..309F; Hiragana 0x30A0, // 30A0..30FF; Katakana 0x3100, // 3100..312F; Bopomofo 0x3130, // 3130..318F; Hangul Compatibility Jamo 0x3190, // 3190..319F; Kanbun 0x31A0, // 31A0..31BF; Bopomofo Extended 0x31C0, // 31C0..31EF; CJK Strokes 0x31F0, // 31F0..31FF; Katakana Phonetic Extensions 0x3200, // 3200..32FF; Enclosed CJK Letters and Months 0x3300, // 3300..33FF; CJK Compatibility 0x3400, // 3400..4DBF; CJK Unified Ideographs Extension A 0x4DC0, // 4DC0..4DFF; Yijing Hexagram Symbols 0x4E00, // 4E00..9FFF; CJK Unified Ideographs 0xA000, // A000..A48F; Yi Syllables 0xA490, // A490..A4CF; Yi Radicals 0xA4D0, // A4D0..A4FF; Lisu 0xA500, // A500..A63F; Vai 0xA640, // A640..A69F; Cyrillic Extended-B 0xA6A0, // A6A0..A6FF; Bamum 0xA700, // A700..A71F; Modifier Tone Letters 0xA720, // A720..A7FF; Latin Extended-D 0xA800, // A800..A82F; Syloti Nagri 0xA830, // A830..A83F; Common Indic Number Forms 0xA840, // A840..A87F; Phags-pa 0xA880, // A880..A8DF; Saurashtra 0xA8E0, // A8E0..A8FF; Devanagari Extended 0xA900, // A900..A92F; Kayah Li 0xA930, // A930..A95F; Rejang 0xA960, // A960..A97F; Hangul Jamo Extended-A 0xA980, // A980..A9DF; Javanese 0xA9E0, // unassigned 0xAA00, // AA00..AA5F; Cham 0xAA60, // AA60..AA7F; Myanmar Extended-A 0xAA80, // AA80..AADF; Tai Viet 0xAAE0, // AAE0..AAFF; Meetei Mayek Extensions 0xAB00, // AB00..AB2F; Ethiopic Extended-A 0xAB30, // unassigned 0xABC0, // ABC0..ABFF; Meetei Mayek 0xAC00, // AC00..D7AF; Hangul Syllables 0xD7B0, // D7B0..D7FF; Hangul Jamo Extended-B 0xD800, // D800..DB7F; High Surrogates 0xDB80, // DB80..DBFF; High Private Use Surrogates 0xDC00, // DC00..DFFF; Low Surrogates 0xE000, // E000..F8FF; Private Use Area 0xF900, // F900..FAFF; CJK Compatibility Ideographs 0xFB00, // FB00..FB4F; Alphabetic Presentation Forms 0xFB50, // FB50..FDFF; Arabic Presentation Forms-A 0xFE00, // FE00..FE0F; Variation Selectors 0xFE10, // FE10..FE1F; Vertical Forms 0xFE20, // FE20..FE2F; Combining Half Marks 0xFE30, // FE30..FE4F; CJK Compatibility Forms 0xFE50, // FE50..FE6F; Small Form Variants 0xFE70, // FE70..FEFF; Arabic Presentation Forms-B 0xFF00, // FF00..FFEF; Halfwidth and Fullwidth Forms 0xFFF0, // FFF0..FFFF; Specials 0x10000, // 10000..1007F; Linear B Syllabary 0x10080, // 10080..100FF; Linear B Ideograms 0x10100, // 10100..1013F; Aegean Numbers 0x10140, // 10140..1018F; Ancient Greek Numbers 0x10190, // 10190..101CF; Ancient Symbols 0x101D0, // 101D0..101FF; Phaistos Disc 0x10200, // unassigned 0x10280, // 10280..1029F; Lycian 0x102A0, // 102A0..102DF; Carian 0x102E0, // unassigned 0x10300, // 10300..1032F; Old Italic 0x10330, // 10330..1034F; Gothic 0x10350, // unassigned 0x10380, // 10380..1039F; Ugaritic 0x103A0, // 103A0..103DF; Old Persian 0x103E0, // unassigned 0x10400, // 10400..1044F; Deseret 0x10450, // 10450..1047F; Shavian 0x10480, // 10480..104AF; Osmanya 0x104B0, // unassigned 0x10800, // 10800..1083F; Cypriot Syllabary 0x10840, // 10840..1085F; Imperial Aramaic 0x10860, // unassigned 0x10900, // 10900..1091F; Phoenician 0x10920, // 10920..1093F; Lydian 0x10940, // unassigned 0x10980, // 10980..1099F; Meroitic Hieroglyphs 0x109A0, // 109A0..109FF; Meroitic Cursive 0x10A00, // 10A00..10A5F; Kharoshthi 0x10A60, // 10A60..10A7F; Old South Arabian 0x10A80, // unassigned 0x10B00, // 10B00..10B3F; Avestan 0x10B40, // 10B40..10B5F; Inscriptional Parthian 0x10B60, // 10B60..10B7F; Inscriptional Pahlavi 0x10B80, // unassigned 0x10C00, // 10C00..10C4F; Old Turkic 0x10C50, // unassigned 0x10E60, // 10E60..10E7F; Rumi Numeral Symbols 0x10E80, // unassigned 0x11000, // 11000..1107F; Brahmi 0x11080, // 11080..110CF; Kaithi 0x110D0, // 110D0..110FF; Sora Sompeng 0x11100, // 11100..1114F; Chakma 0x11150, // unassigned 0x11180, // 11180..111DF; Sharada 0x111E0, // unassigned 0x11680, // 11680..116CF; Takri 0x116D0, // unassigned 0x12000, // 12000..123FF; Cuneiform 0x12400, // 12400..1247F; Cuneiform Numbers and Punctuation 0x12480, // unassigned 0x13000, // 13000..1342F; Egyptian Hieroglyphs 0x13430, // unassigned 0x16800, // 16800..16A3F; Bamum Supplement 0x16A40, // unassigned 0x16F00, // 16F00..16F9F; Miao 0x16FA0, // unassigned 0x1B000, // 1B000..1B0FF; Kana Supplement 0x1B100, // unassigned 0x1D000, // 1D000..1D0FF; Byzantine Musical Symbols 0x1D100, // 1D100..1D1FF; Musical Symbols 0x1D200, // 1D200..1D24F; Ancient Greek Musical Notation 0x1D250, // unassigned 0x1D300, // 1D300..1D35F; Tai Xuan Jing Symbols 0x1D360, // 1D360..1D37F; Counting Rod Numerals 0x1D380, // unassigned 0x1D400, // 1D400..1D7FF; Mathematical Alphanumeric Symbols 0x1D800, // unassigned 0x1EE00, // 1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols 0x1EF00, // unassigned 0x1F000, // 1F000..1F02F; Mahjong Tiles 0x1F030, // 1F030..1F09F; Domino Tiles 0x1F0A0, // 1F0A0..1F0FF; Playing Cards 0x1F100, // 1F100..1F1FF; Enclosed Alphanumeric Supplement 0x1F200, // 1F200..1F2FF; Enclosed Ideographic Supplement 0x1F300, // 1F300..1F5FF; Miscellaneous Symbols And Pictographs 0x1F600, // 1F600..1F64F; Emoticons 0x1F650, // unassigned 0x1F680, // 1F680..1F6FF; Transport And Map Symbols 0x1F700, // 1F700..1F77F; Alchemical Symbols 0x1F780, // unassigned 0x20000, // 20000..2A6DF; CJK Unified Ideographs Extension B 0x2A6E0, // unassigned 0x2A700, // 2A700..2B73F; CJK Unified Ideographs Extension C 0x2B740, // 2B740..2B81F; CJK Unified Ideographs Extension D 0x2B820, // 2B820..2CEAF; CJK Unified Ideographs Extension E 0x2CEB0, // unassigned 0x2F800, // 2F800..2FA1F; CJK Compatibility Ideographs Supplement 0x2FA20, // unassigned 0xE0000, // E0000..E007F; Tags 0xE0080, // unassigned 0xE0100, // E0100..E01EF; Variation Selectors Supplement 0xE01F0, // unassigned 0xF0000, // F0000..FFFFF; Supplementary Private Use Area-A 0x100000 // 100000..10FFFF; Supplementary Private Use Area-B }; private static final UnicodeBlock[] blocks = { BASIC_LATIN, LATIN_1_SUPPLEMENT, LATIN_EXTENDED_A, LATIN_EXTENDED_B, IPA_EXTENSIONS, SPACING_MODIFIER_LETTERS, COMBINING_DIACRITICAL_MARKS, GREEK, CYRILLIC, CYRILLIC_SUPPLEMENTARY, ARMENIAN, HEBREW, ARABIC, SYRIAC, ARABIC_SUPPLEMENT, THAANA, NKO, SAMARITAN, MANDAIC, null, ARABIC_EXTENDED_A, DEVANAGARI, BENGALI, GURMUKHI, GUJARATI, ORIYA, TAMIL, TELUGU, KANNADA, MALAYALAM, SINHALA, THAI, LAO, TIBETAN, MYANMAR, GEORGIAN, HANGUL_JAMO, ETHIOPIC, ETHIOPIC_SUPPLEMENT, CHEROKEE, UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, OGHAM, RUNIC, TAGALOG, HANUNOO, BUHID, TAGBANWA, KHMER, MONGOLIAN, UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED, LIMBU, TAI_LE, NEW_TAI_LUE, KHMER_SYMBOLS, BUGINESE, TAI_THAM, null, BALINESE, SUNDANESE, BATAK, LEPCHA, OL_CHIKI, null, SUNDANESE_SUPPLEMENT, VEDIC_EXTENSIONS, PHONETIC_EXTENSIONS, PHONETIC_EXTENSIONS_SUPPLEMENT, COMBINING_DIACRITICAL_MARKS_SUPPLEMENT, LATIN_EXTENDED_ADDITIONAL, GREEK_EXTENDED, GENERAL_PUNCTUATION, SUPERSCRIPTS_AND_SUBSCRIPTS, CURRENCY_SYMBOLS, COMBINING_MARKS_FOR_SYMBOLS, LETTERLIKE_SYMBOLS, NUMBER_FORMS, ARROWS, MATHEMATICAL_OPERATORS, MISCELLANEOUS_TECHNICAL, CONTROL_PICTURES, OPTICAL_CHARACTER_RECOGNITION, ENCLOSED_ALPHANUMERICS, BOX_DRAWING, BLOCK_ELEMENTS, GEOMETRIC_SHAPES, MISCELLANEOUS_SYMBOLS, DINGBATS, MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, SUPPLEMENTAL_ARROWS_A, BRAILLE_PATTERNS, SUPPLEMENTAL_ARROWS_B, MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, SUPPLEMENTAL_MATHEMATICAL_OPERATORS, MISCELLANEOUS_SYMBOLS_AND_ARROWS, GLAGOLITIC, LATIN_EXTENDED_C, COPTIC, GEORGIAN_SUPPLEMENT, TIFINAGH, ETHIOPIC_EXTENDED, CYRILLIC_EXTENDED_A, SUPPLEMENTAL_PUNCTUATION, CJK_RADICALS_SUPPLEMENT, KANGXI_RADICALS, null, IDEOGRAPHIC_DESCRIPTION_CHARACTERS, CJK_SYMBOLS_AND_PUNCTUATION, HIRAGANA, KATAKANA, BOPOMOFO, HANGUL_COMPATIBILITY_JAMO, KANBUN, BOPOMOFO_EXTENDED, CJK_STROKES, KATAKANA_PHONETIC_EXTENSIONS, ENCLOSED_CJK_LETTERS_AND_MONTHS, CJK_COMPATIBILITY, CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, YIJING_HEXAGRAM_SYMBOLS, CJK_UNIFIED_IDEOGRAPHS, YI_SYLLABLES, YI_RADICALS, LISU, VAI, CYRILLIC_EXTENDED_B, BAMUM, MODIFIER_TONE_LETTERS, LATIN_EXTENDED_D, SYLOTI_NAGRI, COMMON_INDIC_NUMBER_FORMS, PHAGS_PA, SAURASHTRA, DEVANAGARI_EXTENDED, KAYAH_LI, REJANG, HANGUL_JAMO_EXTENDED_A, JAVANESE, null, CHAM, MYANMAR_EXTENDED_A, TAI_VIET, MEETEI_MAYEK_EXTENSIONS, ETHIOPIC_EXTENDED_A, null, MEETEI_MAYEK, HANGUL_SYLLABLES, HANGUL_JAMO_EXTENDED_B, HIGH_SURROGATES, HIGH_PRIVATE_USE_SURROGATES, LOW_SURROGATES, PRIVATE_USE_AREA, CJK_COMPATIBILITY_IDEOGRAPHS, ALPHABETIC_PRESENTATION_FORMS, ARABIC_PRESENTATION_FORMS_A, VARIATION_SELECTORS, VERTICAL_FORMS, COMBINING_HALF_MARKS, CJK_COMPATIBILITY_FORMS, SMALL_FORM_VARIANTS, ARABIC_PRESENTATION_FORMS_B, HALFWIDTH_AND_FULLWIDTH_FORMS, SPECIALS, LINEAR_B_SYLLABARY, LINEAR_B_IDEOGRAMS, AEGEAN_NUMBERS, ANCIENT_GREEK_NUMBERS, ANCIENT_SYMBOLS, PHAISTOS_DISC, null, LYCIAN, CARIAN, null, OLD_ITALIC, GOTHIC, null, UGARITIC, OLD_PERSIAN, null, DESERET, SHAVIAN, OSMANYA, null, CYPRIOT_SYLLABARY, IMPERIAL_ARAMAIC, null, PHOENICIAN, LYDIAN, null, MEROITIC_HIEROGLYPHS, MEROITIC_CURSIVE, KHAROSHTHI, OLD_SOUTH_ARABIAN, null, AVESTAN, INSCRIPTIONAL_PARTHIAN, INSCRIPTIONAL_PAHLAVI, null, OLD_TURKIC, null, RUMI_NUMERAL_SYMBOLS, null, BRAHMI, KAITHI, SORA_SOMPENG, CHAKMA, null, SHARADA, null, TAKRI, null, CUNEIFORM, CUNEIFORM_NUMBERS_AND_PUNCTUATION, null, EGYPTIAN_HIEROGLYPHS, null, BAMUM_SUPPLEMENT, null, MIAO, null, KANA_SUPPLEMENT, null, BYZANTINE_MUSICAL_SYMBOLS, MUSICAL_SYMBOLS, ANCIENT_GREEK_MUSICAL_NOTATION, null, TAI_XUAN_JING_SYMBOLS, COUNTING_ROD_NUMERALS, null, MATHEMATICAL_ALPHANUMERIC_SYMBOLS, null, ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS, null, MAHJONG_TILES, DOMINO_TILES, PLAYING_CARDS, ENCLOSED_ALPHANUMERIC_SUPPLEMENT, ENCLOSED_IDEOGRAPHIC_SUPPLEMENT, MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS, EMOTICONS, null, TRANSPORT_AND_MAP_SYMBOLS, ALCHEMICAL_SYMBOLS, null, CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, null, CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C, CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D, CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E, null, CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, null, TAGS, null, VARIATION_SELECTORS_SUPPLEMENT, null, SUPPLEMENTARY_PRIVATE_USE_AREA_A, SUPPLEMENTARY_PRIVATE_USE_AREA_B }; /** * Returns the object representing the Unicode block containing the * given character, or {@code null} if the character is not a * member of a defined block. * * <p><b>Note:</b> This method cannot handle * <a href="Character.html#supplementary"> supplementary * characters</a>. To support all Unicode characters, including * supplementary characters, use the {@link #of(int)} method. * * @param c The character in question * @return The {@code UnicodeBlock} instance representing the * Unicode block of which this character is a member, or * {@code null} if the character is not a member of any * Unicode block */ public static UnicodeBlock of(char c) { return of((int)c); } /** * Returns the object representing the Unicode block * containing the given character (Unicode code point), or * {@code null} if the character is not a member of a * defined block. * * @param codePoint the character (Unicode code point) in question. * @return The {@code UnicodeBlock} instance representing the * Unicode block of which this character is a member, or * {@code null} if the character is not a member of any * Unicode block * @exception IllegalArgumentException if the specified * {@code codePoint} is an invalid Unicode code point. * @see Character#isValidCodePoint(int) * @since 1.5 */ public static UnicodeBlock of(int codePoint) { if (!isValidCodePoint(codePoint)) { throw new IllegalArgumentException(); } int top, bottom, current; bottom = 0; top = blockStarts.length; current = top/2; // invariant: top > current >= bottom && codePoint >= unicodeBlockStarts[bottom] while (top - bottom > 1) { if (codePoint >= blockStarts[current]) { bottom = current; } else { top = current; } current = (top + bottom) / 2; } return blocks[current]; } /** * Returns the UnicodeBlock with the given name. Block * names are determined by The Unicode Standard. The file * Blocks-&lt;version&gt;.txt defines blocks for a particular * version of the standard. The {@link Character} class specifies * the version of the standard that it supports. * <p> * This method accepts block names in the following forms: * <ol> * <li> Canonical block names as defined by the Unicode Standard. * For example, the standard defines a "Basic Latin" block. Therefore, this * method accepts "Basic Latin" as a valid block name. The documentation of * each UnicodeBlock provides the canonical name. * <li>Canonical block names with all spaces removed. For example, "BasicLatin" * is a valid block name for the "Basic Latin" block. * <li>The text representation of each constant UnicodeBlock identifier. * For example, this method will return the {@link #BASIC_LATIN} block if * provided with the "BASIC_LATIN" name. This form replaces all spaces and * hyphens in the canonical name with underscores. * </ol> * Finally, character case is ignored for all of the valid block name forms. * For example, "BASIC_LATIN" and "basic_latin" are both valid block names. * The en_US locale's case mapping rules are used to provide case-insensitive * string comparisons for block name validation. * <p> * If the Unicode Standard changes block names, both the previous and * current names will be accepted. * * @param blockName A {@code UnicodeBlock} name. * @return The {@code UnicodeBlock} instance identified * by {@code blockName} * @throws IllegalArgumentException if {@code blockName} is an * invalid name * @throws NullPointerException if {@code blockName} is null * @since 1.5 */ public static final UnicodeBlock forName(String blockName) { UnicodeBlock block = map.get(blockName.toUpperCase(Locale.US)); if (block == null) { throw new IllegalArgumentException(); } return block; } } /** * A family of character subsets representing the character scripts * defined in the <a href="http://www.unicode.org/reports/tr24/"> * <i>Unicode Standard Annex #24: Script Names</i></a>. Every Unicode * character is assigned to a single Unicode script, either a specific * script, such as {@link Character.UnicodeScript#LATIN Latin}, or * one of the following three special values, * {@link Character.UnicodeScript#INHERITED Inherited}, * {@link Character.UnicodeScript#COMMON Common} or * {@link Character.UnicodeScript#UNKNOWN Unknown}. * * @since 1.7 */ public static enum UnicodeScript { /** * Unicode script "Common". */ COMMON, /** * Unicode script "Latin". */ LATIN, /** * Unicode script "Greek". */ GREEK, /** * Unicode script "Cyrillic". */ CYRILLIC, /** * Unicode script "Armenian". */ ARMENIAN, /** * Unicode script "Hebrew". */ HEBREW, /** * Unicode script "Arabic". */ ARABIC, /** * Unicode script "Syriac". */ SYRIAC, /** * Unicode script "Thaana". */ THAANA, /** * Unicode script "Devanagari". */ DEVANAGARI, /** * Unicode script "Bengali". */ BENGALI, /** * Unicode script "Gurmukhi". */ GURMUKHI, /** * Unicode script "Gujarati". */ GUJARATI, /** * Unicode script "Oriya". */ ORIYA, /** * Unicode script "Tamil". */ TAMIL, /** * Unicode script "Telugu". */ TELUGU, /** * Unicode script "Kannada". */ KANNADA, /** * Unicode script "Malayalam". */ MALAYALAM, /** * Unicode script "Sinhala". */ SINHALA, /** * Unicode script "Thai". */ THAI, /** * Unicode script "Lao". */ LAO, /** * Unicode script "Tibetan". */ TIBETAN, /** * Unicode script "Myanmar". */ MYANMAR, /** * Unicode script "Georgian". */ GEORGIAN, /** * Unicode script "Hangul". */ HANGUL, /** * Unicode script "Ethiopic". */ ETHIOPIC, /** * Unicode script "Cherokee". */ CHEROKEE, /** * Unicode script "Canadian_Aboriginal". */ CANADIAN_ABORIGINAL, /** * Unicode script "Ogham". */ OGHAM, /** * Unicode script "Runic". */ RUNIC, /** * Unicode script "Khmer". */ KHMER, /** * Unicode script "Mongolian". */ MONGOLIAN, /** * Unicode script "Hiragana". */ HIRAGANA, /** * Unicode script "Katakana". */ KATAKANA, /** * Unicode script "Bopomofo". */ BOPOMOFO, /** * Unicode script "Han". */ HAN, /** * Unicode script "Yi". */ YI, /** * Unicode script "Old_Italic". */ OLD_ITALIC, /** * Unicode script "Gothic". */ GOTHIC, /** * Unicode script "Deseret". */ DESERET, /** * Unicode script "Inherited". */ INHERITED, /** * Unicode script "Tagalog". */ TAGALOG, /** * Unicode script "Hanunoo". */ HANUNOO, /** * Unicode script "Buhid". */ BUHID, /** * Unicode script "Tagbanwa". */ TAGBANWA, /** * Unicode script "Limbu". */ LIMBU, /** * Unicode script "Tai_Le". */ TAI_LE, /** * Unicode script "Linear_B". */ LINEAR_B, /** * Unicode script "Ugaritic". */ UGARITIC, /** * Unicode script "Shavian". */ SHAVIAN, /** * Unicode script "Osmanya". */ OSMANYA, /** * Unicode script "Cypriot". */ CYPRIOT, /** * Unicode script "Braille". */ BRAILLE, /** * Unicode script "Buginese". */ BUGINESE, /** * Unicode script "Coptic". */ COPTIC, /** * Unicode script "New_Tai_Lue". */ NEW_TAI_LUE, /** * Unicode script "Glagolitic". */ GLAGOLITIC, /** * Unicode script "Tifinagh". */ TIFINAGH, /** * Unicode script "Syloti_Nagri". */ SYLOTI_NAGRI, /** * Unicode script "Old_Persian". */ OLD_PERSIAN, /** * Unicode script "Kharoshthi". */ KHAROSHTHI, /** * Unicode script "Balinese". */ BALINESE, /** * Unicode script "Cuneiform". */ CUNEIFORM, /** * Unicode script "Phoenician". */ PHOENICIAN, /** * Unicode script "Phags_Pa". */ PHAGS_PA, /** * Unicode script "Nko". */ NKO, /** * Unicode script "Sundanese". */ SUNDANESE, /** * Unicode script "Batak". */ BATAK, /** * Unicode script "Lepcha". */ LEPCHA, /** * Unicode script "Ol_Chiki". */ OL_CHIKI, /** * Unicode script "Vai". */ VAI, /** * Unicode script "Saurashtra". */ SAURASHTRA, /** * Unicode script "Kayah_Li". */ KAYAH_LI, /** * Unicode script "Rejang". */ REJANG, /** * Unicode script "Lycian". */ LYCIAN, /** * Unicode script "Carian". */ CARIAN, /** * Unicode script "Lydian". */ LYDIAN, /** * Unicode script "Cham". */ CHAM, /** * Unicode script "Tai_Tham". */ TAI_THAM, /** * Unicode script "Tai_Viet". */ TAI_VIET, /** * Unicode script "Avestan". */ AVESTAN, /** * Unicode script "Egyptian_Hieroglyphs". */ EGYPTIAN_HIEROGLYPHS, /** * Unicode script "Samaritan". */ SAMARITAN, /** * Unicode script "Mandaic". */ MANDAIC, /** * Unicode script "Lisu". */ LISU, /** * Unicode script "Bamum". */ BAMUM, /** * Unicode script "Javanese". */ JAVANESE, /** * Unicode script "Meetei_Mayek". */ MEETEI_MAYEK, /** * Unicode script "Imperial_Aramaic". */ IMPERIAL_ARAMAIC, /** * Unicode script "Old_South_Arabian". */ OLD_SOUTH_ARABIAN, /** * Unicode script "Inscriptional_Parthian". */ INSCRIPTIONAL_PARTHIAN, /** * Unicode script "Inscriptional_Pahlavi". */ INSCRIPTIONAL_PAHLAVI, /** * Unicode script "Old_Turkic". */ OLD_TURKIC, /** * Unicode script "Brahmi". */ BRAHMI, /** * Unicode script "Kaithi". */ KAITHI, /** * Unicode script "Meroitic Hieroglyphs". */ MEROITIC_HIEROGLYPHS, /** * Unicode script "Meroitic Cursive". */ MEROITIC_CURSIVE, /** * Unicode script "Sora Sompeng". */ SORA_SOMPENG, /** * Unicode script "Chakma". */ CHAKMA, /** * Unicode script "Sharada". */ SHARADA, /** * Unicode script "Takri". */ TAKRI, /** * Unicode script "Miao". */ MIAO, /** * Unicode script "Unknown". */ UNKNOWN; private static final int[] scriptStarts = { 0x0000, // 0000..0040; COMMON 0x0041, // 0041..005A; LATIN 0x005B, // 005B..0060; COMMON 0x0061, // 0061..007A; LATIN 0x007B, // 007B..00A9; COMMON 0x00AA, // 00AA..00AA; LATIN 0x00AB, // 00AB..00B9; COMMON 0x00BA, // 00BA..00BA; LATIN 0x00BB, // 00BB..00BF; COMMON 0x00C0, // 00C0..00D6; LATIN 0x00D7, // 00D7..00D7; COMMON 0x00D8, // 00D8..00F6; LATIN 0x00F7, // 00F7..00F7; COMMON 0x00F8, // 00F8..02B8; LATIN 0x02B9, // 02B9..02DF; COMMON 0x02E0, // 02E0..02E4; LATIN 0x02E5, // 02E5..02E9; COMMON 0x02EA, // 02EA..02EB; BOPOMOFO 0x02EC, // 02EC..02FF; COMMON 0x0300, // 0300..036F; INHERITED 0x0370, // 0370..0373; GREEK 0x0374, // 0374..0374; COMMON 0x0375, // 0375..037D; GREEK 0x037E, // 037E..0383; COMMON 0x0384, // 0384..0384; GREEK 0x0385, // 0385..0385; COMMON 0x0386, // 0386..0386; GREEK 0x0387, // 0387..0387; COMMON 0x0388, // 0388..03E1; GREEK 0x03E2, // 03E2..03EF; COPTIC 0x03F0, // 03F0..03FF; GREEK 0x0400, // 0400..0484; CYRILLIC 0x0485, // 0485..0486; INHERITED 0x0487, // 0487..0530; CYRILLIC 0x0531, // 0531..0588; ARMENIAN 0x0589, // 0589..0589; COMMON 0x058A, // 058A..0590; ARMENIAN 0x0591, // 0591..05FF; HEBREW 0x0600, // 0600..060B; ARABIC 0x060C, // 060C..060C; COMMON 0x060D, // 060D..061A; ARABIC 0x061B, // 061B..061D; COMMON 0x061E, // 061E..061E; ARABIC 0x061F, // 061F..061F; COMMON 0x0620, // 0620..063F; ARABIC 0x0640, // 0640..0640; COMMON 0x0641, // 0641..064A; ARABIC 0x064B, // 064B..0655; INHERITED 0x0656, // 0656..065F; ARABIC 0x0660, // 0660..0669; COMMON 0x066A, // 066A..066F; ARABIC 0x0670, // 0670..0670; INHERITED 0x0671, // 0671..06DC; ARABIC 0x06DD, // 06DD..06DD; COMMON 0x06DE, // 06DE..06FF; ARABIC 0x0700, // 0700..074F; SYRIAC 0x0750, // 0750..077F; ARABIC 0x0780, // 0780..07BF; THAANA 0x07C0, // 07C0..07FF; NKO 0x0800, // 0800..083F; SAMARITAN 0x0840, // 0840..089F; MANDAIC 0x08A0, // 08A0..08FF; ARABIC 0x0900, // 0900..0950; DEVANAGARI 0x0951, // 0951..0952; INHERITED 0x0953, // 0953..0963; DEVANAGARI 0x0964, // 0964..0965; COMMON 0x0966, // 0966..0980; DEVANAGARI 0x0981, // 0981..0A00; BENGALI 0x0A01, // 0A01..0A80; GURMUKHI 0x0A81, // 0A81..0B00; GUJARATI 0x0B01, // 0B01..0B81; ORIYA 0x0B82, // 0B82..0C00; TAMIL 0x0C01, // 0C01..0C81; TELUGU 0x0C82, // 0C82..0CF0; KANNADA 0x0D02, // 0D02..0D81; MALAYALAM 0x0D82, // 0D82..0E00; SINHALA 0x0E01, // 0E01..0E3E; THAI 0x0E3F, // 0E3F..0E3F; COMMON 0x0E40, // 0E40..0E80; THAI 0x0E81, // 0E81..0EFF; LAO 0x0F00, // 0F00..0FD4; TIBETAN 0x0FD5, // 0FD5..0FD8; COMMON 0x0FD9, // 0FD9..0FFF; TIBETAN 0x1000, // 1000..109F; MYANMAR 0x10A0, // 10A0..10FA; GEORGIAN 0x10FB, // 10FB..10FB; COMMON 0x10FC, // 10FC..10FF; GEORGIAN 0x1100, // 1100..11FF; HANGUL 0x1200, // 1200..139F; ETHIOPIC 0x13A0, // 13A0..13FF; CHEROKEE 0x1400, // 1400..167F; CANADIAN_ABORIGINAL 0x1680, // 1680..169F; OGHAM 0x16A0, // 16A0..16EA; RUNIC 0x16EB, // 16EB..16ED; COMMON 0x16EE, // 16EE..16FF; RUNIC 0x1700, // 1700..171F; TAGALOG 0x1720, // 1720..1734; HANUNOO 0x1735, // 1735..173F; COMMON 0x1740, // 1740..175F; BUHID 0x1760, // 1760..177F; TAGBANWA 0x1780, // 1780..17FF; KHMER 0x1800, // 1800..1801; MONGOLIAN 0x1802, // 1802..1803; COMMON 0x1804, // 1804..1804; MONGOLIAN 0x1805, // 1805..1805; COMMON 0x1806, // 1806..18AF; MONGOLIAN 0x18B0, // 18B0..18FF; CANADIAN_ABORIGINAL 0x1900, // 1900..194F; LIMBU 0x1950, // 1950..197F; TAI_LE 0x1980, // 1980..19DF; NEW_TAI_LUE 0x19E0, // 19E0..19FF; KHMER 0x1A00, // 1A00..1A1F; BUGINESE 0x1A20, // 1A20..1AFF; TAI_THAM 0x1B00, // 1B00..1B7F; BALINESE 0x1B80, // 1B80..1BBF; SUNDANESE 0x1BC0, // 1BC0..1BFF; BATAK 0x1C00, // 1C00..1C4F; LEPCHA 0x1C50, // 1C50..1CBF; OL_CHIKI 0x1CC0, // 1CC0..1CCF; SUNDANESE 0x1CD0, // 1CD0..1CD2; INHERITED 0x1CD3, // 1CD3..1CD3; COMMON 0x1CD4, // 1CD4..1CE0; INHERITED 0x1CE1, // 1CE1..1CE1; COMMON 0x1CE2, // 1CE2..1CE8; INHERITED 0x1CE9, // 1CE9..1CEC; COMMON 0x1CED, // 1CED..1CED; INHERITED 0x1CEE, // 1CEE..1CF3; COMMON 0x1CF4, // 1CF4..1CF4; INHERITED 0x1CF5, // 1CF5..1CFF; COMMON 0x1D00, // 1D00..1D25; LATIN 0x1D26, // 1D26..1D2A; GREEK 0x1D2B, // 1D2B..1D2B; CYRILLIC 0x1D2C, // 1D2C..1D5C; LATIN 0x1D5D, // 1D5D..1D61; GREEK 0x1D62, // 1D62..1D65; LATIN 0x1D66, // 1D66..1D6A; GREEK 0x1D6B, // 1D6B..1D77; LATIN 0x1D78, // 1D78..1D78; CYRILLIC 0x1D79, // 1D79..1DBE; LATIN 0x1DBF, // 1DBF..1DBF; GREEK 0x1DC0, // 1DC0..1DFF; INHERITED 0x1E00, // 1E00..1EFF; LATIN 0x1F00, // 1F00..1FFF; GREEK 0x2000, // 2000..200B; COMMON 0x200C, // 200C..200D; INHERITED 0x200E, // 200E..2070; COMMON 0x2071, // 2071..2073; LATIN 0x2074, // 2074..207E; COMMON 0x207F, // 207F..207F; LATIN 0x2080, // 2080..208F; COMMON 0x2090, // 2090..209F; LATIN 0x20A0, // 20A0..20CF; COMMON 0x20D0, // 20D0..20FF; INHERITED 0x2100, // 2100..2125; COMMON 0x2126, // 2126..2126; GREEK 0x2127, // 2127..2129; COMMON 0x212A, // 212A..212B; LATIN 0x212C, // 212C..2131; COMMON 0x2132, // 2132..2132; LATIN 0x2133, // 2133..214D; COMMON 0x214E, // 214E..214E; LATIN 0x214F, // 214F..215F; COMMON 0x2160, // 2160..2188; LATIN 0x2189, // 2189..27FF; COMMON 0x2800, // 2800..28FF; BRAILLE 0x2900, // 2900..2BFF; COMMON 0x2C00, // 2C00..2C5F; GLAGOLITIC 0x2C60, // 2C60..2C7F; LATIN 0x2C80, // 2C80..2CFF; COPTIC 0x2D00, // 2D00..2D2F; GEORGIAN 0x2D30, // 2D30..2D7F; TIFINAGH 0x2D80, // 2D80..2DDF; ETHIOPIC 0x2DE0, // 2DE0..2DFF; CYRILLIC 0x2E00, // 2E00..2E7F; COMMON 0x2E80, // 2E80..2FEF; HAN 0x2FF0, // 2FF0..3004; COMMON 0x3005, // 3005..3005; HAN 0x3006, // 3006..3006; COMMON 0x3007, // 3007..3007; HAN 0x3008, // 3008..3020; COMMON 0x3021, // 3021..3029; HAN 0x302A, // 302A..302D; INHERITED 0x302E, // 302E..302F; HANGUL 0x3030, // 3030..3037; COMMON 0x3038, // 3038..303B; HAN 0x303C, // 303C..3040; COMMON 0x3041, // 3041..3098; HIRAGANA 0x3099, // 3099..309A; INHERITED 0x309B, // 309B..309C; COMMON 0x309D, // 309D..309F; HIRAGANA 0x30A0, // 30A0..30A0; COMMON 0x30A1, // 30A1..30FA; KATAKANA 0x30FB, // 30FB..30FC; COMMON 0x30FD, // 30FD..3104; KATAKANA 0x3105, // 3105..3130; BOPOMOFO 0x3131, // 3131..318F; HANGUL 0x3190, // 3190..319F; COMMON 0x31A0, // 31A0..31BF; BOPOMOFO 0x31C0, // 31C0..31EF; COMMON 0x31F0, // 31F0..31FF; KATAKANA 0x3200, // 3200..321F; HANGUL 0x3220, // 3220..325F; COMMON 0x3260, // 3260..327E; HANGUL 0x327F, // 327F..32CF; COMMON 0x32D0, // 32D0..32FE; KATAKANA 0x32FF, // 32FF ; COMMON 0x3300, // 3300..3357; KATAKANA 0x3358, // 3358..33FF; COMMON 0x3400, // 3400..4DBF; HAN 0x4DC0, // 4DC0..4DFF; COMMON 0x4E00, // 4E00..9FFF; HAN 0xA000, // A000..A4CF; YI 0xA4D0, // A4D0..A4FF; LISU 0xA500, // A500..A63F; VAI 0xA640, // A640..A69F; CYRILLIC 0xA6A0, // A6A0..A6FF; BAMUM 0xA700, // A700..A721; COMMON 0xA722, // A722..A787; LATIN 0xA788, // A788..A78A; COMMON 0xA78B, // A78B..A7FF; LATIN 0xA800, // A800..A82F; SYLOTI_NAGRI 0xA830, // A830..A83F; COMMON 0xA840, // A840..A87F; PHAGS_PA 0xA880, // A880..A8DF; SAURASHTRA 0xA8E0, // A8E0..A8FF; DEVANAGARI 0xA900, // A900..A92F; KAYAH_LI 0xA930, // A930..A95F; REJANG 0xA960, // A960..A97F; HANGUL 0xA980, // A980..A9FF; JAVANESE 0xAA00, // AA00..AA5F; CHAM 0xAA60, // AA60..AA7F; MYANMAR 0xAA80, // AA80..AADF; TAI_VIET 0xAAE0, // AAE0..AB00; MEETEI_MAYEK 0xAB01, // AB01..ABBF; ETHIOPIC 0xABC0, // ABC0..ABFF; MEETEI_MAYEK 0xAC00, // AC00..D7FB; HANGUL 0xD7FC, // D7FC..F8FF; UNKNOWN 0xF900, // F900..FAFF; HAN 0xFB00, // FB00..FB12; LATIN 0xFB13, // FB13..FB1C; ARMENIAN 0xFB1D, // FB1D..FB4F; HEBREW 0xFB50, // FB50..FD3D; ARABIC 0xFD3E, // FD3E..FD4F; COMMON 0xFD50, // FD50..FDFC; ARABIC 0xFDFD, // FDFD..FDFF; COMMON 0xFE00, // FE00..FE0F; INHERITED 0xFE10, // FE10..FE1F; COMMON 0xFE20, // FE20..FE2F; INHERITED 0xFE30, // FE30..FE6F; COMMON 0xFE70, // FE70..FEFE; ARABIC 0xFEFF, // FEFF..FF20; COMMON 0xFF21, // FF21..FF3A; LATIN 0xFF3B, // FF3B..FF40; COMMON 0xFF41, // FF41..FF5A; LATIN 0xFF5B, // FF5B..FF65; COMMON 0xFF66, // FF66..FF6F; KATAKANA 0xFF70, // FF70..FF70; COMMON 0xFF71, // FF71..FF9D; KATAKANA 0xFF9E, // FF9E..FF9F; COMMON 0xFFA0, // FFA0..FFDF; HANGUL 0xFFE0, // FFE0..FFFF; COMMON 0x10000, // 10000..100FF; LINEAR_B 0x10100, // 10100..1013F; COMMON 0x10140, // 10140..1018F; GREEK 0x10190, // 10190..101FC; COMMON 0x101FD, // 101FD..1027F; INHERITED 0x10280, // 10280..1029F; LYCIAN 0x102A0, // 102A0..102FF; CARIAN 0x10300, // 10300..1032F; OLD_ITALIC 0x10330, // 10330..1037F; GOTHIC 0x10380, // 10380..1039F; UGARITIC 0x103A0, // 103A0..103FF; OLD_PERSIAN 0x10400, // 10400..1044F; DESERET 0x10450, // 10450..1047F; SHAVIAN 0x10480, // 10480..107FF; OSMANYA 0x10800, // 10800..1083F; CYPRIOT 0x10840, // 10840..108FF; IMPERIAL_ARAMAIC 0x10900, // 10900..1091F; PHOENICIAN 0x10920, // 10920..1097F; LYDIAN 0x10980, // 10980..1099F; MEROITIC_HIEROGLYPHS 0x109A0, // 109A0..109FF; MEROITIC_CURSIVE 0x10A00, // 10A00..10A5F; KHAROSHTHI 0x10A60, // 10A60..10AFF; OLD_SOUTH_ARABIAN 0x10B00, // 10B00..10B3F; AVESTAN 0x10B40, // 10B40..10B5F; INSCRIPTIONAL_PARTHIAN 0x10B60, // 10B60..10BFF; INSCRIPTIONAL_PAHLAVI 0x10C00, // 10C00..10E5F; OLD_TURKIC 0x10E60, // 10E60..10FFF; ARABIC 0x11000, // 11000..1107F; BRAHMI 0x11080, // 11080..110CF; KAITHI 0x110D0, // 110D0..110FF; SORA_SOMPENG 0x11100, // 11100..1117F; CHAKMA 0x11180, // 11180..1167F; SHARADA 0x11680, // 11680..116CF; TAKRI 0x12000, // 12000..12FFF; CUNEIFORM 0x13000, // 13000..167FF; EGYPTIAN_HIEROGLYPHS 0x16800, // 16800..16A38; BAMUM 0x16F00, // 16F00..16F9F; MIAO 0x1B000, // 1B000..1B000; KATAKANA 0x1B001, // 1B001..1CFFF; HIRAGANA 0x1D000, // 1D000..1D166; COMMON 0x1D167, // 1D167..1D169; INHERITED 0x1D16A, // 1D16A..1D17A; COMMON 0x1D17B, // 1D17B..1D182; INHERITED 0x1D183, // 1D183..1D184; COMMON 0x1D185, // 1D185..1D18B; INHERITED 0x1D18C, // 1D18C..1D1A9; COMMON 0x1D1AA, // 1D1AA..1D1AD; INHERITED 0x1D1AE, // 1D1AE..1D1FF; COMMON 0x1D200, // 1D200..1D2FF; GREEK 0x1D300, // 1D300..1EDFF; COMMON 0x1EE00, // 1EE00..1EFFF; ARABIC 0x1F000, // 1F000..1F1FF; COMMON 0x1F200, // 1F200..1F200; HIRAGANA 0x1F201, // 1F210..1FFFF; COMMON 0x20000, // 20000..E0000; HAN 0xE0001, // E0001..E00FF; COMMON 0xE0100, // E0100..E01EF; INHERITED 0xE01F0 // E01F0..10FFFF; UNKNOWN }; private static final UnicodeScript[] scripts = { COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, BOPOMOFO, COMMON, INHERITED, GREEK, COMMON, GREEK, COMMON, GREEK, COMMON, GREEK, COMMON, GREEK, COPTIC, GREEK, CYRILLIC, INHERITED, CYRILLIC, ARMENIAN, COMMON, ARMENIAN, HEBREW, ARABIC, COMMON, ARABIC, COMMON, ARABIC, COMMON, ARABIC, COMMON, ARABIC, INHERITED, ARABIC, COMMON, ARABIC, INHERITED, ARABIC, COMMON, ARABIC, SYRIAC, ARABIC, THAANA, NKO, SAMARITAN, MANDAIC, ARABIC, DEVANAGARI, INHERITED, DEVANAGARI, COMMON, DEVANAGARI, BENGALI, GURMUKHI, GUJARATI, ORIYA, TAMIL, TELUGU, KANNADA, MALAYALAM, SINHALA, THAI, COMMON, THAI, LAO, TIBETAN, COMMON, TIBETAN, MYANMAR, GEORGIAN, COMMON, GEORGIAN, HANGUL, ETHIOPIC, CHEROKEE, CANADIAN_ABORIGINAL, OGHAM, RUNIC, COMMON, RUNIC, TAGALOG, HANUNOO, COMMON, BUHID, TAGBANWA, KHMER, MONGOLIAN, COMMON, MONGOLIAN, COMMON, MONGOLIAN, CANADIAN_ABORIGINAL, LIMBU, TAI_LE, NEW_TAI_LUE, KHMER, BUGINESE, TAI_THAM, BALINESE, SUNDANESE, BATAK, LEPCHA, OL_CHIKI, SUNDANESE, INHERITED, COMMON, INHERITED, COMMON, INHERITED, COMMON, INHERITED, COMMON, INHERITED, COMMON, LATIN, GREEK, CYRILLIC, LATIN, GREEK, LATIN, GREEK, LATIN, CYRILLIC, LATIN, GREEK, INHERITED, LATIN, GREEK, COMMON, INHERITED, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, INHERITED, COMMON, GREEK, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, LATIN, COMMON, BRAILLE, COMMON, GLAGOLITIC, LATIN, COPTIC, GEORGIAN, TIFINAGH, ETHIOPIC, CYRILLIC, COMMON, HAN, COMMON, HAN, COMMON, HAN, COMMON, HAN, INHERITED, HANGUL, COMMON, HAN, COMMON, HIRAGANA, INHERITED, COMMON, HIRAGANA, COMMON, KATAKANA, COMMON, KATAKANA, BOPOMOFO, HANGUL, COMMON, BOPOMOFO, COMMON, KATAKANA, HANGUL, COMMON, HANGUL, COMMON, KATAKANA, // 32D0..32FE COMMON, // 32FF KATAKANA, // 3300..3357 COMMON, HAN, COMMON, HAN, YI, LISU, VAI, CYRILLIC, BAMUM, COMMON, LATIN, COMMON, LATIN, SYLOTI_NAGRI, COMMON, PHAGS_PA, SAURASHTRA, DEVANAGARI, KAYAH_LI, REJANG, HANGUL, JAVANESE, CHAM, MYANMAR, TAI_VIET, MEETEI_MAYEK, ETHIOPIC, MEETEI_MAYEK, HANGUL, UNKNOWN , HAN, LATIN, ARMENIAN, HEBREW, ARABIC, COMMON, ARABIC, COMMON, INHERITED, COMMON, INHERITED, COMMON, ARABIC, COMMON, LATIN, COMMON, LATIN, COMMON, KATAKANA, COMMON, KATAKANA, COMMON, HANGUL, COMMON, LINEAR_B, COMMON, GREEK, COMMON, INHERITED, LYCIAN, CARIAN, OLD_ITALIC, GOTHIC, UGARITIC, OLD_PERSIAN, DESERET, SHAVIAN, OSMANYA, CYPRIOT, IMPERIAL_ARAMAIC, PHOENICIAN, LYDIAN, MEROITIC_HIEROGLYPHS, MEROITIC_CURSIVE, KHAROSHTHI, OLD_SOUTH_ARABIAN, AVESTAN, INSCRIPTIONAL_PARTHIAN, INSCRIPTIONAL_PAHLAVI, OLD_TURKIC, ARABIC, BRAHMI, KAITHI, SORA_SOMPENG, CHAKMA, SHARADA, TAKRI, CUNEIFORM, EGYPTIAN_HIEROGLYPHS, BAMUM, MIAO, KATAKANA, HIRAGANA, COMMON, INHERITED, COMMON, INHERITED, COMMON, INHERITED, COMMON, INHERITED, COMMON, GREEK, COMMON, ARABIC, COMMON, HIRAGANA, COMMON, HAN, COMMON, INHERITED, UNKNOWN }; private static final HashMap<String, Character.UnicodeScript> aliases; static { aliases = new HashMap<>(128); aliases.put("ARAB", ARABIC); aliases.put("ARMI", IMPERIAL_ARAMAIC); aliases.put("ARMN", ARMENIAN); aliases.put("AVST", AVESTAN); aliases.put("BALI", BALINESE); aliases.put("BAMU", BAMUM); aliases.put("BATK", BATAK); aliases.put("BENG", BENGALI); aliases.put("BOPO", BOPOMOFO); aliases.put("BRAI", BRAILLE); aliases.put("BRAH", BRAHMI); aliases.put("BUGI", BUGINESE); aliases.put("BUHD", BUHID); aliases.put("CAKM", CHAKMA); aliases.put("CANS", CANADIAN_ABORIGINAL); aliases.put("CARI", CARIAN); aliases.put("CHAM", CHAM); aliases.put("CHER", CHEROKEE); aliases.put("COPT", COPTIC); aliases.put("CPRT", CYPRIOT); aliases.put("CYRL", CYRILLIC); aliases.put("DEVA", DEVANAGARI); aliases.put("DSRT", DESERET); aliases.put("EGYP", EGYPTIAN_HIEROGLYPHS); aliases.put("ETHI", ETHIOPIC); aliases.put("GEOR", GEORGIAN); aliases.put("GLAG", GLAGOLITIC); aliases.put("GOTH", GOTHIC); aliases.put("GREK", GREEK); aliases.put("GUJR", GUJARATI); aliases.put("GURU", GURMUKHI); aliases.put("HANG", HANGUL); aliases.put("HANI", HAN); aliases.put("HANO", HANUNOO); aliases.put("HEBR", HEBREW); aliases.put("HIRA", HIRAGANA); // it appears we don't have the KATAKANA_OR_HIRAGANA //aliases.put("HRKT", KATAKANA_OR_HIRAGANA); aliases.put("ITAL", OLD_ITALIC); aliases.put("JAVA", JAVANESE); aliases.put("KALI", KAYAH_LI); aliases.put("KANA", KATAKANA); aliases.put("KHAR", KHAROSHTHI); aliases.put("KHMR", KHMER); aliases.put("KNDA", KANNADA); aliases.put("KTHI", KAITHI); aliases.put("LANA", TAI_THAM); aliases.put("LAOO", LAO); aliases.put("LATN", LATIN); aliases.put("LEPC", LEPCHA); aliases.put("LIMB", LIMBU); aliases.put("LINB", LINEAR_B); aliases.put("LISU", LISU); aliases.put("LYCI", LYCIAN); aliases.put("LYDI", LYDIAN); aliases.put("MAND", MANDAIC); aliases.put("MERC", MEROITIC_CURSIVE); aliases.put("MERO", MEROITIC_HIEROGLYPHS); aliases.put("MLYM", MALAYALAM); aliases.put("MONG", MONGOLIAN); aliases.put("MTEI", MEETEI_MAYEK); aliases.put("MYMR", MYANMAR); aliases.put("NKOO", NKO); aliases.put("OGAM", OGHAM); aliases.put("OLCK", OL_CHIKI); aliases.put("ORKH", OLD_TURKIC); aliases.put("ORYA", ORIYA); aliases.put("OSMA", OSMANYA); aliases.put("PHAG", PHAGS_PA); aliases.put("PLRD", MIAO); aliases.put("PHLI", INSCRIPTIONAL_PAHLAVI); aliases.put("PHNX", PHOENICIAN); aliases.put("PRTI", INSCRIPTIONAL_PARTHIAN); aliases.put("RJNG", REJANG); aliases.put("RUNR", RUNIC); aliases.put("SAMR", SAMARITAN); aliases.put("SARB", OLD_SOUTH_ARABIAN); aliases.put("SAUR", SAURASHTRA); aliases.put("SHAW", SHAVIAN); aliases.put("SHRD", SHARADA); aliases.put("SINH", SINHALA); aliases.put("SORA", SORA_SOMPENG); aliases.put("SUND", SUNDANESE); aliases.put("SYLO", SYLOTI_NAGRI); aliases.put("SYRC", SYRIAC); aliases.put("TAGB", TAGBANWA); aliases.put("TALE", TAI_LE); aliases.put("TAKR", TAKRI); aliases.put("TALU", NEW_TAI_LUE); aliases.put("TAML", TAMIL); aliases.put("TAVT", TAI_VIET); aliases.put("TELU", TELUGU); aliases.put("TFNG", TIFINAGH); aliases.put("TGLG", TAGALOG); aliases.put("THAA", THAANA); aliases.put("THAI", THAI); aliases.put("TIBT", TIBETAN); aliases.put("UGAR", UGARITIC); aliases.put("VAII", VAI); aliases.put("XPEO", OLD_PERSIAN); aliases.put("XSUX", CUNEIFORM); aliases.put("YIII", YI); aliases.put("ZINH", INHERITED); aliases.put("ZYYY", COMMON); aliases.put("ZZZZ", UNKNOWN); } /** * Returns the enum constant representing the Unicode script of which * the given character (Unicode code point) is assigned to. * * @param codePoint the character (Unicode code point) in question. * @return The {@code UnicodeScript} constant representing the * Unicode script of which this character is assigned to. * * @exception IllegalArgumentException if the specified * {@code codePoint} is an invalid Unicode code point. * @see Character#isValidCodePoint(int) * */ public static UnicodeScript of(int codePoint) { if (!isValidCodePoint(codePoint)) throw new IllegalArgumentException(); int type = getType(codePoint); // leave SURROGATE and PRIVATE_USE for table lookup if (type == UNASSIGNED) return UNKNOWN; int index = Arrays.binarySearch(scriptStarts, codePoint); if (index < 0) index = -index - 2; return scripts[index]; } /** * Returns the UnicodeScript constant with the given Unicode script * name or the script name alias. Script names and their aliases are * determined by The Unicode Standard. The files Scripts&lt;version&gt;.txt * and PropertyValueAliases&lt;version&gt;.txt define script names * and the script name aliases for a particular version of the * standard. The {@link Character} class specifies the version of * the standard that it supports. * <p> * Character case is ignored for all of the valid script names. * The en_US locale's case mapping rules are used to provide * case-insensitive string comparisons for script name validation. * <p> * * @param scriptName A {@code UnicodeScript} name. * @return The {@code UnicodeScript} constant identified * by {@code scriptName} * @throws IllegalArgumentException if {@code scriptName} is an * invalid name * @throws NullPointerException if {@code scriptName} is null */ public static final UnicodeScript forName(String scriptName) { scriptName = scriptName.toUpperCase(Locale.ENGLISH); //.replace(' ', '_')); UnicodeScript sc = aliases.get(scriptName); if (sc != null) return sc; return valueOf(scriptName); } } /** * The value of the {@code Character}. * * @serial */ private final char value; /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 3786198910865385080L; /** * Constructs a newly allocated {@code Character} object that * represents the specified {@code char} value. * * @param value the value to be represented by the * {@code Character} object. */ public Character(char value) { this.value = value; } private static class CharacterCache { private CharacterCache(){} static final Character cache[] = new Character[127 + 1]; static { for (int i = 0; i < cache.length; i++) cache[i] = new Character((char)i); } } /** * Returns a <tt>Character</tt> instance representing the specified * <tt>char</tt> value. * If a new <tt>Character</tt> instance is not required, this method * should generally be used in preference to the constructor * {@link #Character(char)}, as this method is likely to yield * significantly better space and time performance by caching * frequently requested values. * * This method will always cache values in the range {@code * '\u005Cu0000'} to {@code '\u005Cu007F'}, inclusive, and may * cache other values outside of this range. * * @param c a char value. * @return a <tt>Character</tt> instance representing <tt>c</tt>. * @since 1.5 */ public static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); } /** * Returns the value of this {@code Character} object. * @return the primitive {@code char} value represented by * this object. */ public char charValue() { return value; } /** * Returns a hash code for this {@code Character}; equal to the result * of invoking {@code charValue()}. * * @return a hash code value for this {@code Character} */ @Override public int hashCode() { return Character.hashCode(value); } /** * Returns a hash code for a {@code char} value; compatible with * {@code Character.hashCode()}. * * @since 1.8 * * @param value The {@code char} for which to return a hash code. * @return a hash code value for a {@code char} value. */ public static int hashCode(char value) { return (int)value; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is not * {@code null} and is a {@code Character} object that * represents the same {@code char} value as this object. * * @param obj the object to compare with. * @return {@code true} if the objects are the same; * {@code false} otherwise. */ public boolean equals(Object obj) { if (obj instanceof Character) { return value == ((Character)obj).charValue(); } return false; } /** * Returns a {@code String} object representing this * {@code Character}'s value. The result is a string of * length 1 whose sole component is the primitive * {@code char} value represented by this * {@code Character} object. * * @return a string representation of this object. */ public String toString() { return String.valueOf(value); } /** * Returns a {@code String} object representing the * specified {@code char}. The result is a string of length * 1 consisting solely of the specified {@code char}. * * @param c the {@code char} to be converted * @return the string representation of the specified {@code char} * @since 1.4 */ public static String toString(char c) { return String.valueOf(c); } /** * Determines whether the specified code point is a valid * <a href="http://www.unicode.org/glossary/#code_point"> * Unicode code point value</a>. * * @param codePoint the Unicode code point to be tested * @return {@code true} if the specified code point value is between * {@link #MIN_CODE_POINT} and * {@link #MAX_CODE_POINT} inclusive; * {@code false} otherwise. * @since 1.5 */ public static boolean isValidCodePoint(int codePoint) { // Optimized form of: // codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT int plane = codePoint >>> 16; return plane < ((MAX_CODE_POINT + 1) >>> 16); } /** * Determines whether the specified character (Unicode code point) * is in the <a href="#BMP">Basic Multilingual Plane (BMP)</a>. * Such code points can be represented using a single {@code char}. * * @param codePoint the character (Unicode code point) to be tested * @return {@code true} if the specified code point is between * {@link #MIN_VALUE} and {@link #MAX_VALUE} inclusive; * {@code false} otherwise. * @since 1.7 */ public static boolean isBmpCodePoint(int codePoint) { return codePoint >>> 16 == 0; // Optimized form of: // codePoint >= MIN_VALUE && codePoint <= MAX_VALUE // We consistently use logical shift (>>>) to facilitate // additional runtime optimizations. } /** * Determines whether the specified character (Unicode code point) * is in the <a href="#supplementary">supplementary character</a> range. * * @param codePoint the character (Unicode code point) to be tested * @return {@code true} if the specified code point is between * {@link #MIN_SUPPLEMENTARY_CODE_POINT} and * {@link #MAX_CODE_POINT} inclusive; * {@code false} otherwise. * @since 1.5 */ public static boolean isSupplementaryCodePoint(int codePoint) { return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT && codePoint < MAX_CODE_POINT + 1; } /** * Determines if the given {@code char} value is a * <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit"> * Unicode high-surrogate code unit</a> * (also known as <i>leading-surrogate code unit</i>). * * <p>Such values do not represent characters by themselves, * but are used in the representation of * <a href="#supplementary">supplementary characters</a> * in the UTF-16 encoding. * * @param ch the {@code char} value to be tested. * @return {@code true} if the {@code char} value is between * {@link #MIN_HIGH_SURROGATE} and * {@link #MAX_HIGH_SURROGATE} inclusive; * {@code false} otherwise. * @see Character#isLowSurrogate(char) * @see Character.UnicodeBlock#of(int) * @since 1.5 */ public static boolean isHighSurrogate(char ch) { // Help VM constant-fold; MAX_HIGH_SURROGATE + 1 == MIN_LOW_SURROGATE return ch >= MIN_HIGH_SURROGATE && ch < (MAX_HIGH_SURROGATE + 1); } /** * Determines if the given {@code char} value is a * <a href="http://www.unicode.org/glossary/#low_surrogate_code_unit"> * Unicode low-surrogate code unit</a> * (also known as <i>trailing-surrogate code unit</i>). * * <p>Such values do not represent characters by themselves, * but are used in the representation of * <a href="#supplementary">supplementary characters</a> * in the UTF-16 encoding. * * @param ch the {@code char} value to be tested. * @return {@code true} if the {@code char} value is between * {@link #MIN_LOW_SURROGATE} and * {@link #MAX_LOW_SURROGATE} inclusive; * {@code false} otherwise. * @see Character#isHighSurrogate(char) * @since 1.5 */ public static boolean isLowSurrogate(char ch) { return ch >= MIN_LOW_SURROGATE && ch < (MAX_LOW_SURROGATE + 1); } /** * Determines if the given {@code char} value is a Unicode * <i>surrogate code unit</i>. * * <p>Such values do not represent characters by themselves, * but are used in the representation of * <a href="#supplementary">supplementary characters</a> * in the UTF-16 encoding. * * <p>A char value is a surrogate code unit if and only if it is either * a {@linkplain #isLowSurrogate(char) low-surrogate code unit} or * a {@linkplain #isHighSurrogate(char) high-surrogate code unit}. * * @param ch the {@code char} value to be tested. * @return {@code true} if the {@code char} value is between * {@link #MIN_SURROGATE} and * {@link #MAX_SURROGATE} inclusive; * {@code false} otherwise. * @since 1.7 */ public static boolean isSurrogate(char ch) { return ch >= MIN_SURROGATE && ch < (MAX_SURROGATE + 1); } /** * Determines whether the specified pair of {@code char} * values is a valid * <a href="http://www.unicode.org/glossary/#surrogate_pair"> * Unicode surrogate pair</a>. * <p>This method is equivalent to the expression: * <blockquote><pre>{@code * isHighSurrogate(high) && isLowSurrogate(low) * }</pre></blockquote> * * @param high the high-surrogate code value to be tested * @param low the low-surrogate code value to be tested * @return {@code true} if the specified high and * low-surrogate code values represent a valid surrogate pair; * {@code false} otherwise. * @since 1.5 */ public static boolean isSurrogatePair(char high, char low) { return isHighSurrogate(high) && isLowSurrogate(low); } /** * Determines the number of {@code char} values needed to * represent the specified character (Unicode code point). If the * specified character is equal to or greater than 0x10000, then * the method returns 2. Otherwise, the method returns 1. * * <p>This method doesn't validate the specified character to be a * valid Unicode code point. The caller must validate the * character value using {@link #isValidCodePoint(int) isValidCodePoint} * if necessary. * * @param codePoint the character (Unicode code point) to be tested. * @return 2 if the character is a valid supplementary character; 1 otherwise. * @see Character#isSupplementaryCodePoint(int) * @since 1.5 */ public static int charCount(int codePoint) { return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT ? 2 : 1; } /** * Converts the specified surrogate pair to its supplementary code * point value. This method does not validate the specified * surrogate pair. The caller must validate it using {@link * #isSurrogatePair(char, char) isSurrogatePair} if necessary. * * @param high the high-surrogate code unit * @param low the low-surrogate code unit * @return the supplementary code point composed from the * specified surrogate pair. * @since 1.5 */ public static int toCodePoint(char high, char low) { // Optimized form of: // return ((high - MIN_HIGH_SURROGATE) << 10) // + (low - MIN_LOW_SURROGATE) // + MIN_SUPPLEMENTARY_CODE_POINT; return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT - (MIN_HIGH_SURROGATE << 10) - MIN_LOW_SURROGATE); } /** * Returns the code point at the given index of the * {@code CharSequence}. If the {@code char} value at * the given index in the {@code CharSequence} is in the * high-surrogate range, the following index is less than the * length of the {@code CharSequence}, and the * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at the given index is returned. * * @param seq a sequence of {@code char} values (Unicode code * units) * @param index the index to the {@code char} values (Unicode * code units) in {@code seq} to be converted * @return the Unicode code point at the given index * @exception NullPointerException if {@code seq} is null. * @exception IndexOutOfBoundsException if the value * {@code index} is negative or not less than * {@link CharSequence#length() seq.length()}. * @since 1.5 */ public static int codePointAt(CharSequence seq, int index) { char c1 = seq.charAt(index); if (isHighSurrogate(c1) && ++index < seq.length()) { char c2 = seq.charAt(index); if (isLowSurrogate(c2)) { return toCodePoint(c1, c2); } } return c1; } /** * Returns the code point at the given index of the * {@code char} array. If the {@code char} value at * the given index in the {@code char} array is in the * high-surrogate range, the following index is less than the * length of the {@code char} array, and the * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at the given index is returned. * * @param a the {@code char} array * @param index the index to the {@code char} values (Unicode * code units) in the {@code char} array to be converted * @return the Unicode code point at the given index * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException if the value * {@code index} is negative or not less than * the length of the {@code char} array. * @since 1.5 */ public static int codePointAt(char[] a, int index) { return codePointAtImpl(a, index, a.length); } /** * Returns the code point at the given index of the * {@code char} array, where only array elements with * {@code index} less than {@code limit} can be used. If * the {@code char} value at the given index in the * {@code char} array is in the high-surrogate range, the * following index is less than the {@code limit}, and the * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at the given index is returned. * * @param a the {@code char} array * @param index the index to the {@code char} values (Unicode * code units) in the {@code char} array to be converted * @param limit the index after the last array element that * can be used in the {@code char} array * @return the Unicode code point at the given index * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException if the {@code index} * argument is negative or not less than the {@code limit} * argument, or if the {@code limit} argument is negative or * greater than the length of the {@code char} array. * @since 1.5 */ public static int codePointAt(char[] a, int index, int limit) { if (index >= limit || limit < 0 || limit > a.length) { throw new IndexOutOfBoundsException(); } return codePointAtImpl(a, index, limit); } // throws ArrayIndexOutOfBoundsException if index out of bounds static int codePointAtImpl(char[] a, int index, int limit) { char c1 = a[index]; if (isHighSurrogate(c1) && ++index < limit) { char c2 = a[index]; if (isLowSurrogate(c2)) { return toCodePoint(c1, c2); } } return c1; } /** * Returns the code point preceding the given index of the * {@code CharSequence}. If the {@code char} value at * {@code (index - 1)} in the {@code CharSequence} is in * the low-surrogate range, {@code (index - 2)} is not * negative, and the {@code char} value at {@code (index - 2)} * in the {@code CharSequence} is in the * high-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at {@code (index - 1)} is * returned. * * @param seq the {@code CharSequence} instance * @param index the index following the code point that should be returned * @return the Unicode code point value before the given index. * @exception NullPointerException if {@code seq} is null. * @exception IndexOutOfBoundsException if the {@code index} * argument is less than 1 or greater than {@link * CharSequence#length() seq.length()}. * @since 1.5 */ public static int codePointBefore(CharSequence seq, int index) { char c2 = seq.charAt(--index); if (isLowSurrogate(c2) && index > 0) { char c1 = seq.charAt(--index); if (isHighSurrogate(c1)) { return toCodePoint(c1, c2); } } return c2; } /** * Returns the code point preceding the given index of the * {@code char} array. If the {@code char} value at * {@code (index - 1)} in the {@code char} array is in * the low-surrogate range, {@code (index - 2)} is not * negative, and the {@code char} value at {@code (index - 2)} * in the {@code char} array is in the * high-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at {@code (index - 1)} is * returned. * * @param a the {@code char} array * @param index the index following the code point that should be returned * @return the Unicode code point value before the given index. * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException if the {@code index} * argument is less than 1 or greater than the length of the * {@code char} array * @since 1.5 */ public static int codePointBefore(char[] a, int index) { return codePointBeforeImpl(a, index, 0); } /** * Returns the code point preceding the given index of the * {@code char} array, where only array elements with * {@code index} greater than or equal to {@code start} * can be used. If the {@code char} value at {@code (index - 1)} * in the {@code char} array is in the * low-surrogate range, {@code (index - 2)} is not less than * {@code start}, and the {@code char} value at * {@code (index - 2)} in the {@code char} array is in * the high-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at {@code (index - 1)} is * returned. * * @param a the {@code char} array * @param index the index following the code point that should be returned * @param start the index of the first array element in the * {@code char} array * @return the Unicode code point value before the given index. * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException if the {@code index} * argument is not greater than the {@code start} argument or * is greater than the length of the {@code char} array, or * if the {@code start} argument is negative or not less than * the length of the {@code char} array. * @since 1.5 */ public static int codePointBefore(char[] a, int index, int start) { if (index <= start || start < 0 || start >= a.length) { throw new IndexOutOfBoundsException(); } return codePointBeforeImpl(a, index, start); } // throws ArrayIndexOutOfBoundsException if index-1 out of bounds static int codePointBeforeImpl(char[] a, int index, int start) { char c2 = a[--index]; if (isLowSurrogate(c2) && index > start) { char c1 = a[--index]; if (isHighSurrogate(c1)) { return toCodePoint(c1, c2); } } return c2; } /** * Returns the leading surrogate (a * <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit"> * high surrogate code unit</a>) of the * <a href="http://www.unicode.org/glossary/#surrogate_pair"> * surrogate pair</a> * representing the specified supplementary character (Unicode * code point) in the UTF-16 encoding. If the specified character * is not a * <a href="Character.html#supplementary">supplementary character</a>, * an unspecified {@code char} is returned. * * <p>If * {@link #isSupplementaryCodePoint isSupplementaryCodePoint(x)} * is {@code true}, then * {@link #isHighSurrogate isHighSurrogate}{@code (highSurrogate(x))} and * {@link #toCodePoint toCodePoint}{@code (highSurrogate(x), }{@link #lowSurrogate lowSurrogate}{@code (x)) == x} * are also always {@code true}. * * @param codePoint a supplementary character (Unicode code point) * @return the leading surrogate code unit used to represent the * character in the UTF-16 encoding * @since 1.7 */ public static char highSurrogate(int codePoint) { return (char) ((codePoint >>> 10) + (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10))); } /** * Returns the trailing surrogate (a * <a href="http://www.unicode.org/glossary/#low_surrogate_code_unit"> * low surrogate code unit</a>) of the * <a href="http://www.unicode.org/glossary/#surrogate_pair"> * surrogate pair</a> * representing the specified supplementary character (Unicode * code point) in the UTF-16 encoding. If the specified character * is not a * <a href="Character.html#supplementary">supplementary character</a>, * an unspecified {@code char} is returned. * * <p>If * {@link #isSupplementaryCodePoint isSupplementaryCodePoint(x)} * is {@code true}, then * {@link #isLowSurrogate isLowSurrogate}{@code (lowSurrogate(x))} and * {@link #toCodePoint toCodePoint}{@code (}{@link #highSurrogate highSurrogate}{@code (x), lowSurrogate(x)) == x} * are also always {@code true}. * * @param codePoint a supplementary character (Unicode code point) * @return the trailing surrogate code unit used to represent the * character in the UTF-16 encoding * @since 1.7 */ public static char lowSurrogate(int codePoint) { return (char) ((codePoint & 0x3ff) + MIN_LOW_SURROGATE); } /** * Converts the specified character (Unicode code point) to its * UTF-16 representation. If the specified code point is a BMP * (Basic Multilingual Plane or Plane 0) value, the same value is * stored in {@code dst[dstIndex]}, and 1 is returned. If the * specified code point is a supplementary character, its * surrogate values are stored in {@code dst[dstIndex]} * (high-surrogate) and {@code dst[dstIndex+1]} * (low-surrogate), and 2 is returned. * * @param codePoint the character (Unicode code point) to be converted. * @param dst an array of {@code char} in which the * {@code codePoint}'s UTF-16 value is stored. * @param dstIndex the start index into the {@code dst} * array where the converted value is stored. * @return 1 if the code point is a BMP code point, 2 if the * code point is a supplementary code point. * @exception IllegalArgumentException if the specified * {@code codePoint} is not a valid Unicode code point. * @exception NullPointerException if the specified {@code dst} is null. * @exception IndexOutOfBoundsException if {@code dstIndex} * is negative or not less than {@code dst.length}, or if * {@code dst} at {@code dstIndex} doesn't have enough * array element(s) to store the resulting {@code char} * value(s). (If {@code dstIndex} is equal to * {@code dst.length-1} and the specified * {@code codePoint} is a supplementary character, the * high-surrogate value is not stored in * {@code dst[dstIndex]}.) * @since 1.5 */ public static int toChars(int codePoint, char[] dst, int dstIndex) { if (isBmpCodePoint(codePoint)) { dst[dstIndex] = (char) codePoint; return 1; } else if (isValidCodePoint(codePoint)) { toSurrogates(codePoint, dst, dstIndex); return 2; } else { throw new IllegalArgumentException(); } } /** * Converts the specified character (Unicode code point) to its * UTF-16 representation stored in a {@code char} array. If * the specified code point is a BMP (Basic Multilingual Plane or * Plane 0) value, the resulting {@code char} array has * the same value as {@code codePoint}. If the specified code * point is a supplementary code point, the resulting * {@code char} array has the corresponding surrogate pair. * * @param codePoint a Unicode code point * @return a {@code char} array having * {@code codePoint}'s UTF-16 representation. * @exception IllegalArgumentException if the specified * {@code codePoint} is not a valid Unicode code point. * @since 1.5 */ public static char[] toChars(int codePoint) { if (isBmpCodePoint(codePoint)) { return new char[] { (char) codePoint }; } else if (isValidCodePoint(codePoint)) { char[] result = new char[2]; toSurrogates(codePoint, result, 0); return result; } else { throw new IllegalArgumentException(); } } static void toSurrogates(int codePoint, char[] dst, int index) { // We write elements "backwards" to guarantee all-or-nothing dst[index+1] = lowSurrogate(codePoint); dst[index] = highSurrogate(codePoint); } /** * Returns the number of Unicode code points in the text range of * the specified char sequence. The text range begins at the * specified {@code beginIndex} and extends to the * {@code char} at index {@code endIndex - 1}. Thus the * length (in {@code char}s) of the text range is * {@code endIndex-beginIndex}. Unpaired surrogates within * the text range count as one code point each. * * @param seq the char sequence * @param beginIndex the index to the first {@code char} of * the text range. * @param endIndex the index after the last {@code char} of * the text range. * @return the number of Unicode code points in the specified text * range * @exception NullPointerException if {@code seq} is null. * @exception IndexOutOfBoundsException if the * {@code beginIndex} is negative, or {@code endIndex} * is larger than the length of the given sequence, or * {@code beginIndex} is larger than {@code endIndex}. * @since 1.5 */ public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) { int length = seq.length(); if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) { throw new IndexOutOfBoundsException(); } int n = endIndex - beginIndex; for (int i = beginIndex; i < endIndex; ) { if (isHighSurrogate(seq.charAt(i++)) && i < endIndex && isLowSurrogate(seq.charAt(i))) { n--; i++; } } return n; } /** * Returns the number of Unicode code points in a subarray of the * {@code char} array argument. The {@code offset} * argument is the index of the first {@code char} of the * subarray and the {@code count} argument specifies the * length of the subarray in {@code char}s. Unpaired * surrogates within the subarray count as one code point each. * * @param a the {@code char} array * @param offset the index of the first {@code char} in the * given {@code char} array * @param count the length of the subarray in {@code char}s * @return the number of Unicode code points in the specified subarray * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException if {@code offset} or * {@code count} is negative, or if {@code offset + * count} is larger than the length of the given array. * @since 1.5 */ public static int codePointCount(char[] a, int offset, int count) { if (count > a.length - offset || offset < 0 || count < 0) { throw new IndexOutOfBoundsException(); } return codePointCountImpl(a, offset, count); } static int codePointCountImpl(char[] a, int offset, int count) { int endIndex = offset + count; int n = count; for (int i = offset; i < endIndex; ) { if (isHighSurrogate(a[i++]) && i < endIndex && isLowSurrogate(a[i])) { n--; i++; } } return n; } /** * Returns the index within the given char sequence that is offset * from the given {@code index} by {@code codePointOffset} * code points. Unpaired surrogates within the text range given by * {@code index} and {@code codePointOffset} count as * one code point each. * * @param seq the char sequence * @param index the index to be offset * @param codePointOffset the offset in code points * @return the index within the char sequence * @exception NullPointerException if {@code seq} is null. * @exception IndexOutOfBoundsException if {@code index} * is negative or larger then the length of the char sequence, * or if {@code codePointOffset} is positive and the * subsequence starting with {@code index} has fewer than * {@code codePointOffset} code points, or if * {@code codePointOffset} is negative and the subsequence * before {@code index} has fewer than the absolute value * of {@code codePointOffset} code points. * @since 1.5 */ public static int offsetByCodePoints(CharSequence seq, int index, int codePointOffset) { int length = seq.length(); if (index < 0 || index > length) { throw new IndexOutOfBoundsException(); } int x = index; if (codePointOffset >= 0) { int i; for (i = 0; x < length && i < codePointOffset; i++) { if (isHighSurrogate(seq.charAt(x++)) && x < length && isLowSurrogate(seq.charAt(x))) { x++; } } if (i < codePointOffset) { throw new IndexOutOfBoundsException(); } } else { int i; for (i = codePointOffset; x > 0 && i < 0; i++) { if (isLowSurrogate(seq.charAt(--x)) && x > 0 && isHighSurrogate(seq.charAt(x-1))) { x--; } } if (i < 0) { throw new IndexOutOfBoundsException(); } } return x; } /** * Returns the index within the given {@code char} subarray * that is offset from the given {@code index} by * {@code codePointOffset} code points. The * {@code start} and {@code count} arguments specify a * subarray of the {@code char} array. Unpaired surrogates * within the text range given by {@code index} and * {@code codePointOffset} count as one code point each. * * @param a the {@code char} array * @param start the index of the first {@code char} of the * subarray * @param count the length of the subarray in {@code char}s * @param index the index to be offset * @param codePointOffset the offset in code points * @return the index within the subarray * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException * if {@code start} or {@code count} is negative, * or if {@code start + count} is larger than the length of * the given array, * or if {@code index} is less than {@code start} or * larger then {@code start + count}, * or if {@code codePointOffset} is positive and the text range * starting with {@code index} and ending with {@code start + count - 1} * has fewer than {@code codePointOffset} code * points, * or if {@code codePointOffset} is negative and the text range * starting with {@code start} and ending with {@code index - 1} * has fewer than the absolute value of * {@code codePointOffset} code points. * @since 1.5 */ public static int offsetByCodePoints(char[] a, int start, int count, int index, int codePointOffset) { if (count > a.length-start || start < 0 || count < 0 || index < start || index > start+count) { throw new IndexOutOfBoundsException(); } return offsetByCodePointsImpl(a, start, count, index, codePointOffset); } static int offsetByCodePointsImpl(char[]a, int start, int count, int index, int codePointOffset) { int x = index; if (codePointOffset >= 0) { int limit = start + count; int i; for (i = 0; x < limit && i < codePointOffset; i++) { if (isHighSurrogate(a[x++]) && x < limit && isLowSurrogate(a[x])) { x++; } } if (i < codePointOffset) { throw new IndexOutOfBoundsException(); } } else { int i; for (i = codePointOffset; x > start && i < 0; i++) { if (isLowSurrogate(a[--x]) && x > start && isHighSurrogate(a[x-1])) { x--; } } if (i < 0) { throw new IndexOutOfBoundsException(); } } return x; } /** * Determines if the specified character is a lowercase character. * <p> * A character is lowercase if its general category type, provided * by {@code Character.getType(ch)}, is * {@code LOWERCASE_LETTER}, or it has contributory property * Other_Lowercase as defined by the Unicode Standard. * <p> * The following are examples of lowercase characters: * <blockquote><pre> * a b c d e f g h i j k l m n o p q r s t u v w x y z * '&#92;u00DF' '&#92;u00E0' '&#92;u00E1' '&#92;u00E2' '&#92;u00E3' '&#92;u00E4' '&#92;u00E5' '&#92;u00E6' * '&#92;u00E7' '&#92;u00E8' '&#92;u00E9' '&#92;u00EA' '&#92;u00EB' '&#92;u00EC' '&#92;u00ED' '&#92;u00EE' * '&#92;u00EF' '&#92;u00F0' '&#92;u00F1' '&#92;u00F2' '&#92;u00F3' '&#92;u00F4' '&#92;u00F5' '&#92;u00F6' * '&#92;u00F8' '&#92;u00F9' '&#92;u00FA' '&#92;u00FB' '&#92;u00FC' '&#92;u00FD' '&#92;u00FE' '&#92;u00FF' * </pre></blockquote> * <p> Many other Unicode characters are lowercase too. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isLowerCase(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is lowercase; * {@code false} otherwise. * @see Character#isLowerCase(char) * @see Character#isTitleCase(char) * @see Character#toLowerCase(char) * @see Character#getType(char) */ public static boolean isLowerCase(char ch) { return isLowerCase((int)ch); } /** * Determines if the specified character (Unicode code point) is a * lowercase character. * <p> * A character is lowercase if its general category type, provided * by {@link Character#getType getType(codePoint)}, is * {@code LOWERCASE_LETTER}, or it has contributory property * Other_Lowercase as defined by the Unicode Standard. * <p> * The following are examples of lowercase characters: * <blockquote><pre> * a b c d e f g h i j k l m n o p q r s t u v w x y z * '&#92;u00DF' '&#92;u00E0' '&#92;u00E1' '&#92;u00E2' '&#92;u00E3' '&#92;u00E4' '&#92;u00E5' '&#92;u00E6' * '&#92;u00E7' '&#92;u00E8' '&#92;u00E9' '&#92;u00EA' '&#92;u00EB' '&#92;u00EC' '&#92;u00ED' '&#92;u00EE' * '&#92;u00EF' '&#92;u00F0' '&#92;u00F1' '&#92;u00F2' '&#92;u00F3' '&#92;u00F4' '&#92;u00F5' '&#92;u00F6' * '&#92;u00F8' '&#92;u00F9' '&#92;u00FA' '&#92;u00FB' '&#92;u00FC' '&#92;u00FD' '&#92;u00FE' '&#92;u00FF' * </pre></blockquote> * <p> Many other Unicode characters are lowercase too. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is lowercase; * {@code false} otherwise. * @see Character#isLowerCase(int) * @see Character#isTitleCase(int) * @see Character#toLowerCase(int) * @see Character#getType(int) * @since 1.5 */ public static boolean isLowerCase(int codePoint) { return getType(codePoint) == Character.LOWERCASE_LETTER || CharacterData.of(codePoint).isOtherLowercase(codePoint); } /** * Determines if the specified character is an uppercase character. * <p> * A character is uppercase if its general category type, provided by * {@code Character.getType(ch)}, is {@code UPPERCASE_LETTER}. * or it has contributory property Other_Uppercase as defined by the Unicode Standard. * <p> * The following are examples of uppercase characters: * <blockquote><pre> * A B C D E F G H I J K L M N O P Q R S T U V W X Y Z * '&#92;u00C0' '&#92;u00C1' '&#92;u00C2' '&#92;u00C3' '&#92;u00C4' '&#92;u00C5' '&#92;u00C6' '&#92;u00C7' * '&#92;u00C8' '&#92;u00C9' '&#92;u00CA' '&#92;u00CB' '&#92;u00CC' '&#92;u00CD' '&#92;u00CE' '&#92;u00CF' * '&#92;u00D0' '&#92;u00D1' '&#92;u00D2' '&#92;u00D3' '&#92;u00D4' '&#92;u00D5' '&#92;u00D6' '&#92;u00D8' * '&#92;u00D9' '&#92;u00DA' '&#92;u00DB' '&#92;u00DC' '&#92;u00DD' '&#92;u00DE' * </pre></blockquote> * <p> Many other Unicode characters are uppercase too. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isUpperCase(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is uppercase; * {@code false} otherwise. * @see Character#isLowerCase(char) * @see Character#isTitleCase(char) * @see Character#toUpperCase(char) * @see Character#getType(char) * @since 1.0 */ public static boolean isUpperCase(char ch) { return isUpperCase((int)ch); } /** * Determines if the specified character (Unicode code point) is an uppercase character. * <p> * A character is uppercase if its general category type, provided by * {@link Character#getType(int) getType(codePoint)}, is {@code UPPERCASE_LETTER}, * or it has contributory property Other_Uppercase as defined by the Unicode Standard. * <p> * The following are examples of uppercase characters: * <blockquote><pre> * A B C D E F G H I J K L M N O P Q R S T U V W X Y Z * '&#92;u00C0' '&#92;u00C1' '&#92;u00C2' '&#92;u00C3' '&#92;u00C4' '&#92;u00C5' '&#92;u00C6' '&#92;u00C7' * '&#92;u00C8' '&#92;u00C9' '&#92;u00CA' '&#92;u00CB' '&#92;u00CC' '&#92;u00CD' '&#92;u00CE' '&#92;u00CF' * '&#92;u00D0' '&#92;u00D1' '&#92;u00D2' '&#92;u00D3' '&#92;u00D4' '&#92;u00D5' '&#92;u00D6' '&#92;u00D8' * '&#92;u00D9' '&#92;u00DA' '&#92;u00DB' '&#92;u00DC' '&#92;u00DD' '&#92;u00DE' * </pre></blockquote> * <p> Many other Unicode characters are uppercase too.<p> * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is uppercase; * {@code false} otherwise. * @see Character#isLowerCase(int) * @see Character#isTitleCase(int) * @see Character#toUpperCase(int) * @see Character#getType(int) * @since 1.5 */ public static boolean isUpperCase(int codePoint) { return getType(codePoint) == Character.UPPERCASE_LETTER || CharacterData.of(codePoint).isOtherUppercase(codePoint); } /** * Determines if the specified character is a titlecase character. * <p> * A character is a titlecase character if its general * category type, provided by {@code Character.getType(ch)}, * is {@code TITLECASE_LETTER}. * <p> * Some characters look like pairs of Latin letters. For example, there * is an uppercase letter that looks like "LJ" and has a corresponding * lowercase letter that looks like "lj". A third form, which looks like "Lj", * is the appropriate form to use when rendering a word in lowercase * with initial capitals, as for a book title. * <p> * These are some of the Unicode characters for which this method returns * {@code true}: * <ul> * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} * <li>{@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} * <li>{@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} * </ul> * <p> Many other Unicode characters are titlecase too. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isTitleCase(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is titlecase; * {@code false} otherwise. * @see Character#isLowerCase(char) * @see Character#isUpperCase(char) * @see Character#toTitleCase(char) * @see Character#getType(char) * @since 1.0.2 */ public static boolean isTitleCase(char ch) { return isTitleCase((int)ch); } /** * Determines if the specified character (Unicode code point) is a titlecase character. * <p> * A character is a titlecase character if its general * category type, provided by {@link Character#getType(int) getType(codePoint)}, * is {@code TITLECASE_LETTER}. * <p> * Some characters look like pairs of Latin letters. For example, there * is an uppercase letter that looks like "LJ" and has a corresponding * lowercase letter that looks like "lj". A third form, which looks like "Lj", * is the appropriate form to use when rendering a word in lowercase * with initial capitals, as for a book title. * <p> * These are some of the Unicode characters for which this method returns * {@code true}: * <ul> * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} * <li>{@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} * <li>{@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} * </ul> * <p> Many other Unicode characters are titlecase too.<p> * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is titlecase; * {@code false} otherwise. * @see Character#isLowerCase(int) * @see Character#isUpperCase(int) * @see Character#toTitleCase(int) * @see Character#getType(int) * @since 1.5 */ public static boolean isTitleCase(int codePoint) { return getType(codePoint) == Character.TITLECASE_LETTER; } /** * Determines if the specified character is a digit. * <p> * A character is a digit if its general category type, provided * by {@code Character.getType(ch)}, is * {@code DECIMAL_DIGIT_NUMBER}. * <p> * Some Unicode character ranges that contain digits: * <ul> * <li>{@code '\u005Cu0030'} through {@code '\u005Cu0039'}, * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) * <li>{@code '\u005Cu0660'} through {@code '\u005Cu0669'}, * Arabic-Indic digits * <li>{@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, * Extended Arabic-Indic digits * <li>{@code '\u005Cu0966'} through {@code '\u005Cu096F'}, * Devanagari digits * <li>{@code '\u005CuFF10'} through {@code '\u005CuFF19'}, * Fullwidth digits * </ul> * * Many other character ranges contain digits as well. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isDigit(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is a digit; * {@code false} otherwise. * @see Character#digit(char, int) * @see Character#forDigit(int, int) * @see Character#getType(char) */ public static boolean isDigit(char ch) { return isDigit((int)ch); } /** * Determines if the specified character (Unicode code point) is a digit. * <p> * A character is a digit if its general category type, provided * by {@link Character#getType(int) getType(codePoint)}, is * {@code DECIMAL_DIGIT_NUMBER}. * <p> * Some Unicode character ranges that contain digits: * <ul> * <li>{@code '\u005Cu0030'} through {@code '\u005Cu0039'}, * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) * <li>{@code '\u005Cu0660'} through {@code '\u005Cu0669'}, * Arabic-Indic digits * <li>{@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, * Extended Arabic-Indic digits * <li>{@code '\u005Cu0966'} through {@code '\u005Cu096F'}, * Devanagari digits * <li>{@code '\u005CuFF10'} through {@code '\u005CuFF19'}, * Fullwidth digits * </ul> * * Many other character ranges contain digits as well. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is a digit; * {@code false} otherwise. * @see Character#forDigit(int, int) * @see Character#getType(int) * @since 1.5 */ public static boolean isDigit(int codePoint) { return getType(codePoint) == Character.DECIMAL_DIGIT_NUMBER; } /** * Determines if a character is defined in Unicode. * <p> * A character is defined if at least one of the following is true: * <ul> * <li>It has an entry in the UnicodeData file. * <li>It has a value in a range defined by the UnicodeData file. * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isDefined(int)} method. * * @param ch the character to be tested * @return {@code true} if the character has a defined meaning * in Unicode; {@code false} otherwise. * @see Character#isDigit(char) * @see Character#isLetter(char) * @see Character#isLetterOrDigit(char) * @see Character#isLowerCase(char) * @see Character#isTitleCase(char) * @see Character#isUpperCase(char) * @since 1.0.2 */ public static boolean isDefined(char ch) { return isDefined((int)ch); } /** * Determines if a character (Unicode code point) is defined in Unicode. * <p> * A character is defined if at least one of the following is true: * <ul> * <li>It has an entry in the UnicodeData file. * <li>It has a value in a range defined by the UnicodeData file. * </ul> * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character has a defined meaning * in Unicode; {@code false} otherwise. * @see Character#isDigit(int) * @see Character#isLetter(int) * @see Character#isLetterOrDigit(int) * @see Character#isLowerCase(int) * @see Character#isTitleCase(int) * @see Character#isUpperCase(int) * @since 1.5 */ public static boolean isDefined(int codePoint) { return getType(codePoint) != Character.UNASSIGNED; } /** * Determines if the specified character is a letter. * <p> * A character is considered to be a letter if its general * category type, provided by {@code Character.getType(ch)}, * is any of the following: * <ul> * <li> {@code UPPERCASE_LETTER} * <li> {@code LOWERCASE_LETTER} * <li> {@code TITLECASE_LETTER} * <li> {@code MODIFIER_LETTER} * <li> {@code OTHER_LETTER} * </ul> * * Not all letters have case. Many characters are * letters but are neither uppercase nor lowercase nor titlecase. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isLetter(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is a letter; * {@code false} otherwise. * @see Character#isDigit(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isJavaLetter(char) * @see Character#isJavaLetterOrDigit(char) * @see Character#isLetterOrDigit(char) * @see Character#isLowerCase(char) * @see Character#isTitleCase(char) * @see Character#isUnicodeIdentifierStart(char) * @see Character#isUpperCase(char) */ public static boolean isLetter(char ch) { return isLetter((int)ch); } /** * Determines if the specified character (Unicode code point) is a letter. * <p> * A character is considered to be a letter if its general * category type, provided by {@link Character#getType(int) getType(codePoint)}, * is any of the following: * <ul> * <li> {@code UPPERCASE_LETTER} * <li> {@code LOWERCASE_LETTER} * <li> {@code TITLECASE_LETTER} * <li> {@code MODIFIER_LETTER} * <li> {@code OTHER_LETTER} * </ul> * * Not all letters have case. Many characters are * letters but are neither uppercase nor lowercase nor titlecase. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is a letter; * {@code false} otherwise. * @see Character#isDigit(int) * @see Character#isJavaIdentifierStart(int) * @see Character#isLetterOrDigit(int) * @see Character#isLowerCase(int) * @see Character#isTitleCase(int) * @see Character#isUnicodeIdentifierStart(int) * @see Character#isUpperCase(int) * @since 1.5 */ public static boolean isLetter(int codePoint) { return ((((1 << Character.UPPERCASE_LETTER) | (1 << Character.LOWERCASE_LETTER) | (1 << Character.TITLECASE_LETTER) | (1 << Character.MODIFIER_LETTER) | (1 << Character.OTHER_LETTER)) >> getType(codePoint)) & 1) != 0; } /** * Determines if the specified character is a letter or digit. * <p> * A character is considered to be a letter or digit if either * {@code Character.isLetter(char ch)} or * {@code Character.isDigit(char ch)} returns * {@code true} for the character. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isLetterOrDigit(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is a letter or digit; * {@code false} otherwise. * @see Character#isDigit(char) * @see Character#isJavaIdentifierPart(char) * @see Character#isJavaLetter(char) * @see Character#isJavaLetterOrDigit(char) * @see Character#isLetter(char) * @see Character#isUnicodeIdentifierPart(char) * @since 1.0.2 */ public static boolean isLetterOrDigit(char ch) { return isLetterOrDigit((int)ch); } /** * Determines if the specified character (Unicode code point) is a letter or digit. * <p> * A character is considered to be a letter or digit if either * {@link #isLetter(int) isLetter(codePoint)} or * {@link #isDigit(int) isDigit(codePoint)} returns * {@code true} for the character. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is a letter or digit; * {@code false} otherwise. * @see Character#isDigit(int) * @see Character#isJavaIdentifierPart(int) * @see Character#isLetter(int) * @see Character#isUnicodeIdentifierPart(int) * @since 1.5 */ public static boolean isLetterOrDigit(int codePoint) { return ((((1 << Character.UPPERCASE_LETTER) | (1 << Character.LOWERCASE_LETTER) | (1 << Character.TITLECASE_LETTER) | (1 << Character.MODIFIER_LETTER) | (1 << Character.OTHER_LETTER) | (1 << Character.DECIMAL_DIGIT_NUMBER)) >> getType(codePoint)) & 1) != 0; } /** * Determines if the specified character is permissible as the first * character in a Java identifier. * <p> * A character may start a Java identifier if and only if * one of the following conditions is true: * <ul> * <li> {@link #isLetter(char) isLetter(ch)} returns {@code true} * <li> {@link #getType(char) getType(ch)} returns {@code LETTER_NUMBER} * <li> {@code ch} is a currency symbol (such as {@code '$'}) * <li> {@code ch} is a connecting punctuation character (such as {@code '_'}). * </ul> * * These conditions are tested against the character information from version * 6.2 of the Unicode Standard. * * @param ch the character to be tested. * @return {@code true} if the character may start a Java * identifier; {@code false} otherwise. * @see Character#isJavaLetterOrDigit(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isJavaIdentifierPart(char) * @see Character#isLetter(char) * @see Character#isLetterOrDigit(char) * @see Character#isUnicodeIdentifierStart(char) * @since 1.02 * @deprecated Replaced by isJavaIdentifierStart(char). */ @Deprecated public static boolean isJavaLetter(char ch) { return isJavaIdentifierStart(ch); } /** * Determines if the specified character may be part of a Java * identifier as other than the first character. * <p> * A character may be part of a Java identifier if and only if any * of the following conditions are true: * <ul> * <li> it is a letter * <li> it is a currency symbol (such as {@code '$'}) * <li> it is a connecting punctuation character (such as {@code '_'}) * <li> it is a digit * <li> it is a numeric letter (such as a Roman numeral character) * <li> it is a combining mark * <li> it is a non-spacing mark * <li> {@code isIdentifierIgnorable} returns * {@code true} for the character. * </ul> * * These conditions are tested against the character information from version * 6.2 of the Unicode Standard. * * @param ch the character to be tested. * @return {@code true} if the character may be part of a * Java identifier; {@code false} otherwise. * @see Character#isJavaLetter(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isJavaIdentifierPart(char) * @see Character#isLetter(char) * @see Character#isLetterOrDigit(char) * @see Character#isUnicodeIdentifierPart(char) * @see Character#isIdentifierIgnorable(char) * @since 1.02 * @deprecated Replaced by isJavaIdentifierPart(char). */ @Deprecated public static boolean isJavaLetterOrDigit(char ch) { return isJavaIdentifierPart(ch); } /** * Determines if the specified character (Unicode code point) is an alphabet. * <p> * A character is considered to be alphabetic if its general category type, * provided by {@link Character#getType(int) getType(codePoint)}, is any of * the following: * <ul> * <li> <code>UPPERCASE_LETTER</code> * <li> <code>LOWERCASE_LETTER</code> * <li> <code>TITLECASE_LETTER</code> * <li> <code>MODIFIER_LETTER</code> * <li> <code>OTHER_LETTER</code> * <li> <code>LETTER_NUMBER</code> * </ul> * or it has contributory property Other_Alphabetic as defined by the * Unicode Standard. * * @param codePoint the character (Unicode code point) to be tested. * @return <code>true</code> if the character is a Unicode alphabet * character, <code>false</code> otherwise. * @since 1.7 */ public static boolean isAlphabetic(int codePoint) { return (((((1 << Character.UPPERCASE_LETTER) | (1 << Character.LOWERCASE_LETTER) | (1 << Character.TITLECASE_LETTER) | (1 << Character.MODIFIER_LETTER) | (1 << Character.OTHER_LETTER) | (1 << Character.LETTER_NUMBER)) >> getType(codePoint)) & 1) != 0) || CharacterData.of(codePoint).isOtherAlphabetic(codePoint); } /** * Determines if the specified character (Unicode code point) is a CJKV * (Chinese, Japanese, Korean and Vietnamese) ideograph, as defined by * the Unicode Standard. * * @param codePoint the character (Unicode code point) to be tested. * @return <code>true</code> if the character is a Unicode ideograph * character, <code>false</code> otherwise. * @since 1.7 */ public static boolean isIdeographic(int codePoint) { return CharacterData.of(codePoint).isIdeographic(codePoint); } /** * Determines if the specified character is * permissible as the first character in a Java identifier. * <p> * A character may start a Java identifier if and only if * one of the following conditions is true: * <ul> * <li> {@link #isLetter(char) isLetter(ch)} returns {@code true} * <li> {@link #getType(char) getType(ch)} returns {@code LETTER_NUMBER} * <li> {@code ch} is a currency symbol (such as {@code '$'}) * <li> {@code ch} is a connecting punctuation character (such as {@code '_'}). * </ul> * * These conditions are tested against the character information from version * 6.2 of the Unicode Standard. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isJavaIdentifierStart(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character may start a Java identifier; * {@code false} otherwise. * @see Character#isJavaIdentifierPart(char) * @see Character#isLetter(char) * @see Character#isUnicodeIdentifierStart(char) * @see javax.lang.model.SourceVersion#isIdentifier(CharSequence) * @since 1.1 */ public static boolean isJavaIdentifierStart(char ch) { return isJavaIdentifierStart((int)ch); } /** * Determines if the character (Unicode code point) is * permissible as the first character in a Java identifier. * <p> * A character may start a Java identifier if and only if * one of the following conditions is true: * <ul> * <li> {@link #isLetter(int) isLetter(codePoint)} * returns {@code true} * <li> {@link #getType(int) getType(codePoint)} * returns {@code LETTER_NUMBER} * <li> the referenced character is a currency symbol (such as {@code '$'}) * <li> the referenced character is a connecting punctuation character * (such as {@code '_'}). * </ul> * * These conditions are tested against the character information from version * 6.2 of the Unicode Standard. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character may start a Java identifier; * {@code false} otherwise. * @see Character#isJavaIdentifierPart(int) * @see Character#isLetter(int) * @see Character#isUnicodeIdentifierStart(int) * @see javax.lang.model.SourceVersion#isIdentifier(CharSequence) * @since 1.5 */ public static boolean isJavaIdentifierStart(int codePoint) { return CharacterData.of(codePoint).isJavaIdentifierStart(codePoint); } /** * Determines if the specified character may be part of a Java * identifier as other than the first character. * <p> * A character may be part of a Java identifier if any of the following * conditions are true: * <ul> * <li> it is a letter * <li> it is a currency symbol (such as {@code '$'}) * <li> it is a connecting punctuation character (such as {@code '_'}) * <li> it is a digit * <li> it is a numeric letter (such as a Roman numeral character) * <li> it is a combining mark * <li> it is a non-spacing mark * <li> {@code isIdentifierIgnorable} returns * {@code true} for the character * </ul> * * These conditions are tested against the character information from version * 6.2 of the Unicode Standard. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isJavaIdentifierPart(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character may be part of a * Java identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isLetterOrDigit(char) * @see Character#isUnicodeIdentifierPart(char) * @see javax.lang.model.SourceVersion#isIdentifier(CharSequence) * @since 1.1 */ public static boolean isJavaIdentifierPart(char ch) { return isJavaIdentifierPart((int)ch); } /** * Determines if the character (Unicode code point) may be part of a Java * identifier as other than the first character. * <p> * A character may be part of a Java identifier if any of the following * conditions are true: * <ul> * <li> it is a letter * <li> it is a currency symbol (such as {@code '$'}) * <li> it is a connecting punctuation character (such as {@code '_'}) * <li> it is a digit * <li> it is a numeric letter (such as a Roman numeral character) * <li> it is a combining mark * <li> it is a non-spacing mark * <li> {@link #isIdentifierIgnorable(int) * isIdentifierIgnorable(codePoint)} returns {@code true} for * the code point * </ul> * * These conditions are tested against the character information from version * 6.2 of the Unicode Standard. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character may be part of a * Java identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(int) * @see Character#isJavaIdentifierStart(int) * @see Character#isLetterOrDigit(int) * @see Character#isUnicodeIdentifierPart(int) * @see javax.lang.model.SourceVersion#isIdentifier(CharSequence) * @since 1.5 */ public static boolean isJavaIdentifierPart(int codePoint) { return CharacterData.of(codePoint).isJavaIdentifierPart(codePoint); } /** * Determines if the specified character is permissible as the * first character in a Unicode identifier. * <p> * A character may start a Unicode identifier if and only if * one of the following conditions is true: * <ul> * <li> {@link #isLetter(char) isLetter(ch)} returns {@code true} * <li> {@link #getType(char) getType(ch)} returns * {@code LETTER_NUMBER}. * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isUnicodeIdentifierStart(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character may start a Unicode * identifier; {@code false} otherwise. * @see Character#isJavaIdentifierStart(char) * @see Character#isLetter(char) * @see Character#isUnicodeIdentifierPart(char) * @since 1.1 */ public static boolean isUnicodeIdentifierStart(char ch) { return isUnicodeIdentifierStart((int)ch); } /** * Determines if the specified character (Unicode code point) is permissible as the * first character in a Unicode identifier. * <p> * A character may start a Unicode identifier if and only if * one of the following conditions is true: * <ul> * <li> {@link #isLetter(int) isLetter(codePoint)} * returns {@code true} * <li> {@link #getType(int) getType(codePoint)} * returns {@code LETTER_NUMBER}. * </ul> * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character may start a Unicode * identifier; {@code false} otherwise. * @see Character#isJavaIdentifierStart(int) * @see Character#isLetter(int) * @see Character#isUnicodeIdentifierPart(int) * @since 1.5 */ public static boolean isUnicodeIdentifierStart(int codePoint) { return CharacterData.of(codePoint).isUnicodeIdentifierStart(codePoint); } /** * Determines if the specified character may be part of a Unicode * identifier as other than the first character. * <p> * A character may be part of a Unicode identifier if and only if * one of the following statements is true: * <ul> * <li> it is a letter * <li> it is a connecting punctuation character (such as {@code '_'}) * <li> it is a digit * <li> it is a numeric letter (such as a Roman numeral character) * <li> it is a combining mark * <li> it is a non-spacing mark * <li> {@code isIdentifierIgnorable} returns * {@code true} for this character. * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isUnicodeIdentifierPart(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character may be part of a * Unicode identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(char) * @see Character#isJavaIdentifierPart(char) * @see Character#isLetterOrDigit(char) * @see Character#isUnicodeIdentifierStart(char) * @since 1.1 */ public static boolean isUnicodeIdentifierPart(char ch) { return isUnicodeIdentifierPart((int)ch); } /** * Determines if the specified character (Unicode code point) may be part of a Unicode * identifier as other than the first character. * <p> * A character may be part of a Unicode identifier if and only if * one of the following statements is true: * <ul> * <li> it is a letter * <li> it is a connecting punctuation character (such as {@code '_'}) * <li> it is a digit * <li> it is a numeric letter (such as a Roman numeral character) * <li> it is a combining mark * <li> it is a non-spacing mark * <li> {@code isIdentifierIgnorable} returns * {@code true} for this character. * </ul> * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character may be part of a * Unicode identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(int) * @see Character#isJavaIdentifierPart(int) * @see Character#isLetterOrDigit(int) * @see Character#isUnicodeIdentifierStart(int) * @since 1.5 */ public static boolean isUnicodeIdentifierPart(int codePoint) { return CharacterData.of(codePoint).isUnicodeIdentifierPart(codePoint); } /** * Determines if the specified character should be regarded as * an ignorable character in a Java identifier or a Unicode identifier. * <p> * The following Unicode characters are ignorable in a Java identifier * or a Unicode identifier: * <ul> * <li>ISO control characters that are not whitespace * <ul> * <li>{@code '\u005Cu0000'} through {@code '\u005Cu0008'} * <li>{@code '\u005Cu000E'} through {@code '\u005Cu001B'} * <li>{@code '\u005Cu007F'} through {@code '\u005Cu009F'} * </ul> * * <li>all characters that have the {@code FORMAT} general * category value * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isIdentifierIgnorable(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is an ignorable control * character that may be part of a Java or Unicode identifier; * {@code false} otherwise. * @see Character#isJavaIdentifierPart(char) * @see Character#isUnicodeIdentifierPart(char) * @since 1.1 */ public static boolean isIdentifierIgnorable(char ch) { return isIdentifierIgnorable((int)ch); } /** * Determines if the specified character (Unicode code point) should be regarded as * an ignorable character in a Java identifier or a Unicode identifier. * <p> * The following Unicode characters are ignorable in a Java identifier * or a Unicode identifier: * <ul> * <li>ISO control characters that are not whitespace * <ul> * <li>{@code '\u005Cu0000'} through {@code '\u005Cu0008'} * <li>{@code '\u005Cu000E'} through {@code '\u005Cu001B'} * <li>{@code '\u005Cu007F'} through {@code '\u005Cu009F'} * </ul> * * <li>all characters that have the {@code FORMAT} general * category value * </ul> * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is an ignorable control * character that may be part of a Java or Unicode identifier; * {@code false} otherwise. * @see Character#isJavaIdentifierPart(int) * @see Character#isUnicodeIdentifierPart(int) * @since 1.5 */ public static boolean isIdentifierIgnorable(int codePoint) { return CharacterData.of(codePoint).isIdentifierIgnorable(codePoint); } /** * Converts the character argument to lowercase using case * mapping information from the UnicodeData file. * <p> * Note that * {@code Character.isLowerCase(Character.toLowerCase(ch))} * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * * <p>In general, {@link String#toLowerCase()} should be used to map * characters to lowercase. {@code String} case mapping methods * have several benefits over {@code Character} case mapping methods. * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas * the {@code Character} case mapping methods cannot. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #toLowerCase(int)} method. * * @param ch the character to be converted. * @return the lowercase equivalent of the character, if any; * otherwise, the character itself. * @see Character#isLowerCase(char) * @see String#toLowerCase() */ public static char toLowerCase(char ch) { return (char)toLowerCase((int)ch); } /** * Converts the character (Unicode code point) argument to * lowercase using case mapping information from the UnicodeData * file. * * <p> Note that * {@code Character.isLowerCase(Character.toLowerCase(codePoint))} * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * * <p>In general, {@link String#toLowerCase()} should be used to map * characters to lowercase. {@code String} case mapping methods * have several benefits over {@code Character} case mapping methods. * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas * the {@code Character} case mapping methods cannot. * * @param codePoint the character (Unicode code point) to be converted. * @return the lowercase equivalent of the character (Unicode code * point), if any; otherwise, the character itself. * @see Character#isLowerCase(int) * @see String#toLowerCase() * * @since 1.5 */ public static int toLowerCase(int codePoint) { return CharacterData.of(codePoint).toLowerCase(codePoint); } /** * Converts the character argument to uppercase using case mapping * information from the UnicodeData file. * <p> * Note that * {@code Character.isUpperCase(Character.toUpperCase(ch))} * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * * <p>In general, {@link String#toUpperCase()} should be used to map * characters to uppercase. {@code String} case mapping methods * have several benefits over {@code Character} case mapping methods. * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas * the {@code Character} case mapping methods cannot. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #toUpperCase(int)} method. * * @param ch the character to be converted. * @return the uppercase equivalent of the character, if any; * otherwise, the character itself. * @see Character#isUpperCase(char) * @see String#toUpperCase() */ public static char toUpperCase(char ch) { return (char)toUpperCase((int)ch); } /** * Converts the character (Unicode code point) argument to * uppercase using case mapping information from the UnicodeData * file. * * <p>Note that * {@code Character.isUpperCase(Character.toUpperCase(codePoint))} * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * * <p>In general, {@link String#toUpperCase()} should be used to map * characters to uppercase. {@code String} case mapping methods * have several benefits over {@code Character} case mapping methods. * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas * the {@code Character} case mapping methods cannot. * * @param codePoint the character (Unicode code point) to be converted. * @return the uppercase equivalent of the character, if any; * otherwise, the character itself. * @see Character#isUpperCase(int) * @see String#toUpperCase() * * @since 1.5 */ public static int toUpperCase(int codePoint) { return CharacterData.of(codePoint).toUpperCase(codePoint); } /** * Converts the character argument to titlecase using case mapping * information from the UnicodeData file. If a character has no * explicit titlecase mapping and is not itself a titlecase char * according to UnicodeData, then the uppercase mapping is * returned as an equivalent titlecase mapping. If the * {@code char} argument is already a titlecase * {@code char}, the same {@code char} value will be * returned. * <p> * Note that * {@code Character.isTitleCase(Character.toTitleCase(ch))} * does not always return {@code true} for some ranges of * characters. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #toTitleCase(int)} method. * * @param ch the character to be converted. * @return the titlecase equivalent of the character, if any; * otherwise, the character itself. * @see Character#isTitleCase(char) * @see Character#toLowerCase(char) * @see Character#toUpperCase(char) * @since 1.0.2 */ public static char toTitleCase(char ch) { return (char)toTitleCase((int)ch); } /** * Converts the character (Unicode code point) argument to titlecase using case mapping * information from the UnicodeData file. If a character has no * explicit titlecase mapping and is not itself a titlecase char * according to UnicodeData, then the uppercase mapping is * returned as an equivalent titlecase mapping. If the * character argument is already a titlecase * character, the same character value will be * returned. * * <p>Note that * {@code Character.isTitleCase(Character.toTitleCase(codePoint))} * does not always return {@code true} for some ranges of * characters. * * @param codePoint the character (Unicode code point) to be converted. * @return the titlecase equivalent of the character, if any; * otherwise, the character itself. * @see Character#isTitleCase(int) * @see Character#toLowerCase(int) * @see Character#toUpperCase(int) * @since 1.5 */ public static int toTitleCase(int codePoint) { return CharacterData.of(codePoint).toTitleCase(codePoint); } /** * Returns the numeric value of the character {@code ch} in the * specified radix. * <p> * If the radix is not in the range {@code MIN_RADIX} &le; * {@code radix} &le; {@code MAX_RADIX} or if the * value of {@code ch} is not a valid digit in the specified * radix, {@code -1} is returned. A character is a valid digit * if at least one of the following is true: * <ul> * <li>The method {@code isDigit} is {@code true} of the character * and the Unicode decimal digit value of the character (or its * single-character decomposition) is less than the specified radix. * In this case the decimal digit value is returned. * <li>The character is one of the uppercase Latin letters * {@code 'A'} through {@code 'Z'} and its code is less than * {@code radix + 'A' - 10}. * In this case, {@code ch - 'A' + 10} * is returned. * <li>The character is one of the lowercase Latin letters * {@code 'a'} through {@code 'z'} and its code is less than * {@code radix + 'a' - 10}. * In this case, {@code ch - 'a' + 10} * is returned. * <li>The character is one of the fullwidth uppercase Latin letters A * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) * and its code is less than * {@code radix + '\u005CuFF21' - 10}. * In this case, {@code ch - '\u005CuFF21' + 10} * is returned. * <li>The character is one of the fullwidth lowercase Latin letters a * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) * and its code is less than * {@code radix + '\u005CuFF41' - 10}. * In this case, {@code ch - '\u005CuFF41' + 10} * is returned. * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #digit(int, int)} method. * * @param ch the character to be converted. * @param radix the radix. * @return the numeric value represented by the character in the * specified radix. * @see Character#forDigit(int, int) * @see Character#isDigit(char) */ public static int digit(char ch, int radix) { return digit((int)ch, radix); } /** * Returns the numeric value of the specified character (Unicode * code point) in the specified radix. * * <p>If the radix is not in the range {@code MIN_RADIX} &le; * {@code radix} &le; {@code MAX_RADIX} or if the * character is not a valid digit in the specified * radix, {@code -1} is returned. A character is a valid digit * if at least one of the following is true: * <ul> * <li>The method {@link #isDigit(int) isDigit(codePoint)} is {@code true} of the character * and the Unicode decimal digit value of the character (or its * single-character decomposition) is less than the specified radix. * In this case the decimal digit value is returned. * <li>The character is one of the uppercase Latin letters * {@code 'A'} through {@code 'Z'} and its code is less than * {@code radix + 'A' - 10}. * In this case, {@code codePoint - 'A' + 10} * is returned. * <li>The character is one of the lowercase Latin letters * {@code 'a'} through {@code 'z'} and its code is less than * {@code radix + 'a' - 10}. * In this case, {@code codePoint - 'a' + 10} * is returned. * <li>The character is one of the fullwidth uppercase Latin letters A * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) * and its code is less than * {@code radix + '\u005CuFF21' - 10}. * In this case, * {@code codePoint - '\u005CuFF21' + 10} * is returned. * <li>The character is one of the fullwidth lowercase Latin letters a * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) * and its code is less than * {@code radix + '\u005CuFF41'- 10}. * In this case, * {@code codePoint - '\u005CuFF41' + 10} * is returned. * </ul> * * @param codePoint the character (Unicode code point) to be converted. * @param radix the radix. * @return the numeric value represented by the character in the * specified radix. * @see Character#forDigit(int, int) * @see Character#isDigit(int) * @since 1.5 */ public static int digit(int codePoint, int radix) { return CharacterData.of(codePoint).digit(codePoint, radix); } /** * Returns the {@code int} value that the specified Unicode * character represents. For example, the character * {@code '\u005Cu216C'} (the roman numeral fifty) will return * an int with a value of 50. * <p> * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through * {@code '\u005Cu005A'}), lowercase * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and * full width variant ({@code '\u005CuFF21'} through * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through * {@code '\u005CuFF5A'}) forms have numeric values from 10 * through 35. This is independent of the Unicode specification, * which does not assign numeric values to these {@code char} * values. * <p> * If the character does not have a numeric value, then -1 is returned. * If the character has a numeric value that cannot be represented as a * nonnegative integer (for example, a fractional value), then -2 * is returned. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #getNumericValue(int)} method. * * @param ch the character to be converted. * @return the numeric value of the character, as a nonnegative {@code int} * value; -2 if the character has a numeric value that is not a * nonnegative integer; -1 if the character has no numeric value. * @see Character#forDigit(int, int) * @see Character#isDigit(char) * @since 1.1 */ public static int getNumericValue(char ch) { return getNumericValue((int)ch); } /** * Returns the {@code int} value that the specified * character (Unicode code point) represents. For example, the character * {@code '\u005Cu216C'} (the Roman numeral fifty) will return * an {@code int} with a value of 50. * <p> * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through * {@code '\u005Cu005A'}), lowercase * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and * full width variant ({@code '\u005CuFF21'} through * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through * {@code '\u005CuFF5A'}) forms have numeric values from 10 * through 35. This is independent of the Unicode specification, * which does not assign numeric values to these {@code char} * values. * <p> * If the character does not have a numeric value, then -1 is returned. * If the character has a numeric value that cannot be represented as a * nonnegative integer (for example, a fractional value), then -2 * is returned. * * @param codePoint the character (Unicode code point) to be converted. * @return the numeric value of the character, as a nonnegative {@code int} * value; -2 if the character has a numeric value that is not a * nonnegative integer; -1 if the character has no numeric value. * @see Character#forDigit(int, int) * @see Character#isDigit(int) * @since 1.5 */ public static int getNumericValue(int codePoint) { return CharacterData.of(codePoint).getNumericValue(codePoint); } /** * Determines if the specified character is ISO-LATIN-1 white space. * This method returns {@code true} for the following five * characters only: * <table summary="truechars"> * <tr><td>{@code '\t'}</td> <td>{@code U+0009}</td> * <td>{@code HORIZONTAL TABULATION}</td></tr> * <tr><td>{@code '\n'}</td> <td>{@code U+000A}</td> * <td>{@code NEW LINE}</td></tr> * <tr><td>{@code '\f'}</td> <td>{@code U+000C}</td> * <td>{@code FORM FEED}</td></tr> * <tr><td>{@code '\r'}</td> <td>{@code U+000D}</td> * <td>{@code CARRIAGE RETURN}</td></tr> * <tr><td>{@code ' '}</td> <td>{@code U+0020}</td> * <td>{@code SPACE}</td></tr> * </table> * * @param ch the character to be tested. * @return {@code true} if the character is ISO-LATIN-1 white * space; {@code false} otherwise. * @see Character#isSpaceChar(char) * @see Character#isWhitespace(char) * @deprecated Replaced by isWhitespace(char). */ @Deprecated public static boolean isSpace(char ch) { return (ch <= 0x0020) && (((((1L << 0x0009) | (1L << 0x000A) | (1L << 0x000C) | (1L << 0x000D) | (1L << 0x0020)) >> ch) & 1L) != 0); } /** * Determines if the specified character is a Unicode space character. * A character is considered to be a space character if and only if * it is specified to be a space character by the Unicode Standard. This * method returns true if the character's general category type is any of * the following: * <ul> * <li> {@code SPACE_SEPARATOR} * <li> {@code LINE_SEPARATOR} * <li> {@code PARAGRAPH_SEPARATOR} * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isSpaceChar(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is a space character; * {@code false} otherwise. * @see Character#isWhitespace(char) * @since 1.1 */ public static boolean isSpaceChar(char ch) { return isSpaceChar((int)ch); } /** * Determines if the specified character (Unicode code point) is a * Unicode space character. A character is considered to be a * space character if and only if it is specified to be a space * character by the Unicode Standard. This method returns true if * the character's general category type is any of the following: * * <ul> * <li> {@link #SPACE_SEPARATOR} * <li> {@link #LINE_SEPARATOR} * <li> {@link #PARAGRAPH_SEPARATOR} * </ul> * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is a space character; * {@code false} otherwise. * @see Character#isWhitespace(int) * @since 1.5 */ public static boolean isSpaceChar(int codePoint) { return ((((1 << Character.SPACE_SEPARATOR) | (1 << Character.LINE_SEPARATOR) | (1 << Character.PARAGRAPH_SEPARATOR)) >> getType(codePoint)) & 1) != 0; } /** * Determines if the specified character is white space according to Java. * A character is a Java whitespace character if and only if it satisfies * one of the following criteria: * <ul> * <li> It is a Unicode space character ({@code SPACE_SEPARATOR}, * {@code LINE_SEPARATOR}, or {@code PARAGRAPH_SEPARATOR}) * but is not also a non-breaking space ({@code '\u005Cu00A0'}, * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}). * <li> It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION. * <li> It is {@code '\u005Cn'}, U+000A LINE FEED. * <li> It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION. * <li> It is {@code '\u005Cf'}, U+000C FORM FEED. * <li> It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN. * <li> It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR. * <li> It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR. * <li> It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR. * <li> It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR. * </ul> * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isWhitespace(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is a Java whitespace * character; {@code false} otherwise. * @see Character#isSpaceChar(char) * @since 1.1 */ public static boolean isWhitespace(char ch) { return isWhitespace((int)ch); } /** * Determines if the specified character (Unicode code point) is * white space according to Java. A character is a Java * whitespace character if and only if it satisfies one of the * following criteria: * <ul> * <li> It is a Unicode space character ({@link #SPACE_SEPARATOR}, * {@link #LINE_SEPARATOR}, or {@link #PARAGRAPH_SEPARATOR}) * but is not also a non-breaking space ({@code '\u005Cu00A0'}, * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}). * <li> It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION. * <li> It is {@code '\u005Cn'}, U+000A LINE FEED. * <li> It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION. * <li> It is {@code '\u005Cf'}, U+000C FORM FEED. * <li> It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN. * <li> It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR. * <li> It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR. * <li> It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR. * <li> It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR. * </ul> * <p> * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is a Java whitespace * character; {@code false} otherwise. * @see Character#isSpaceChar(int) * @since 1.5 */ public static boolean isWhitespace(int codePoint) { return CharacterData.of(codePoint).isWhitespace(codePoint); } /** * Determines if the specified character is an ISO control * character. A character is considered to be an ISO control * character if its code is in the range {@code '\u005Cu0000'} * through {@code '\u005Cu001F'} or in the range * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isISOControl(int)} method. * * @param ch the character to be tested. * @return {@code true} if the character is an ISO control character; * {@code false} otherwise. * * @see Character#isSpaceChar(char) * @see Character#isWhitespace(char) * @since 1.1 */ public static boolean isISOControl(char ch) { return isISOControl((int)ch); } /** * Determines if the referenced character (Unicode code point) is an ISO control * character. A character is considered to be an ISO control * character if its code is in the range {@code '\u005Cu0000'} * through {@code '\u005Cu001F'} or in the range * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is an ISO control character; * {@code false} otherwise. * @see Character#isSpaceChar(int) * @see Character#isWhitespace(int) * @since 1.5 */ public static boolean isISOControl(int codePoint) { // Optimized form of: // (codePoint >= 0x00 && codePoint <= 0x1F) || // (codePoint >= 0x7F && codePoint <= 0x9F); return codePoint <= 0x9F && (codePoint >= 0x7F || (codePoint >>> 5 == 0)); } /** * Returns a value indicating a character's general category. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #getType(int)} method. * * @param ch the character to be tested. * @return a value of type {@code int} representing the * character's general category. * @see Character#COMBINING_SPACING_MARK * @see Character#CONNECTOR_PUNCTUATION * @see Character#CONTROL * @see Character#CURRENCY_SYMBOL * @see Character#DASH_PUNCTUATION * @see Character#DECIMAL_DIGIT_NUMBER * @see Character#ENCLOSING_MARK * @see Character#END_PUNCTUATION * @see Character#FINAL_QUOTE_PUNCTUATION * @see Character#FORMAT * @see Character#INITIAL_QUOTE_PUNCTUATION * @see Character#LETTER_NUMBER * @see Character#LINE_SEPARATOR * @see Character#LOWERCASE_LETTER * @see Character#MATH_SYMBOL * @see Character#MODIFIER_LETTER * @see Character#MODIFIER_SYMBOL * @see Character#NON_SPACING_MARK * @see Character#OTHER_LETTER * @see Character#OTHER_NUMBER * @see Character#OTHER_PUNCTUATION * @see Character#OTHER_SYMBOL * @see Character#PARAGRAPH_SEPARATOR * @see Character#PRIVATE_USE * @see Character#SPACE_SEPARATOR * @see Character#START_PUNCTUATION * @see Character#SURROGATE * @see Character#TITLECASE_LETTER * @see Character#UNASSIGNED * @see Character#UPPERCASE_LETTER * @since 1.1 */ public static int getType(char ch) { return getType((int)ch); } /** * Returns a value indicating a character's general category. * * @param codePoint the character (Unicode code point) to be tested. * @return a value of type {@code int} representing the * character's general category. * @see Character#COMBINING_SPACING_MARK COMBINING_SPACING_MARK * @see Character#CONNECTOR_PUNCTUATION CONNECTOR_PUNCTUATION * @see Character#CONTROL CONTROL * @see Character#CURRENCY_SYMBOL CURRENCY_SYMBOL * @see Character#DASH_PUNCTUATION DASH_PUNCTUATION * @see Character#DECIMAL_DIGIT_NUMBER DECIMAL_DIGIT_NUMBER * @see Character#ENCLOSING_MARK ENCLOSING_MARK * @see Character#END_PUNCTUATION END_PUNCTUATION * @see Character#FINAL_QUOTE_PUNCTUATION FINAL_QUOTE_PUNCTUATION * @see Character#FORMAT FORMAT * @see Character#INITIAL_QUOTE_PUNCTUATION INITIAL_QUOTE_PUNCTUATION * @see Character#LETTER_NUMBER LETTER_NUMBER * @see Character#LINE_SEPARATOR LINE_SEPARATOR * @see Character#LOWERCASE_LETTER LOWERCASE_LETTER * @see Character#MATH_SYMBOL MATH_SYMBOL * @see Character#MODIFIER_LETTER MODIFIER_LETTER * @see Character#MODIFIER_SYMBOL MODIFIER_SYMBOL * @see Character#NON_SPACING_MARK NON_SPACING_MARK * @see Character#OTHER_LETTER OTHER_LETTER * @see Character#OTHER_NUMBER OTHER_NUMBER * @see Character#OTHER_PUNCTUATION OTHER_PUNCTUATION * @see Character#OTHER_SYMBOL OTHER_SYMBOL * @see Character#PARAGRAPH_SEPARATOR PARAGRAPH_SEPARATOR * @see Character#PRIVATE_USE PRIVATE_USE * @see Character#SPACE_SEPARATOR SPACE_SEPARATOR * @see Character#START_PUNCTUATION START_PUNCTUATION * @see Character#SURROGATE SURROGATE * @see Character#TITLECASE_LETTER TITLECASE_LETTER * @see Character#UNASSIGNED UNASSIGNED * @see Character#UPPERCASE_LETTER UPPERCASE_LETTER * @since 1.5 */ public static int getType(int codePoint) { return CharacterData.of(codePoint).getType(codePoint); } /** * Determines the character representation for a specific digit in * the specified radix. If the value of {@code radix} is not a * valid radix, or the value of {@code digit} is not a valid * digit in the specified radix, the null character * ({@code '\u005Cu0000'}) is returned. * <p> * The {@code radix} argument is valid if it is greater than or * equal to {@code MIN_RADIX} and less than or equal to * {@code MAX_RADIX}. The {@code digit} argument is valid if * {@code 0 <= digit < radix}. * <p> * If the digit is less than 10, then * {@code '0' + digit} is returned. Otherwise, the value * {@code 'a' + digit - 10} is returned. * * @param digit the number to convert to a character. * @param radix the radix. * @return the {@code char} representation of the specified digit * in the specified radix. * @see Character#MIN_RADIX * @see Character#MAX_RADIX * @see Character#digit(char, int) */ public static char forDigit(int digit, int radix) { if ((digit >= radix) || (digit < 0)) { return '\0'; } if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) { return '\0'; } if (digit < 10) { return (char)('0' + digit); } return (char)('a' - 10 + digit); } /** * Returns the Unicode directionality property for the given * character. Character directionality is used to calculate the * visual ordering of text. The directionality value of undefined * {@code char} values is {@code DIRECTIONALITY_UNDEFINED}. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #getDirectionality(int)} method. * * @param ch {@code char} for which the directionality property * is requested. * @return the directionality property of the {@code char} value. * * @see Character#DIRECTIONALITY_UNDEFINED * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC * @see Character#DIRECTIONALITY_EUROPEAN_NUMBER * @see Character#DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR * @see Character#DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR * @see Character#DIRECTIONALITY_ARABIC_NUMBER * @see Character#DIRECTIONALITY_COMMON_NUMBER_SEPARATOR * @see Character#DIRECTIONALITY_NONSPACING_MARK * @see Character#DIRECTIONALITY_BOUNDARY_NEUTRAL * @see Character#DIRECTIONALITY_PARAGRAPH_SEPARATOR * @see Character#DIRECTIONALITY_SEGMENT_SEPARATOR * @see Character#DIRECTIONALITY_WHITESPACE * @see Character#DIRECTIONALITY_OTHER_NEUTRALS * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE * @see Character#DIRECTIONALITY_POP_DIRECTIONAL_FORMAT * @since 1.4 */ public static byte getDirectionality(char ch) { return getDirectionality((int)ch); } /** * Returns the Unicode directionality property for the given * character (Unicode code point). Character directionality is * used to calculate the visual ordering of text. The * directionality value of undefined character is {@link * #DIRECTIONALITY_UNDEFINED}. * * @param codePoint the character (Unicode code point) for which * the directionality property is requested. * @return the directionality property of the character. * * @see Character#DIRECTIONALITY_UNDEFINED DIRECTIONALITY_UNDEFINED * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT DIRECTIONALITY_LEFT_TO_RIGHT * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT DIRECTIONALITY_RIGHT_TO_LEFT * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC * @see Character#DIRECTIONALITY_EUROPEAN_NUMBER DIRECTIONALITY_EUROPEAN_NUMBER * @see Character#DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR * @see Character#DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR * @see Character#DIRECTIONALITY_ARABIC_NUMBER DIRECTIONALITY_ARABIC_NUMBER * @see Character#DIRECTIONALITY_COMMON_NUMBER_SEPARATOR DIRECTIONALITY_COMMON_NUMBER_SEPARATOR * @see Character#DIRECTIONALITY_NONSPACING_MARK DIRECTIONALITY_NONSPACING_MARK * @see Character#DIRECTIONALITY_BOUNDARY_NEUTRAL DIRECTIONALITY_BOUNDARY_NEUTRAL * @see Character#DIRECTIONALITY_PARAGRAPH_SEPARATOR DIRECTIONALITY_PARAGRAPH_SEPARATOR * @see Character#DIRECTIONALITY_SEGMENT_SEPARATOR DIRECTIONALITY_SEGMENT_SEPARATOR * @see Character#DIRECTIONALITY_WHITESPACE DIRECTIONALITY_WHITESPACE * @see Character#DIRECTIONALITY_OTHER_NEUTRALS DIRECTIONALITY_OTHER_NEUTRALS * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING * @see Character#DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE * @see Character#DIRECTIONALITY_POP_DIRECTIONAL_FORMAT DIRECTIONALITY_POP_DIRECTIONAL_FORMAT * @since 1.5 */ public static byte getDirectionality(int codePoint) { return CharacterData.of(codePoint).getDirectionality(codePoint); } /** * Determines whether the character is mirrored according to the * Unicode specification. Mirrored characters should have their * glyphs horizontally mirrored when displayed in text that is * right-to-left. For example, {@code '\u005Cu0028'} LEFT * PARENTHESIS is semantically defined to be an <i>opening * parenthesis</i>. This will appear as a "(" in text that is * left-to-right but as a ")" in text that is right-to-left. * * <p><b>Note:</b> This method cannot handle <a * href="#supplementary"> supplementary characters</a>. To support * all Unicode characters, including supplementary characters, use * the {@link #isMirrored(int)} method. * * @param ch {@code char} for which the mirrored property is requested * @return {@code true} if the char is mirrored, {@code false} * if the {@code char} is not mirrored or is not defined. * @since 1.4 */ public static boolean isMirrored(char ch) { return isMirrored((int)ch); } /** * Determines whether the specified character (Unicode code point) * is mirrored according to the Unicode specification. Mirrored * characters should have their glyphs horizontally mirrored when * displayed in text that is right-to-left. For example, * {@code '\u005Cu0028'} LEFT PARENTHESIS is semantically * defined to be an <i>opening parenthesis</i>. This will appear * as a "(" in text that is left-to-right but as a ")" in text * that is right-to-left. * * @param codePoint the character (Unicode code point) to be tested. * @return {@code true} if the character is mirrored, {@code false} * if the character is not mirrored or is not defined. * @since 1.5 */ public static boolean isMirrored(int codePoint) { return CharacterData.of(codePoint).isMirrored(codePoint); } /** * Compares two {@code Character} objects numerically. * * @param anotherCharacter the {@code Character} to be compared. * @return the value {@code 0} if the argument {@code Character} * is equal to this {@code Character}; a value less than * {@code 0} if this {@code Character} is numerically less * than the {@code Character} argument; and a value greater than * {@code 0} if this {@code Character} is numerically greater * than the {@code Character} argument (unsigned comparison). * Note that this is strictly a numerical comparison; it is not * locale-dependent. * @since 1.2 */ public int compareTo(Character anotherCharacter) { return compare(this.value, anotherCharacter.value); } /** * Compares two {@code char} values numerically. * The value returned is identical to what would be returned by: * <pre> * Character.valueOf(x).compareTo(Character.valueOf(y)) * </pre> * * @param x the first {@code char} to compare * @param y the second {@code char} to compare * @return the value {@code 0} if {@code x == y}; * a value less than {@code 0} if {@code x < y}; and * a value greater than {@code 0} if {@code x > y} * @since 1.7 */ public static int compare(char x, char y) { return x - y; } /** * Converts the character (Unicode code point) argument to uppercase using * information from the UnicodeData file. * <p> * * @param codePoint the character (Unicode code point) to be converted. * @return either the uppercase equivalent of the character, if * any, or an error flag ({@code Character.ERROR}) * that indicates that a 1:M {@code char} mapping exists. * @see Character#isLowerCase(char) * @see Character#isUpperCase(char) * @see Character#toLowerCase(char) * @see Character#toTitleCase(char) * @since 1.4 */ static int toUpperCaseEx(int codePoint) { assert isValidCodePoint(codePoint); return CharacterData.of(codePoint).toUpperCaseEx(codePoint); } /** * Converts the character (Unicode code point) argument to uppercase using case * mapping information from the SpecialCasing file in the Unicode * specification. If a character has no explicit uppercase * mapping, then the {@code char} itself is returned in the * {@code char[]}. * * @param codePoint the character (Unicode code point) to be converted. * @return a {@code char[]} with the uppercased character. * @since 1.4 */ static char[] toUpperCaseCharArray(int codePoint) { // As of Unicode 6.0, 1:M uppercasings only happen in the BMP. assert isBmpCodePoint(codePoint); return CharacterData.of(codePoint).toUpperCaseCharArray(codePoint); } /** * The number of bits used to represent a <tt>char</tt> value in unsigned * binary form, constant {@code 16}. * * @since 1.5 */ public static final int SIZE = 16; /** * The number of bytes used to represent a {@code char} value in unsigned * binary form. * * @since 1.8 */ public static final int BYTES = SIZE / Byte.SIZE; /** * Returns the value obtained by reversing the order of the bytes in the * specified <tt>char</tt> value. * * @param ch The {@code char} of which to reverse the byte order. * @return the value obtained by reversing (or, equivalently, swapping) * the bytes in the specified <tt>char</tt> value. * @since 1.5 */ public static char reverseBytes(char ch) { return (char) (((ch & 0xFF00) >> 8) | (ch << 8)); } /** * Returns the Unicode name of the specified character * {@code codePoint}, or null if the code point is * {@link #UNASSIGNED unassigned}. * <p> * Note: if the specified character is not assigned a name by * the <i>UnicodeData</i> file (part of the Unicode Character * Database maintained by the Unicode Consortium), the returned * name is the same as the result of expression. * * <blockquote>{@code * Character.UnicodeBlock.of(codePoint).toString().replace('_', ' ') * + " " * + Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH); * * }</blockquote> * * @param codePoint the character (Unicode code point) * * @return the Unicode name of the specified character, or null if * the code point is unassigned. * * @exception IllegalArgumentException if the specified * {@code codePoint} is not a valid Unicode * code point. * * @since 1.7 */ public static String getName(int codePoint) { if (!isValidCodePoint(codePoint)) { throw new IllegalArgumentException(); } String name = CharacterName.get(codePoint); if (name != null) return name; if (getType(codePoint) == UNASSIGNED) return null; UnicodeBlock block = UnicodeBlock.of(codePoint); if (block != null) return block.toString().replace('_', ' ') + " " + Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH); // should never come here return Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH); } }
dragonwell-project/dragonwell8
jdk/src/share/classes/java/lang/Character.java
2,325
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.psi.impl.source; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.NotNullLazyKey; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.Strings; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.JavaPsiImplementationHelper; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.psi.impl.PsiFileEx; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.java.stubs.JavaStubElementTypes; import com.intellij.psi.impl.java.stubs.PsiJavaFileStub; import com.intellij.psi.impl.source.resolve.ClassResolverProcessor; import com.intellij.psi.impl.source.resolve.SymbolCollectingProcessor; import com.intellij.psi.impl.source.resolve.SymbolCollectingProcessor.ResultWithContext; import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.scope.*; import com.intellij.psi.scope.processor.MethodsProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.*; import com.intellij.psi.util.CachedValueProvider.Result; import com.intellij.util.FileContentUtilCore; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.containers.MostlySingularMultiMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.execution.ParametersListUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public abstract class PsiJavaFileBaseImpl extends PsiFileImpl implements PsiJavaFile { private static final Logger LOG = Logger.getInstance(PsiJavaFileBaseImpl.class); private static final String[] IMPLICIT_IMPORTS = { CommonClassNames.DEFAULT_PACKAGE }; private final CachedValue<MostlySingularMultiMap<String, ResultWithContext>> myResolveCache; private final CachedValue<Map<String, Iterable<ResultWithContext>>> myCachedDeclarations; private volatile String myPackageName; protected PsiJavaFileBaseImpl(@NotNull IElementType elementType, @NotNull IElementType contentElementType, @NotNull FileViewProvider viewProvider) { super(elementType, contentElementType, viewProvider); CachedValuesManager cachedValuesManager = CachedValuesManager.getManager(myManager.getProject()); myResolveCache = cachedValuesManager.createCachedValue(new MyCacheBuilder(this), false); myCachedDeclarations = cachedValuesManager.createCachedValue(() -> { Map<String, Iterable<ResultWithContext>> declarations = findEnumeratedDeclarations(); if (!this.isPhysical()) { return Result.create(declarations, this.getContainingFile(), PsiModificationTracker.MODIFICATION_COUNT); } return Result.create(declarations, PsiModificationTracker.MODIFICATION_COUNT); }, false); } @Override public void subtreeChanged() { super.subtreeChanged(); myPackageName = null; } @Override public PsiClass @NotNull [] getClasses() { return withGreenStubOrAst( stub -> stub.getChildrenByType(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY), ast -> ast.getChildrenAsPsiElements(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY) ); } @Override public PsiPackageStatement getPackageStatement() { ASTNode node = calcTreeElement().findChildByType(JavaElementType.PACKAGE_STATEMENT); return node != null ? (PsiPackageStatement)node.getPsi() : null; } @Override public @NotNull String getPackageName() { return withGreenStubOrAst( PsiJavaFileStub.class, stub -> stub.getPackageName(), ast -> { String name = myPackageName; if (name == null) { PsiPackageStatement statement = getPackageStatement(); myPackageName = name = statement == null ? "" : statement.getPackageName(); } return name; } ); } @Override public void setPackageName(@NotNull String packageName) throws IncorrectOperationException { if (PsiUtil.isModuleFile(this)) { throw new IncorrectOperationException("Cannot set package name for module declarations"); } PsiPackageStatement packageStatement = getPackageStatement(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(getProject()); if (packageStatement != null) { if (!packageName.isEmpty()) { PsiJavaCodeReferenceElement reference = packageStatement.getPackageReference(); reference.replace(factory.createPackageStatement(packageName).getPackageReference()); } else { packageStatement.delete(); } } else if (!packageName.isEmpty()) { cleanupBrokenPackageKeyword(); PsiElement anchor = getFirstChild(); if (PsiPackage.PACKAGE_INFO_FILE.equals(getName())) { // If javadoc is already present in a package-info.java file, try to position the new package statement after it, // so the package becomes documented. anchor = getImportList(); assert anchor != null; // import list always available inside package-info.java PsiElement prev = anchor.getPrevSibling(); if (prev instanceof PsiComment) { String text = prev.getText().trim(); if (text.startsWith("/*") && !text.endsWith("*/")) { // close any open javadoc/comments before the import list prev.replace(factory.createCommentFromText(text + (StringUtil.containsLineBreak(text) ? "\n*/" : " */"), prev)); } } } addBefore(factory.createPackageStatement(packageName), anchor); } } private void cleanupBrokenPackageKeyword() { PsiElement child = getFirstChild(); while (child instanceof PsiWhiteSpace || child instanceof PsiComment || child instanceof PsiErrorElement) { if (child instanceof PsiErrorElement && child.getFirstChild() != null && child.getFirstChild().textMatches(PsiKeyword.PACKAGE)) { child.delete(); break; } child = child.getNextSibling(); } } @Override public PsiImportList getImportList() { return withGreenStubOrAst( stub -> { PsiImportList[] nodes = stub.getChildrenByType(JavaStubElementTypes.IMPORT_LIST, PsiImportList.ARRAY_FACTORY); if (nodes.length == 1) return nodes[0]; assert nodes.length == 0; return null; }, ast -> { ASTNode node = ast.findChildByType(JavaElementType.IMPORT_LIST); return (PsiImportList)SourceTreeToPsiMap.treeElementToPsi(node); } ); } @Override public PsiElement @NotNull [] getOnDemandImports(boolean includeImplicit, boolean checkIncludes) { PsiImportList importList = getImportList(); if (importList == null) return EMPTY_ARRAY; List<PsiElement> array = new ArrayList<>(); PsiImportStatement[] statements = importList.getImportStatements(); for (PsiImportStatement statement : statements) { if (statement.isOnDemand()) { PsiElement resolved = statement.resolve(); if (resolved != null) { array.add(resolved); } } } if (includeImplicit){ PsiJavaCodeReferenceElement[] implicitRefs = getImplicitlyImportedPackageReferences(); for (PsiJavaCodeReferenceElement implicitRef : implicitRefs) { PsiElement resolved = implicitRef.resolve(); if (resolved != null) { array.add(resolved); } } } return PsiUtilCore.toPsiElementArray(array); } @Override public PsiClass @NotNull [] getSingleClassImports(boolean checkIncludes) { PsiImportList importList = getImportList(); if (importList == null) return PsiClass.EMPTY_ARRAY; List<PsiClass> array = new ArrayList<>(); PsiImportStatement[] statements = importList.getImportStatements(); for (PsiImportStatement statement : statements) { if (!statement.isOnDemand()) { PsiElement ref = statement.resolve(); if (ref instanceof PsiClass) { array.add((PsiClass)ref); } } } return array.toArray(PsiClass.EMPTY_ARRAY); } @Override public PsiJavaCodeReferenceElement findImportReferenceTo(@NotNull PsiClass aClass) { PsiImportList importList = getImportList(); if (importList != null) { PsiImportStatement[] statements = importList.getImportStatements(); for (PsiImportStatement statement : statements) { if (!statement.isOnDemand()) { PsiElement ref = statement.resolve(); if (ref != null && getManager().areElementsEquivalent(ref, aClass)) { return statement.getImportReference(); } } } } return null; } @Override public String @NotNull [] getImplicitlyImportedPackages() { return IMPLICIT_IMPORTS; } @Override public PsiJavaCodeReferenceElement @NotNull [] getImplicitlyImportedPackageReferences() { return PsiImplUtil.namesToPackageReferences(myManager, IMPLICIT_IMPORTS); } private static class StaticImportFilteringProcessor extends DelegatingScopeProcessor { private final Map<String, Iterable<ResultWithContext>> myExplicitlyEnumerated; private final Collection<PsiElement> myCollectedElements = new HashSet<>(); StaticImportFilteringProcessor(@NotNull Map<String, Iterable<ResultWithContext>> explicitlyEnumerated, @NotNull PsiScopeProcessor delegate) { super(delegate); myExplicitlyEnumerated = explicitlyEnumerated; } @Override public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) { if (element instanceof PsiModifierListOwner && ((PsiModifierListOwner)element).hasModifierProperty(PsiModifier.STATIC)) { PsiScopeProcessor delegate = getDelegate(); if (element instanceof PsiNamedElement) { String name = ((PsiNamedElement)element).getName(); Iterable<ResultWithContext> shadowing = myExplicitlyEnumerated.get(name); if (shadowing != null && ContainerUtil.exists(shadowing, rwc -> hasSameDeclarationKind(element, rwc.getElement()))) return true; if (delegate instanceof MethodsProcessor && element instanceof PsiMethod) { PsiClass containingClass = ((PsiMethod)element).getContainingClass(); if (containingClass != null && containingClass.isInterface()) { PsiElement currentFileContext = ((MethodsProcessor)delegate).getCurrentFileContext(); if (currentFileContext instanceof PsiImportStaticStatement && ((PsiImportStaticStatement)currentFileContext).isOnDemand() && !containingClass.isEquivalentTo(((PsiImportStaticStatement)currentFileContext).resolveTargetClass())) { return true; } } } } if (myCollectedElements.add(element)) { return delegate.execute(element, state); } } return true; } private static boolean hasSameDeclarationKind(PsiElement e1, PsiElement e2) { return e1 instanceof PsiClass ? e2 instanceof PsiClass : e1 instanceof PsiMethod ? e2 instanceof PsiMethod : e2 instanceof PsiField; } } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { NameHint nameHint = processor.getHint(NameHint.KEY); String name = nameHint != null ? nameHint.getName(state) : null; Map<String, Iterable<ResultWithContext>> explicitlyEnumerated = getEnumeratedDeclarations(); //noinspection unchecked Iterable<ResultWithContext> iterable = name != null ? explicitlyEnumerated.get(name) : ContainerUtil.concat(explicitlyEnumerated.values().toArray(new Iterable[0])); if (iterable != null && !ContainerUtil.process(iterable, new MyResolveCacheProcessor(state, processor))) return false; if (processor instanceof ClassResolverProcessor && (getUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING) == Boolean.TRUE || myResolveCache.hasUpToDateValue()) && !PsiUtil.isInsideJavadocComment(place)) { MostlySingularMultiMap<String, ResultWithContext> cache = myResolveCache.getValue(); MyResolveCacheProcessor cacheProcessor = new MyResolveCacheProcessor(state, processor); return name != null ? cache.processForKey(name, cacheProcessor) : cache.processAllValues(cacheProcessor); } return processOnDemandPackages(state, place, processor); } private @NotNull Map<String, Iterable<ResultWithContext>> getEnumeratedDeclarations() { return myCachedDeclarations.getValue(); } private @NotNull Map<String, Iterable<ResultWithContext>> findEnumeratedDeclarations() { MultiMap<String, PsiClass> ownClasses = MultiMap.create(); MultiMap<String, PsiImportStatement> typeImports = MultiMap.create(); MultiMap<String, PsiImportStaticStatement> staticImports = MultiMap.create(); for (PsiClass psiClass : getClasses()) { String name = psiClass.getName(); if (name != null) { ownClasses.putValue(name, psiClass); } } for (PsiImportStatement anImport : getImportStatements()) { if (!anImport.isOnDemand()) { String qName = anImport.getQualifiedName(); if (qName != null) { typeImports.putValue(StringUtil.getShortName(qName), anImport); } } } for (PsiImportStaticStatement staticImport : getImportStaticStatements()) { String name = staticImport.getReferenceName(); if (name != null) { staticImports.putValue(name, staticImport); } } for (PsiImportStaticStatement staticImport : PsiImplUtil.getImplicitStaticImports(this)) { staticImports.putValue(staticImport.getReferenceName(), staticImport); } Map<String, Iterable<ResultWithContext>> result = new LinkedHashMap<>(); for (String name : ContainerUtil.newLinkedHashSet( ContainerUtil.concat(ownClasses.keySet(), typeImports.keySet(), staticImports.keySet()))) { NotNullLazyValue<Iterable<ResultWithContext>> lazy = NotNullLazyValue.volatileLazy(() -> findExplicitDeclarations(name, ownClasses, typeImports, staticImports)); result.put(name, () -> lazy.getValue().iterator()); } return result; } private static @NotNull Iterable<ResultWithContext> findExplicitDeclarations(@NotNull String name, @NotNull MultiMap<String, PsiClass> ownClasses, @NotNull MultiMap<String, PsiImportStatement> typeImports, @NotNull MultiMap<String, PsiImportStaticStatement> staticImports) { List<ResultWithContext> result = new ArrayList<>(); for (PsiClass psiClass : ownClasses.get(name)) { result.add(new ResultWithContext(psiClass, null)); } for (PsiImportStatement statement : typeImports.get(name)) { PsiElement target = statement.resolve(); if (target instanceof PsiClass) { result.add(new ResultWithContext((PsiNamedElement)target, statement)); } } for (PsiImportStaticStatement statement : staticImports.get(name)) { PsiJavaCodeReferenceElement reference = statement.getImportReference(); if (reference != null) { for (JavaResolveResult result1 : reference.multiResolve(false)) { PsiElement element = result1.getElement(); if (element instanceof PsiNamedElement) { result.add(new ResultWithContext((PsiNamedElement)element, statement)); } } } } return JBIterable.from(result).unique(ResultWithContext::getElement); } private boolean processOnDemandPackages(@NotNull ResolveState state, @NotNull PsiElement place, @NotNull PsiScopeProcessor processor) { ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); boolean shouldProcessClasses = classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS); if (shouldProcessClasses && !processCurrentPackage(state, place, processor)) return false; if (!processOnDemandStaticImports(state, new StaticImportFilteringProcessor(getEnumeratedDeclarations(), processor))) { return false; } if (shouldProcessClasses && !processOnDemandTypeImports(state, place, processor)) return false; return !shouldProcessClasses || processImplicitImports(state, place, processor); } private PsiImportStaticStatement @NotNull [] getImportStaticStatements() { return getImportList() != null ? getImportList().getImportStaticStatements() : PsiImportStaticStatement.EMPTY_ARRAY; } private PsiImportStatement @NotNull [] getImportStatements() { return getImportList() != null ? getImportList().getImportStatements() : PsiImportStatement.EMPTY_ARRAY; } private boolean processCurrentPackage(@NotNull ResolveState state, @NotNull PsiElement place, @NotNull PsiScopeProcessor processor) { processor.handleEvent(JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT, null); PsiPackage aPackage = JavaPsiFacade.getInstance(myManager.getProject()).findPackage(getPackageName()); return aPackage == null || processPackageDeclarations(state, place, aPackage, processor); } private boolean processOnDemandTypeImports(@NotNull ResolveState state, @NotNull PsiElement place, @NotNull PsiScopeProcessor processor) { for (PsiImportStatement statement : getImportStatements()) { if (statement.isOnDemand()) { PsiElement resolved = statement.resolve(); if (resolved != null) { processor.handleEvent(JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT, statement); if (!processOnDemandTarget(resolved, state, place, processor)) return false; } } } return true; } private boolean processOnDemandStaticImports(@NotNull ResolveState state, @NotNull StaticImportFilteringProcessor processor) { for (PsiImportStaticStatement importStaticStatement : getImportStaticStatements()) { if (!importStaticStatement.isOnDemand()) continue; PsiClass targetElement = importStaticStatement.resolveTargetClass(); if (targetElement != null) { processor.handleEvent(JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT, importStaticStatement); if (!PsiClassImplUtil.processAllMembersWithoutSubstitutors(targetElement, processor, state)) return false; } } return true; } private boolean processImplicitImports(@NotNull ResolveState state, @NotNull PsiElement place, @NotNull PsiScopeProcessor processor) { processor.handleEvent(JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT, null); for (PsiJavaCodeReferenceElement aImplicitlyImported : getImplicitlyImportedPackageReferences()) { PsiElement resolved = aImplicitlyImported.resolve(); if (resolved != null) { if (!processOnDemandTarget(resolved, state, place, processor)) return false; } } return true; } private static boolean processPackageDeclarations(@NotNull ResolveState state, @NotNull PsiElement place, @NotNull PsiPackage aPackage, @NotNull PsiScopeProcessor processor) { if (!aPackage.getQualifiedName().isEmpty()) { processor = new DelegatingScopeProcessor(processor) { @Override public @Nullable <T> T getHint(@NotNull Key<T> hintKey) { if (hintKey == ElementClassHint.KEY) { //noinspection unchecked return (T)(ElementClassHint)kind -> kind == ElementClassHint.DeclarationKind.CLASS; } return super.getHint(hintKey); } }; } return aPackage.processDeclarations(processor, state, null, place); } private static @NotNull PsiSubstitutor createRawSubstitutor(@NotNull PsiClass containingClass) { return JavaPsiFacade.getElementFactory(containingClass.getProject()).createRawSubstitutor(containingClass); } private static boolean processOnDemandTarget(@NotNull PsiElement target, @NotNull ResolveState substitutor, @NotNull PsiElement place, @NotNull PsiScopeProcessor processor) { if (target instanceof PsiPackage) { return processPackageDeclarations(substitutor, place, (PsiPackage)target, processor); } if (target instanceof PsiClass) { PsiClass[] inners = ((PsiClass)target).getInnerClasses(); if (((PsiClass)target).hasTypeParameters()) { substitutor = substitutor.put(PsiSubstitutor.KEY, createRawSubstitutor((PsiClass)target)); } for (PsiClass inner : inners) { if (!processor.execute(inner, substitutor)) return false; } } else { LOG.error("Unexpected target type: " + target); } return true; } @Override public void accept(@NotNull PsiElementVisitor visitor){ if (visitor instanceof JavaElementVisitor) { ((JavaElementVisitor)visitor).visitJavaFile(this); } else { visitor.visitFile(this); } } @Override public @NotNull Language getLanguage() { return JavaLanguage.INSTANCE; } @Override public boolean importClass(@NotNull PsiClass aClass) { return JavaCodeStyleManager.getInstance(getProject()).addImport(this, aClass); } private static final NotNullLazyKey<LanguageLevel, PsiJavaFileBaseImpl> LANGUAGE_LEVEL_KEY = NotNullLazyKey.createLazyKey("LANGUAGE_LEVEL", file -> file.getLanguageLevelInner()); @Override public @NotNull LanguageLevel getLanguageLevel() { return LANGUAGE_LEVEL_KEY.getValue(this); } @Override public @Nullable PsiJavaModule getModuleDeclaration() { return null; } @Override public void clearCaches() { super.clearCaches(); putUserData(LANGUAGE_LEVEL_KEY, null); } @Override public void setOriginalFile(@NotNull PsiFile originalFile) { super.setOriginalFile(originalFile); clearCaches(); } private static final Key<String> SHEBANG_SOURCE_LEVEL = Key.create("SHEBANG_SOURCE_LEVEL"); private @NotNull LanguageLevel getLanguageLevelInner() { if (myOriginalFile instanceof PsiJavaFile) { return ((PsiJavaFile)myOriginalFile).getLanguageLevel(); } LanguageLevel forcedLanguageLevel = getUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY); if (forcedLanguageLevel != null) return forcedLanguageLevel; VirtualFile virtualFile = getVirtualFile(); if (virtualFile == null) virtualFile = getViewProvider().getVirtualFile(); String sourceLevel = null; try { CharSequence contents = getViewProvider().getContents(); int lineBound = Strings.indexOf(contents, "\n"); CharSequence line = lineBound > 0 ? contents.subSequence(0, lineBound) : contents; if (Strings.startsWith(line, 0,"#!")) { List<String> params = ParametersListUtil.parse(line.toString()); int srcIdx = params.indexOf("--source"); if (srcIdx > 0 && srcIdx + 1 < params.size()) { sourceLevel = params.get(srcIdx + 1); LanguageLevel sheBangLevel = LanguageLevel.parse(sourceLevel); if (sheBangLevel != null) { return sheBangLevel; } } } } catch (Throwable ignored) { } finally { if (!Objects.equals(sourceLevel, virtualFile.getUserData(SHEBANG_SOURCE_LEVEL)) && virtualFile.isInLocalFileSystem()) { virtualFile.putUserData(SHEBANG_SOURCE_LEVEL, sourceLevel); VirtualFile file = virtualFile; ApplicationManager.getApplication().invokeLater(() -> FileContentUtilCore.reparseFiles(file), ModalityState.nonModal(), ApplicationManager.getApplication().getDisposed()); } } return JavaPsiImplementationHelper.getInstance(getProject()).getEffectiveLanguageLevel(virtualFile); } private static class MyCacheBuilder implements CachedValueProvider<MostlySingularMultiMap<String, ResultWithContext>> { private final @NotNull PsiJavaFileBaseImpl myFile; MyCacheBuilder(@NotNull PsiJavaFileBaseImpl file) { myFile = file; } @Override public @NotNull Result<MostlySingularMultiMap<String, ResultWithContext>> compute() { SymbolCollectingProcessor p = new SymbolCollectingProcessor(); myFile.processOnDemandPackages(ResolveState.initial(), myFile, p); MostlySingularMultiMap<String, ResultWithContext> results = p.getResults(); return Result.create(results, PsiModificationTracker.MODIFICATION_COUNT, myFile); } } private static class MyResolveCacheProcessor implements Processor<ResultWithContext> { private final PsiScopeProcessor myProcessor; private final ResolveState myState; MyResolveCacheProcessor(@NotNull ResolveState state, @NotNull PsiScopeProcessor processor) { myProcessor = processor; myState = state; } @Override public boolean process(@NotNull ResultWithContext result) { PsiElement context = result.getFileContext(); myProcessor.handleEvent(JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT, context); PsiNamedElement element = result.getElement(); if (element instanceof PsiClass && context instanceof PsiImportStatement) { PsiClass containingClass = ((PsiClass)element).getContainingClass(); if (containingClass != null && containingClass.hasTypeParameters()) { return myProcessor.execute(element, myState.put(PsiSubstitutor.KEY, createRawSubstitutor(containingClass))); } } return myProcessor.execute(element, myState); } } }
JetBrains/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java
2,326
package Facade; // Kara liste ile ilgili işlemlerin yapıldığı sınıf public class BlackListService { public Boolean checkEmployeeIsTheBlackList(Customer customer) { // Müşterinin kara listede olup olmadığının kontrolünün yapıldığı yer. // Kara listede ise false, değilse true dönmekte olduğunu var sayalım. // Burada veri tabanı kodları ya da harici bir servis ile iletişim sağlanabilir. // Default olarak true döndürdük. return true; } }
yusufyilmazfr/tasarim-desenleri-turkce-kaynak
facade/java/BlackListService.java
2,327
package com.fishercoder.solutions; public class _1861 { public static class Solution1 { public char[][] rotateTheBox(char[][] box) { int m = box.length; int n = box[0].length; for (int i = 0; i < m; i++) { for (int j = n - 1; j >= 0; j--) { if (box[i][j] == '#') { int empty = j + 1; while (empty < n && box[i][empty] == '.') { empty++; } if (empty < n && box[i][empty] == '.') { box[i][empty] = '#'; box[i][j] = '.'; } else if (empty - 1 < n && box[i][empty - 1] == '.') { box[i][empty - 1] = '#'; box[i][j] = '.'; } } } } char[][] result = new char[n][m]; int k = m - 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { result[j][k] = box[i][j]; } k--; } return result; } } }
fishercoder1534/Leetcode
src/main/java/com/fishercoder/solutions/_1861.java
2,328
package io.quarkus.cli.image; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import io.quarkus.cli.BuildToolContext; import picocli.CommandLine; @CommandLine.Command(name = "jib", sortOptions = false, showDefaultValues = true, mixinStandardHelpOptions = false, header = "Build a container image using Jib.", description = "%n" + "This command will build or push a container image for the project, using Jib.", footer = "%n" + "For example (using default values), it will create a container image using with REPOSITORY='${user.name}/<project.artifactId>' and TAG='<project.version>'.", headerHeading = "%n", commandListHeading = "%nCommands:%n", synopsisHeading = "%nUsage: ", parameterListHeading = "%n", optionListHeading = "Options:%n") public class Jib extends BaseImageSubCommand { private static final String JIB = "jib"; private static final String JIB_CONFIG_PREFIX = "quarkus.jib."; private static final String BASE_JVM_IMAGE = "base-jvm-image"; private static final String JVM_ARGUMENTS = "jvm-arguments"; private static final String JVM_ENTRYPOINT = "jvm-entrypoint"; private static final String BASE_NATIVE_IMAGE = "base-native-image"; private static final String NATIVE_ARGUMENTS = "native-arguments"; private static final String NATIVE_ENTRYPOINT = "native-entrypoint"; private static final String LABELS = "labels."; private static final String ENV_VARS = "environment-varialbes."; private static final String PORTS = "ports"; private static final String PLATFORMS = "platforms"; private static final String IMAGE_DIGEST_FILE = "image-digest-file"; private static final String IMAGE_ID_FILE = "image-id-file"; private static final String OFFLINE_MODE = "offline-mode"; private static final String USER = "user"; @CommandLine.Option(order = 7, names = { "--base-image" }, description = "The base image to use.") public Optional<String> baseImage; @CommandLine.Option(order = 8, names = { "--arg" }, description = "Additional argument to pass when starting the application.") public List<String> arguments = new ArrayList<>(); @CommandLine.Option(order = 9, names = { "--entrypoint" }, description = "The entrypoint of the container image.") public List<String> entrypoint = new ArrayList<>(); @CommandLine.Option(order = 10, names = { "--env" }, description = "Environment variables to add to the container image.") public Map<String, String> environmentVariables = new HashMap<>(); @CommandLine.Option(order = 11, names = { "--label" }, description = "Custom labels to add to the generated image.") public Map<String, String> labels = new HashMap<>(); @CommandLine.Option(order = 12, names = { "--port" }, description = "The ports to expose.") public List<Integer> ports = new ArrayList<>(); @CommandLine.Option(order = 13, names = { "--user" }, description = "The user in the generated image.") public String user; @CommandLine.Option(order = 14, names = { "--always-cache-base-image" }, description = "Controls the optimization which skips downloading base image layers that exist in a target registry.") public boolean alwaysCacheBaseImage; @CommandLine.Option(order = 15, names = { "--platform" }, description = "The target platforms defined using the pattern <os>[/arch][/variant]|<os>/<arch>[/variant]") public Set<String> platforms = new HashSet<>(); @CommandLine.Option(order = 16, names = { "--image-digest-file" }, description = "The path of a file that will be written containing the digest of the generated image.") public String imageDigestFile; @CommandLine.Option(order = 17, names = { "--image-id-file" }, description = "The path of a file that will be written containing the id of the generated image.") public String imageIdFile; @Override public void populateContext(BuildToolContext context) { super.populateContext(context); Map<String, String> properties = context.getPropertiesOptions().properties; properties.put(QUARKUS_CONTAINER_IMAGE_BUILDER, JIB); baseImage.ifPresent( d -> properties.put( JIB_CONFIG_PREFIX + (context.getBuildOptions().buildNative ? BASE_NATIVE_IMAGE : BASE_JVM_IMAGE), d)); if (!arguments.isEmpty()) { String joinedArgs = arguments.stream().collect(Collectors.joining(",")); properties.put(JIB_CONFIG_PREFIX + (context.getBuildOptions().buildNative ? NATIVE_ARGUMENTS : JVM_ARGUMENTS), joinedArgs); } if (!entrypoint.isEmpty()) { String joinedEntrypoint = entrypoint.stream().collect(Collectors.joining(",")); properties.put(JIB_CONFIG_PREFIX + (context.getBuildOptions().buildNative ? NATIVE_ENTRYPOINT : JVM_ENTRYPOINT), joinedEntrypoint); } if (!environmentVariables.isEmpty()) { environmentVariables.forEach((key, value) -> { properties.put(JIB_CONFIG_PREFIX + ENV_VARS + key, value); }); } if (!labels.isEmpty()) { labels.forEach((key, value) -> { properties.put(JIB_CONFIG_PREFIX + LABELS + key, value); }); } if (!ports.isEmpty()) { String joinedPorts = ports.stream().map(String::valueOf).collect(Collectors.joining(",")); properties.put(JIB_CONFIG_PREFIX + PORTS, joinedPorts); } if (!platforms.isEmpty()) { String joinedPlatforms = platforms.stream().collect(Collectors.joining(",")); properties.put(JIB_CONFIG_PREFIX + PLATFORMS, joinedPlatforms); } if (user != null && !user.isEmpty()) { properties.put(JIB_CONFIG_PREFIX + USER, user); } if (imageDigestFile != null && !imageDigestFile.isEmpty()) { properties.put(JIB_CONFIG_PREFIX + IMAGE_DIGEST_FILE, imageDigestFile); } if (imageIdFile != null && !imageIdFile.isEmpty()) { properties.put(JIB_CONFIG_PREFIX + IMAGE_ID_FILE, imageIdFile); } if (context.getBuildOptions().offline) { properties.put(JIB_CONFIG_PREFIX + OFFLINE_MODE, "true"); } context.getForcedExtensions().add(QUARKUS_CONTAINER_IMAGE_EXTENSION_KEY_PREFIX + JIB); } @Override public String toString() { return "Jib {imageOptions='" + imageOptions + "', baseImage:'" + baseImage.orElse("<none>") + "'}"; } }
quarkusio/quarkus
devtools/cli/src/main/java/io/quarkus/cli/image/Jib.java
2,329
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Components; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Animatable; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.util.Log; import android.view.View; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimatedFileDrawableStream; import org.telegram.messenger.BuildVars; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.DispatchQueuePoolBackground; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.utils.BitmapsCache; import org.telegram.tgnet.TLRPC; import java.io.File; import java.util.ArrayList; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class AnimatedFileDrawable extends BitmapDrawable implements Animatable, BitmapsCache.Cacheable { public boolean skipFrameUpdate; public long currentTime; // canvas.drawPath lead to glitches // clipPath not use antialias private final boolean USE_BITMAP_SHADER = Build.VERSION.SDK_INT < 29; private boolean PRERENDER_FRAME = true; private static native long createDecoder(String src, int[] params, int account, long streamFileSize, Object readCallback, boolean preview); private static native void destroyDecoder(long ptr); private static native void stopDecoder(long ptr); private static native int getVideoFrame(long ptr, Bitmap bitmap, int[] params, int stride, boolean preview, float startTimeSeconds, float endTimeSeconds, boolean loop); private static native void seekToMs(long ptr, long ms, boolean precise); private static native int getFrameAtTime(long ptr, long ms, Bitmap bitmap, int[] data, int stride); private static native void prepareToSeek(long ptr); private static native void getVideoInfo(int sdkVersion, String src, int[] params); public final static int PARAM_NUM_SUPPORTED_VIDEO_CODEC = 0; public final static int PARAM_NUM_WIDTH = 1; public final static int PARAM_NUM_HEIGHT = 2; public final static int PARAM_NUM_BITRATE = 3; public final static int PARAM_NUM_DURATION = 4; public final static int PARAM_NUM_AUDIO_FRAME_SIZE = 5; public final static int PARAM_NUM_VIDEO_FRAME_SIZE = 6; public final static int PARAM_NUM_FRAMERATE = 7; public final static int PARAM_NUM_ROTATION = 8; public final static int PARAM_NUM_SUPPORTED_AUDIO_CODEC = 9; public final static int PARAM_NUM_HAS_AUDIO = 10; public final static int PARAM_NUM_COUNT = 11; private long lastFrameTime; private int lastTimeStamp; private int invalidateAfter = 50; private final int[] metaData = new int[6]; private Runnable loadFrameTask; private Bitmap renderingBitmap; private int renderingBitmapTime; private Bitmap nextRenderingBitmap; private Bitmap nextRenderingBitmap2; private int nextRenderingBitmapTime; private int nextRenderingBitmapTime2; private Bitmap backgroundBitmap; private int backgroundBitmapTime; private boolean destroyWhenDone; private boolean decoderCreated; private boolean decodeSingleFrame; private boolean singleFrameDecoded; private boolean forceDecodeAfterNextFrame; private File path; private long streamFileSize; private int streamLoadingPriority; private int currentAccount; private boolean recycleWithSecond; private volatile long pendingSeekTo = -1; private volatile long pendingSeekToUI = -1; private boolean pendingRemoveLoading; private int pendingRemoveLoadingFramesReset; private boolean isRestarted; private final Object sync = new Object(); private boolean invalidateParentViewWithSecond; public boolean ignoreNoParent; private long lastFrameDecodeTime; private RectF actualDrawRect = new RectF(); private BitmapShader[] renderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private BitmapShader[] nextRenderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private BitmapShader[] nextRenderingShader2 = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private BitmapShader[] backgroundShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; ArrayList<Bitmap> unusedBitmaps = new ArrayList<>(); private BitmapShader renderingShaderBackgroundDraw; private int[] roundRadius = new int[4]; private int[] roundRadiusBackup; private Matrix[] shaderMatrix = new Matrix[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Path[] roundPath = new Path[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private static float[] radii = new float[8]; private Matrix shaderMatrixBackgroundDraw; private float scaleX = 1.0f; private float scaleY = 1.0f; private boolean applyTransformation; private final RectF dstRect = new RectF(); private volatile boolean isRunning; private volatile boolean isRecycled; public volatile long nativePtr; private boolean ptrFail; private DispatchQueue decodeQueue; private float startTime; private float endTime; private int renderingHeight; private int renderingWidth; private boolean precache; private float scaleFactor = 1f; public boolean isWebmSticker; private final TLRPC.Document document; private RectF[] dstRectBackground = new RectF[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Paint[] backgroundPaint = new Paint[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Matrix[] shaderMatrixBackground = new Matrix[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Path[] roundPathBackground = new Path[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private View parentView; private ArrayList<View> secondParentViews = new ArrayList<>(); private ArrayList<ImageReceiver> parents = new ArrayList<>(); private AnimatedFileDrawableStream stream; private boolean useSharedQueue; private boolean invalidatePath = true; private boolean invalidateTaskIsRunning; private boolean limitFps; public int repeatCount; BitmapsCache bitmapsCache; BitmapsCache.Metadata cacheMetadata; private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(8, new ThreadPoolExecutor.DiscardPolicy()); private Runnable uiRunnableNoFrame = new Runnable() { @Override public void run() { chekDestroyDecoder(); loadFrameTask = null; scheduleNextGetFrame(); invalidateInternal(); } }; boolean generatingCache; Runnable cacheGenRunnable; private Runnable uiRunnableGenerateCache = new Runnable() { @Override public void run() { if (!isRecycled && !destroyWhenDone && !generatingCache && cacheGenRunnable == null) { startTime = System.currentTimeMillis(); if (RLottieDrawable.lottieCacheGenerateQueue == null) { RLottieDrawable.createCacheGenQueue(); } generatingCache = true; loadFrameTask = null; BitmapsCache.incrementTaskCounter(); RLottieDrawable.lottieCacheGenerateQueue.postRunnable(cacheGenRunnable = () -> { bitmapsCache.createCache(); AndroidUtilities.runOnUIThread(() -> { if (cacheGenRunnable != null) { BitmapsCache.decrementTaskCounter(); cacheGenRunnable = null; } generatingCache = false; chekDestroyDecoder(); scheduleNextGetFrame(); }); }); } } }; private void chekDestroyDecoder() { if (loadFrameRunnable == null && destroyWhenDone && nativePtr != 0 && !generatingCache) { destroyDecoder(nativePtr); nativePtr = 0; } if (!canLoadFrames()) { if (renderingBitmap != null) { renderingBitmap.recycle(); renderingBitmap = null; } if (backgroundBitmap != null) { backgroundBitmap.recycle(); backgroundBitmap = null; } if (decodeQueue != null) { decodeQueue.recycle(); decodeQueue = null; } for (int i = 0; i < unusedBitmaps.size(); i++) { unusedBitmaps.get(i).recycle(); } unusedBitmaps.clear(); invalidateInternal(); } } private void invalidateInternal() { for (int i = 0; i < parents.size(); i++) { parents.get(i).invalidate(); } } private Runnable uiRunnable = new Runnable() { @Override public void run() { chekDestroyDecoder(); if (stream != null && pendingRemoveLoading) { FileLoader.getInstance(currentAccount).removeLoadingVideo(stream.getDocument(), false, false); } if (pendingRemoveLoadingFramesReset <= 0) { pendingRemoveLoading = true; } else { pendingRemoveLoadingFramesReset--; } if (!forceDecodeAfterNextFrame) { singleFrameDecoded = true; } else { forceDecodeAfterNextFrame = false; } loadFrameTask = null; if (!PRERENDER_FRAME) { nextRenderingBitmap = backgroundBitmap; nextRenderingBitmapTime = backgroundBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { nextRenderingShader[i] = backgroundShader[i]; } } else { if (nextRenderingBitmap == null && nextRenderingBitmap2 == null) { nextRenderingBitmap = backgroundBitmap; nextRenderingBitmapTime = backgroundBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { nextRenderingShader[i] = backgroundShader[i]; } } else if (nextRenderingBitmap == null) { nextRenderingBitmap = nextRenderingBitmap2; nextRenderingBitmapTime = nextRenderingBitmapTime2; nextRenderingBitmap2 = backgroundBitmap; nextRenderingBitmapTime2 = backgroundBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { nextRenderingShader[i] = nextRenderingShader2[i]; nextRenderingShader2[i] = backgroundShader[i]; } } else { nextRenderingBitmap2 = backgroundBitmap; nextRenderingBitmapTime2 = backgroundBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { nextRenderingShader2[i] = backgroundShader[i]; } } } backgroundBitmap = null; for (int i = 0; i < backgroundShader.length; i++) { backgroundShader[i] = null; } if (isRestarted) { isRestarted = false; repeatCount++; checkRepeat(); } if (metaData[3] < lastTimeStamp) { lastTimeStamp = startTime > 0 ? (int) (startTime * 1000) : 0; } if (metaData[3] - lastTimeStamp != 0) { invalidateAfter = metaData[3] - lastTimeStamp; if (limitFps && invalidateAfter < 32) { invalidateAfter = 32; } } if (pendingSeekToUI >= 0 && pendingSeekTo == -1) { pendingSeekToUI = -1; invalidateAfter = 0; } lastTimeStamp = metaData[3]; if (!secondParentViews.isEmpty()) { for (int a = 0, N = secondParentViews.size(); a < N; a++) { secondParentViews.get(a).invalidate(); } } invalidateInternal(); scheduleNextGetFrame(); } }; public void checkRepeat() { if (ignoreNoParent) { start(); return; } int count = 0; for (int j = 0; j < parents.size(); j++) { ImageReceiver parent = parents.get(j); if (!parent.isAttachedToWindow()) { parents.remove(j); j--; } if (parent.animatedFileDrawableRepeatMaxCount > 0 && repeatCount >= parent.animatedFileDrawableRepeatMaxCount) { count++; } } if (parents.size() == count) { stop(); } else { start(); } } private int decoderTryCount = 0; private final int MAX_TRIES = 15; private Runnable loadFrameRunnable = new Runnable() { @Override public void run() { if (!isRecycled) { if (!decoderCreated && nativePtr == 0) { nativePtr = createDecoder(path.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, false); ptrFail = nativePtr == 0 && (!isWebmSticker || decoderTryCount > MAX_TRIES); if (nativePtr != 0 && (metaData[0] > 3840 || metaData[1] > 3840)) { destroyDecoder(nativePtr); nativePtr = 0; } updateScaleFactor(); decoderCreated = !isWebmSticker || nativePtr != 0 || (decoderTryCount++) > MAX_TRIES; } try { if (bitmapsCache != null) { if (backgroundBitmap == null) { if (!unusedBitmaps.isEmpty()) { backgroundBitmap = unusedBitmaps.remove(0); } else { backgroundBitmap = Bitmap.createBitmap(renderingWidth, renderingHeight, Bitmap.Config.ARGB_8888); } } if (cacheMetadata == null) { cacheMetadata = new BitmapsCache.Metadata(); } lastFrameDecodeTime = System.currentTimeMillis(); int lastFrame = cacheMetadata.frame; int result = bitmapsCache.getFrame(backgroundBitmap, cacheMetadata); if (result != -1 && cacheMetadata.frame < lastFrame) { isRestarted = true; } metaData[3] = backgroundBitmapTime = cacheMetadata.frame * Math.max(16, metaData[4] / Math.max(1, bitmapsCache.getFrameCount())); if (bitmapsCache.needGenCache()) { AndroidUtilities.runOnUIThread(uiRunnableGenerateCache); } if (result == -1) { AndroidUtilities.runOnUIThread(uiRunnableNoFrame); } else { AndroidUtilities.runOnUIThread(uiRunnable); } return; } if (nativePtr != 0 || metaData[0] == 0 || metaData[1] == 0) { if (backgroundBitmap == null && metaData[0] > 0 && metaData[1] > 0) { try { if (!unusedBitmaps.isEmpty()) { backgroundBitmap = unusedBitmaps.remove(0); } else { backgroundBitmap = Bitmap.createBitmap((int) (metaData[0] * scaleFactor), (int) (metaData[1] * scaleFactor), Bitmap.Config.ARGB_8888); } } catch (Throwable e) { FileLog.e(e); } if (USE_BITMAP_SHADER && backgroundShader[0] == null && backgroundBitmap != null && hasRoundRadius()) { backgroundShader[0] = new BitmapShader(backgroundBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); } } boolean seekWas = false; if (pendingSeekTo >= 0) { metaData[3] = (int) pendingSeekTo; long seekTo = pendingSeekTo; synchronized (sync) { pendingSeekTo = -1; } seekWas = true; if (stream != null) { stream.reset(); } seekToMs(nativePtr, seekTo, true); } if (backgroundBitmap != null) { lastFrameDecodeTime = System.currentTimeMillis(); if (getVideoFrame(nativePtr, backgroundBitmap, metaData, backgroundBitmap.getRowBytes(), false, startTime, endTime, true) == 0) { AndroidUtilities.runOnUIThread(uiRunnableNoFrame); return; } if (metaData[3] < lastTimeStamp) { isRestarted = true; } if (seekWas) { lastTimeStamp = metaData[3]; } backgroundBitmapTime = metaData[3]; } } else { AndroidUtilities.runOnUIThread(uiRunnableNoFrame); return; } } catch (Throwable e) { FileLog.e(e); } } AndroidUtilities.runOnUIThread(uiRunnable); } }; private void updateScaleFactor() { if (!isWebmSticker && renderingHeight > 0 && renderingWidth > 0 && metaData[0] > 0 && metaData[1] > 0) { scaleFactor = Math.max(renderingWidth / (float) metaData[0], renderingHeight / (float) metaData[1]); if (scaleFactor <= 0 || scaleFactor > 0.7) { scaleFactor = 1; } } else { scaleFactor = 1f; } } private final Runnable mStartTask = () -> { if (!secondParentViews.isEmpty()) { for (int a = 0, N = secondParentViews.size(); a < N; a++) { secondParentViews.get(a).invalidate(); } } if ((secondParentViews.isEmpty() || invalidateParentViewWithSecond) && parentView != null) { parentView.invalidate(); } }; public AnimatedFileDrawable(File file, boolean createDecoder, long streamSize, int streamLoadingPriority, TLRPC.Document document, ImageLocation location, Object parentObject, long seekTo, int account, boolean preview, BitmapsCache.CacheOptions cacheOptions) { this(file, createDecoder, streamSize, streamLoadingPriority, document, location, parentObject, seekTo, account, preview, 0, 0, cacheOptions); } public AnimatedFileDrawable(File file, boolean createDecoder, long streamSize, int streamLoadingPriority, TLRPC.Document document, ImageLocation location, Object parentObject, long seekTo, int account, boolean preview, int w, int h, BitmapsCache.CacheOptions cacheOptions) { this(file, createDecoder, streamSize, streamLoadingPriority, document, location, parentObject, seekTo, account, preview, w, h, cacheOptions, document != null ? 1 : 0); } public AnimatedFileDrawable(File file, boolean createDecoder, long streamSize, int streamLoadingPriority, TLRPC.Document document, ImageLocation location, Object parentObject, long seekTo, int account, boolean preview, int w, int h, BitmapsCache.CacheOptions cacheOptions, int cacheType) { path = file; PRERENDER_FRAME = SharedConfig.deviceIsAboveAverage(); streamFileSize = streamSize; this.streamLoadingPriority = streamLoadingPriority; currentAccount = account; renderingHeight = h; renderingWidth = w; this.precache = cacheOptions != null && renderingWidth > 0 && renderingHeight > 0; this.document = document; getPaint().setFlags(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); if (streamSize != 0 && (document != null || location != null)) { stream = new AnimatedFileDrawableStream(document, location, parentObject, account, preview, streamLoadingPriority, cacheType); } if (createDecoder && !this.precache) { nativePtr = createDecoder(file.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, preview); ptrFail = nativePtr == 0 && (!isWebmSticker || decoderTryCount > MAX_TRIES); if (nativePtr != 0 && (metaData[0] > 3840 || metaData[1] > 3840)) { destroyDecoder(nativePtr); nativePtr = 0; } updateScaleFactor(); decoderCreated = true; } if (this.precache) { nativePtr = createDecoder(file.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, preview); ptrFail = nativePtr == 0 && (!isWebmSticker || decoderTryCount > MAX_TRIES); if (nativePtr != 0 && (metaData[0] > 3840 || metaData[1] > 3840)) { destroyDecoder(nativePtr); nativePtr = 0; } else { bitmapsCache = new BitmapsCache(file, this, cacheOptions, renderingWidth, renderingHeight, !limitFps); } } if (seekTo != 0) { seekTo(seekTo, false); } } public void setIsWebmSticker(boolean b) { isWebmSticker = b; if (isWebmSticker) { PRERENDER_FRAME = false; useSharedQueue = true; } } public Bitmap getFrameAtTime(long ms) { return getFrameAtTime(ms, false); } public Bitmap getFrameAtTime(long ms, boolean precise) { if (!decoderCreated || nativePtr == 0) { return null; } if (stream != null) { stream.cancel(false); stream.reset(); } if (!precise) { seekToMs(nativePtr, ms, precise); } Bitmap backgroundBitmap = Bitmap.createBitmap(metaData[0], metaData[1], Bitmap.Config.ARGB_8888); int result; if (precise) { result = getFrameAtTime(nativePtr, ms, backgroundBitmap, metaData, backgroundBitmap.getRowBytes()); } else { result = getVideoFrame(nativePtr, backgroundBitmap, metaData, backgroundBitmap.getRowBytes(), true, 0, 0, true); } return result != 0 ? backgroundBitmap : null; } public void setParentView(View view) { if (parentView != null) { return; } parentView = view; } public void addParent(ImageReceiver imageReceiver) { if (imageReceiver != null && !parents.contains(imageReceiver)) { parents.add(imageReceiver); if (isRunning) { scheduleNextGetFrame(); } } checkCacheCancel(); } public void removeParent(ImageReceiver imageReceiver) { parents.remove(imageReceiver); if (parents.size() == 0) { repeatCount = 0; } checkCacheCancel(); } private Runnable cancelCache; public void checkCacheCancel() { if (bitmapsCache == null) { return; } boolean mustCancel = parents.isEmpty(); if (mustCancel && cancelCache == null) { AndroidUtilities.runOnUIThread(cancelCache = () -> { if (bitmapsCache != null) { bitmapsCache.cancelCreate(); } }, 600); } else if (!mustCancel && cancelCache != null) { AndroidUtilities.cancelRunOnUIThread(cancelCache); cancelCache = null; } } public void setInvalidateParentViewWithSecond(boolean value) { invalidateParentViewWithSecond = value; } public void addSecondParentView(View view) { if (view == null || secondParentViews.contains(view)) { return; } secondParentViews.add(view); } public void removeSecondParentView(View view) { secondParentViews.remove(view); if (secondParentViews.isEmpty()) { if (recycleWithSecond) { recycle(); } else { if (roundRadiusBackup != null) { setRoundRadius(roundRadiusBackup); } } } } public void setAllowDecodeSingleFrame(boolean value) { decodeSingleFrame = value; if (decodeSingleFrame) { scheduleNextGetFrame(); } } public void seekTo(long ms, boolean removeLoading) { seekTo(ms, removeLoading, false); } public void seekTo(long ms, boolean removeLoading, boolean force) { synchronized (sync) { pendingSeekTo = ms; pendingSeekToUI = ms; if (nativePtr != 0) { prepareToSeek(nativePtr); } if (decoderCreated && stream != null) { stream.cancel(removeLoading); pendingRemoveLoading = removeLoading; pendingRemoveLoadingFramesReset = pendingRemoveLoading ? 0 : 10; } if (force && decodeSingleFrame) { singleFrameDecoded = false; if (loadFrameTask == null) { scheduleNextGetFrame(); } else { forceDecodeAfterNextFrame = true; } } } } public void recycle() { if (!secondParentViews.isEmpty()) { recycleWithSecond = true; return; } isRunning = false; isRecycled = true; if (cacheGenRunnable != null) { BitmapsCache.decrementTaskCounter(); RLottieDrawable.lottieCacheGenerateQueue.cancelRunnable(cacheGenRunnable); cacheGenRunnable = null; } if (loadFrameTask == null) { if (nativePtr != 0) { destroyDecoder(nativePtr); nativePtr = 0; } ArrayList<Bitmap> bitmapToRecycle = new ArrayList<>(); bitmapToRecycle.add(renderingBitmap); bitmapToRecycle.add(nextRenderingBitmap); bitmapToRecycle.add(nextRenderingBitmap2); bitmapToRecycle.add(backgroundBitmap); bitmapToRecycle.addAll(unusedBitmaps); // unusedBitmaps.remove(backgroundBitmap); unusedBitmaps.clear(); renderingBitmap = null; nextRenderingBitmap = null; nextRenderingBitmap2 = null; backgroundBitmap = null; if (decodeQueue != null) { decodeQueue.recycle(); decodeQueue = null; } getPaint().setShader(null); AndroidUtilities.recycleBitmaps(bitmapToRecycle); } else { destroyWhenDone = true; } if (stream != null) { stream.cancel(true); stream = null; } invalidateInternal(); } public void resetStream(boolean stop) { if (stream != null) { stream.cancel(true); } if (nativePtr != 0) { if (stop) { stopDecoder(nativePtr); } else { prepareToSeek(nativePtr); } } } public void setUseSharedQueue(boolean value) { if (isWebmSticker) { return; } useSharedQueue = value; } @Override protected void finalize() throws Throwable { try { secondParentViews.clear(); recycle(); } finally { super.finalize(); } } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public void start() { if (isRunning || parents.size() == 0 && !ignoreNoParent) { return; } isRunning = true; scheduleNextGetFrame(); AndroidUtilities.runOnUIThread(mStartTask); } public float getCurrentProgress() { if (metaData[4] == 0) { return 0; } if (pendingSeekToUI >= 0) { return pendingSeekToUI / (float) metaData[4]; } return metaData[3] / (float) metaData[4]; } public int getCurrentProgressMs() { if (pendingSeekToUI >= 0) { return (int) pendingSeekToUI; } return nextRenderingBitmapTime != 0 ? nextRenderingBitmapTime : renderingBitmapTime; } public int getProgressMs() { return metaData[3]; } public int getDurationMs() { return metaData[4]; } private void scheduleNextGetFrame() { if (loadFrameTask != null || ((!PRERENDER_FRAME || nextRenderingBitmap2 != null) && nextRenderingBitmap != null) || !canLoadFrames() || destroyWhenDone || !isRunning && (!decodeSingleFrame || decodeSingleFrame && singleFrameDecoded) || parents.size() == 0 && !ignoreNoParent || generatingCache) { return; } long ms = 0; if (lastFrameDecodeTime != 0) { ms = Math.min(invalidateAfter, Math.max(0, invalidateAfter - (System.currentTimeMillis() - lastFrameDecodeTime))); } if (useSharedQueue) { if (limitFps) { DispatchQueuePoolBackground.execute(loadFrameTask = loadFrameRunnable); } else { executor.schedule(loadFrameTask = loadFrameRunnable, ms, TimeUnit.MILLISECONDS); } } else { if (decodeQueue == null) { decodeQueue = new DispatchQueue("decodeQueue" + this); } decodeQueue.postRunnable(loadFrameTask = loadFrameRunnable, ms); } } public boolean isLoadingStream() { return stream != null && stream.isWaitingForLoad(); } @Override public void stop() { isRunning = false; } @Override public boolean isRunning() { return isRunning; } @Override public int getIntrinsicHeight() { int height = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[0] : metaData[1]) : 0; if (height == 0) { return AndroidUtilities.dp(100); } else { height *= scaleFactor; } return height; } @Override public int getIntrinsicWidth() { int width = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[1] : metaData[0]) : 0; if (width == 0) { return AndroidUtilities.dp(100); } else { width *= scaleFactor; } return width; } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); applyTransformation = true; } @Override public void draw(Canvas canvas) { drawInternal(canvas, false, System.currentTimeMillis(), 0); } public void drawInBackground(Canvas canvas, float x, float y, float w, float h, int alpha, ColorFilter colorFilter, int threadIndex) { if (dstRectBackground[threadIndex] == null) { dstRectBackground[threadIndex] = new RectF(); backgroundPaint[threadIndex] = new Paint(); backgroundPaint[threadIndex].setFilterBitmap(true); } backgroundPaint[threadIndex].setAlpha(alpha); backgroundPaint[threadIndex].setColorFilter(colorFilter); dstRectBackground[threadIndex].set(x, y, x + w, y + h); drawInternal(canvas, true, 0, threadIndex); } public void drawInternal(Canvas canvas, boolean drawInBackground, long currentTime, int threadIndex) { if (!canLoadFrames() || destroyWhenDone) { return; } if (currentTime == 0) { currentTime = System.currentTimeMillis(); } RectF rect = drawInBackground ? dstRectBackground[threadIndex] : dstRect; Paint paint = drawInBackground ? backgroundPaint[threadIndex] : getPaint(); if (!drawInBackground) { updateCurrentFrame(currentTime, false); } if (renderingBitmap != null) { float scaleX = this.scaleX; float scaleY = this.scaleY; if (drawInBackground) { int bitmapW = renderingBitmap.getWidth(); int bitmapH = renderingBitmap.getHeight(); if (metaData[2] == 90 || metaData[2] == 270) { int temp = bitmapW; bitmapW = bitmapH; bitmapH = temp; } scaleX = rect.width() / bitmapW; scaleY = rect.height() / bitmapH; } else if (applyTransformation) { int bitmapW = renderingBitmap.getWidth(); int bitmapH = renderingBitmap.getHeight(); if (metaData[2] == 90 || metaData[2] == 270) { int temp = bitmapW; bitmapW = bitmapH; bitmapH = temp; } rect.set(getBounds()); this.scaleX = scaleX = rect.width() / bitmapW; this.scaleY = scaleY = rect.height() / bitmapH; applyTransformation = false; } if (hasRoundRadius()) { int index = drawInBackground ? threadIndex + 1 : 0; if (USE_BITMAP_SHADER) { if (renderingShader[index] == null) { renderingShader[index] = new BitmapShader(renderingBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); } paint.setShader(renderingShader[index]); Matrix matrix = shaderMatrix[index]; if (matrix == null) { matrix = shaderMatrix[index] = new Matrix(); } matrix.reset(); matrix.setTranslate(rect.left, rect.top); if (metaData[2] == 90) { matrix.preRotate(90); matrix.preTranslate(0, -rect.width()); } else if (metaData[2] == 180) { matrix.preRotate(180); matrix.preTranslate(-rect.width(), -rect.height()); } else if (metaData[2] == 270) { matrix.preRotate(270); matrix.preTranslate(-rect.height(), 0); } matrix.preScale(scaleX, scaleY); renderingShader[index].setLocalMatrix(matrix); } Path path = roundPath[index]; if (path == null) { path = roundPath[index] = new Path(); } if (invalidatePath || drawInBackground) { if (!drawInBackground) { invalidatePath = false; } for (int a = 0; a < roundRadius.length; a++) { radii[a * 2] = roundRadius[a]; radii[a * 2 + 1] = roundRadius[a]; } path.rewind(); path.addRoundRect(drawInBackground ? rect : actualDrawRect, radii, Path.Direction.CW); } if (USE_BITMAP_SHADER) { canvas.drawPath(path, paint); } else { canvas.save(); canvas.clipPath(path); drawBitmap(rect, paint, canvas, scaleX, scaleY); canvas.restore(); } } else { drawBitmap(rect, paint, canvas, scaleX, scaleY); } } } private void drawBitmap(RectF rect, Paint paint, Canvas canvas, float sx, float sy) { canvas.translate(rect.left, rect.top); if (metaData[2] == 90) { canvas.rotate(90); canvas.translate(0, -rect.width()); } else if (metaData[2] == 180) { canvas.rotate(180); canvas.translate(-rect.width(), -rect.height()); } else if (metaData[2] == 270) { canvas.rotate(270); canvas.translate(-rect.height(), 0); } canvas.scale(sx, sy); canvas.drawBitmap(renderingBitmap, 0, 0, paint); } public long getLastFrameTimestamp() { return lastTimeStamp; } @Override public int getMinimumHeight() { int height = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[0] : metaData[1]) : 0; if (height == 0) { return AndroidUtilities.dp(100); } return height; } @Override public int getMinimumWidth() { int width = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[1] : metaData[0]) : 0; if (width == 0) { return AndroidUtilities.dp(100); } return width; } public Bitmap getRenderingBitmap() { return renderingBitmap; } public Bitmap getNextRenderingBitmap() { return nextRenderingBitmap; } public Bitmap getBackgroundBitmap() { return backgroundBitmap; } public Bitmap getAnimatedBitmap() { if (renderingBitmap != null) { return renderingBitmap; } else if (nextRenderingBitmap != null) { return nextRenderingBitmap; } else if (nextRenderingBitmap2 != null) { return nextRenderingBitmap2; } return null; } public void setActualDrawRect(float x, float y, float width, float height) { float bottom = y + height; float right = x + width; if (actualDrawRect.left != x || actualDrawRect.top != y || actualDrawRect.right != right || actualDrawRect.bottom != bottom) { actualDrawRect.set(x, y, right, bottom); invalidatePath = true; } } public void setRoundRadius(int[] value) { if (!secondParentViews.isEmpty()) { if (roundRadiusBackup == null) { roundRadiusBackup = new int[4]; } System.arraycopy(roundRadius, 0, roundRadiusBackup, 0, roundRadiusBackup.length); } for (int i = 0; i < 4; i++) { if (!invalidatePath && value[i] != roundRadius[i]) { invalidatePath = true; } roundRadius[i] = value[i]; } } private boolean hasRoundRadius() { for (int a = 0; a < roundRadius.length; a++) { if (roundRadius[a] != 0) { return true; } } return false; } public boolean hasBitmap() { return canLoadFrames() && (renderingBitmap != null || nextRenderingBitmap != null); } public int getOrientation() { return metaData[2]; } public AnimatedFileDrawable makeCopy() { AnimatedFileDrawable drawable; if (stream != null) { drawable = new AnimatedFileDrawable(path, false, streamFileSize, streamLoadingPriority, stream.getDocument(), stream.getLocation(), stream.getParentObject(), pendingSeekToUI, currentAccount, stream != null && stream.isPreview(), null); } else { drawable = new AnimatedFileDrawable(path, false, streamFileSize, streamLoadingPriority, document, null, null, pendingSeekToUI, currentAccount, stream != null && stream.isPreview(), null); } drawable.metaData[0] = metaData[0]; drawable.metaData[1] = metaData[1]; return drawable; } public static void getVideoInfo(String src, int[] params) { getVideoInfo(Build.VERSION.SDK_INT, src, params); } public void setStartEndTime(long startTime, long endTime) { this.startTime = startTime / 1000f; this.endTime = endTime / 1000f; if (getCurrentProgressMs() < startTime) { seekTo(startTime, true); } } public long getStartTime() { return (long) (startTime * 1000); } public boolean isRecycled() { return isRecycled || decoderTryCount >= MAX_TRIES; } public boolean decoderFailed() { return decoderCreated && ptrFail; } public Bitmap getNextFrame(boolean loop) { if (nativePtr == 0) { return backgroundBitmap; } if (backgroundBitmap == null) { if (!unusedBitmaps.isEmpty()) { backgroundBitmap = unusedBitmaps.remove(0); } else { backgroundBitmap = Bitmap.createBitmap((int) (metaData[0] * scaleFactor), (int) (metaData[1] * scaleFactor), Bitmap.Config.ARGB_8888); } } getVideoFrame(nativePtr, backgroundBitmap, metaData, backgroundBitmap.getRowBytes(), false, startTime, endTime, loop); return backgroundBitmap; } public void setLimitFps(boolean limitFps) { this.limitFps = limitFps; if (limitFps) { PRERENDER_FRAME = false; } } public ArrayList<ImageReceiver> getParents() { return parents; } public File getFilePath() { return path; } long cacheGenerateTimestamp; Bitmap generatingCacheBitmap; long cacheGenerateNativePtr; int tryCount; int lastMetadata; @Override public void prepareForGenerateCache() { cacheGenerateNativePtr = createDecoder(path.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, false); } @Override public void releaseForGenerateCache() { if (cacheGenerateNativePtr != 0) { destroyDecoder(cacheGenerateNativePtr); } } @Override public int getNextFrame(Bitmap bitmap) { if (cacheGenerateNativePtr == 0) { return -1; } Canvas canvas = new Canvas(bitmap); if (generatingCacheBitmap == null) { generatingCacheBitmap = Bitmap.createBitmap(metaData[0], metaData[1], Bitmap.Config.ARGB_8888); } getVideoFrame(cacheGenerateNativePtr, generatingCacheBitmap, metaData, generatingCacheBitmap.getRowBytes(), false, startTime, endTime, true); if (cacheGenerateTimestamp != 0 && (metaData[3] == 0 || cacheGenerateTimestamp > metaData[3])) { return 0; } if (lastMetadata == metaData[3]) { tryCount++; if (tryCount > 5) { return 0; } } lastMetadata = metaData[3]; bitmap.eraseColor(Color.TRANSPARENT); canvas.save(); float s = (float) renderingWidth / generatingCacheBitmap.getWidth(); canvas.scale(s, s); canvas.drawBitmap(generatingCacheBitmap, 0, 0, null); canvas.restore(); cacheGenerateTimestamp = metaData[3]; return 1; } @Override public Bitmap getFirstFrame(Bitmap bitmap) { if (bitmap == null) { bitmap = Bitmap.createBitmap(renderingWidth, renderingHeight, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); if (generatingCacheBitmap == null) { generatingCacheBitmap = Bitmap.createBitmap(metaData[0], metaData[1], Bitmap.Config.ARGB_8888); } long nativePtr = createDecoder(path.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, false); if (nativePtr == 0) { return bitmap; } getVideoFrame(nativePtr, generatingCacheBitmap, metaData, generatingCacheBitmap.getRowBytes(), false, startTime, endTime, true); destroyDecoder(nativePtr); bitmap.eraseColor(Color.TRANSPARENT); canvas.save(); float s = (float) renderingWidth / generatingCacheBitmap.getWidth(); canvas.scale(s, s); canvas.drawBitmap(generatingCacheBitmap, 0, 0, null); canvas.restore(); return bitmap; } public void drawFrame(Canvas canvas, int incFrame) { if (nativePtr == 0) { return; } for (int i = 0; i < incFrame; ++i) { getNextFrame(true); } Bitmap bitmap = getBackgroundBitmap(); if (bitmap == null) { bitmap = getNextFrame(true); } AndroidUtilities.rectTmp2.set(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawBitmap(getBackgroundBitmap(), AndroidUtilities.rectTmp2, getBounds(), getPaint()); } public boolean canLoadFrames() { if (precache) { return bitmapsCache != null; } else { return nativePtr != 0 || !decoderCreated; } } public void checkCacheExist() { if (precache && bitmapsCache != null) { bitmapsCache.cacheExist(); } } public void updateCurrentFrame(long now, boolean b) { if (isRunning) { if (renderingBitmap == null && nextRenderingBitmap == null) { scheduleNextGetFrame(); } else if (nextRenderingBitmap != null && (renderingBitmap == null || (Math.abs(now - lastFrameTime) >= invalidateAfter && !skipFrameUpdate))) { unusedBitmaps.add(renderingBitmap); renderingBitmap = nextRenderingBitmap; renderingBitmapTime = nextRenderingBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { renderingShader[i] = nextRenderingShader[i]; nextRenderingShader[i] = nextRenderingShader2[i]; nextRenderingShader2[i] = null; } nextRenderingBitmap = nextRenderingBitmap2; nextRenderingBitmapTime = nextRenderingBitmapTime2; nextRenderingBitmap2 = null; nextRenderingBitmapTime2 = 0; lastFrameTime = now; scheduleNextGetFrame(); } else { invalidateInternal(); } } else if (!isRunning && decodeSingleFrame && Math.abs(now - lastFrameTime) >= invalidateAfter && nextRenderingBitmap != null) { unusedBitmaps.add(renderingBitmap); renderingBitmap = nextRenderingBitmap; renderingBitmapTime = nextRenderingBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { renderingShader[i] = nextRenderingShader[i]; nextRenderingShader[i] = nextRenderingShader2[i]; nextRenderingShader2[i] = null; } nextRenderingBitmap = nextRenderingBitmap2; nextRenderingBitmapTime = nextRenderingBitmapTime2; nextRenderingBitmap2 = null; nextRenderingBitmapTime2 = 0; lastFrameTime = now; scheduleNextGetFrame(); } } public int getFps() { return metaData[5]; } public int getRenderingWidth() { return renderingWidth; } public int getRenderingHeight() { return renderingHeight; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedFileDrawable.java
2,330
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.RelativeSizeSpan; import android.util.LongSparseArray; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.graphics.ColorUtils; import androidx.core.math.MathUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.BotWebViewVibrationEffect; import org.telegram.messenger.BuildVars; import org.telegram.messenger.CacheByChatsController; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.FilePathDatabase; import org.telegram.messenger.FilesMigrationService; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.Utilities; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BackDrawable; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.CheckBoxCell; import org.telegram.ui.Cells.HeaderCell; import org.telegram.ui.Cells.TextCell; import org.telegram.ui.Cells.TextCheckBoxCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextSettingsCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AnimatedTextView; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.CacheChart; import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.FlickerLoadingView; import org.telegram.ui.Components.HideViewAfterAnimation; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.ListView.AdapterWithDiffUtils; import org.telegram.ui.Components.LoadingDrawable; import org.telegram.ui.Components.NestedSizeNotifierLayout; import org.telegram.ui.Components.RLottieImageView; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SlideChooseView; import org.telegram.ui.Components.StorageDiagramView; import org.telegram.ui.Components.StorageUsageView; import org.telegram.ui.Components.TypefaceSpan; import org.telegram.ui.Components.UndoView; import org.telegram.ui.Storage.CacheModel; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Objects; public class CacheControlActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { private static final int VIEW_TYPE_TEXT_SETTINGS = 0; private static final int VIEW_TYPE_INFO = 1; private static final int VIEW_TYPE_STORAGE = 2; private static final int VIEW_TYPE_HEADER = 3; private static final int VIEW_TYPE_CHOOSER = 4; private static final int VIEW_TYPE_CHAT = 5; private static final int VIEW_FLICKER_LOADING_DIALOG = 6; private static final int VIEW_TYPE_KEEP_MEDIA_CELL = 7; private static final int VIEW_TYPE_CACHE_VIEW_PAGER = 8; private static final int VIEW_TYPE_CHART = 9; private static final int VIEW_TYPE_CHART_HEADER = 10; private static final int VIEW_TYPE_SECTION = 11; private static final int VIEW_TYPE_SECTION_LOADING = 12; private static final int VIEW_TYPE_CLEAR_CACHE_BUTTON = 13; private static final int VIEW_TYPE_MAX_CACHE_SIZE = 14; public static final int KEEP_MEDIA_TYPE_USER = 0; public static final int KEEP_MEDIA_TYPE_GROUP = 1; public static final int KEEP_MEDIA_TYPE_CHANNEL = 2; public static final int KEEP_MEDIA_TYPE_STORIES = 3; public static final long UNKNOWN_CHATS_DIALOG_ID = Long.MAX_VALUE; private ListAdapter listAdapter; private RecyclerListView listView; @SuppressWarnings("FieldCanBeLocal") private LinearLayoutManager layoutManager; AlertDialog progressDialog; private boolean[] selected = new boolean[] { true, true, true, true, true, true, true, true, true, true, true }; private long databaseSize = -1; private long cacheSize = -1, cacheEmojiSize = -1, cacheTempSize = -1; private long documentsSize = -1; private long audioSize = -1; private long storiesSize = -1; private long musicSize = -1; private long photoSize = -1; private long videoSize = -1; private long logsSize = -1; private long stickersCacheSize = -1; private long totalSize = -1; private long totalDeviceSize = -1; private long totalDeviceFreeSize = -1; private long migrateOldFolderRow = -1; private boolean calculating = true; private boolean collapsed = true; private CachedMediaLayout cachedMediaLayout; private int[] percents; private float[] tempSizes; private int sectionsStartRow = -1; private int sectionsEndRow = -1; private CacheChart cacheChart; private CacheChartHeader cacheChartHeader; private ClearCacheButtonInternal clearCacheButton; public static volatile boolean canceled = false; private View bottomSheetView; private BottomSheet bottomSheet; private View actionTextView; private UndoView cacheRemovedTooltip; long fragmentCreateTime; private boolean updateDatabaseSize; public final static int TYPE_PHOTOS = 0; public final static int TYPE_VIDEOS = 1; public final static int TYPE_DOCUMENTS = 2; public final static int TYPE_MUSIC = 3; public final static int TYPE_VOICE = 4; public final static int TYPE_ANIMATED_STICKERS_CACHE = 5; public final static int TYPE_OTHER = 6; public final static int TYPE_STORIES = 7; private static final int delete_id = 1; private static final int other_id = 2; private static final int clear_database_id = 3; private static final int reset_database_id = 4; private boolean loadingDialogs; private NestedSizeNotifierLayout nestedSizeNotifierLayout; private ActionBarMenuSubItem clearDatabaseItem; private ActionBarMenuSubItem resetDatabaseItem; private void updateDatabaseItemSize() { if (clearDatabaseItem != null) { SpannableStringBuilder string = new SpannableStringBuilder(); string.append(LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase)); // string.append("\t"); // SpannableString databaseSizeString = new SpannableString(AndroidUtilities.formatFileSize(databaseSize)); // databaseSizeString.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText)), 0, databaseSizeString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // string.append(databaseSizeString); clearDatabaseItem.setText(string); } } private static long lastTotalSizeCalculatedTime; private static Long lastTotalSizeCalculated; private static Long lastDeviceTotalSize, lastDeviceTotalFreeSize; public static void calculateTotalSize(Utilities.Callback<Long> onDone) { if (onDone == null) { return; } if (lastTotalSizeCalculated != null) { onDone.run(lastTotalSizeCalculated); if (System.currentTimeMillis() - lastTotalSizeCalculatedTime < 5000) { return; } } Utilities.cacheClearQueue.postRunnable(() -> { canceled = false; long cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); long cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); long photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), 0); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), 0); long videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), 0); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), 0); long documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); long musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 2); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 2); long stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), 0); stickersCacheSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); long audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); long storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), 0); long logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1); if (!BuildVars.DEBUG_VERSION && logsSize < 1024 * 1024 * 256) { logsSize = 0; } final long totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize + logsSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); if (!canceled) { AndroidUtilities.runOnUIThread(() -> { onDone.run(totalSize); }); } }); } public static void resetCalculatedTotalSIze() { lastTotalSizeCalculated = null; } public static void getDeviceTotalSize(Utilities.Callback2<Long, Long> onDone) { if (lastDeviceTotalSize != null && lastDeviceTotalFreeSize != null) { if (onDone != null) { onDone.run(lastDeviceTotalSize, lastDeviceTotalFreeSize); } return; } Utilities.cacheClearQueue.postRunnable(() -> { File path; if (Build.VERSION.SDK_INT >= 19) { ArrayList<File> storageDirs = AndroidUtilities.getRootDirs(); String dir = (path = storageDirs.get(0)).getAbsolutePath(); if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) { for (int a = 0, N = storageDirs.size(); a < N; a++) { File file = storageDirs.get(a); if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir) && file.canWrite()) { path = file; break; } } } } else { path = new File(SharedConfig.storageCacheDir); } try { StatFs stat = new StatFs(path.getPath()); long blockSize; long blockSizeExternal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } AndroidUtilities.runOnUIThread(() -> { lastDeviceTotalSize = blocksTotal * blockSize; lastDeviceTotalFreeSize = availableBlocks * blockSize; if (onDone != null) { onDone.run(lastDeviceTotalSize, lastDeviceTotalFreeSize); } }); } catch (Exception e) { FileLog.e(e); } }); } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); canceled = false; getNotificationCenter().addObserver(this, NotificationCenter.didClearDatabase); databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize(); loadingDialogs = true; Utilities.globalQueue.postRunnable(() -> { cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); if (canceled) { return; } cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); if (canceled) { return; } photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), 0); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), 0); if (canceled) { return; } videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), 0); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), 0); if (canceled) { return; } logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1); if (!BuildVars.DEBUG_VERSION && logsSize < 1024 * 1024 * 256) { logsSize = 0; } if (canceled) { return; } documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); if (canceled) { return; } musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 2); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 2); if (canceled) { return; } stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), 0); if (canceled) { return; } cacheEmojiSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); if (canceled) { return; } stickersCacheSize += cacheEmojiSize; audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), 0); if (canceled) { return; } totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + logsSize + audioSize + photoSize + documentsSize + musicSize + storiesSize + stickersCacheSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); File path; if (Build.VERSION.SDK_INT >= 19) { ArrayList<File> storageDirs = AndroidUtilities.getRootDirs(); String dir = (path = storageDirs.get(0)).getAbsolutePath(); if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) { for (int a = 0, N = storageDirs.size(); a < N; a++) { File file = storageDirs.get(a); if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { path = file; break; } } } } else { path = new File(SharedConfig.storageCacheDir); } try { StatFs stat = new StatFs(path.getPath()); long blockSize; long blockSizeExternal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } totalDeviceSize = blocksTotal * blockSize; totalDeviceFreeSize = availableBlocks * blockSize; } catch (Exception e) { FileLog.e(e); } AndroidUtilities.runOnUIThread(() -> { resumeDelayedFragmentAnimation(); calculating = false; updateRows(true); updateChart(); }); loadDialogEntities(); }); fragmentCreateTime = System.currentTimeMillis(); updateRows(false); updateChart(); return true; } private void updateChart() { if (cacheChart != null) { if (!calculating && totalSize > 0) { CacheChart.SegmentSize[] segments = new CacheChart.SegmentSize[11]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item = itemInners.get(i); if (item.viewType == VIEW_TYPE_SECTION) { if (item.index < 0) { if (collapsed) { segments[10] = CacheChart.SegmentSize.of(item.size, selected[10]); } } else { segments[item.index] = CacheChart.SegmentSize.of(item.size, selected[item.index]); } } } if (System.currentTimeMillis() - fragmentCreateTime < 80) { cacheChart.loadingFloat.set(0, true); } cacheChart.setSegments(totalSize, true, segments); } else if (calculating) { cacheChart.setSegments(-1, true); } else { cacheChart.setSegments(0, true); } } if (clearCacheButton != null && !calculating) { clearCacheButton.updateSize(); } } private void loadDialogEntities() { getFileLoader().getFileDatabase().getQueue().postRunnable(() -> { getFileLoader().getFileDatabase().ensureDatabaseCreated(); CacheModel cacheModel = new CacheModel(false); LongSparseArray<DialogFileEntities> dilogsFilesEntities = new LongSparseArray<>(); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), TYPE_OTHER, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), TYPE_PHOTOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), TYPE_PHOTOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), TYPE_VIDEOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), TYPE_VIDEOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), TYPE_VOICE, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), TYPE_OTHER, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), TYPE_DOCUMENTS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), TYPE_DOCUMENTS, dilogsFilesEntities, cacheModel); ArrayList<DialogFileEntities> entities = new ArrayList<>(); ArrayList<Long> unknownUsers = new ArrayList<>(); ArrayList<Long> unknownChats = new ArrayList<>(); for (int i = 0; i < dilogsFilesEntities.size(); i++) { DialogFileEntities dialogEntities = dilogsFilesEntities.valueAt(i); entities.add(dialogEntities); if (getMessagesController().getUserOrChat(entities.get(i).dialogId) == null) { if (dialogEntities.dialogId > 0) { unknownUsers.add(dialogEntities.dialogId); } else { unknownChats.add(dialogEntities.dialogId); } } } cacheModel.sortBySize(); getMessagesStorage().getStorageQueue().postRunnable(() -> { ArrayList<TLRPC.User> users = new ArrayList<>(); ArrayList<TLRPC.Chat> chats = new ArrayList<>(); if (!unknownUsers.isEmpty()) { try { getMessagesStorage().getUsersInternal(TextUtils.join(",", unknownUsers), users); } catch (Exception e) { FileLog.e(e); } } if (!unknownChats.isEmpty()) { try { getMessagesStorage().getChatsInternal(TextUtils.join(",", unknownChats), chats); } catch (Exception e) { FileLog.e(e); } } for (int i = 0; i < entities.size(); i++) { if (entities.get(i).totalSize <= 0) { entities.remove(i); i--; } } sort(entities); AndroidUtilities.runOnUIThread(() -> { loadingDialogs = false; getMessagesController().putUsers(users, true); getMessagesController().putChats(chats, true); DialogFileEntities unknownChatsEntity = null; for (int i = 0; i < entities.size(); i++) { DialogFileEntities dialogEntities = entities.get(i); boolean changed = false; if (getMessagesController().getUserOrChat(dialogEntities.dialogId) == null) { dialogEntities.dialogId = UNKNOWN_CHATS_DIALOG_ID; if (unknownChatsEntity != null) { changed = true; unknownChatsEntity.merge(dialogEntities); entities.remove(i); i--; } else { unknownChatsEntity = dialogEntities; } if (changed) { sort(entities); } } } cacheModel.setEntities(entities); if (!canceled) { setCacheModel(cacheModel); updateRows(); updateChart(); if (cacheChartHeader != null && !calculating && System.currentTimeMillis() - fragmentCreateTime > 120) { cacheChartHeader.setData( totalSize > 0, totalDeviceSize <= 0 ? 0 : (float) totalSize / totalDeviceSize, totalDeviceFreeSize <= 0 || totalDeviceSize <= 0 ? 0 : (float) (totalDeviceSize - totalDeviceFreeSize) / totalDeviceSize ); } } }); }); }); } private void sort(ArrayList<DialogFileEntities> entities) { Collections.sort(entities, (o1, o2) -> { if (o2.totalSize > o1.totalSize) { return 1; } else if (o2.totalSize < o1.totalSize) { return -1; } return 0; }); } CacheModel cacheModel; public void setCacheModel(CacheModel cacheModel) { this.cacheModel = cacheModel; if (cachedMediaLayout != null) { cachedMediaLayout.setCacheModel(cacheModel); } } public void fillDialogsEntitiesRecursive(final File fromFolder, int type, LongSparseArray<DialogFileEntities> dilogsFilesEntities, CacheModel cacheModel) { if (fromFolder == null) { return; } File[] files = fromFolder.listFiles(); if (files == null) { return; } for (final File fileEntry : files) { if (canceled) { return; } if (fileEntry.isDirectory()) { fillDialogsEntitiesRecursive(fileEntry, type, dilogsFilesEntities, cacheModel); } else { if (fileEntry.getName().equals(".nomedia")) { continue; } FilePathDatabase.FileMeta fileMetadata = getFileLoader().getFileDatabase().getFileDialogId(fileEntry, null); int addToType = type; String fileName = fileEntry.getName().toLowerCase(); if (fileName.endsWith(".mp3") || fileName.endsWith(".m4a") ) { addToType = TYPE_MUSIC; } CacheModel.FileInfo fileInfo = new CacheModel.FileInfo(fileEntry); fileInfo.size = fileEntry.length(); if (fileMetadata != null) { fileInfo.dialogId = fileMetadata.dialogId; fileInfo.messageId = fileMetadata.messageId; fileInfo.messageType = fileMetadata.messageType; if (fileInfo.messageType == MessageObject.TYPE_STORY && fileInfo.size > 0) { addToType = TYPE_STORIES; } } fileInfo.type = addToType; if (fileInfo.dialogId != 0) { DialogFileEntities dilogEntites = dilogsFilesEntities.get(fileInfo.dialogId, null); if (dilogEntites == null) { dilogEntites = new DialogFileEntities(fileInfo.dialogId); dilogsFilesEntities.put(fileInfo.dialogId, dilogEntites); } dilogEntites.addFile(fileInfo, addToType); } if (cacheModel != null && addToType != TYPE_OTHER) { cacheModel.add(addToType, fileInfo); } //TODO measure for other accounts // for (int i = 0; i < UserConfig.MAX_ACCOUNT_COUNT; i++) { // if (i != currentAccount && UserConfig.getInstance(currentAccount).isClientActivated()) { // FileLoader.getInstance(currentAccount).getFileDatabase().getFileDialogId(fileEntry); // } // } } } } private ArrayList<ItemInner> oldItems = new ArrayList<>(); private ArrayList<ItemInner> itemInners = new ArrayList<>(); private String formatPercent(float k) { return formatPercent(k, true); } private String formatPercent(float k, boolean minimize) { if (minimize && k < 0.001f) { return String.format("<%.1f%%", 0.1f); } final float p = Math.round(k * 100f); if (minimize && p <= 0) { return String.format("<%d%%", 1); } return String.format("%d%%", (int) p); } private CharSequence getCheckBoxTitle(CharSequence header, int percent) { return getCheckBoxTitle(header, percent, false); } private CharSequence getCheckBoxTitle(CharSequence header, int percent, boolean addArrow) { String percentString = percent <= 0 ? String.format("<%.1f%%", 1f) : String.format("%d%%", percent); SpannableString percentStr = new SpannableString(percentString); percentStr.setSpan(new RelativeSizeSpan(.834f), 0, percentStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); percentStr.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), 0, percentStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); SpannableStringBuilder string = new SpannableStringBuilder(header); string.append(" "); string.append(percentStr); return string; } private void updateRows() { updateRows(true); } private void updateRows(boolean animated) { if (animated && System.currentTimeMillis() - fragmentCreateTime < 80) { animated = false; } oldItems.clear(); oldItems.addAll(itemInners); itemInners.clear(); itemInners.add(new ItemInner(VIEW_TYPE_CHART, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_CHART_HEADER, null, null)); sectionsStartRow = itemInners.size(); boolean hasCache = false; if (calculating) { itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); hasCache = true; } else { ArrayList<ItemInner> sections = new ArrayList<>(); if (photoSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalPhotoCache), 0, photoSize, Theme.key_statisticChartLine_lightblue)); } if (videoSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalVideoCache), 1, videoSize, Theme.key_statisticChartLine_blue)); } if (documentsSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalDocumentCache), 2, documentsSize, Theme.key_statisticChartLine_green)); } if (musicSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMusicCache), 3, musicSize, Theme.key_statisticChartLine_purple)); } if (audioSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalAudioCache), 4, audioSize, Theme.key_statisticChartLine_lightgreen)); } if (storiesSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalStoriesCache), 5, storiesSize, Theme.key_statisticChartLine_red)); } if (stickersCacheSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalStickersCache), 6, stickersCacheSize, Theme.key_statisticChartLine_orange)); } if (cacheSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalProfilePhotosCache), 7, cacheSize, Theme.key_statisticChartLine_cyan)); } if (cacheTempSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMiscellaneousCache), 8, cacheTempSize, Theme.key_statisticChartLine_purple)); } if (logsSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalLogsCache), 9, logsSize, Theme.key_statisticChartLine_golden)); } if (!sections.isEmpty()) { Collections.sort(sections, (a, b) -> Long.compare(b.size, a.size)); sections.get(sections.size() - 1).last = true; hasCache = true; if (tempSizes == null) { tempSizes = new float[11]; } for (int i = 0; i < tempSizes.length; ++i) { tempSizes[i] = (float) size(i); } if (percents == null) { percents = new int[11]; } AndroidUtilities.roundPercents(tempSizes, percents); final int MAX_NOT_COLLAPSED = 4; if (sections.size() > MAX_NOT_COLLAPSED + 1) { itemInners.addAll(sections.subList(0, MAX_NOT_COLLAPSED)); int sumPercents = 0; long sum = 0; for (int i = MAX_NOT_COLLAPSED; i < sections.size(); ++i) { sections.get(i).pad = true; sum += sections.get(i).size; sumPercents += percents[sections.get(i).index]; } percents[10] = sumPercents; itemInners.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalOther), -1, sum, Theme.key_statisticChartLine_golden)); if (!collapsed) { itemInners.addAll(sections.subList(MAX_NOT_COLLAPSED, sections.size())); } } else { itemInners.addAll(sections); } } } if (hasCache) { sectionsEndRow = itemInners.size(); itemInners.add(new ItemInner(VIEW_TYPE_CLEAR_CACHE_BUTTON, null, null)); itemInners.add(ItemInner.asInfo(LocaleController.getString("StorageUsageInfo", R.string.StorageUsageInfo))); } else { sectionsEndRow = -1; } itemInners.add(new ItemInner(VIEW_TYPE_HEADER, LocaleController.getString("AutoDeleteCachedMedia", R.string.AutoDeleteCachedMedia), null)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_USER)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_GROUP)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_CHANNEL)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_STORIES)); itemInners.add(ItemInner.asInfo(LocaleController.getString("KeepMediaInfoPart", R.string.KeepMediaInfoPart))); if (totalDeviceSize > 0) { itemInners.add(new ItemInner(VIEW_TYPE_HEADER, LocaleController.getString("MaxCacheSize", R.string.MaxCacheSize), null)); itemInners.add(new ItemInner(VIEW_TYPE_MAX_CACHE_SIZE)); itemInners.add(ItemInner.asInfo(LocaleController.getString("MaxCacheSizeInfo", R.string.MaxCacheSizeInfo))); } if (hasCache && cacheModel != null && !cacheModel.isEmpty()) { itemInners.add(new ItemInner(VIEW_TYPE_CACHE_VIEW_PAGER, null, null)); } if (listAdapter != null) { if (animated) { listAdapter.setItems(oldItems, itemInners); } else { listAdapter.notifyDataSetChanged(); } } if (cachedMediaLayout != null) { cachedMediaLayout.update(); } } @Override public boolean needDelayOpenAnimation() { return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); getNotificationCenter().removeObserver(this, NotificationCenter.didClearDatabase); try { if (progressDialog != null) { progressDialog.dismiss(); } } catch (Exception e) { } progressDialog = null; canceled = true; } private static long getDirectorySize(File dir, int documentsMusicType) { if (dir == null || canceled) { return 0; } long size = 0; if (dir.isDirectory()) { size = Utilities.getDirSize(dir.getAbsolutePath(), documentsMusicType, false); } else if (dir.isFile()) { size += dir.length(); } return size; } private void cleanupFolders(Utilities.Callback2<Float, Boolean> onProgress, Runnable onDone) { if (cacheModel != null) { cacheModel.clearSelection(); } if (cachedMediaLayout != null) { cachedMediaLayout.updateVisibleRows(); cachedMediaLayout.showActionMode(false); } // progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); // progressDialog.setCanCancel(false); // progressDialog.showDelayed(500); getFileLoader().cancelLoadAllFiles(); getFileLoader().getFileLoaderQueue().postRunnable(() -> Utilities.globalQueue.postRunnable(() -> { cleanupFoldersInternal(onProgress, onDone); })); setCacheModel(null); loadingDialogs = true; // updateRows(); } private static int LISTDIR_DOCTYPE_ALL = 0; private static int LISTDIR_DOCTYPE_OTHER_THAN_MUSIC = 1; private static int LISTDIR_DOCTYPE_MUSIC = 2; private static int LISTDIR_DOCTYPE2_EMOJI = 3; private static int LISTDIR_DOCTYPE2_TEMP = 4; private static int LISTDIR_DOCTYPE2_OTHER = 5; public static int countDirJava(String fileName, int docType) { int count = 0; File dir = new File(fileName); if (dir.exists()) { File[] entries = dir.listFiles(); if (entries == null) return count; for (int i = 0; i < entries.length; ++i) { File entry = entries[i]; String name = entry.getName(); if (".".equals(name)) { continue; } if (docType > 0 && name.length() >= 4) { String namelc = name.toLowerCase(); boolean isMusic = namelc.endsWith(".mp3") || namelc.endsWith(".m4a"); boolean isEmoji = namelc.endsWith(".tgs") || namelc.endsWith(".webm"); boolean isTemp = namelc.endsWith(".tmp") || namelc.endsWith(".temp") || namelc.endsWith(".preload"); if ( isMusic && docType == LISTDIR_DOCTYPE_OTHER_THAN_MUSIC || !isMusic && docType == LISTDIR_DOCTYPE_MUSIC || isEmoji && docType == LISTDIR_DOCTYPE2_OTHER || !isEmoji && docType == LISTDIR_DOCTYPE2_EMOJI || isTemp && docType == LISTDIR_DOCTYPE2_OTHER || !isTemp && docType == LISTDIR_DOCTYPE2_TEMP ) { continue; } } if (entry.isDirectory()) { count += countDirJava(fileName + "/" + name, docType); } else { count++; } } } return count; } public static void cleanDirJava(String fileName, int docType, int[] p, Utilities.Callback<Float> onProgress) { int count = countDirJava(fileName, docType); if (p == null) { p = new int[] { 0 }; } File dir = new File(fileName); if (dir.exists()) { File[] entries = dir.listFiles(); if (entries == null) return; for (int i = 0; i < entries.length; ++i) { File entry = entries[i]; String name = entry.getName(); if (".".equals(name)) { continue; } if (docType > 0 && name.length() >= 4) { String namelc = name.toLowerCase(); boolean isMusic = namelc.endsWith(".mp3") || namelc.endsWith(".m4a"); boolean isEmoji = namelc.endsWith(".tgs") || namelc.endsWith(".webm"); boolean isTemp = namelc.endsWith(".tmp") || namelc.endsWith(".temp") || namelc.endsWith(".preload"); if ( isMusic && docType == LISTDIR_DOCTYPE_OTHER_THAN_MUSIC || !isMusic && docType == LISTDIR_DOCTYPE_MUSIC || isEmoji && docType == LISTDIR_DOCTYPE2_OTHER || !isEmoji && docType == LISTDIR_DOCTYPE2_EMOJI || isTemp && docType == LISTDIR_DOCTYPE2_OTHER || !isTemp && docType == LISTDIR_DOCTYPE2_TEMP ) { continue; } } if (entry.isDirectory()) { if ("drafts".equals(entry.getName())) { continue; } cleanDirJava(fileName + "/" + name, docType, p, onProgress); } else { entry.delete(); p[0]++; onProgress.run(p[0] / (float) count); } } } } private void cleanupFoldersInternal(Utilities.Callback2<Float, Boolean> onProgress, Runnable onDone) { boolean imagesCleared = false; long clearedSize = 0; boolean allItemsClear = true; final int[] clearDirI = new int[] { 0 }; int clearDirCount = (selected[0] ? 2 : 0) + (selected[1] ? 2 : 0) + (selected[2] ? 2 : 0) + (selected[3] ? 2 : 0) + (selected[4] ? 1 : 0) + (selected[5] ? 2 : 0) + (selected[6] ? 1 : 0) + (selected[7] ? 1 : 0) + (selected[8] ? 1 : 0) + (selected[9] ? 1 : 0); long time = System.currentTimeMillis(); Utilities.Callback<Float> updateProgress = t -> { onProgress.run(clearDirI[0] / (float) clearDirCount + (1f / clearDirCount) * MathUtils.clamp(t, 0, 1), false); }; Runnable next = () -> { final long now = System.currentTimeMillis(); onProgress.run(clearDirI[0] / (float) clearDirCount, now - time > 250); }; for (int a = 0; a < 10; a++) { if (!selected[a]) { allItemsClear = false; continue; } int type = -1; int documentsMusicType = 0; if (a == 0) { type = FileLoader.MEDIA_DIR_IMAGE; clearedSize += photoSize; } else if (a == 1) { type = FileLoader.MEDIA_DIR_VIDEO; clearedSize += videoSize; } else if (a == 2) { type = FileLoader.MEDIA_DIR_DOCUMENT; documentsMusicType = 1; clearedSize += documentsSize; } else if (a == 3) { type = FileLoader.MEDIA_DIR_DOCUMENT; documentsMusicType = 2; clearedSize += musicSize; } else if (a == 4) { type = FileLoader.MEDIA_DIR_AUDIO; clearedSize += audioSize; } else if (a == 5) { type = FileLoader.MEDIA_DIR_STORIES; clearedSize += storiesSize; } else if (a == 6) { type = 100; clearedSize += stickersCacheSize; } else if (a == 7) { clearedSize += cacheSize; documentsMusicType = 5; type = FileLoader.MEDIA_DIR_CACHE; } else if (a == 8) { clearedSize += cacheTempSize; documentsMusicType = 4; type = FileLoader.MEDIA_DIR_CACHE; } else if (a == 9) { clearedSize += logsSize; documentsMusicType = 1; type = 0; } if (type == -1) { continue; } File file; if (a == 9) { file = AndroidUtilities.getLogsDir(); } else if (type == 100) { file = new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"); } else { file = FileLoader.checkDirectory(type); } if (file != null) { cleanDirJava(file.getAbsolutePath(), documentsMusicType, null, updateProgress); } clearDirI[0]++; next.run(); if (type == 100) { file = FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE); if (file != null) { cleanDirJava(file.getAbsolutePath(), 3, null, updateProgress); } clearDirI[0]++; next.run(); } if (type == FileLoader.MEDIA_DIR_IMAGE || type == FileLoader.MEDIA_DIR_VIDEO) { int publicDirectoryType; if (type == FileLoader.MEDIA_DIR_IMAGE) { publicDirectoryType = FileLoader.MEDIA_DIR_IMAGE_PUBLIC; } else { publicDirectoryType = FileLoader.MEDIA_DIR_VIDEO_PUBLIC; } file = FileLoader.checkDirectory(publicDirectoryType); if (file != null) { cleanDirJava(file.getAbsolutePath(), documentsMusicType, null, updateProgress); } clearDirI[0]++; next.run(); } if (type == FileLoader.MEDIA_DIR_DOCUMENT) { file = FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES); if (file != null) { cleanDirJava(file.getAbsolutePath(), documentsMusicType, null, updateProgress); } clearDirI[0]++; next.run(); } if (a == 9) { logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1); } else if (type == FileLoader.MEDIA_DIR_CACHE) { cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); imagesCleared = true; } else if (type == FileLoader.MEDIA_DIR_AUDIO) { audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_STORIES) { storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_DOCUMENT) { if (documentsMusicType == 1) { documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), documentsMusicType); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), documentsMusicType); } else { musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), documentsMusicType); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), documentsMusicType); } } else if (type == FileLoader.MEDIA_DIR_IMAGE) { imagesCleared = true; photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), documentsMusicType); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_VIDEO) { videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), documentsMusicType); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), documentsMusicType); } else if (type == 100) { imagesCleared = true; stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), documentsMusicType); cacheEmojiSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); stickersCacheSize += cacheEmojiSize; } } final boolean imagesClearedFinal = imagesCleared; totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + logsSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); Arrays.fill(selected, true); File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } totalDeviceSize = blocksTotal * blockSize; totalDeviceFreeSize = availableBlocks * blockSize; long finalClearedSize = clearedSize; if (allItemsClear) { FileLoader.getInstance(currentAccount).clearFilePaths(); } FileLoader.getInstance(currentAccount).checkCurrentDownloadsFiles(); AndroidUtilities.runOnUIThread(() -> { if (imagesClearedFinal) { ImageLoader.getInstance().clearMemory(); } try { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } catch (Exception e) { FileLog.e(e); } getMediaDataController().ringtoneDataStore.checkRingtoneSoundsLoaded(); AndroidUtilities.runOnUIThread(() -> { cacheRemovedTooltip.setInfoText(LocaleController.formatString("CacheWasCleared", R.string.CacheWasCleared, AndroidUtilities.formatFileSize(finalClearedSize))); cacheRemovedTooltip.showWithAction(0, UndoView.ACTION_CACHE_WAS_CLEARED, null, null); }, 150); MediaDataController.getInstance(currentAccount).checkAllMedia(true); loadDialogEntities(); if (onDone != null) { onDone.run(); } }); } private boolean changeStatusBar; @Override public void onTransitionAnimationProgress(boolean isOpen, float progress) { if (progress > .5f && !changeStatusBar) { changeStatusBar = true; NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needCheckSystemBarColors); } super.onTransitionAnimationProgress(isOpen, progress); } @Override public boolean isLightStatusBar() { if (!changeStatusBar) { return super.isLightStatusBar(); } return AndroidUtilities.computePerceivedBrightness(Theme.getColor(Theme.key_windowBackgroundGray)) > 0.721f; } private long size(int type) { switch (type) { case 0: return photoSize; case 1: return videoSize; case 2: return documentsSize; case 3: return musicSize; case 4: return audioSize; case 5: return storiesSize; case 6: return stickersCacheSize; case 7: return cacheSize; case 8: return cacheTempSize; case 9: return logsSize; default: return 0; } } private int sectionsSelected() { int count = 0; for (int i = 0; i < 10; ++i) { if (selected[i] && size(i) > 0) { count++; } } return count; } private ActionBarMenu actionMode; private AnimatedTextView actionModeTitle; private AnimatedTextView actionModeSubtitle; private TextView actionModeClearButton; @Override public View createView(Context context) { actionBar.setBackgroundDrawable(null); actionBar.setCastShadows(false); actionBar.setAddToContainer(false); actionBar.setOccupyStatusBar(true); actionBar.setTitleColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), 0)); actionBar.setItemsColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), false); actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_listSelector), false); actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setAllowOverlayTitle(false); actionBar.setTitle(LocaleController.getString("StorageUsage", R.string.StorageUsage)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { if (actionBar.isActionModeShowed()) { if (cacheModel != null) { cacheModel.clearSelection(); } if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return; } finishFragment(); } else if (id == delete_id) { clearSelectedFiles(); } else if (id == clear_database_id) { clearDatabase(false); } else if (id == reset_database_id) { clearDatabase(true); } } }); actionMode = actionBar.createActionMode(); FrameLayout actionModeLayout = new FrameLayout(context); actionMode.addView(actionModeLayout, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 72, 0, 0, 0)); actionModeTitle = new AnimatedTextView(context, true, true, true); actionModeTitle.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); actionModeTitle.setTextSize(AndroidUtilities.dp(18)); actionModeTitle.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); actionModeTitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); actionModeLayout.addView(actionModeTitle, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, -11, 18, 0)); actionModeSubtitle = new AnimatedTextView(context, true, true, true); actionModeSubtitle.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); actionModeSubtitle.setTextSize(AndroidUtilities.dp(14)); actionModeSubtitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); actionModeLayout.addView(actionModeSubtitle, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 10, 18, 0)); actionModeClearButton = new TextView(context); actionModeClearButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); actionModeClearButton.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(14), 0); actionModeClearButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); actionModeClearButton.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 6)); actionModeClearButton.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); actionModeClearButton.setGravity(Gravity.CENTER); actionModeClearButton.setText(LocaleController.getString("CacheClear", R.string.CacheClear)); actionModeClearButton.setOnClickListener(e -> clearSelectedFiles()); if (LocaleController.isRTL) { actionModeLayout.addView(actionModeClearButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 28, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0)); } else { actionModeLayout.addView(actionModeClearButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 28, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 14, 0)); } ActionBarMenuItem otherItem = actionBar.createMenu().addItem(other_id, R.drawable.ic_ab_other); clearDatabaseItem = otherItem.addSubItem(clear_database_id, R.drawable.msg_delete, LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase)); clearDatabaseItem.setIconColor(Theme.getColor(Theme.key_text_RedRegular)); clearDatabaseItem.setTextColor(Theme.getColor(Theme.key_text_RedBold)); clearDatabaseItem.setSelectorColor(Theme.multAlpha(Theme.getColor(Theme.key_text_RedRegular), .12f)); if (BuildVars.DEBUG_PRIVATE_VERSION) { resetDatabaseItem = otherItem.addSubItem(reset_database_id, R.drawable.msg_delete, "Full Reset Database"); resetDatabaseItem.setIconColor(Theme.getColor(Theme.key_text_RedRegular)); resetDatabaseItem.setTextColor(Theme.getColor(Theme.key_text_RedBold)); resetDatabaseItem.setSelectorColor(Theme.multAlpha(Theme.getColor(Theme.key_text_RedRegular), .12f)); } updateDatabaseItemSize(); listAdapter = new ListAdapter(context); nestedSizeNotifierLayout = new NestedSizeNotifierLayout(context) { @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); boolean show = !isPinnedToTop(); if (!show && actionBarShadowAlpha != 0) { actionBarShadowAlpha -= 16f / 100f; invalidate(); } else if (show && actionBarShadowAlpha != 1f) { actionBarShadowAlpha += 16f / 100f; invalidate(); } actionBarShadowAlpha = Utilities.clamp(actionBarShadowAlpha, 1f, 0); if (parentLayout != null) { parentLayout.drawHeaderShadow(canvas, (int) (0xFF * actionBarShownT * actionBarShadowAlpha), AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight()); } } }; fragmentView = nestedSizeNotifierLayout; FrameLayout frameLayout = nestedSizeNotifierLayout; frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); listView = new RecyclerListView(context) { @Override protected void dispatchDraw(Canvas canvas) { if (sectionsStartRow >= 0 && sectionsEndRow >= 0) { drawSectionBackgroundExclusive(canvas, sectionsStartRow - 1, sectionsEndRow, Theme.getColor(Theme.key_windowBackgroundWhite)); } super.dispatchDraw(canvas); } @Override protected boolean allowSelectChildAtPosition(View child) { return child != cacheChart; } }; listView.setVerticalScrollBarEnabled(false); listView.setClipToPadding(false); listView.setPadding(0, AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight() / 2, 0, 0); listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); listView.setAdapter(listAdapter); DefaultItemAnimator itemAnimator = new DefaultItemAnimator() { @Override protected void onMoveAnimationUpdate(RecyclerView.ViewHolder holder) { listView.invalidate(); } }; itemAnimator.setDurations(350); itemAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); itemAnimator.setDelayAnimations(false); itemAnimator.setSupportsChangeAnimations(false); listView.setItemAnimator(itemAnimator); listView.setOnItemClickListener((view, position, x, y) -> { if (getParentActivity() == null) { return; } if (position < 0 || position >= itemInners.size()) { return; } ItemInner item = itemInners.get(position); // if (position == databaseRow) { // clearDatabase(); // } else if (item.viewType == VIEW_TYPE_SECTION && view instanceof CheckBoxCell) { if (item.index < 0) { collapsed = !collapsed; updateRows(); updateChart(); return; } toggleSection(item, view); } else if (item.entities != null) { // if (view instanceof UserCell && selectedDialogs.size() > 0) { // selectDialog((UserCell) view, itemInners.get(position).entities.dialogId); // return; // } showClearCacheDialog(item.entities); } else if (item.keepMediaType >= 0) { KeepMediaPopupView windowLayout = new KeepMediaPopupView(this, view.getContext()); ActionBarPopupWindow popupWindow = AlertsCreator.createSimplePopup(CacheControlActivity.this, windowLayout, view, x, y); windowLayout.update(itemInners.get(position).keepMediaType); windowLayout.setParentWindow(popupWindow); windowLayout.setCallback((type, keepMedia) -> { AndroidUtilities.updateVisibleRows(listView); }); } }); listView.addOnScrollListener(new RecyclerView.OnScrollListener() { boolean pinned; @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); updateActionBar(layoutManager.findFirstVisibleItemPosition() > 0 || actionBar.isActionModeShowed()); if (pinned != nestedSizeNotifierLayout.isPinnedToTop()) { pinned = nestedSizeNotifierLayout.isPinnedToTop(); nestedSizeNotifierLayout.invalidate(); } } }); frameLayout.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); cacheRemovedTooltip = new UndoView(context); frameLayout.addView(cacheRemovedTooltip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); nestedSizeNotifierLayout.setTargetListView(listView); return fragmentView; } private void clearSelectedFiles() { if (cacheModel.getSelectedFiles() == 0 || getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(LocaleController.getString("ClearCache", R.string.ClearCache)); builder.setMessage(LocaleController.getString("ClearCacheForChats", R.string.ClearCacheForChats)); builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (di, which) -> { DialogFileEntities mergedEntities = cacheModel.removeSelectedFiles(); if (mergedEntities.totalSize > 0) { cleanupDialogFiles(mergedEntities, null, null); } cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.update(); cachedMediaLayout.showActionMode(false); } updateRows(); updateChart(); }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); AlertDialog dialog = builder.create(); showDialog(dialog); TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); } } private ValueAnimator actionBarAnimator; private float actionBarShownT; private boolean actionBarShown; private float actionBarShadowAlpha = 1f; private void updateActionBar(boolean show) { if (show != actionBarShown) { if (actionBarAnimator != null) { actionBarAnimator.cancel(); } actionBarAnimator = ValueAnimator.ofFloat(actionBarShownT, (actionBarShown = show) ? 1f : 0f); actionBarAnimator.addUpdateListener(anm -> { actionBarShownT = (float) anm.getAnimatedValue(); actionBar.setTitleColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), (int) (255 * actionBarShownT))); actionBar.setBackgroundColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhite), (int) (255 * actionBarShownT))); fragmentView.invalidate(); }); actionBarAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); actionBarAnimator.setDuration(380); actionBarAnimator.start(); } } private void showClearCacheDialog(DialogFileEntities entities) { if (totalSize <= 0 || getParentActivity() == null) { return; } bottomSheet = new DilogCacheBottomSheet(CacheControlActivity.this, entities, entities.createCacheModel(), new DilogCacheBottomSheet.Delegate() { @Override public void onAvatarClick() { bottomSheet.dismiss(); Bundle args = new Bundle(); if (entities.dialogId > 0) { args.putLong("user_id", entities.dialogId); } else { args.putLong("chat_id", -entities.dialogId); } presentFragment(new ProfileActivity(args, null)); } @Override public void cleanupDialogFiles(DialogFileEntities entities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel cacheModel) { CacheControlActivity.this.cleanupDialogFiles(entities, clearViewData, cacheModel); } }); showDialog(bottomSheet); } private void cleanupDialogFiles(DialogFileEntities dialogEntities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel dialogCacheModel) { final AlertDialog progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); HashSet<CacheModel.FileInfo> filesToRemove = new HashSet<>(); long totalSizeBefore = totalSize; for (int a = 0; a < 8; a++) { if (clearViewData != null) { if (clearViewData[a] == null || !clearViewData[a].clear) { continue; } } FileEntities entitiesToDelete = dialogEntities.entitiesByType.get(a); if (entitiesToDelete == null) { continue; } filesToRemove.addAll(entitiesToDelete.files); dialogEntities.totalSize -= entitiesToDelete.totalSize; totalSize -= entitiesToDelete.totalSize; totalDeviceFreeSize += entitiesToDelete.totalSize; dialogEntities.entitiesByType.delete(a); if (a == TYPE_PHOTOS) { photoSize -= entitiesToDelete.totalSize; } else if (a == TYPE_VIDEOS) { videoSize -= entitiesToDelete.totalSize; } else if (a == TYPE_DOCUMENTS) { documentsSize -= entitiesToDelete.totalSize; } else if (a == TYPE_MUSIC) { musicSize -= entitiesToDelete.totalSize; } else if (a == TYPE_VOICE) { audioSize -= entitiesToDelete.totalSize; } else if (a == TYPE_ANIMATED_STICKERS_CACHE) { stickersCacheSize -= entitiesToDelete.totalSize; } else if (a == TYPE_STORIES) { for (int i = 0; i < entitiesToDelete.files.size(); i++) { CacheModel.FileInfo fileInfo = entitiesToDelete.files.get(i); int type = getTypeByPath(entitiesToDelete.files.get(i).file.getAbsolutePath()); if (type == TYPE_STORIES) { storiesSize -= fileInfo.size; } else if (type == TYPE_PHOTOS) { photoSize -= fileInfo.size; } else if (type == TYPE_VIDEOS) { videoSize -= fileInfo.size; } else { cacheSize -= fileInfo.size; } } // cacheSize -= entitiesToDelete.totalSize; }else { cacheSize -= entitiesToDelete.totalSize; } } if (dialogEntities.entitiesByType.size() == 0) { cacheModel.remove(dialogEntities); } updateRows(); if (dialogCacheModel != null) { for (CacheModel.FileInfo fileInfo : dialogCacheModel.selectedFiles) { if (!filesToRemove.contains(fileInfo)) { totalSize -= fileInfo.size; totalDeviceFreeSize += fileInfo.size; filesToRemove.add(fileInfo); dialogEntities.removeFile(fileInfo); if (fileInfo.type == TYPE_PHOTOS) { photoSize -= fileInfo.size; } else if (fileInfo.type == TYPE_VIDEOS) { videoSize -= fileInfo.size; } else if (fileInfo.type == TYPE_DOCUMENTS) { documentsSize -= fileInfo.size; } else if (fileInfo.type == TYPE_MUSIC) { musicSize -= fileInfo.size; } else if (fileInfo.type == TYPE_VOICE) { audioSize -= fileInfo.size; } } } } for (CacheModel.FileInfo fileInfo : filesToRemove) { this.cacheModel.onFileDeleted(fileInfo); } cacheRemovedTooltip.setInfoText(LocaleController.formatString("CacheWasCleared", R.string.CacheWasCleared, AndroidUtilities.formatFileSize(totalSizeBefore - totalSize))); cacheRemovedTooltip.showWithAction(0, UndoView.ACTION_CACHE_WAS_CLEARED, null, null); ArrayList<CacheModel.FileInfo> fileInfos = new ArrayList<>(filesToRemove); getFileLoader().getFileDatabase().removeFiles(fileInfos); getFileLoader().cancelLoadAllFiles(); getFileLoader().getFileLoaderQueue().postRunnable(() -> { for (int i = 0; i < fileInfos.size(); i++) { fileInfos.get(i).file.delete(); } AndroidUtilities.runOnUIThread(() -> { FileLoader.getInstance(currentAccount).checkCurrentDownloadsFiles(); try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e(e); } }); }); } private int getTypeByPath(String absolutePath) { if (pathContains(absolutePath, FileLoader.MEDIA_DIR_STORIES)) { return TYPE_STORIES; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_IMAGE)) { return TYPE_PHOTOS; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_IMAGE_PUBLIC)) { return TYPE_PHOTOS; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_VIDEO)) { return TYPE_VIDEOS; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_VIDEO_PUBLIC)) { return TYPE_VIDEOS; } return TYPE_OTHER; } private boolean pathContains(String path, int mediaDirType) { if (path == null || FileLoader.checkDirectory(mediaDirType) == null) { return false; } return path.contains(FileLoader.checkDirectory(mediaDirType).getAbsolutePath()); } @RequiresApi(api = Build.VERSION_CODES.R) private void migrateOldFolder() { FilesMigrationService.checkBottomSheet(this); } private void clearDatabase(boolean fullReset) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("LocalDatabaseClearTextTitle", R.string.LocalDatabaseClearTextTitle)); SpannableStringBuilder message = new SpannableStringBuilder(); message.append(LocaleController.getString("LocalDatabaseClearText", R.string.LocalDatabaseClearText)); message.append("\n\n"); message.append(AndroidUtilities.replaceTags(LocaleController.formatString("LocalDatabaseClearText2", R.string.LocalDatabaseClearText2, AndroidUtilities.formatFileSize(databaseSize)))); builder.setMessage(message); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear), (dialogInterface, i) -> { if (getParentActivity() == null) { return; } progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); MessagesController.getInstance(currentAccount).clearQueryTime(); if (fullReset) { getMessagesStorage().fullReset(); } else { getMessagesStorage().clearLocalDatabase(); } }); AlertDialog alertDialog = builder.create(); showDialog(alertDialog); TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); } } @Override public void onResume() { super.onResume(); listAdapter.notifyDataSetChanged(); if (!calculating) { // loadDialogEntities(); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.didClearDatabase) { try { if (progressDialog != null) { progressDialog.dismiss(); } } catch (Exception e) { FileLog.e(e); } progressDialog = null; if (listAdapter != null) { databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize(); updateDatabaseSize = true; updateDatabaseItemSize(); updateRows(); } } } class CacheChartHeader extends FrameLayout { AnimatedTextView title; TextView[] subtitle = new TextView[3]; View bottomImage; RectF progressRect = new RectF(); LoadingDrawable loadingDrawable = new LoadingDrawable(); Float percent, usedPercent; AnimatedFloat percentAnimated = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat usedPercentAnimated = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat loadingFloat = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); Paint loadingBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint percentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint usedPercentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); boolean firstSet = true; public CacheChartHeader(Context context) { super(context); title = new AnimatedTextView(context); title.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); title.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); title.setTextSize(AndroidUtilities.dp(20)); title.setText(LocaleController.getString("StorageUsage", R.string.StorageUsage)); title.setGravity(Gravity.CENTER); title.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); addView(title, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 26, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); for (int i = 0; i < 3; ++i) { subtitle[i] = new TextView(context); subtitle[i].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); subtitle[i].setGravity(Gravity.CENTER); subtitle[i].setPadding(AndroidUtilities.dp(24), 0, AndroidUtilities.dp(24), 0); if (i == 0) { subtitle[i].setText(LocaleController.getString("StorageUsageCalculating", R.string.StorageUsageCalculating)); } else if (i == 1) { subtitle[i].setAlpha(0); subtitle[i].setText(LocaleController.getString("StorageUsageTelegram", R.string.StorageUsageTelegram)); subtitle[i].setVisibility(View.INVISIBLE); } else if (i == 2) { subtitle[i].setText(LocaleController.getString("StorageCleared2", R.string.StorageCleared2)); subtitle[i].setAlpha(0); subtitle[i].setVisibility(View.INVISIBLE); } subtitle[i].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4)); addView(subtitle[i], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, i == 2 ? 12 : -6, 0, 0)); } bottomImage = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec) + getPaddingLeft() + getPaddingRight(), MeasureSpec.EXACTLY), heightMeasureSpec); } }; Drawable bottomImageDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert2).mutate(); bottomImageDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhite), PorterDuff.Mode.MULTIPLY)); bottomImage.setBackground(bottomImageDrawable); MarginLayoutParams bottomImageParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 24, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL); bottomImageParams.leftMargin = -bottomImage.getPaddingLeft(); bottomImageParams.bottomMargin = -AndroidUtilities.dp(11); bottomImageParams.rightMargin = -bottomImage.getPaddingRight(); addView(bottomImage, bottomImageParams); int color = Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4); loadingDrawable.setColors( Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), Theme.multAlpha(color, .2f) ); loadingDrawable.setRadiiDp(4); loadingDrawable.setCallback(this); } public void setData(boolean hasCache, float percent, float usedPercent) { title.setText( hasCache ? LocaleController.getString("StorageUsage", R.string.StorageUsage) : LocaleController.getString("StorageCleared", R.string.StorageCleared) ); if (hasCache) { if (percent < 0.01f) { subtitle[1].setText(LocaleController.formatString("StorageUsageTelegramLess", R.string.StorageUsageTelegramLess, formatPercent(percent))); } else { subtitle[1].setText(LocaleController.formatString("StorageUsageTelegram", R.string.StorageUsageTelegram, formatPercent(percent))); } switchSubtitle(1); } else { switchSubtitle(2); } bottomImage.animate().cancel(); if (firstSet) { bottomImage.setAlpha(hasCache ? 1 : 0); } else { bottomImage.animate().alpha(hasCache ? 1 : 0).setDuration(365).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start(); } firstSet = false; this.percent = percent; this.usedPercent = usedPercent; invalidate(); } private void switchSubtitle(int type) { boolean animated = System.currentTimeMillis() - fragmentCreateTime > 40; updateViewVisible(subtitle[0], type == 0, animated); updateViewVisible(subtitle[1], type == 1, animated); updateViewVisible(subtitle[2], type == 2, animated); } private void updateViewVisible(View view, boolean show, boolean animated) { if (view == null) { return; } if (view.getParent() == null) { animated = false; } view.animate().setListener(null).cancel(); if (!animated) { view.setVisibility(show ? View.VISIBLE : View.INVISIBLE); view.setTag(show ? 1 : null); view.setAlpha(show ? 1f : 0f); view.setTranslationY(show ? 0 : AndroidUtilities.dp(8)); invalidate(); } else if (show) { if (view.getVisibility() != View.VISIBLE) { view.setVisibility(View.VISIBLE); view.setAlpha(0f); view.setTranslationY(AndroidUtilities.dp(8)); } view.animate().alpha(1f).translationY(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340).setUpdateListener(anm -> invalidate()).start(); } else { view.animate().alpha(0).translationY(AndroidUtilities.dp(8)).setListener(new HideViewAfterAnimation(view)).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340).setUpdateListener(anm -> invalidate()).start(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int fullWidth = MeasureSpec.getSize(widthMeasureSpec); int width = (int) Math.min(AndroidUtilities.dp(174), fullWidth * .8); super.measureChildren(MeasureSpec.makeMeasureSpec(fullWidth, MeasureSpec.EXACTLY), heightMeasureSpec); int height = AndroidUtilities.dp(90 - 18); int maxSubtitleHeight = 0; for (int i = 0; i < subtitle.length; ++i) { maxSubtitleHeight = Math.max(maxSubtitleHeight, subtitle[i].getMeasuredHeight() - (i == 2 ? AndroidUtilities.dp(16) : 0)); } height += maxSubtitleHeight; setMeasuredDimension(fullWidth, height); progressRect.set( (fullWidth - width) / 2f, height - AndroidUtilities.dp(30), (fullWidth + width) / 2f, height - AndroidUtilities.dp(30 - 4) ); } @Override protected void dispatchDraw(Canvas canvas) { float barAlpha = 1f - subtitle[2].getAlpha(); float loading = this.loadingFloat.set(this.percent == null ? 1f : 0f); float percent = this.percentAnimated.set(this.percent == null ? 0 : this.percent); float usedPercent = this.usedPercentAnimated.set(this.usedPercent == null ? 0 : this.usedPercent); loadingBackgroundPaint.setColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector)); loadingBackgroundPaint.setAlpha((int) (loadingBackgroundPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set( Math.max( progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), usedPercent * progressRect.width()), progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()) ) + AndroidUtilities.dp(1), progressRect.top, progressRect.right, progressRect.bottom ); if (AndroidUtilities.rectTmp.left < AndroidUtilities.rectTmp.right && AndroidUtilities.rectTmp.width() > AndroidUtilities.dp(3)) { drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(AndroidUtilities.lerp(1, 2, loading)), AndroidUtilities.dp(2), loadingBackgroundPaint); } loadingDrawable.setBounds(progressRect); loadingDrawable.setAlpha((int) (0xFF * barAlpha * loading)); loadingDrawable.draw(canvas); usedPercentPaint.setColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_radioBackgroundChecked), Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), .75f)); usedPercentPaint.setAlpha((int) (usedPercentPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set( progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()) + AndroidUtilities.dp(1), progressRect.top, progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), usedPercent * progressRect.width()), progressRect.bottom ); if (AndroidUtilities.rectTmp.width() > AndroidUtilities.dp(3)) { drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(1), AndroidUtilities.dp(usedPercent > .97f ? 2 : 1), usedPercentPaint); } percentPaint.setColor(Theme.getColor(Theme.key_radioBackgroundChecked)); percentPaint.setAlpha((int) (percentPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set(progressRect.left, progressRect.top, progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()), progressRect.bottom); drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(2), AndroidUtilities.dp(percent > .97f ? 2 : 1), percentPaint); if (loading > 0 || this.percentAnimated.isInProgress()) { invalidate(); } super.dispatchDraw(canvas); } private Path roundPath; private float[] radii; private void drawRoundRect(Canvas canvas, RectF rect, float left, float right, Paint paint) { if (roundPath == null) { roundPath = new Path(); } else { roundPath.rewind(); } if (radii == null) { radii = new float[8]; } radii[0] = radii[1] = radii[6] = radii[7] = left; radii[2] = radii[3] = radii[4] = radii[5] = right; roundPath.addRoundRect(rect, radii, Path.Direction.CW); canvas.drawPath(roundPath, paint); } } private class ClearingCacheView extends FrameLayout { RLottieImageView imageView; AnimatedTextView percentsTextView; ProgressView progressView; TextView title, subtitle; public ClearingCacheView(Context context) { super(context); imageView = new RLottieImageView(context); imageView.setAutoRepeat(true); imageView.setAnimation(R.raw.utyan_cache, 150, 150); addView(imageView, LayoutHelper.createFrame(150, 150, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0)); imageView.playAnimation(); percentsTextView = new AnimatedTextView(context, false, true, true); percentsTextView.setAnimationProperties(.35f, 0, 120, CubicBezierInterpolator.EASE_OUT); percentsTextView.setGravity(Gravity.CENTER_HORIZONTAL); percentsTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); percentsTextView.setTextSize(AndroidUtilities.dp(24)); percentsTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); addView(percentsTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 - 6, 0, 0)); progressView = new ProgressView(context); addView(progressView, LayoutHelper.createFrame(240, 5, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 + 28 + 16, 0, 0)); title = new TextView(context); title.setGravity(Gravity.CENTER_HORIZONTAL); title.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); title.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); title.setText(LocaleController.getString("ClearingCache", R.string.ClearingCache)); addView(title, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 + 28 + 16 + 5 + 30, 0, 0)); subtitle = new TextView(context); subtitle.setGravity(Gravity.CENTER_HORIZONTAL); subtitle.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); subtitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitle.setText(LocaleController.getString("ClearingCacheDescription", R.string.ClearingCacheDescription)); addView(subtitle, LayoutHelper.createFrame(240, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 + 28 + 16 + 5 + 30 + 18 + 10, 0, 0)); setProgress(0); } public void setProgress(float t) { percentsTextView.cancelAnimation(); percentsTextView.setText(String.format("%d%%", (int) Math.ceil(MathUtils.clamp(t, 0, 1) * 100)), !LocaleController.isRTL); progressView.setProgress(t); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure( MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(350), MeasureSpec.EXACTLY) ); } class ProgressView extends View { Paint in = new Paint(Paint.ANTI_ALIAS_FLAG), out = new Paint(Paint.ANTI_ALIAS_FLAG); public ProgressView(Context context) { super(context); in.setColor(Theme.getColor(Theme.key_switchTrackChecked)); out.setColor(Theme.multAlpha(Theme.getColor(Theme.key_switchTrackChecked), .2f)); } float progress; AnimatedFloat progressT = new AnimatedFloat(this, 350, CubicBezierInterpolator.EASE_OUT); public void setProgress(float t) { this.progress = t; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); AndroidUtilities.rectTmp.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(3), AndroidUtilities.dp(3), out); AndroidUtilities.rectTmp.set(0, 0, getMeasuredWidth() * progressT.set(this.progress), getMeasuredHeight()); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(3), AndroidUtilities.dp(3), in); } } } private class ClearCacheButtonInternal extends ClearCacheButton { public ClearCacheButtonInternal(Context context) { super(context); ((MarginLayoutParams) button.getLayoutParams()).topMargin = AndroidUtilities.dp(5); button.setOnClickListener(e -> { AlertDialog dialog = new AlertDialog.Builder(getContext()) .setTitle(LocaleController.getString("ClearCache", R.string.ClearCache) + (TextUtils.isEmpty(valueTextView.getText()) ? "" : " (" + valueTextView.getText() + ")")) .setMessage(LocaleController.getString("StorageUsageInfo", R.string.StorageUsageInfo)) .setPositiveButton(textView.getText(), (di, v) -> doClearCache()) .setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null) .create(); showDialog(dialog); View clearButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); if (clearButton instanceof TextView) { ((TextView) clearButton).setTextColor(Theme.getColor(Theme.key_text_RedRegular)); clearButton.setBackground(Theme.getRoundRectSelectorDrawable(AndroidUtilities.dp(6), Theme.multAlpha(Theme.getColor(Theme.key_text_RedRegular), .12f))); } }); } private void doClearCache() { BottomSheet bottomSheet = new BottomSheet(getContext(), false) { @Override protected boolean canDismissWithTouchOutside() { return false; } }; bottomSheet.fixNavigationBar(); bottomSheet.setCanDismissWithSwipe(false); bottomSheet.setCancelable(false); ClearingCacheView cacheView = new ClearingCacheView(getContext()); bottomSheet.setCustomView(cacheView); final boolean[] done = new boolean[] { false }; final float[] progress = new float[] { 0 }; final boolean[] nextSection = new boolean[] { false }; Runnable updateProgress = () -> { cacheView.setProgress(progress[0]); if (nextSection[0]) { updateRows(); } }; final long[] start = new long[] { -1 }; AndroidUtilities.runOnUIThread(() -> { if (!done[0]) { start[0] = System.currentTimeMillis(); showDialog(bottomSheet); } }, 150); cleanupFolders( (progressValue, next) -> { progress[0] = progressValue; nextSection[0] = next; AndroidUtilities.cancelRunOnUIThread(updateProgress); AndroidUtilities.runOnUIThread(updateProgress); }, () -> AndroidUtilities.runOnUIThread(() -> { done[0] = true; cacheView.setProgress(1F); if (start[0] > 0) { AndroidUtilities.runOnUIThread(bottomSheet::dismiss, Math.max(0, 1000 - (System.currentTimeMillis() - start[0]))); } else { bottomSheet.dismiss(); } }) ); } public void updateSize() { long size = ( (selected[0] ? photoSize : 0) + (selected[1] ? videoSize : 0) + (selected[2] ? documentsSize : 0) + (selected[3] ? musicSize : 0) + (selected[4] ? audioSize : 0) + (selected[5] ? storiesSize : 0) + (selected[6] ? stickersCacheSize : 0) + (selected[7] ? cacheSize : 0) + (selected[8] ? cacheTempSize : 0) + (selected[9] ? logsSize : 0) ); setSize( isAllSectionsSelected(), size ); } } private boolean isAllSectionsSelected() { for (int i = 0; i < itemInners.size(); ++i) { ItemInner item = itemInners.get(i); if (item.viewType != VIEW_TYPE_SECTION) { continue; } int index = item.index; if (index < 0) { index = selected.length - 1; } if (!selected[index]) { return false; } } return true; } public static class ClearCacheButton extends FrameLayout { FrameLayout button; AnimatedTextView.AnimatedTextDrawable textView; AnimatedTextView.AnimatedTextDrawable valueTextView; TextView rtlTextView; public ClearCacheButton(Context context) { super(context); button = new FrameLayout(context) { @Override protected void dispatchDraw(Canvas canvas) { final int margin = AndroidUtilities.dp(8); int x = (getMeasuredWidth() - margin - (int) valueTextView.getCurrentWidth() + (int) textView.getCurrentWidth()) / 2; if (LocaleController.isRTL) { super.dispatchDraw(canvas); } else { textView.setBounds(0, 0, x, getHeight()); textView.draw(canvas); valueTextView.setBounds(x + AndroidUtilities.dp(8), 0, getWidth(), getHeight()); valueTextView.draw(canvas); } } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return who == valueTextView || who == textView || super.verifyDrawable(who); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName("android.widget.Button"); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { super.onInterceptTouchEvent(ev); return true; } }; button.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 8)); button.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); if (LocaleController.isRTL) { rtlTextView = new TextView(context); rtlTextView.setText(LocaleController.getString("ClearCache", R.string.ClearCache)); rtlTextView.setGravity(Gravity.CENTER); rtlTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); rtlTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); rtlTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); button.addView(rtlTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER)); } textView = new AnimatedTextView.AnimatedTextDrawable(true, true, true); textView.setAnimationProperties(.25f, 0, 300, CubicBezierInterpolator.EASE_OUT_QUINT); textView.setCallback(button); textView.setTextSize(AndroidUtilities.dp(14)); textView.setText(LocaleController.getString("ClearCache", R.string.ClearCache)); textView.setGravity(Gravity.RIGHT); textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); valueTextView = new AnimatedTextView.AnimatedTextDrawable(true, true, true); valueTextView.setAnimationProperties(.25f, 0, 300, CubicBezierInterpolator.EASE_OUT_QUINT); valueTextView.setCallback(button); valueTextView.setTextSize(AndroidUtilities.dp(14)); valueTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); valueTextView.setTextColor(Theme.blendOver(Theme.getColor(Theme.key_featuredStickers_addButton), Theme.multAlpha(Theme.getColor(Theme.key_featuredStickers_buttonText), .7f))); valueTextView.setText(""); button.setContentDescription(TextUtils.concat(textView.getText(), "\t", valueTextView.getText())); setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); addView(button, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.FILL, 16, 16, 16, 16)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure( MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), heightMeasureSpec ); } public void setSize(boolean allSelected, long size) { textView.setText(( allSelected ? LocaleController.getString("ClearCache", R.string.ClearCache) : LocaleController.getString("ClearSelectedCache", R.string.ClearSelectedCache) )); valueTextView.setText(size <= 0 ? "" : AndroidUtilities.formatFileSize(size)); setDisabled(size <= 0); button.invalidate(); button.setContentDescription(TextUtils.concat(textView.getText(), "\t", valueTextView.getText())); } public void setDisabled(boolean disabled) { button.animate().cancel(); button.animate().alpha(disabled ? .65f : 1f).start(); button.setClickable(!disabled); } } private boolean isOtherSelected() { boolean[] indexes = new boolean[CacheControlActivity.this.selected.length]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0) { indexes[item2.index] = true; } } for (int i = 0; i < indexes.length; ++i) { if (!indexes[i] && !CacheControlActivity.this.selected[i]) { return false; } } return true; } private void toggleSection(ItemInner item, View cell) { if (item.index < 0) { toggleOtherSelected(cell); return; } if (selected[item.index] && sectionsSelected() <= 1) { BotWebViewVibrationEffect.APP_ERROR.vibrate(); if (cell != null) { AndroidUtilities.shakeViewSpring(cell, -3); } return; } if (cell instanceof CheckBoxCell) { ((CheckBoxCell) cell).setChecked(selected[item.index] = !selected[item.index], true); } else { selected[item.index] = !selected[item.index]; int position = itemInners.indexOf(item); if (position >= 0) { for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell && position == listView.getChildAdapterPosition(child)) { ((CheckBoxCell) child).setChecked(selected[item.index], true); } } } } if (item.pad) { for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell) { int pos = listView.getChildAdapterPosition(child); if (pos >= 0 && pos < itemInners.size() && itemInners.get(pos).index < 0) { ((CheckBoxCell) child).setChecked(isOtherSelected(), true); break; } } } } updateChart(); } private void toggleOtherSelected(View cell) { boolean selected = isOtherSelected(); if (selected) { boolean hasNonOtherSelected = false; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0 && CacheControlActivity.this.selected[item2.index]) { hasNonOtherSelected = true; break; } } if (!hasNonOtherSelected) { BotWebViewVibrationEffect.APP_ERROR.vibrate(); if (cell != null) { AndroidUtilities.shakeViewSpring(cell, -3); } return; } } if (collapsed) { boolean[] indexes = new boolean[CacheControlActivity.this.selected.length]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0) { indexes[item2.index] = true; } } for (int i = 0; i < indexes.length; ++i) { if (!indexes[i]) { CacheControlActivity.this.selected[i] = !selected; } } } else { for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && item2.pad && item2.index >= 0) { CacheControlActivity.this.selected[item2.index] = !selected; } } } for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell) { int pos = listView.getChildAdapterPosition(child); if (pos >= 0) { ItemInner item2 = itemInners.get(pos); if (item2.viewType == VIEW_TYPE_SECTION) { if (item2.index < 0) { ((CheckBoxCell) child).setChecked(!selected, true); } else { ((CheckBoxCell) child).setChecked(CacheControlActivity.this.selected[item2.index], true); } } } } } updateChart(); } private class ListAdapter extends AdapterWithDiffUtils { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { int position = holder.getAdapterPosition(); return position == migrateOldFolderRow || (holder.getItemViewType() == VIEW_TYPE_STORAGE && (totalSize > 0) && !calculating) || holder.getItemViewType() == VIEW_TYPE_CHAT || holder.getItemViewType() == VIEW_TYPE_KEEP_MEDIA_CELL || holder.getItemViewType() == VIEW_TYPE_SECTION; } @Override public int getItemCount() { return itemInners.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; switch (viewType) { case VIEW_TYPE_TEXT_SETTINGS: view = new TextSettingsCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_STORAGE: view = new StorageUsageView(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_HEADER: view = new HeaderCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_CHOOSER: SlideChooseView slideChooseView = new SlideChooseView(mContext); view = slideChooseView; view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); slideChooseView.setCallback(index -> { if (index == 0) { SharedConfig.setKeepMedia(3); } else if (index == 1) { SharedConfig.setKeepMedia(0); } else if (index == 2) { SharedConfig.setKeepMedia(1); } else if (index == 3) { SharedConfig.setKeepMedia(2); } }); int keepMedia = SharedConfig.keepMedia; int index; if (keepMedia == 3) { index = 0; } else { index = keepMedia + 1; } slideChooseView.setOptions(index, LocaleController.formatPluralString("Days", 3), LocaleController.formatPluralString("Weeks", 1), LocaleController.formatPluralString("Months", 1), LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever)); break; case VIEW_TYPE_CHAT: UserCell userCell = new UserCell(getContext(), getResourceProvider()); userCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = userCell; break; case VIEW_FLICKER_LOADING_DIALOG: FlickerLoadingView flickerLoadingView = new FlickerLoadingView(getContext()); flickerLoadingView.setIsSingleCell(true); flickerLoadingView.setItemsCount(3); flickerLoadingView.setIgnoreHeightCheck(true); flickerLoadingView.setViewType(FlickerLoadingView.DIALOG_CACHE_CONTROL); flickerLoadingView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = flickerLoadingView; break; case VIEW_TYPE_KEEP_MEDIA_CELL: view = new TextCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_CHART: view = cacheChart = new CacheChart(mContext) { @Override protected void onSectionClick(int index) { // if (index == 8) { // index = -1; // } // for (int i = 0; i < itemInners.size(); ++i) { // ItemInner item = itemInners.get(i); // if (item != null && item.index == index) { // toggleSection(item, null); // return; // } // } } @Override protected void onSectionDown(int index, boolean down) { if (!down) { listView.removeHighlightRow(); return; } if (index == 8) { index = -1; } int position = -1; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2 != null && item2.viewType == VIEW_TYPE_SECTION && item2.index == index) { position = i; break; } } if (position >= 0) { final int finalPosition = position; listView.highlightRow(() -> finalPosition, 0); } else { listView.removeHighlightRow(); } } }; break; case VIEW_TYPE_CHART_HEADER: view = cacheChartHeader = new CacheChartHeader(mContext); break; case VIEW_TYPE_SECTION_LOADING: FlickerLoadingView flickerLoadingView2 = new FlickerLoadingView(getContext()); flickerLoadingView2.setIsSingleCell(true); flickerLoadingView2.setItemsCount(1); flickerLoadingView2.setIgnoreHeightCheck(true); flickerLoadingView2.setViewType(FlickerLoadingView.CHECKBOX_TYPE); flickerLoadingView2.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = flickerLoadingView2; break; case VIEW_TYPE_SECTION: view = new CheckBoxCell(mContext, 4, 21, getResourceProvider()); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_INFO: default: view = new TextInfoPrivacyCell(mContext); break; case VIEW_TYPE_CACHE_VIEW_PAGER: view = cachedMediaLayout = new CachedMediaLayout(mContext, CacheControlActivity.this) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - (ActionBar.getCurrentActionBarHeight() / 2), MeasureSpec.EXACTLY)); } @Override protected void showActionMode(boolean show) { if (show) { updateActionBar(true); actionBar.showActionMode(); } else { actionBar.hideActionMode(); } } @Override protected boolean actionModeIsVisible() { return actionBar.isActionModeShowed(); } }; cachedMediaLayout.setDelegate(new CachedMediaLayout.Delegate() { @Override public void onItemSelected(DialogFileEntities entities, CacheModel.FileInfo fileInfo, boolean longPress) { if (entities != null) { if ((cacheModel.getSelectedFiles() > 0 || longPress)) { cacheModel.toggleSelect(entities); cachedMediaLayout.updateVisibleRows(); updateActionMode(); } else { showClearCacheDialog(entities); } return; } if (fileInfo != null) { cacheModel.toggleSelect(fileInfo); cachedMediaLayout.updateVisibleRows(); updateActionMode(); } } @Override public void clear() { clearSelectedFiles(); } @Override public void clearSelection() { if (cacheModel != null && cacheModel.getSelectedFiles() > 0) { cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return; } } }); cachedMediaLayout.setCacheModel(cacheModel); nestedSizeNotifierLayout.setChildLayout(cachedMediaLayout); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); break; case VIEW_TYPE_CLEAR_CACHE_BUTTON: view = clearCacheButton = new ClearCacheButtonInternal(mContext); break; case VIEW_TYPE_MAX_CACHE_SIZE: SlideChooseView slideChooseView2 = new SlideChooseView(mContext); view = slideChooseView2; view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); float totalSizeInGb = (int) (totalDeviceSize / 1024L / 1024L) / 1000.0f; ArrayList<Integer> options = new ArrayList<>(); // if (BuildVars.DEBUG_PRIVATE_VERSION) { // options.add(1); // } if (totalSizeInGb <= 17) { options.add(2); } if (totalSizeInGb > 5) { options.add(5); } if (totalSizeInGb > 16) { options.add(16); } if (totalSizeInGb > 32) { options.add(32); } options.add(Integer.MAX_VALUE); String[] values = new String[options.size()]; for (int i = 0; i < options.size(); i++) { if (options.get(i) == 1) { values[i] = String.format("300 MB"); } else if (options.get(i) == Integer.MAX_VALUE) { values[i] = LocaleController.getString("NoLimit", R.string.NoLimit); } else { values[i] = String.format("%d GB", options.get(i)); } } slideChooseView2.setCallback(i -> { SharedConfig.getPreferences().edit().putInt("cache_limit", options.get(i)).apply(); }); int currentLimit = SharedConfig.getPreferences().getInt("cache_limit", Integer.MAX_VALUE); int i = options.indexOf(currentLimit); if (i < 0) { i = options.size() - 1; } slideChooseView2.setOptions(i, values); break; } return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final ItemInner item = itemInners.get(position); switch (holder.getItemViewType()) { case VIEW_TYPE_CHART: updateChart(); break; case VIEW_TYPE_CHART_HEADER: if (cacheChartHeader != null && !calculating) { cacheChartHeader.setData( totalSize > 0, totalDeviceSize <= 0 ? 0 : (float) totalSize / totalDeviceSize, totalDeviceFreeSize <= 0 || totalDeviceSize <= 0 ? 0 : (float) (totalDeviceSize - totalDeviceFreeSize) / totalDeviceSize ); } break; case VIEW_TYPE_SECTION: CheckBoxCell cell = (CheckBoxCell) holder.itemView; final boolean selected; if (item.index < 0) { selected = isOtherSelected(); } else { selected = CacheControlActivity.this.selected[item.index]; } cell.setText(getCheckBoxTitle(item.headerName, percents[item.index < 0 ? 9 : item.index], item.index < 0), AndroidUtilities.formatFileSize(item.size), selected, item.index < 0 ? !collapsed : !item.last); cell.setCheckBoxColor(item.colorKey, Theme.key_windowBackgroundWhiteGrayIcon, Theme.key_checkboxCheck); cell.setCollapsed(item.index < 0 ? collapsed : null); if (item.index == -1) { cell.setOnSectionsClickListener(e -> { collapsed = !collapsed; updateRows(); updateChart(); }, e -> toggleOtherSelected(cell)); } else { cell.setOnSectionsClickListener(null, null); } cell.setPad(item.pad ? 1 : 0); break; case VIEW_TYPE_KEEP_MEDIA_CELL: TextCell textCell2 = (TextCell) holder.itemView; CacheByChatsController cacheByChatsController = getMessagesController().getCacheByChatsController(); int keepMediaType = item.keepMediaType; int exceptionsCount = cacheByChatsController.getKeepMediaExceptions(itemInners.get(position).keepMediaType).size(); String subtitle = null; if (exceptionsCount > 0) { subtitle = LocaleController.formatPluralString("ExceptionShort", exceptionsCount, exceptionsCount); } String value = CacheByChatsController.getKeepMediaString(cacheByChatsController.getKeepMedia(keepMediaType)); if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_USER) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("PrivateChats", R.string.PrivateChats), value, true, R.drawable.msg_filled_menu_users, getThemedColor(Theme.key_statisticChartLine_lightblue), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_GROUP) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("GroupChats", R.string.GroupChats), value, true, R.drawable.msg_filled_menu_groups, getThemedColor(Theme.key_statisticChartLine_green), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_CHANNEL) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("CacheChannels", R.string.CacheChannels), value, true, R.drawable.msg_filled_menu_channels, getThemedColor(Theme.key_statisticChartLine_golden), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_STORIES) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("CacheStories", R.string.CacheStories), value, false, R.drawable.msg_filled_stories, getThemedColor(Theme.key_statisticChartLine_red), false); } textCell2.setSubtitle(subtitle); break; case VIEW_TYPE_TEXT_SETTINGS: TextSettingsCell textCell = (TextSettingsCell) holder.itemView; // if (position == databaseRow) { // textCell.setTextAndValue(LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase), AndroidUtilities.formatFileSize(databaseSize), updateDatabaseSize, false); // updateDatabaseSize = false; // } else if (position == migrateOldFolderRow) { textCell.setTextAndValue(LocaleController.getString("MigrateOldFolder", R.string.MigrateOldFolder), null, false); } break; case VIEW_TYPE_INFO: TextInfoPrivacyCell privacyCell = (TextInfoPrivacyCell) holder.itemView; // if (position == databaseInfoRow) { // privacyCell.setText(LocaleController.getString("LocalDatabaseInfo", R.string.LocalDatabaseInfo)); // privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); // } else if (position == keepMediaInfoRow) { // privacyCell.setText(AndroidUtilities.replaceTags(LocaleController.getString("KeepMediaInfo", R.string.KeepMediaInfo))); // privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); // } else { privacyCell.setText(AndroidUtilities.replaceTags(item.text)); privacyCell.setBackgroundDrawable(Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); // } break; case VIEW_TYPE_STORAGE: StorageUsageView storageUsageView = (StorageUsageView) holder.itemView; storageUsageView.setStorageUsage(calculating, databaseSize, totalSize, totalDeviceFreeSize, totalDeviceSize); break; case VIEW_TYPE_HEADER: HeaderCell headerCell = (HeaderCell) holder.itemView; headerCell.setText(itemInners.get(position).headerName); headerCell.setTopMargin(itemInners.get(position).headerTopMargin); headerCell.setBottomMargin(itemInners.get(position).headerBottomMargin); break; } } @Override public int getItemViewType(int i) { return itemInners.get(i).viewType; } } private void updateActionMode() { if (cacheModel.getSelectedFiles() > 0) { if (cachedMediaLayout != null) { String filesString; if (!cacheModel.selectedDialogs.isEmpty()) { int filesInChats = 0; for (CacheControlActivity.DialogFileEntities entity : cacheModel.entities) { if (cacheModel.selectedDialogs.contains(entity.dialogId)) { filesInChats += entity.filesCount; } } int filesNotInChat = cacheModel.getSelectedFiles() - filesInChats; if (filesNotInChat > 0) { filesString = String.format("%s, %s", LocaleController.formatPluralString("Chats", cacheModel.selectedDialogs.size(), cacheModel.selectedDialogs.size()), LocaleController.formatPluralString("Files", filesNotInChat, filesNotInChat) ); } else { filesString = LocaleController.formatPluralString("Chats", cacheModel.selectedDialogs.size(), cacheModel.selectedDialogs.size()); } } else { filesString = LocaleController.formatPluralString("Files", cacheModel.getSelectedFiles(), cacheModel.getSelectedFiles()); } String sizeString = AndroidUtilities.formatFileSize(cacheModel.getSelectedFilesSize()); actionModeTitle.setText(sizeString, !LocaleController.isRTL); actionModeSubtitle.setText(filesString, !LocaleController.isRTL); cachedMediaLayout.showActionMode(true); } } else { cachedMediaLayout.showActionMode(false); return; } } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ThemeDescription.ThemeDescriptionDelegate deldegagte = () -> { if (bottomSheet != null) { bottomSheet.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); } if (actionTextView != null) { actionTextView.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 4)); } }; ArrayList<ThemeDescription> arrayList = new ArrayList<>(); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{TextSettingsCell.class, SlideChooseView.class, StorageUsageView.class, HeaderCell.class}, null, null, null, Theme.key_windowBackgroundWhite)); arrayList.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundGray)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_SELECTOR, null, null, null, null, Theme.key_listSelector)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextSettingsCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextSettingsCell.class}, new String[]{"valueTextView"}, null, null, null, Theme.key_windowBackgroundWhiteValueText)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{TextInfoPrivacyCell.class}, null, null, null, Theme.key_windowBackgroundGrayShadow)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextInfoPrivacyCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText4)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{HeaderCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueHeader)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"paintFill"}, null, null, null, Theme.key_player_progressBackground)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"paintProgress"}, null, null, null, Theme.key_player_progress)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"telegramCacheTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"freeSizeTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"calculationgTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_switchTrack)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_switchTrackChecked)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, new String[]{"valueTextView"}, null, null, null, Theme.key_windowBackgroundWhiteValueText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, Theme.dividerPaint, null, null, Theme.key_divider)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{StorageDiagramView.class}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(null, 0, new Class[]{TextCheckBoxCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(null, 0, null, null, null, deldegagte, Theme.key_dialogBackground)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_blue)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_green)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_red)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_golden)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_lightblue)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_lightgreen)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_orange)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_indigo)); return arrayList; } public static class UserCell extends FrameLayout implements NotificationCenter.NotificationCenterDelegate { public DialogFileEntities dialogFileEntities; private Theme.ResourcesProvider resourcesProvider; private TextView textView; private AnimatedTextView valueTextView; private BackupImageView imageView; private boolean needDivider; private boolean canDisable; protected CheckBox2 checkBox; public UserCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; textView = new TextView(context); textView.setSingleLine(); textView.setLines(1); textView.setMaxLines(1); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setEllipsize(TextUtils.TruncateAt.END); // textView.setEllipsizeByGradient(true); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 21 : 72, 0, LocaleController.isRTL ? 72 : 21, 0)); valueTextView = new AnimatedTextView(context, true, true, !LocaleController.isRTL); valueTextView.setAnimationProperties(.55f, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT); valueTextView.setTextSize(AndroidUtilities.dp(16)); valueTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL); valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteValueText, resourcesProvider)); addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, LocaleController.isRTL ? 21 : 72, 0, LocaleController.isRTL ? 72 : 21, 0)); imageView = new BackupImageView(context); imageView.getAvatarDrawable().setScaleSize(.8f); addView(imageView, LayoutHelper.createFrame(38, 38, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, 17, 0, 17, 0)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(50) + (needDivider ? 1 : 0)); int availableWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - AndroidUtilities.dp(34); int width = availableWidth / 2; if (imageView.getVisibility() == VISIBLE) { imageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY)); } if (valueTextView.getVisibility() == VISIBLE) { valueTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); width = availableWidth - valueTextView.getMeasuredWidth() - AndroidUtilities.dp(8); } else { width = availableWidth; } int padding = valueTextView.getMeasuredWidth() + AndroidUtilities.dp(12); if (LocaleController.isRTL) { ((MarginLayoutParams) textView.getLayoutParams()).leftMargin = padding; } else { ((MarginLayoutParams) textView.getLayoutParams()).rightMargin = padding; } textView.measure(MeasureSpec.makeMeasureSpec(width - padding, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); if (checkBox != null) { checkBox.measure( MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY) ); } } public BackupImageView getImageView() { return imageView; } public TextView getTextView() { return textView; } public void setCanDisable(boolean value) { canDisable = value; } public AnimatedTextView getValueTextView() { return valueTextView; } public void setTextColor(int color) { textView.setTextColor(color); } public void setTextValueColor(int color) { valueTextView.setTextColor(color); } public void setText(CharSequence text, boolean divider) { text = Emoji.replaceEmoji(text, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false); textView.setText(text); valueTextView.setVisibility(INVISIBLE); needDivider = divider; setWillNotDraw(!divider); } public void setTextAndValue(CharSequence text, CharSequence value, boolean divider) { setTextAndValue(text, value, false, divider); } public void setTextAndValue(CharSequence text, CharSequence value, boolean animated, boolean divider) { text = Emoji.replaceEmoji(text, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false); textView.setText(text); if (value != null) { valueTextView.setText(value, animated); valueTextView.setVisibility(VISIBLE); } else { valueTextView.setVisibility(INVISIBLE); } needDivider = divider; setWillNotDraw(!divider); requestLayout(); } public void setEnabled(boolean value, ArrayList<Animator> animators) { setEnabled(value); if (animators != null) { animators.add(ObjectAnimator.ofFloat(textView, "alpha", value ? 1.0f : 0.5f)); if (valueTextView.getVisibility() == VISIBLE) { animators.add(ObjectAnimator.ofFloat(valueTextView, "alpha", value ? 1.0f : 0.5f)); } } else { textView.setAlpha(value ? 1.0f : 0.5f); if (valueTextView.getVisibility() == VISIBLE) { valueTextView.setAlpha(value ? 1.0f : 0.5f); } } } @Override public void setEnabled(boolean value) { super.setEnabled(value); textView.setAlpha(value || !canDisable ? 1.0f : 0.5f); if (valueTextView.getVisibility() == VISIBLE) { valueTextView.setAlpha(value || !canDisable ? 1.0f : 0.5f); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (needDivider) { canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(72), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(72) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setText(textView.getText() + (valueTextView != null && valueTextView.getVisibility() == View.VISIBLE ? "\n" + valueTextView.getText() : "")); info.setEnabled(isEnabled()); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.emojiLoaded) { if (textView != null) { textView.invalidate(); } } } public void setChecked(boolean checked, boolean animated) { if (checkBox == null && !checked) { return; } if (checkBox == null) { checkBox = new CheckBox2(getContext(), 21, resourcesProvider); checkBox.setColor(-1, Theme.key_windowBackgroundWhite, Theme.key_checkboxCheck); checkBox.setDrawUnchecked(false); checkBox.setDrawBackgroundAsArc(3); addView(checkBox, LayoutHelper.createFrame(24, 24, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 38, 25, 38, 0)); } checkBox.setChecked(checked, animated); } } @Override public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == 4) { boolean allGranted = true; for (int a = 0; a < grantResults.length; a++) { if (grantResults[a] != PackageManager.PERMISSION_GRANTED) { allGranted = false; break; } } if (allGranted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && FilesMigrationService.filesMigrationBottomSheet != null) { FilesMigrationService.filesMigrationBottomSheet.migrateOldFolder(); } } } public static class DialogFileEntities { public long dialogId; int filesCount; long totalSize; public final SparseArray<FileEntities> entitiesByType = new SparseArray<>(); public DialogFileEntities(long dialogId) { this.dialogId = dialogId; } public void addFile(CacheModel.FileInfo file, int type) { FileEntities entities = entitiesByType.get(type, null); if (entities == null) { entities = new FileEntities(); entitiesByType.put(type, entities); } entities.count++; long fileSize = file.size; entities.totalSize += fileSize; totalSize += fileSize; filesCount++; entities.files.add(file); } public void merge(DialogFileEntities dialogEntities) { for (int i = 0; i < dialogEntities.entitiesByType.size(); i++) { int type = dialogEntities.entitiesByType.keyAt(i); FileEntities entitesToMerge = dialogEntities.entitiesByType.valueAt(i); FileEntities entities = entitiesByType.get(type, null); if (entities == null) { entities = new FileEntities(); entitiesByType.put(type, entities); } entities.count += entitesToMerge.count; entities.totalSize += entitesToMerge.totalSize; totalSize += entitesToMerge.totalSize; entities.files.addAll(entitesToMerge.files); } filesCount += dialogEntities.filesCount; } public void removeFile(CacheModel.FileInfo fileInfo) { FileEntities entities = entitiesByType.get(fileInfo.type, null); if (entities == null) { return; } if (entities.files.remove(fileInfo)) { entities.count--; entities.totalSize -= fileInfo.size; totalSize -= fileInfo.size; filesCount--; } } public boolean isEmpty() { return totalSize <= 0; } public CacheModel createCacheModel() { CacheModel cacheModel = new CacheModel(true); if (entitiesByType.get(TYPE_PHOTOS) != null) { cacheModel.media.addAll(entitiesByType.get(TYPE_PHOTOS).files); } if (entitiesByType.get(TYPE_VIDEOS) != null) { cacheModel.media.addAll(entitiesByType.get(TYPE_VIDEOS).files); } if (entitiesByType.get(TYPE_DOCUMENTS) != null) { cacheModel.documents.addAll(entitiesByType.get(TYPE_DOCUMENTS).files); } if (entitiesByType.get(TYPE_MUSIC) != null) { cacheModel.music.addAll(entitiesByType.get(TYPE_MUSIC).files); } if (entitiesByType.get(TYPE_VOICE) != null) { cacheModel.voice.addAll(entitiesByType.get(TYPE_VOICE).files); } cacheModel.selectAllFiles(); cacheModel.sortBySize(); return cacheModel; } } public static class FileEntities { public long totalSize; public int count; public ArrayList<CacheModel.FileInfo> files = new ArrayList<>(); } public static class ItemInner extends AdapterWithDiffUtils.Item { int headerTopMargin = 15; int headerBottomMargin = 0; int keepMediaType = -1; CharSequence headerName; String text; DialogFileEntities entities; public int index; public long size; int colorKey; public boolean pad; boolean last; public ItemInner(int viewType, String headerName, DialogFileEntities dialogFileEntities) { super(viewType, true); this.headerName = headerName; this.entities = dialogFileEntities; } public ItemInner(int viewType, int keepMediaType) { super(viewType, true); this.keepMediaType = keepMediaType; } public ItemInner(int viewType, String headerName, int headerTopMargin, int headerBottomMargin, DialogFileEntities dialogFileEntities) { super(viewType, true); this.headerName = headerName; this.headerTopMargin = headerTopMargin; this.headerBottomMargin = headerBottomMargin; this.entities = dialogFileEntities; } private ItemInner(int viewType) { super(viewType, true); } public static ItemInner asCheckBox(CharSequence text, int index, long size, int colorKey) { return asCheckBox(text, index, size, colorKey, false); } public static ItemInner asCheckBox(CharSequence text, int index, long size, int colorKey, boolean last) { ItemInner item = new ItemInner(VIEW_TYPE_SECTION); item.index = index; item.headerName = text; item.size = size; item.colorKey = colorKey; item.last = last; return item; } public static ItemInner asInfo(String text) { ItemInner item = new ItemInner(VIEW_TYPE_INFO); item.text = text; return item; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ItemInner itemInner = (ItemInner) o; if (viewType == itemInner.viewType) { if (viewType == VIEW_TYPE_CHART || viewType == VIEW_TYPE_CHART_HEADER) { return true; } if (viewType == VIEW_TYPE_CHAT && entities != null && itemInner.entities != null) { return entities.dialogId == itemInner.entities.dialogId; } if (viewType == VIEW_TYPE_CACHE_VIEW_PAGER || viewType == VIEW_TYPE_CHOOSER || viewType == VIEW_TYPE_STORAGE || viewType == VIEW_TYPE_TEXT_SETTINGS || viewType == VIEW_TYPE_CLEAR_CACHE_BUTTON) { return true; } if (viewType == VIEW_TYPE_HEADER) { return Objects.equals(headerName, itemInner.headerName); } if (viewType == VIEW_TYPE_INFO) { return Objects.equals(text, itemInner.text); } if (viewType == VIEW_TYPE_SECTION) { return index == itemInner.index && size == itemInner.size; } if (viewType == VIEW_TYPE_KEEP_MEDIA_CELL) { return keepMediaType == itemInner.keepMediaType; } return false; } return false; } } AnimatedTextView selectedDialogsCountTextView; @Override public boolean isSwipeBackEnabled(MotionEvent event) { if (cachedMediaLayout != null && event != null) { cachedMediaLayout.getHitRect(AndroidUtilities.rectTmp2); if (!AndroidUtilities.rectTmp2.contains((int) event.getX(), (int) event.getY() - actionBar.getMeasuredHeight())) { return true; } else { return cachedMediaLayout.viewPagerFixed.isCurrentTabFirst(); } } return true; } @Override public boolean onBackPressed() { if (cacheModel != null && !cacheModel.selectedFiles.isEmpty()) { cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return false; } return super.onBackPressed(); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java
2,331
package org.telegram.ui; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Cells.CheckBoxCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Components.BottomSheetWithRecyclerListView; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.StorageDiagramView; import org.telegram.ui.Storage.CacheModel; public class DilogCacheBottomSheet extends BottomSheetWithRecyclerListView { private final StorageDiagramView circleDiagramView; CacheControlActivity.DialogFileEntities entities; private final Delegate cacheDelegate; private CacheControlActivity.ClearCacheButton button; private StorageDiagramView.ClearViewData[] clearViewData = new StorageDiagramView.ClearViewData[8]; CheckBoxCell[] checkBoxes = new CheckBoxCell[8]; LinearLayout linearLayout; CachedMediaLayout cachedMediaLayout; long dialogId; private final CacheModel cacheModel; @Override protected CharSequence getTitle() { return getBaseFragment().getMessagesController().getFullName(dialogId); } @Override protected RecyclerListView.SelectionAdapter createAdapter(RecyclerListView listView) { return new RecyclerListView.SelectionAdapter() { @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { return false; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; if (viewType == 0) { view = linearLayout; } else if (viewType == 2) { view = cachedMediaLayout; RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp.leftMargin = backgroundPaddingLeft; lp.rightMargin = backgroundPaddingLeft; view.setLayoutParams(lp); } else { TextInfoPrivacyCell textInfoPrivacyCell = new TextInfoPrivacyCell(parent.getContext()); textInfoPrivacyCell.setFixedSize(12); CombinedDrawable combinedDrawable = new CombinedDrawable( new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), Theme.getThemedDrawableByKey(parent.getContext(), R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow) ); combinedDrawable.setFullsize(true); textInfoPrivacyCell.setBackgroundDrawable(combinedDrawable); view = textInfoPrivacyCell; } return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { } @Override public int getItemViewType(int position) { return position; } @Override public int getItemCount() { return cacheModel.isEmpty() ? 1 : 3; } }; } @Override protected boolean canDismissWithSwipe() { return false; } public DilogCacheBottomSheet(CacheControlActivity baseFragment, CacheControlActivity.DialogFileEntities entities, CacheModel cacheModel, Delegate delegate) { super(baseFragment, false, false, !cacheModel.isEmpty(), null); this.cacheDelegate = delegate; this.entities = entities; this.cacheModel = cacheModel; dialogId = entities.dialogId; allowNestedScroll = false; updateTitle(); setAllowNestedScroll(true); topPadding = 0.2f; Context context = baseFragment.getContext(); fixNavigationBar(); setApplyBottomPadding(false); linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); if (entities != null) { circleDiagramView = new StorageDiagramView(getContext(), entities.dialogId) { @Override protected void onAvatarClick() { delegate.onAvatarClick(); } }; } else { circleDiagramView = new StorageDiagramView(getContext()); } linearLayout.addView(circleDiagramView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL, 0, 16, 0, 16)); CheckBoxCell lastCreatedCheckbox = null; for (int a = 0; a < 8; a++) { long size = 0; String name; int color; if (a == CacheControlActivity.TYPE_PHOTOS) { name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache); color = Theme.key_statisticChartLine_lightblue; } else if (a == CacheControlActivity.TYPE_VIDEOS) { name = LocaleController.getString("LocalVideoCache", R.string.LocalVideoCache); color = Theme.key_statisticChartLine_blue; } else if (a == CacheControlActivity.TYPE_DOCUMENTS) { name = LocaleController.getString("LocalDocumentCache", R.string.LocalDocumentCache); color = Theme.key_statisticChartLine_green; } else if (a == CacheControlActivity.TYPE_MUSIC) { name = LocaleController.getString("LocalMusicCache", R.string.LocalMusicCache); color = Theme.key_statisticChartLine_red; } else if (a == CacheControlActivity.TYPE_VOICE) { name = LocaleController.getString("LocalAudioCache", R.string.LocalAudioCache); color = Theme.key_statisticChartLine_lightgreen; } else if (a == CacheControlActivity.TYPE_ANIMATED_STICKERS_CACHE) { name = LocaleController.getString("LocalStickersCache", R.string.LocalStickersCache); color = Theme.key_statisticChartLine_orange; } else if (a == CacheControlActivity.TYPE_STORIES) { name = LocaleController.getString("LocalStoriesCache", R.string.LocalStoriesCache); color = Theme.key_statisticChartLine_indigo; } else { name = LocaleController.getString("LocalMiscellaneousCache", R.string.LocalMiscellaneousCache); color = Theme.key_statisticChartLine_purple; } if (entities != null) { CacheControlActivity.FileEntities fileEntities = entities.entitiesByType.get(a); if (fileEntities != null) { size = fileEntities.totalSize; } else { size = 0; } } if (size > 0) { clearViewData[a] = new StorageDiagramView.ClearViewData(circleDiagramView); clearViewData[a].size = size; clearViewData[a].colorKey = color; CheckBoxCell checkBoxCell = new CheckBoxCell(context, 4, 21, null); lastCreatedCheckbox = checkBoxCell; checkBoxCell.setTag(a); checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); checkBoxCell.setText(name, AndroidUtilities.formatFileSize(size), true, true); checkBoxCell.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); checkBoxCell.setCheckBoxColor(color, Theme.key_windowBackgroundWhiteGrayIcon, Theme.key_checkboxCheck); checkBoxCell.setOnClickListener(v -> { int enabledCount = 0; for (int i = 0; i < clearViewData.length; i++) { if (clearViewData[i] != null && clearViewData[i].clear) { enabledCount++; } } CheckBoxCell cell = (CheckBoxCell) v; int num = (Integer) cell.getTag(); // if (enabledCount == 1 && clearViewData[num].clear) { // BotWebViewVibrationEffect.APP_ERROR.vibrate(); // AndroidUtilities.shakeViewSpring(((CheckBoxCell) v).getCheckBoxView(), -3); // return; // } clearViewData[num].setClear(!clearViewData[num].clear); cell.setChecked(clearViewData[num].clear, true); cacheModel.allFilesSelcetedByType(num, clearViewData[num].clear); cachedMediaLayout.update(); long totalSize = circleDiagramView.updateDescription(); button.setSize(true, totalSize); circleDiagramView.update(true); }); checkBoxes[a] = checkBoxCell; } else { clearViewData[a] = null; checkBoxes[a] = null; } } if (lastCreatedCheckbox != null) { lastCreatedCheckbox.setNeedDivider(false); } circleDiagramView.setData(cacheModel, clearViewData); cachedMediaLayout = new CachedMediaLayout(getContext(), baseFragment) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(contentHeight - ActionBar.getCurrentActionBarHeight() - AndroidUtilities.statusBarHeight, MeasureSpec.EXACTLY)); } }; cachedMediaLayout.setBottomPadding(AndroidUtilities.dp(80)); cachedMediaLayout.setCacheModel(cacheModel); cachedMediaLayout.setDelegate(new CachedMediaLayout.Delegate() { @Override public void onItemSelected(CacheControlActivity.DialogFileEntities entities, CacheModel.FileInfo fileInfo, boolean longPress) { if (fileInfo != null) { cacheModel.toggleSelect(fileInfo); cachedMediaLayout.updateVisibleRows(); syncCheckBoxes(); long totalSize = circleDiagramView.updateDescription(); button.setSize(true, totalSize); circleDiagramView.update(true); } } @Override public void dismiss() { DilogCacheBottomSheet.this.dismiss(); } @Override public void clear() { } @Override public void clearSelection() { } }); if (nestedSizeNotifierLayout != null) { nestedSizeNotifierLayout.setChildLayout(cachedMediaLayout); } else { createButton(); linearLayout.addView(button, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 72, Gravity.BOTTOM)); } if (button != null) { long totalSize = circleDiagramView.calculateSize(); button.setSize(true, totalSize); } } private void syncCheckBoxes() { if (checkBoxes[CacheControlActivity.TYPE_PHOTOS] != null) { checkBoxes[CacheControlActivity.TYPE_PHOTOS].setChecked(clearViewData[CacheControlActivity.TYPE_PHOTOS].clear = cacheModel.allPhotosSelected, true); } if (checkBoxes[CacheControlActivity.TYPE_VIDEOS] != null) { checkBoxes[CacheControlActivity.TYPE_VIDEOS].setChecked(clearViewData[CacheControlActivity.TYPE_VIDEOS].clear = cacheModel.allVideosSelected, true); } if (checkBoxes[CacheControlActivity.TYPE_DOCUMENTS] != null) { checkBoxes[CacheControlActivity.TYPE_DOCUMENTS].setChecked(clearViewData[CacheControlActivity.TYPE_DOCUMENTS].clear = cacheModel.allDocumentsSelected, true); } if (checkBoxes[CacheControlActivity.TYPE_MUSIC] != null) { checkBoxes[CacheControlActivity.TYPE_MUSIC].setChecked(clearViewData[CacheControlActivity.TYPE_MUSIC].clear = cacheModel.allMusicSelected, true); } if (checkBoxes[CacheControlActivity.TYPE_VOICE] != null) { checkBoxes[CacheControlActivity.TYPE_VOICE].setChecked(clearViewData[CacheControlActivity.TYPE_VOICE].clear = cacheModel.allVoiceSelected, true); } } @Override public void onViewCreated(FrameLayout containerView) { super.onViewCreated(containerView); recyclerListView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (nestedSizeNotifierLayout != null) { setShowShadow(!nestedSizeNotifierLayout.isPinnedToTop()); } } }); if (nestedSizeNotifierLayout != null) { createButton(); containerView.addView(button, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 72, Gravity.BOTTOM)); } } private void createButton() { button = new CacheControlActivity.ClearCacheButton(getContext()); button.button.setOnClickListener(v -> { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(LocaleController.getString("ClearCache", R.string.ClearCache)); builder.setMessage(LocaleController.getString("ClearCacheForChat", R.string.ClearCacheForChat)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (di, which) -> { dismiss(); }); builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (di, which) -> { dismiss(); cacheDelegate.cleanupDialogFiles(entities, clearViewData, cacheModel); }); AlertDialog alertDialog = builder.create(); alertDialog.show(); alertDialog.redPositive(); }); if (circleDiagramView != null) { long totalSize = circleDiagramView.calculateSize(); button.setSize(true, totalSize); } } public interface Delegate { void onAvatarClick(); void cleanupDialogFiles(CacheControlActivity.DialogFileEntities entities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel cacheModel); } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/DilogCacheBottomSheet.java
2,332
/***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * 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.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2001 Chad Fowler <[email protected]> * Copyright (C) 2001-2002 Jan Arne Petersen <[email protected]> * Copyright (C) 2002 Benoit Cerrina <[email protected]> * Copyright (C) 2002-2004 Thomas E Enebo <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby; import org.jruby.anno.JRubyMethod; import org.jruby.anno.JRubyModule; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; @JRubyModule(name="Math") public class RubyMath { /** Create the Math module and add it to the Ruby runtime. * */ public static RubyModule createMathModule(Ruby runtime) { RubyModule result = runtime.defineModule("Math"); result.defineConstant("E", RubyFloat.newFloat(runtime, Math.E)); result.defineConstant("PI", RubyFloat.newFloat(runtime, Math.PI)); result.defineAnnotatedMethods(RubyMath.class); return result; } private static void domainCheck(IRubyObject recv, double value, String msg) { if (Double.isNaN(value)) { throw recv.getRuntime().newErrnoEDOMError(msg); } } private static void domainCheck19(IRubyObject recv, double value, String msg) { if (Double.isNaN(value)) { throw recv.getRuntime().newMathDomainError(msg); } } public static double chebylevSerie(double x, double coef[]) { double b0, b1, b2, twox; int i; b1 = 0.0; b0 = 0.0; b2 = 0.0; twox = 2.0 * x; for (i = coef.length-1; i >= 0; i--) { b2 = b1; b1 = b0; b0 = twox * b1 - b2 + coef[i]; } return 0.5*(b0 - b2); } public static double sign(double x, double y) { double abs = ((x < 0) ? -x : x); return (y < 0.0) ? -abs : abs; } @JRubyMethod(name = "atan2", module = true, visibility = Visibility.PRIVATE) public static RubyFloat atan2(ThreadContext context, IRubyObject recv, IRubyObject x, IRubyObject y) { double valuea = RubyNumeric.num2dbl(context, x); double valueb = RubyNumeric.num2dbl(context, y); return RubyFloat.newFloat(context.runtime, Math.atan2(valuea, valueb)); } @Deprecated public static RubyFloat atan219(ThreadContext context, IRubyObject recv, IRubyObject x, IRubyObject y) { return atan2(context, recv, x, y); } @JRubyMethod(name = "cos", module = true, visibility = Visibility.PRIVATE) public static RubyFloat cos(ThreadContext context, IRubyObject recv, IRubyObject x) { return RubyFloat.newFloat(context.runtime, Math.cos(RubyNumeric.num2dbl(context, x))); } @Deprecated public static RubyFloat cos19(ThreadContext context, IRubyObject recv, IRubyObject x) { return cos(context, recv, x); } @JRubyMethod(name = "sin", module = true, visibility = Visibility.PRIVATE) public static RubyFloat sin(ThreadContext context, IRubyObject recv, IRubyObject x) { return RubyFloat.newFloat(context.runtime, Math.sin(RubyNumeric.num2dbl(context, x))); } @Deprecated public static RubyFloat sin19(ThreadContext context, IRubyObject recv, IRubyObject x) { return sin(context, recv, x); } @JRubyMethod(name = "tan", module = true, visibility = Visibility.PRIVATE) public static RubyFloat tan(ThreadContext context, IRubyObject recv, IRubyObject x) { return RubyFloat.newFloat(context.runtime, Math.tan(RubyNumeric.num2dbl(context, x))); } @Deprecated public static RubyFloat tan19(ThreadContext context, IRubyObject recv, IRubyObject x) { return tan(context, recv, x); } @JRubyMethod(name = "asin", module = true, visibility = Visibility.PRIVATE) public static RubyFloat asin(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); if (value < -1.0 || value > 1.0) throw context.runtime.newMathDomainError("asin"); return RubyFloat.newFloat(context.runtime, Math.asin(value)); } @Deprecated public static RubyFloat asin19(ThreadContext context, IRubyObject recv, IRubyObject x) { return asin(context, recv, x); } @JRubyMethod(name = "acos", module = true, visibility = Visibility.PRIVATE) public static RubyFloat acos(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); if (value < -1.0 || value > 1.0) throw context.runtime.newMathDomainError("acos"); return RubyFloat.newFloat(context.runtime, Math.acos(value)); } @Deprecated public static RubyFloat acos19(ThreadContext context, IRubyObject recv, IRubyObject x) { return acos(context, recv, x); } @JRubyMethod(name = "atan", module = true, visibility = Visibility.PRIVATE) public static RubyFloat atan(ThreadContext context, IRubyObject recv, IRubyObject x) { return RubyFloat.newFloat(context.runtime, Math.atan(RubyNumeric.num2dbl(context, x))); } @Deprecated public static RubyFloat atan19(ThreadContext context, IRubyObject recv, IRubyObject x) { return atan(context, recv, x); } @JRubyMethod(name = "cosh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat cosh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); return RubyFloat.newFloat(context.runtime, (Math.exp(value) + Math.exp(-value)) / 2.0); } @Deprecated public static RubyFloat cosh19(ThreadContext context, IRubyObject recv, IRubyObject x) { return cosh(context, recv, x); } @JRubyMethod(name = "sinh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat sinh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); return RubyFloat.newFloat(context.runtime, (Math.exp(value) - Math.exp(-value)) / 2.0); } @Deprecated public static RubyFloat sinh19(ThreadContext context, IRubyObject recv, IRubyObject x) { return sinh(context, recv, x); } @JRubyMethod(name = "tanh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat tanh(ThreadContext context, IRubyObject recv, IRubyObject x) { return RubyFloat.newFloat(context.runtime, Math.tanh(RubyNumeric.num2dbl(context, x))); } @Deprecated public static RubyFloat tanh19(ThreadContext context, IRubyObject recv, IRubyObject x) { return tanh(context, recv, x); } @JRubyMethod(name = "acosh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat acosh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); double result; if (Double.isNaN(value)) { result = Double.NaN; } else if (value < 1) { throw context.runtime.newMathDomainError("acosh"); } else if (value < 94906265.62) { result = Math.log(value + Math.sqrt(value * value - 1.0)); } else{ result = 0.69314718055994530941723212145818 + Math.log(value); } return RubyFloat.newFloat(context.runtime,result); } @Deprecated public static RubyFloat acosh19(ThreadContext context, IRubyObject recv, IRubyObject x) { return acosh(context, recv, x); } public static final double[] ASINH_COEF = { -.12820039911738186343372127359268e+0, -.58811761189951767565211757138362e-1, .47274654322124815640725249756029e-2, -.49383631626536172101360174790273e-3, .58506207058557412287494835259321e-4, -.74669983289313681354755069217188e-5, .10011693583558199265966192015812e-5, -.13903543858708333608616472258886e-6, .19823169483172793547317360237148e-7, -.28847468417848843612747272800317e-8, .42672965467159937953457514995907e-9, -.63976084654366357868752632309681e-10, .96991686089064704147878293131179e-11, -.14844276972043770830246658365696e-11, .22903737939027447988040184378983e-12, -.35588395132732645159978942651310e-13, .55639694080056789953374539088554e-14, -.87462509599624678045666593520162e-15, .13815248844526692155868802298129e-15, -.21916688282900363984955142264149e-16, .34904658524827565638313923706880e-17 }; @JRubyMethod(name = "asinh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat asinh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); double y = Math.abs(value); double result; if (Double.isNaN(value)) { result = Double.NaN; } else if (y <= 1.05367e-08) { result = value; } else if (y <= 1.0) { result = value * (1.0 + chebylevSerie(2.0 * value * value - 1.0, ASINH_COEF)); } else if (y < 94906265.62) { result = Math.log(value + Math.sqrt(value * value + 1.0)); } else { result = 0.69314718055994530941723212145818 + Math.log(y); if (value < 0) result *= -1; } return RubyFloat.newFloat(context.runtime, result); } @Deprecated public static RubyFloat asinh19(ThreadContext context, IRubyObject recv, IRubyObject x) { return asinh(context, recv, x); } public static final double[] ATANH_COEF = { .9439510239319549230842892218633e-1, .4919843705578615947200034576668e-1, .2102593522455432763479327331752e-2, .1073554449776116584640731045276e-3, .5978267249293031478642787517872e-5, .3505062030889134845966834886200e-6, .2126374343765340350896219314431e-7, .1321694535715527192129801723055e-8, .8365875501178070364623604052959e-10, .5370503749311002163881434587772e-11, .3486659470157107922971245784290e-12, .2284549509603433015524024119722e-13, .1508407105944793044874229067558e-14, .1002418816804109126136995722837e-15, .6698674738165069539715526882986e-17, .4497954546494931083083327624533e-18 }; @JRubyMethod(name = "atanh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat atanh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); if (value < -1.0 || value > 1.0) throw context.runtime.newMathDomainError("atanh"); final double y = Math.abs(value); final double result; if (Double.isNaN(value)) { result = Double.NaN; } else if (y < 1.82501e-08) { result = value; } else if (y <= 0.5) { result = value * (1.0 + chebylevSerie(8.0 * value * value - 1.0, ATANH_COEF)); } else if (y < 1.0) { result = 0.5 * Math.log((1.0 + value) / (1.0 - value)); } else if (y == 1.0) { result = value * Double.POSITIVE_INFINITY; } else { result = Double.NaN; } return RubyFloat.newFloat(context.runtime, result); } @Deprecated public static RubyFloat atanh_19(ThreadContext context, IRubyObject recv, IRubyObject x) { return atanh(context, recv, x); } @JRubyMethod(name = "exp", module = true, visibility = Visibility.PRIVATE) public static RubyFloat exp(ThreadContext context, IRubyObject recv, IRubyObject exponent) { return exp(context, exponent); } public static RubyFloat exp(ThreadContext context, IRubyObject exponent) { return RubyFloat.newFloat(context.runtime, Math.exp(RubyNumeric.num2dbl(context, exponent))); } @Deprecated public static RubyFloat exp19(ThreadContext context, IRubyObject recv, IRubyObject exponent) { return exp(context, recv, exponent); } // MRI : get_double_rshift private static double[] get_double_rshift(ThreadContext context, IRubyObject x) { int numbits = 0; if (x instanceof RubyBignum) { RubyBignum bignum = (RubyBignum)x; numbits = bignum.getValue().abs().bitLength(); if (bignum.getValue().signum() > 0 && numbits >= DBL_MAX_EXP) { numbits -= DBL_MANT_DIG; x = bignum.op_rshift(context, numbits); } else { numbits = 0; } } return new double[]{RubyNumeric.num2dbl(context, x), numbits}; } private static int DBL_MANT_DIG = 53; private static int DBL_MAX_EXP = 1024; private static double LOG_E_2 = Math.log(2); private static double LOG_10_2 = Math.log10(2); /** Returns the natural logarithm of x. * */ @JRubyMethod(name = "log", module = true, visibility = Visibility.PRIVATE) public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject val) { return log(context, val); } public static RubyFloat log(ThreadContext context, IRubyObject val) { double [] ret = get_double_rshift(context, val); if (ret[0] < 0) { throw context.runtime.newMathDomainError("log"); } /* log(d * 2 ** numbits) */ return RubyFloat.newFloat(context.runtime, Math.log(ret[0]) + ret[1] * LOG_E_2); } @JRubyMethod(name = "log", module = true, visibility = Visibility.PRIVATE) public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject val, IRubyObject base) { double [] ret = get_double_rshift(context, val); double _base = RubyNumeric.num2dbl(context, base); if (ret[0] < 0 || _base < 0) { throw context.runtime.newMathDomainError("log"); } /* log(d * 2 ** numbits) / log(base) */ return RubyFloat.newFloat(context.runtime, Math.log(ret[0]) / Math.log(_base) + ret[1]); } public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject... args) { if (args.length == 2) { return log(context, recv, args[0], args[1]); } return log(context, recv, args[0]); } @Deprecated public static RubyFloat log_19(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return log(context, recv, args); } /** Returns the base 10 logarithm of x. * */ @JRubyMethod(name = "log10", module = true, visibility = Visibility.PRIVATE) public static RubyFloat log10(ThreadContext context, IRubyObject recv, IRubyObject x) { double [] ret = get_double_rshift(context, x); if (ret[0] < 0) { throw context.runtime.newMathDomainError("log10"); } /* log10(d * 2 ** numbits) */ return RubyFloat.newFloat(context.runtime, Math.log10(ret[0]) + ret[1] * LOG_10_2); } @Deprecated public static RubyFloat log10_19(ThreadContext context, IRubyObject recv, IRubyObject x) { return log10(context, recv, x); } /** Returns the base 2 logarithm of x. * */ @JRubyMethod(name = "log2", module = true, visibility = Visibility.PRIVATE) public static RubyFloat log2(ThreadContext context, IRubyObject recv, IRubyObject x) { double [] ret = get_double_rshift(context, x); if (ret[0] < 0) { throw context.runtime.newMathDomainError("log2"); } /* log2(d * 2 ** numbits) */ return RubyFloat.newFloat(context.runtime, Math.log(ret[0]) / LOG_E_2 + ret[1]); } @Deprecated public static RubyFloat log2_19(ThreadContext context, IRubyObject recv, IRubyObject x) { return log2(context, recv, x); } @JRubyMethod(name = "sqrt", module = true, visibility = Visibility.PRIVATE) public static RubyFloat sqrt(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); if (value < 0) throw context.runtime.newMathDomainError("sqrt"); return RubyFloat.newFloat(context.runtime, value == 0.0 ? 0.0 : Math.sqrt(value)); } @Deprecated public static RubyFloat sqrt19(ThreadContext context, IRubyObject recv, IRubyObject x) { return sqrt(context, recv, x); } @JRubyMethod(name = "cbrt", module = true, visibility = Visibility.PRIVATE) public static RubyFloat cbrt(ThreadContext context, IRubyObject recv, IRubyObject x) { double result = Math.cbrt(RubyNumeric.num2dbl(context, x)); return RubyFloat.newFloat(context.runtime, result); } public static RubyFloat hypot(ThreadContext context, IRubyObject recv, IRubyObject x, IRubyObject y) { return hypot19(context, recv, x, y); } @JRubyMethod(name = "hypot", module = true, visibility = Visibility.PRIVATE) public static RubyFloat hypot19(ThreadContext context, IRubyObject recv, IRubyObject x, IRubyObject y) { double valuea = RubyNumeric.num2dbl(context, x); double valueb = RubyNumeric.num2dbl(context, y); double result; if (Math.abs(valuea) > Math.abs(valueb)) { result = valueb / valuea; result = Math.abs(valuea) * Math.sqrt(1 + result * result); } else if (valueb != 0) { result = valuea / valueb; result = Math.abs(valueb) * Math.sqrt(1 + result * result); } else if (Double.isNaN(valuea) || Double.isNaN(valueb)) { result = Double.NaN; } else { result = 0; } return RubyFloat.newFloat(context.runtime,result); } /* * x = mantissa * 2 ** exponent * * Where mantissa is in the range of [.5, 1) * */ @JRubyMethod(name = "frexp", module = true, visibility = Visibility.PRIVATE) public static RubyArray frexp(ThreadContext context, IRubyObject recv, IRubyObject other) { double mantissa = RubyNumeric.num2dbl(context, other); short sign = 1; long exponent = 0; if (!Double.isInfinite(mantissa) && mantissa != 0.0) { // Make mantissa same sign so we only have one code path. if (mantissa < 0) { mantissa = -mantissa; sign = -1; } // Increase value to hit lower range. for (; mantissa < 0.5; mantissa *= 2.0, exponent -=1) { } // Decrease value to hit upper range. for (; mantissa >= 1.0; mantissa *= 0.5, exponent +=1) { } } return RubyArray.newArray(context.runtime, RubyFloat.newFloat(context.runtime, sign * mantissa), RubyNumeric.int2fix(context.runtime, exponent)); } @Deprecated public static RubyArray frexp19(ThreadContext context, IRubyObject recv, IRubyObject other) { return frexp(context, recv, other); } /* * r = x * 2 ** y */ @JRubyMethod(name = "ldexp", module = true, visibility = Visibility.PRIVATE) public static RubyFloat ldexp(ThreadContext context, IRubyObject recv, IRubyObject mantissa, IRubyObject exponent) { double m = RubyNumeric.num2dbl(context, mantissa); int e = RubyNumeric.num2int(exponent); if (e > 1023) { // avoid overflow. Math.power(2.0, 1024) is greater than Math.MAX_VALUE. return RubyFloat.newFloat(context.runtime, m * Math.pow(2.0, e - 1023) * Math.pow(2.0, 1023)); } return RubyFloat.newFloat(context.runtime, m * Math.pow(2.0, e)); } public static RubyFloat ldexp19(ThreadContext context, IRubyObject recv, IRubyObject mantissa, IRubyObject exponent) { return ldexp(context, recv, mantissa, exponent); } public static final double[] ERFC_COEF = { -.490461212346918080399845440334e-1, -.142261205103713642378247418996e0, .100355821875997955757546767129e-1, -.576876469976748476508270255092e-3, .274199312521960610344221607915e-4, -.110431755073445076041353812959e-5, .384887554203450369499613114982e-7, -.118085825338754669696317518016e-8, .323342158260509096464029309534e-10, -.799101594700454875816073747086e-12, .179907251139614556119672454866e-13, -.371863548781869263823168282095e-15, .710359900371425297116899083947e-17, -.126124551191552258324954248533e-18 }; @JRubyMethod(name = "erf", module = true, visibility = Visibility.PRIVATE) public static RubyFloat erf(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); double result; double y = Math.abs(value); if (y <= 1.49012e-08) { result = 2 * value / 1.77245385090551602729816748334; } else if (y <= 1) { result = value * (1 + chebylevSerie(2 * value * value - 1, ERFC_COEF)); } else if (y < 6.013687357) { result = sign(1 - erfc(context, recv, RubyFloat.newFloat(context.runtime, y)).value, value); } else if (Double.isNaN(y)) { result = Double.NaN; } else { result = sign(1, value); } return RubyFloat.newFloat(context.runtime,result); } public static RubyFloat erf19(ThreadContext context, IRubyObject recv, IRubyObject x) { return erf(context, recv, x); } public static final double[] ERFC2_COEF = { -.69601346602309501127391508262e-1, -.411013393626208934898221208467e-1, .391449586668962688156114370524e-2, -.490639565054897916128093545077e-3, .715747900137703638076089414183e-4, -.115307163413123283380823284791e-4, .199467059020199763505231486771e-5, -.364266647159922287393611843071e-6, .694437261000501258993127721463e-7, -.137122090210436601953460514121e-7, .278838966100713713196386034809e-8, -.581416472433116155186479105032e-9, .123892049175275318118016881795e-9, -.269063914530674343239042493789e-10, .594261435084791098244470968384e-11, -.133238673575811957928775442057e-11, .30280468061771320171736972433e-12, -.696664881494103258879586758895e-13, .162085454105392296981289322763e-13, -.380993446525049199987691305773e-14, .904048781597883114936897101298e-15, -.2164006195089607347809812047e-15, .522210223399585498460798024417e-16, -.126972960236455533637241552778e-16, .310914550427619758383622741295e-17, -.766376292032038552400956671481e-18, .190081925136274520253692973329e-18 }; public static final double[] ERFCC_COEF = { .715179310202924774503697709496e-1, -.265324343376067157558893386681e-1, .171115397792085588332699194606e-2, -.163751663458517884163746404749e-3, .198712935005520364995974806758e-4, -.284371241276655508750175183152e-5, .460616130896313036969379968464e-6, -.822775302587920842057766536366e-7, .159214187277090112989358340826e-7, -.329507136225284321486631665072e-8, .72234397604005554658126115389e-9, -.166485581339872959344695966886e-9, .401039258823766482077671768814e-10, -.100481621442573113272170176283e-10, .260827591330033380859341009439e-11, -.699111056040402486557697812476e-12, .192949233326170708624205749803e-12, -.547013118875433106490125085271e-13, .158966330976269744839084032762e-13, -.47268939801975548392036958429e-14, .14358733767849847867287399784e-14, -.444951056181735839417250062829e-15, .140481088476823343737305537466e-15, -.451381838776421089625963281623e-16, .147452154104513307787018713262e-16, -.489262140694577615436841552532e-17, .164761214141064673895301522827e-17, -.562681717632940809299928521323e-18, .194744338223207851429197867821e-18 }; @JRubyMethod(name = "erfc", module = true, visibility = Visibility.PRIVATE) public static RubyFloat erfc(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); double result; double y = Math.abs(value); if (value <= -6.013687357) { result = 2; } else if (y < 1.49012e-08) { result = 1 - 2 * value / 1.77245385090551602729816748334; } else { double ysq = y*y; if (y < 1) { result = 1 - value * (1 + chebylevSerie(2 * ysq - 1, ERFC_COEF)); } else if (y <= 4.0) { result = Math.exp(-ysq)/y*(0.5+chebylevSerie((8.0 / ysq - 5.0) / 3.0, ERFC2_COEF)); if (value < 0) result = 2.0 - result; if (value < 0) result = 2.0 - result; if (value < 0) result = 2.0 - result; } else { result = Math.exp(-ysq) / y * (0.5 + chebylevSerie(8.0 / ysq - 1, ERFCC_COEF)); if (value < 0) result = 2.0 - result; } } return RubyFloat.newFloat(context.runtime,result); } @Deprecated public static RubyFloat erfc19(ThreadContext context, IRubyObject recv, IRubyObject x) { return erfc(context, recv, x); } private static final double FACTORIAL[] = { /* 0! */ 1.0, /* 1! */ 1.0, /* 2! */ 2.0, /* 3! */ 6.0, /* 4! */ 24.0, /* 5! */ 120.0, /* 6! */ 720.0, /* 7! */ 5040.0, /* 8! */ 40320.0, /* 9! */ 362880.0, /* 10! */ 3628800.0, /* 11! */ 39916800.0, /* 12! */ 479001600.0, /* 13! */ 6227020800.0, /* 14! */ 87178291200.0, /* 15! */ 1307674368000.0, /* 16! */ 20922789888000.0, /* 17! */ 355687428096000.0, /* 18! */ 6402373705728000.0, /* 19! */ 121645100408832000.0, /* 20! */ 2432902008176640000.0, /* 21! */ 51090942171709440000.0, /* 22! */ 1124000727777607680000.0 }; private static final double NEMES_GAMMA_COEFF[] = { 1.00000000000000000000000000000000000, 0 , 0.08333333333333333333333333333333333, 0 , 0.00069444444444444444444444444444444, 0 , 0.00065861992945326278659611992945326, 0 , -0.00053287817827748383303938859494415, 0 , 0.00079278588700608376534302460228386, 0 , -0.00184758189322033028400606295961969, 0 , 0.00625067824784941846328836824623616, 0 , -0.02901710246301150993444701506844402, 0 , 0.17718457242491308890302832366796470, 0 , -1.37747681703993534399676348903067470 }; /** * Based on Gerg&#337; Nemes's Gamma Function approximation formula, we compute * approximate value of Gamma function of x. * @param recv Math module * @param x a real number * @return &Gamma;(x) for real number x * @see <a href="http://www.ebyte.it/library/downloads/2008_MTH_Nemes_GammaApproximationUpdate.pdf"> * New asymptotic expansion for the &Gamma;(x) function</a> */ @JRubyMethod(name = "gamma", module = true, visibility = Visibility.PRIVATE) public static RubyFloat gamma(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyKernel.new_float(context.runtime, x).value; double result = nemes_gamma(value); /* note nemes_gamma can return Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY * when value is an integer less than 1. * We treat 0 as a special case to avoid Domain error. */ if (Double.isInfinite(result)) { if (value < 0) { result = Double.NaN; } else { if (value == 0 && 1 / value < 0) { result = Double.NEGATIVE_INFINITY; } else { result = Double.POSITIVE_INFINITY; } } } if (Double.isNaN(value)) { return RubyFloat.newFloat(context.runtime, Double.NaN); } domainCheck19(recv, result, "gamma"); return RubyFloat.newFloat(context.runtime, result); } /** * Based on Gerg&#337; Nemes's Gamma Function approximation formula, we compute * Log Gamma function for real number x. * @param recv Math module * @param x a real number * @return 2-element array [ln(&Gamma;(x)), sgn] for real number x, * where sgn is the sign of &Gamma;(x) when exponentiated * @see #gamma(ThreadContext, org.jruby.runtime.builtin.IRubyObject, org.jruby.runtime.builtin.IRubyObject) */ @JRubyMethod(name = "lgamma", module = true, visibility = Visibility.PRIVATE) public static RubyArray lgamma(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyKernel.new_float(context.runtime, x).value; // JRUBY-4653: Could this error checking done more elegantly? if (value < 0 && Double.isInfinite(value)) throw context.runtime.newMathDomainError("lgamma"); NemesLogGamma l = new NemesLogGamma(value); return RubyArray.newArray(context.runtime, RubyFloat.newFloat(context.runtime, l.value), RubyInteger.int2fix(context.runtime, (int) l.sign)); } public static double nemes_gamma(double x) { double int_part = (int) x; if ((x - int_part) == 0.0 && 0 < int_part && int_part <= FACTORIAL.length) { return FACTORIAL[(int) int_part - 1]; } NemesLogGamma l = new NemesLogGamma(x); return l.sign * Math.exp(l.value); } /** * Inner class to help with &Gamma; functions */ public static class NemesLogGamma { public final double value; public final double sign; public NemesLogGamma(double x) { if (Double.isInfinite(x)) { value = Double.POSITIVE_INFINITY; sign = 1; return; } if (Double.isNaN(x)) { value = Double.NaN; sign = 1; return; } double int_part = (int) x; sign = signum(x, int_part); if ((x - int_part) == 0.0 && 0 < int_part && int_part <= FACTORIAL.length) { value = Math.log(FACTORIAL[(int) int_part - 1]); } else if (x < 10) { double rising_factorial = 1; for (int i = 0; i < (int) Math.abs(x) - int_part + 10; i++) { rising_factorial *= (x + i); } NemesLogGamma l = new NemesLogGamma(x + (int) Math.abs(x) - int_part + 10); value = l.value - Math.log(Math.abs(rising_factorial)); } else { double temp = 0.0; for (int i = 0; i < NEMES_GAMMA_COEFF.length; i++) { temp += NEMES_GAMMA_COEFF[i] * 1.0 / Math.pow(x, i); } value = x * (Math.log(x) - 1 + Math.log(temp)) + (Math.log(2) + Math.log(Math.PI) - Math.log(x)) / 2.0; } } private static int signum(final double x, final double int_part) { return ( (int_part % 2 == 0 && (x - int_part) != 0.0 && (x < 0)) || negZero(x) ) ? -1 : 1; } private static boolean negZero(final double x) { return x == 0.0 && Double.doubleToRawLongBits(x) != 0; // detect -0.0 (since in Java: `0.0 == -0.0`) } } }
jruby/jruby
core/src/main/java/org/jruby/RubyMath.java
2,333
/* * Copyright 2010 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 * * 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.gradle.internal.service.scopes; import org.gradle.StartParameter; import org.gradle.api.Project; import org.gradle.api.flow.FlowScope; import org.gradle.api.internal.BuildDefinition; import org.gradle.api.internal.ClassPathRegistry; import org.gradle.api.internal.DefaultClassPathProvider; import org.gradle.api.internal.DefaultClassPathRegistry; import org.gradle.api.internal.DependencyClassPathProvider; import org.gradle.api.internal.DocumentationRegistry; import org.gradle.api.internal.ExternalProcessStartedListener; import org.gradle.api.internal.FeaturePreviews; import org.gradle.api.internal.GradleInternal; import org.gradle.api.internal.StartParameterInternal; import org.gradle.api.internal.artifacts.DefaultModule; import org.gradle.api.internal.artifacts.Module; import org.gradle.api.internal.artifacts.configurations.DependencyMetaDataProvider; import org.gradle.api.internal.classpath.ModuleRegistry; import org.gradle.api.internal.classpath.PluginModuleRegistry; import org.gradle.api.internal.collections.DomainObjectCollectionFactory; import org.gradle.api.internal.component.ComponentTypeRegistry; import org.gradle.api.internal.component.DefaultComponentTypeRegistry; import org.gradle.api.internal.file.DefaultArchiveOperations; import org.gradle.api.internal.file.DefaultFileOperations; import org.gradle.api.internal.file.DefaultFileSystemOperations; import org.gradle.api.internal.file.FileCollectionFactory; import org.gradle.api.internal.file.FileResolver; import org.gradle.api.internal.file.temp.TemporaryFileProvider; import org.gradle.api.internal.initialization.BuildLogicBuildQueue; import org.gradle.api.internal.initialization.BuildLogicBuilder; import org.gradle.api.internal.initialization.DefaultBuildLogicBuilder; import org.gradle.api.internal.initialization.DefaultScriptClassPathResolver; import org.gradle.api.internal.initialization.DefaultScriptHandlerFactory; import org.gradle.api.internal.initialization.ScriptClassPathResolver; import org.gradle.api.internal.initialization.ScriptHandlerFactory; import org.gradle.api.internal.plugins.DefaultPluginRegistry; import org.gradle.api.internal.plugins.PluginInspector; import org.gradle.api.internal.plugins.PluginRegistry; import org.gradle.api.internal.project.DefaultProjectRegistry; import org.gradle.api.internal.project.DefaultProjectTaskLister; import org.gradle.api.internal.project.IsolatedAntBuilder; import org.gradle.api.internal.project.ProjectFactory; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.api.internal.project.ProjectStateRegistry; import org.gradle.api.internal.project.ProjectTaskLister; import org.gradle.api.internal.project.antbuilder.DefaultIsolatedAntBuilder; import org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory; import org.gradle.api.internal.project.taskfactory.ITaskFactory; import org.gradle.api.internal.project.taskfactory.TaskClassInfoStore; import org.gradle.api.internal.project.taskfactory.TaskFactory; import org.gradle.api.internal.properties.GradleProperties; import org.gradle.api.internal.provider.DefaultProviderFactory; import org.gradle.api.internal.provider.DefaultValueSourceProviderFactory; import org.gradle.api.internal.provider.ValueSourceProviderFactory; import org.gradle.api.internal.provider.sources.process.ExecSpecFactory; import org.gradle.api.internal.provider.sources.process.ProcessOutputProviderFactory; import org.gradle.api.internal.resources.ApiTextResourceAdapter; import org.gradle.api.internal.resources.DefaultResourceHandler; import org.gradle.api.internal.tasks.TaskDependencyFactory; import org.gradle.api.internal.tasks.TaskStatistics; import org.gradle.api.invocation.BuildInvocationDetails; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ProviderFactory; import org.gradle.api.services.internal.BuildServiceProvider; import org.gradle.api.services.internal.BuildServiceProviderNagger; import org.gradle.api.services.internal.DefaultBuildServicesRegistry; import org.gradle.cache.UnscopedCacheBuilderFactory; import org.gradle.cache.internal.BuildScopeCacheDir; import org.gradle.cache.internal.scopes.DefaultBuildScopedCacheBuilderFactory; import org.gradle.cache.scopes.BuildScopedCacheBuilderFactory; import org.gradle.caching.internal.BuildCacheServices; import org.gradle.configuration.BuildOperationFiringProjectsPreparer; import org.gradle.configuration.BuildTreePreparingProjectsPreparer; import org.gradle.configuration.CompileOperationFactory; import org.gradle.configuration.DefaultInitScriptProcessor; import org.gradle.configuration.DefaultProjectsPreparer; import org.gradle.configuration.DefaultScriptPluginFactory; import org.gradle.configuration.ImportsReader; import org.gradle.configuration.ProjectsPreparer; import org.gradle.configuration.ScriptPluginFactory; import org.gradle.configuration.ScriptPluginFactorySelector; import org.gradle.configuration.project.DefaultCompileOperationFactory; import org.gradle.configuration.project.PluginsProjectConfigureActions; import org.gradle.execution.ProjectConfigurer; import org.gradle.execution.plan.DefaultNodeValidator; import org.gradle.execution.plan.ExecutionNodeAccessHierarchies; import org.gradle.execution.plan.ExecutionPlanFactory; import org.gradle.execution.plan.OrdinalGroupFactory; import org.gradle.execution.plan.TaskDependencyResolver; import org.gradle.execution.plan.TaskNodeDependencyResolver; import org.gradle.execution.plan.TaskNodeFactory; import org.gradle.execution.plan.ToPlannedNodeConverterRegistry; import org.gradle.execution.plan.WorkNodeDependencyResolver; import org.gradle.execution.selection.BuildTaskSelector; import org.gradle.groovy.scripts.DefaultScriptCompilerFactory; import org.gradle.groovy.scripts.ScriptCompilerFactory; import org.gradle.groovy.scripts.internal.BuildOperationBackedScriptCompilationHandler; import org.gradle.groovy.scripts.internal.BuildScopeInMemoryCachingScriptClassCompiler; import org.gradle.groovy.scripts.internal.CrossBuildInMemoryCachingScriptClassCache; import org.gradle.groovy.scripts.internal.DefaultScriptCompilationHandler; import org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory; import org.gradle.groovy.scripts.internal.GroovyDslWorkspaceProvider; import org.gradle.groovy.scripts.internal.GroovyScriptClassCompiler; import org.gradle.groovy.scripts.internal.ScriptRunnerFactory; import org.gradle.groovy.scripts.internal.ScriptSourceListener; import org.gradle.initialization.BuildLoader; import org.gradle.initialization.BuildOperationFiringSettingsPreparer; import org.gradle.initialization.BuildOperationSettingsProcessor; import org.gradle.initialization.ClassLoaderScopeRegistry; import org.gradle.initialization.DefaultGradlePropertiesController; import org.gradle.initialization.DefaultGradlePropertiesLoader; import org.gradle.initialization.DefaultSettingsLoaderFactory; import org.gradle.initialization.DefaultSettingsPreparer; import org.gradle.initialization.DefaultToolchainManagement; import org.gradle.initialization.Environment; import org.gradle.initialization.EnvironmentChangeTracker; import org.gradle.initialization.GradlePropertiesController; import org.gradle.initialization.GradleUserHomeDirProvider; import org.gradle.initialization.IGradlePropertiesLoader; import org.gradle.initialization.InitScriptHandler; import org.gradle.initialization.InstantiatingBuildLoader; import org.gradle.initialization.NotifyingBuildLoader; import org.gradle.initialization.ProjectPropertySettingBuildLoader; import org.gradle.initialization.RootBuildCacheControllerSettingsProcessor; import org.gradle.initialization.ScriptEvaluatingSettingsProcessor; import org.gradle.initialization.SettingsEvaluatedCallbackFiringSettingsProcessor; import org.gradle.initialization.SettingsFactory; import org.gradle.initialization.SettingsLoaderFactory; import org.gradle.initialization.SettingsPreparer; import org.gradle.initialization.SettingsProcessor; import org.gradle.initialization.buildsrc.BuildSourceBuilder; import org.gradle.initialization.buildsrc.BuildSrcBuildListenerFactory; import org.gradle.initialization.buildsrc.BuildSrcProjectConfigurationAction; import org.gradle.initialization.layout.BuildLayout; import org.gradle.initialization.layout.BuildLayoutConfiguration; import org.gradle.initialization.layout.BuildLayoutFactory; import org.gradle.initialization.layout.ResolvedBuildLayout; import org.gradle.initialization.properties.DefaultProjectPropertiesLoader; import org.gradle.initialization.properties.DefaultSystemPropertiesInstaller; import org.gradle.initialization.properties.ProjectPropertiesLoader; import org.gradle.initialization.properties.SystemPropertiesInstaller; import org.gradle.internal.actor.ActorFactory; import org.gradle.internal.actor.internal.DefaultActorFactory; import org.gradle.internal.authentication.AuthenticationSchemeRegistry; import org.gradle.internal.authentication.DefaultAuthenticationSchemeRegistry; import org.gradle.internal.build.BuildModelControllerServices; import org.gradle.internal.build.BuildOperationFiringBuildWorkPreparer; import org.gradle.internal.build.BuildState; import org.gradle.internal.build.BuildStateRegistry; import org.gradle.internal.build.BuildWorkPreparer; import org.gradle.internal.build.DefaultBuildWorkGraphController; import org.gradle.internal.build.DefaultBuildWorkPreparer; import org.gradle.internal.build.DefaultPublicBuildPath; import org.gradle.internal.build.PublicBuildPath; import org.gradle.internal.buildevents.BuildStartedTime; import org.gradle.internal.buildoption.FeatureFlags; import org.gradle.internal.buildtree.BuildInclusionCoordinator; import org.gradle.internal.buildtree.BuildModelParameters; import org.gradle.internal.classloader.ClassLoaderFactory; import org.gradle.internal.classpath.CachedClasspathTransformer; import org.gradle.internal.classpath.transforms.ClasspathElementTransformFactoryForLegacy; import org.gradle.internal.cleanup.DefaultBuildOutputCleanupRegistry; import org.gradle.internal.code.UserCodeApplicationContext; import org.gradle.internal.composite.DefaultBuildIncluder; import org.gradle.internal.concurrent.ExecutorFactory; import org.gradle.internal.event.ListenerManager; import org.gradle.internal.event.ScopedListenerManager; import org.gradle.internal.execution.ExecutionEngine; import org.gradle.internal.execution.InputFingerprinter; import org.gradle.internal.execution.WorkExecutionTracker; import org.gradle.internal.file.Deleter; import org.gradle.internal.file.RelativeFilePathResolver; import org.gradle.internal.file.Stat; import org.gradle.internal.hash.ClassLoaderHierarchyHasher; import org.gradle.internal.instantiation.InstantiatorFactory; import org.gradle.internal.invocation.DefaultBuildInvocationDetails; import org.gradle.internal.isolation.IsolatableFactory; import org.gradle.internal.jvm.JavaModuleDetector; import org.gradle.internal.logging.LoggingManagerInternal; import org.gradle.internal.model.CalculatedValueFactory; import org.gradle.internal.nativeintegration.filesystem.FileSystem; import org.gradle.internal.operations.BuildOperationProgressEventEmitter; import org.gradle.internal.operations.BuildOperationRunner; import org.gradle.internal.operations.logging.BuildOperationLoggerFactory; import org.gradle.internal.operations.logging.DefaultBuildOperationLoggerFactory; import org.gradle.internal.reflect.Instantiator; import org.gradle.internal.resource.DefaultTextFileResourceLoader; import org.gradle.internal.resource.TextFileResourceLoader; import org.gradle.internal.resource.local.FileResourceListener; import org.gradle.internal.resources.ResourceLockCoordinationService; import org.gradle.internal.resources.SharedResourceLeaseRegistry; import org.gradle.internal.scripts.ScriptExecutionListener; import org.gradle.internal.service.CachingServiceLocator; import org.gradle.internal.service.ScopedServiceRegistry; import org.gradle.internal.service.ServiceRegistry; import org.gradle.internal.snapshot.CaseSensitivity; import org.gradle.model.internal.inspect.ModelRuleSourceDetector; import org.gradle.plugin.management.internal.autoapply.AutoAppliedPluginHandler; import org.gradle.plugin.use.internal.PluginRequestApplicator; import org.gradle.process.internal.DefaultExecOperations; import org.gradle.process.internal.DefaultExecSpecFactory; import org.gradle.process.internal.ExecActionFactory; import org.gradle.process.internal.ExecFactory; import org.gradle.tooling.provider.model.internal.BuildScopeToolingModelBuilderRegistryAction; import org.gradle.tooling.provider.model.internal.DefaultToolingModelBuilderRegistry; import java.util.List; /** * Contains the singleton services for a single build invocation. */ public class BuildScopeServices extends ScopedServiceRegistry { public BuildScopeServices(ServiceRegistry parent, BuildModelControllerServices.Supplier supplier) { super(Scope.Build.class, "build-scope services", parent); addProvider(new BuildCacheServices()); register(registration -> { registration.add(DefaultExecOperations.class); registration.add(DefaultFileOperations.class); registration.add(DefaultFileSystemOperations.class); registration.add(DefaultArchiveOperations.class); registration.add(ProjectFactory.class); registration.add(DefaultSettingsLoaderFactory.class); registration.add(ResolvedBuildLayout.class); registration.add(DefaultNodeValidator.class); registration.add(TaskNodeFactory.class); registration.add(TaskNodeDependencyResolver.class); registration.add(WorkNodeDependencyResolver.class); registration.add(TaskDependencyResolver.class); registration.add(DefaultBuildWorkGraphController.class); registration.add(DefaultBuildIncluder.class); registration.add(DefaultScriptClassPathResolver.class); registration.add(DefaultScriptHandlerFactory.class); registration.add(DefaultBuildOutputCleanupRegistry.class); supplier.applyServicesTo(registration, this); for (PluginServiceRegistry pluginServiceRegistry : parent.getAll(PluginServiceRegistry.class)) { pluginServiceRegistry.registerBuildServices(registration); } }); } OrdinalGroupFactory createOrdinalGroupFactory() { return new OrdinalGroupFactory(); } ExecutionPlanFactory createExecutionPlanFactory( BuildState build, TaskNodeFactory taskNodeFactory, OrdinalGroupFactory ordinalGroupFactory, TaskDependencyResolver dependencyResolver, ExecutionNodeAccessHierarchies executionNodeAccessHierarchies, ResourceLockCoordinationService lockCoordinationService ) { return new ExecutionPlanFactory( build.getDisplayName().getDisplayName(), taskNodeFactory, ordinalGroupFactory, dependencyResolver, executionNodeAccessHierarchies.getOutputHierarchy(), executionNodeAccessHierarchies.getDestroyableHierarchy(), lockCoordinationService ); } ExecutionNodeAccessHierarchies createExecutionNodeAccessHierarchies(FileSystem fileSystem, Stat stat) { return new ExecutionNodeAccessHierarchies(fileSystem.isCaseSensitive() ? CaseSensitivity.CASE_SENSITIVE : CaseSensitivity.CASE_INSENSITIVE, stat); } protected BuildScopedCacheBuilderFactory createBuildScopedCacheBuilderFactory( GradleUserHomeDirProvider userHomeDirProvider, BuildLayout buildLayout, StartParameter startParameter, UnscopedCacheBuilderFactory unscopedCacheBuilderFactory ) { BuildScopeCacheDir cacheDir = new BuildScopeCacheDir(userHomeDirProvider, buildLayout, startParameter); return new DefaultBuildScopedCacheBuilderFactory(cacheDir.getDir(), unscopedCacheBuilderFactory); } protected BuildLayout createBuildLocations(BuildLayoutFactory buildLayoutFactory, BuildDefinition buildDefinition) { return buildLayoutFactory.getLayoutFor(new BuildLayoutConfiguration(buildDefinition.getStartParameter())); } protected DefaultResourceHandler.Factory createResourceHandlerFactory(FileResolver fileResolver, TaskDependencyFactory taskDependencyFactory, FileSystem fileSystem, TemporaryFileProvider temporaryFileProvider, ApiTextResourceAdapter.Factory textResourceAdapterFactory) { return DefaultResourceHandler.Factory.from( fileResolver, taskDependencyFactory, fileSystem, temporaryFileProvider, textResourceAdapterFactory ); } protected FileCollectionFactory decorateFileCollectionFactory(FileCollectionFactory fileCollectionFactory, FileResolver fileResolver) { return fileCollectionFactory.withResolver(fileResolver); } protected ExecFactory decorateExecFactory(ExecFactory parent, FileResolver fileResolver, FileCollectionFactory fileCollectionFactory, Instantiator instantiator, ObjectFactory objectFactory, JavaModuleDetector javaModuleDetector, ListenerManager listenerManager) { return parent.forContext() .withFileResolver(fileResolver) .withFileCollectionFactory(fileCollectionFactory) .withInstantiator(instantiator) .withObjectFactory(objectFactory) .withJavaModuleDetector(javaModuleDetector) .withExternalProcessStartedListener(listenerManager.getBroadcaster(ExternalProcessStartedListener.class)) .build(); } protected PublicBuildPath createPublicBuildPath(BuildState buildState) { return new DefaultPublicBuildPath(buildState.getIdentityPath()); } protected TaskStatistics createTaskStatistics() { return new TaskStatistics(); } protected DefaultProjectRegistry<ProjectInternal> createProjectRegistry() { return new DefaultProjectRegistry<ProjectInternal>(); } protected TextFileResourceLoader createTextFileResourceLoader(RelativeFilePathResolver resolver) { return new DefaultTextFileResourceLoader(resolver); } protected ScopedListenerManager createListenerManager(ScopedListenerManager listenerManager) { return listenerManager.createChild(Scope.Build.class); } protected ClassPathRegistry createClassPathRegistry() { ModuleRegistry moduleRegistry = get(ModuleRegistry.class); return new DefaultClassPathRegistry( new DefaultClassPathProvider(moduleRegistry), new DependencyClassPathProvider(moduleRegistry, get(PluginModuleRegistry.class))); } protected IsolatedAntBuilder createIsolatedAntBuilder(ClassPathRegistry classPathRegistry, ClassLoaderFactory classLoaderFactory, ModuleRegistry moduleRegistry) { return new DefaultIsolatedAntBuilder(classPathRegistry, classLoaderFactory, moduleRegistry); } protected GradleProperties createGradleProperties( GradlePropertiesController gradlePropertiesController ) { return gradlePropertiesController.getGradleProperties(); } protected GradlePropertiesController createGradlePropertiesController( IGradlePropertiesLoader propertiesLoader, SystemPropertiesInstaller systemPropertiesInstaller, ProjectPropertiesLoader projectPropertiesLoader ) { return new DefaultGradlePropertiesController(propertiesLoader, systemPropertiesInstaller, projectPropertiesLoader); } protected ProjectPropertiesLoader createProjectPropertiesLoader( Environment environment ) { return new DefaultProjectPropertiesLoader((StartParameterInternal) get(StartParameter.class), environment); } protected IGradlePropertiesLoader createGradlePropertiesLoader( Environment environment ) { return new DefaultGradlePropertiesLoader((StartParameterInternal) get(StartParameter.class), environment); } protected SystemPropertiesInstaller createSystemPropertiesInstaller( EnvironmentChangeTracker environmentChangeTracker, GradleInternal gradleInternal ) { return new DefaultSystemPropertiesInstaller(environmentChangeTracker, (StartParameterInternal) get(StartParameter.class), gradleInternal); } protected ValueSourceProviderFactory createValueSourceProviderFactory( InstantiatorFactory instantiatorFactory, IsolatableFactory isolatableFactory, ServiceRegistry services, GradleProperties gradleProperties, ExecFactory execFactory, ListenerManager listenerManager, CalculatedValueFactory calculatedValueFactory ) { return new DefaultValueSourceProviderFactory( listenerManager, instantiatorFactory, isolatableFactory, gradleProperties, calculatedValueFactory, new DefaultExecOperations(execFactory.forContext().withoutExternalProcessStartedListener().build()), services ); } protected ExecSpecFactory createExecSpecFactory(ExecActionFactory execActionFactory) { return new DefaultExecSpecFactory(execActionFactory); } protected ProcessOutputProviderFactory createProcessOutputProviderFactory(Instantiator instantiator, ExecSpecFactory execSpecFactory) { return new ProcessOutputProviderFactory(instantiator, execSpecFactory); } protected ProviderFactory createProviderFactory( Instantiator instantiator, ValueSourceProviderFactory valueSourceProviderFactory, ProcessOutputProviderFactory processOutputProviderFactory, ListenerManager listenerManager ) { return instantiator.newInstance(DefaultProviderFactory.class, valueSourceProviderFactory, processOutputProviderFactory, listenerManager); } protected ActorFactory createActorFactory() { return new DefaultActorFactory(get(ExecutorFactory.class)); } protected BuildLoader createBuildLoader( GradleProperties gradleProperties, BuildOperationRunner buildOperationRunner, BuildOperationProgressEventEmitter emitter, ListenerManager listenerManager ) { return new NotifyingBuildLoader( new ProjectPropertySettingBuildLoader( gradleProperties, new InstantiatingBuildLoader(), listenerManager.getBroadcaster(FileResourceListener.class) ), buildOperationRunner, emitter ); } protected ITaskFactory createITaskFactory(Instantiator instantiator, TaskClassInfoStore taskClassInfoStore) { return new AnnotationProcessingTaskFactory( instantiator, taskClassInfoStore, new TaskFactory()); } protected ScriptCompilerFactory createScriptCompileFactory( GroovyScriptClassCompiler scriptCompiler, CrossBuildInMemoryCachingScriptClassCache cache, ScriptRunnerFactory scriptRunnerFactory ) { return new DefaultScriptCompilerFactory( new BuildScopeInMemoryCachingScriptClassCompiler(cache, scriptCompiler), scriptRunnerFactory ); } protected GroovyScriptClassCompiler createFileCacheBackedScriptClassCompiler( BuildOperationRunner buildOperationRunner, ClassLoaderHierarchyHasher classLoaderHierarchyHasher, DefaultScriptCompilationHandler scriptCompilationHandler, CachedClasspathTransformer classpathTransformer, ExecutionEngine executionEngine, FileCollectionFactory fileCollectionFactory, InputFingerprinter inputFingerprinter, GroovyDslWorkspaceProvider groovyDslWorkspaceProvider, ClasspathElementTransformFactoryForLegacy transformFactoryForLegacy ) { return new GroovyScriptClassCompiler( new BuildOperationBackedScriptCompilationHandler(scriptCompilationHandler, buildOperationRunner), classLoaderHierarchyHasher, classpathTransformer, executionEngine, fileCollectionFactory, inputFingerprinter, groovyDslWorkspaceProvider.getWorkspace(), transformFactoryForLegacy ); } protected ScriptPluginFactory createScriptPluginFactory(InstantiatorFactory instantiatorFactory, BuildOperationRunner buildOperationRunner, UserCodeApplicationContext userCodeApplicationContext, ListenerManager listenerManager) { DefaultScriptPluginFactory defaultScriptPluginFactory = defaultScriptPluginFactory(); ScriptPluginFactorySelector.ProviderInstantiator instantiator = ScriptPluginFactorySelector.defaultProviderInstantiatorFor(instantiatorFactory.inject(this)); ScriptPluginFactorySelector scriptPluginFactorySelector = new ScriptPluginFactorySelector(defaultScriptPluginFactory, instantiator, buildOperationRunner, userCodeApplicationContext, listenerManager.getBroadcaster(ScriptSourceListener.class)); defaultScriptPluginFactory.setScriptPluginFactory(scriptPluginFactorySelector); return scriptPluginFactorySelector; } private DefaultScriptPluginFactory defaultScriptPluginFactory() { return new DefaultScriptPluginFactory( this, get(ScriptCompilerFactory.class), getFactory(LoggingManagerInternal.class), get(AutoAppliedPluginHandler.class), get(PluginRequestApplicator.class), get(CompileOperationFactory.class)); } protected BuildSourceBuilder createBuildSourceBuilder( BuildState currentBuild, BuildOperationRunner buildOperationRunner, CachingServiceLocator cachingServiceLocator, BuildStateRegistry buildRegistry, PublicBuildPath publicBuildPath, ScriptClassPathResolver scriptClassPathResolver, BuildLogicBuildQueue buildQueue ) { return new BuildSourceBuilder( currentBuild, buildOperationRunner, new BuildSrcBuildListenerFactory( PluginsProjectConfigureActions.of( BuildSrcProjectConfigurationAction.class, cachingServiceLocator), scriptClassPathResolver), buildRegistry, publicBuildPath, buildQueue); } protected BuildLogicBuilder createBuildLogicBuilder( BuildState currentBuild, ScriptClassPathResolver scriptClassPathResolver, BuildLogicBuildQueue buildQueue ) { return new DefaultBuildLogicBuilder(currentBuild, scriptClassPathResolver, buildQueue); } protected InitScriptHandler createInitScriptHandler(ScriptPluginFactory scriptPluginFactory, ScriptHandlerFactory scriptHandlerFactory, BuildOperationRunner buildOperationRunner, TextFileResourceLoader resourceLoader) { return new InitScriptHandler( new DefaultInitScriptProcessor( scriptPluginFactory, scriptHandlerFactory ), buildOperationRunner, resourceLoader ); } protected SettingsProcessor createSettingsProcessor( ScriptPluginFactory scriptPluginFactory, ScriptHandlerFactory scriptHandlerFactory, Instantiator instantiator, GradleProperties gradleProperties, BuildOperationRunner buildOperationRunner, TextFileResourceLoader textFileResourceLoader ) { return new BuildOperationSettingsProcessor( new RootBuildCacheControllerSettingsProcessor( new SettingsEvaluatedCallbackFiringSettingsProcessor( new ScriptEvaluatingSettingsProcessor( scriptPluginFactory, new SettingsFactory( instantiator, this, scriptHandlerFactory ), gradleProperties, textFileResourceLoader ) ) ), buildOperationRunner ); } protected SettingsPreparer createSettingsPreparer(SettingsLoaderFactory settingsLoaderFactory, BuildOperationRunner buildOperationRunner, BuildOperationProgressEventEmitter emitter, BuildDefinition buildDefinition) { return new BuildOperationFiringSettingsPreparer( new DefaultSettingsPreparer( settingsLoaderFactory ), buildOperationRunner, emitter, buildDefinition.getFromBuild()); } protected ProjectsPreparer createBuildConfigurer( ProjectConfigurer projectConfigurer, BuildSourceBuilder buildSourceBuilder, BuildInclusionCoordinator inclusionCoordinator, BuildLoader buildLoader, BuildOperationRunner buildOperationRunner, BuildModelParameters buildModelParameters ) { return new BuildOperationFiringProjectsPreparer( new BuildTreePreparingProjectsPreparer( new DefaultProjectsPreparer( projectConfigurer, buildModelParameters, buildOperationRunner), buildLoader, inclusionCoordinator, buildSourceBuilder), buildOperationRunner); } protected BuildWorkPreparer createWorkPreparer(BuildOperationRunner buildOperationRunner, ExecutionPlanFactory executionPlanFactory, ToPlannedNodeConverterRegistry converterRegistry) { return new BuildOperationFiringBuildWorkPreparer( buildOperationRunner, new DefaultBuildWorkPreparer( executionPlanFactory ), converterRegistry ); } protected BuildTaskSelector.BuildSpecificSelector createTaskSelector(BuildTaskSelector selector, BuildState build) { return selector.relativeToBuild(build); } protected PluginRegistry createPluginRegistry(ClassLoaderScopeRegistry scopeRegistry, PluginInspector pluginInspector) { return new DefaultPluginRegistry(pluginInspector, scopeRegistry.getCoreAndPluginsScope()); } protected BuildScopeServiceRegistryFactory createServiceRegistryFactory(final ServiceRegistry services) { return new BuildScopeServiceRegistryFactory(services); } protected ProjectTaskLister createProjectTaskLister() { return new DefaultProjectTaskLister(); } protected DependencyMetaDataProvider createDependencyMetaDataProvider() { return new DependencyMetaDataProviderImpl(); } protected ComponentTypeRegistry createComponentTypeRegistry() { return new DefaultComponentTypeRegistry(); } protected PluginInspector createPluginInspector(ModelRuleSourceDetector modelRuleSourceDetector) { return new PluginInspector(modelRuleSourceDetector); } private static class DependencyMetaDataProviderImpl implements DependencyMetaDataProvider { @Override public Module getModule() { return new DefaultModule("unspecified", "unspecified", Project.DEFAULT_VERSION, Project.DEFAULT_STATUS); } } protected BuildOperationLoggerFactory createBuildOperationLoggerFactory() { return new DefaultBuildOperationLoggerFactory(); } AuthenticationSchemeRegistry createAuthenticationSchemeRegistry() { return new DefaultAuthenticationSchemeRegistry(); } protected DefaultToolingModelBuilderRegistry createBuildScopedToolingModelBuilders( List<BuildScopeToolingModelBuilderRegistryAction> registryActions, BuildOperationRunner buildOperationRunner, ProjectStateRegistry projectStateRegistry, UserCodeApplicationContext userCodeApplicationContext ) { DefaultToolingModelBuilderRegistry registry = new DefaultToolingModelBuilderRegistry(buildOperationRunner, projectStateRegistry, userCodeApplicationContext); // Services are created on demand, and this may happen while applying a plugin userCodeApplicationContext.gradleRuntime(() -> { for (BuildScopeToolingModelBuilderRegistryAction registryAction : registryActions) { registryAction.execute(registry); } }); return registry; } protected BuildInvocationDetails createBuildInvocationDetails(BuildStartedTime buildStartedTime) { return new DefaultBuildInvocationDetails(buildStartedTime); } protected CompileOperationFactory createCompileOperationFactory(DocumentationRegistry documentationRegistry) { return new DefaultCompileOperationFactory(documentationRegistry); } protected DefaultScriptCompilationHandler createScriptCompilationHandler(Deleter deleter, ImportsReader importsReader, ObjectFactory objectFactory) { return objectFactory.newInstance(DefaultScriptCompilationHandler.class, deleter, importsReader); } protected ScriptRunnerFactory createScriptRunnerFactory(ListenerManager listenerManager, InstantiatorFactory instantiatorFactory) { ScriptExecutionListener scriptExecutionListener = listenerManager.getBroadcaster(ScriptExecutionListener.class); return new DefaultScriptRunnerFactory( scriptExecutionListener, instantiatorFactory.inject() ); } protected DefaultToolchainManagement createToolchainManagement(ObjectFactory objectFactory) { return objectFactory.newInstance(DefaultToolchainManagement.class); } protected SharedResourceLeaseRegistry createSharedResourceLeaseRegistry(ResourceLockCoordinationService coordinationService) { return new SharedResourceLeaseRegistry(coordinationService); } protected DefaultBuildServicesRegistry createSharedServiceRegistry( BuildState buildState, Instantiator instantiator, DomainObjectCollectionFactory factory, InstantiatorFactory instantiatorFactory, ServiceRegistry services, ListenerManager listenerManager, IsolatableFactory isolatableFactory, SharedResourceLeaseRegistry sharedResourceLeaseRegistry, FeatureFlags featureFlags ) { // TODO:configuration-cache remove this hack // HACK: force the instantiation of FlowScope so its listeners are registered before DefaultBuildServicesRegistry's services.find(FlowScope.class); // Instantiate via `instantiator` for the DSL decorations to the `BuildServiceRegistry` API return instantiator.newInstance( DefaultBuildServicesRegistry.class, buildState.getBuildIdentifier(), factory, instantiatorFactory, services, listenerManager, isolatableFactory, sharedResourceLeaseRegistry, featureFlags.isEnabled(FeaturePreviews.Feature.STABLE_CONFIGURATION_CACHE) ? new BuildServiceProviderNagger(services.get(WorkExecutionTracker.class)) : BuildServiceProvider.Listener.EMPTY ); } }
gradle/gradle
subprojects/core/src/main/java/org/gradle/internal/service/scopes/BuildScopeServices.java
2,334
package org.telegram.messenger; import android.text.TextUtils; import android.util.LongSparseArray; import org.telegram.tgnet.TLRPC; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; public class CacheByChatsController { public static int KEEP_MEDIA_DELETE = 4; public static int KEEP_MEDIA_FOREVER = 2; public static int KEEP_MEDIA_ONE_DAY = 3; public static int KEEP_MEDIA_ONE_WEEK = 0; public static int KEEP_MEDIA_ONE_MONTH = 1; public static int KEEP_MEDIA_TWO_DAY = 6; //TEST VALUE public static int KEEP_MEDIA_ONE_MINUTE = 5; public static final int KEEP_MEDIA_TYPE_USER = 0; public static final int KEEP_MEDIA_TYPE_GROUP = 1; public static final int KEEP_MEDIA_TYPE_CHANNEL = 2; public static final int KEEP_MEDIA_TYPE_STORIES = 3; private final int currentAccount; int[] keepMediaByTypes = {-1, -1, -1, -1}; public CacheByChatsController(int currentAccount) { this.currentAccount = currentAccount; for (int i = 0; i < 4; i++) { keepMediaByTypes[i] = SharedConfig.getPreferences().getInt("keep_media_type_" + i, getDefault(i)); } } public static int getDefault(int type) { if (type == KEEP_MEDIA_TYPE_USER) { return KEEP_MEDIA_FOREVER; } else if (type == KEEP_MEDIA_TYPE_GROUP) { return KEEP_MEDIA_ONE_MONTH; } else if (type == KEEP_MEDIA_TYPE_CHANNEL) { return KEEP_MEDIA_ONE_WEEK; } else if (type == KEEP_MEDIA_TYPE_STORIES) { return KEEP_MEDIA_TWO_DAY; } return SharedConfig.keepMedia; } public static String getKeepMediaString(int keepMedia) { if (keepMedia == KEEP_MEDIA_ONE_MINUTE) { return LocaleController.formatPluralString("Minutes", 1); } else if (keepMedia == KEEP_MEDIA_ONE_DAY) { return LocaleController.formatPluralString("Days", 1); } else if (keepMedia == KEEP_MEDIA_TWO_DAY) { return LocaleController.formatPluralString("Days", 2); } else if (keepMedia == KEEP_MEDIA_ONE_WEEK) { return LocaleController.formatPluralString("Weeks", 1); } else if (keepMedia == KEEP_MEDIA_ONE_MONTH) { return LocaleController.formatPluralString("Months", 1); } return LocaleController.getString("AutoDeleteMediaNever", R.string.AutoDeleteMediaNever); } public static long getDaysInSeconds(int keepMedia) { long seconds; if (keepMedia == CacheByChatsController.KEEP_MEDIA_ONE_WEEK) { seconds = 60L * 60L * 24L * 7L; } else if (keepMedia == CacheByChatsController.KEEP_MEDIA_ONE_MONTH) { seconds = 60L * 60L * 24L * 30L; } else if (keepMedia == CacheByChatsController.KEEP_MEDIA_ONE_DAY) { seconds = 60L * 60L * 24L; } else if (keepMedia == CacheByChatsController.KEEP_MEDIA_TWO_DAY) { seconds = 60L * 60L * 24L * 2; }else if (keepMedia == CacheByChatsController.KEEP_MEDIA_ONE_MINUTE && BuildVars.DEBUG_PRIVATE_VERSION) { //one min seconds = 60L; } else { seconds = Long.MAX_VALUE; } return seconds; } public ArrayList<KeepMediaException> getKeepMediaExceptions(int type) { ArrayList<KeepMediaException> exceptions = new ArrayList<>(); HashSet<Long> idsSet = new HashSet<>(); String exceptionsHash = UserConfig.getInstance(currentAccount).getPreferences().getString("keep_media_exceptions_" + type, ""); if (TextUtils.isEmpty(exceptionsHash)) { return exceptions; } else { ByteBuffer byteBuffer = ByteBuffer.wrap(Utilities.hexToBytes(exceptionsHash)); int n = byteBuffer.getInt(); for (int i = 0; i < n; i++) { KeepMediaException exception = new KeepMediaException(byteBuffer.getLong(), byteBuffer.getInt()); if (!idsSet.contains(exception.dialogId)) { idsSet.add(exception.dialogId); exceptions.add(exception); } } byteBuffer.clear(); } return exceptions; } public void saveKeepMediaExceptions(int type, ArrayList<KeepMediaException> exceptions) { String key = "keep_media_exceptions_" + type; if (exceptions.isEmpty()) { UserConfig.getInstance(currentAccount).getPreferences().edit().remove(key).apply(); } else { int n = exceptions.size(); ByteBuffer byteBuffer = ByteBuffer.allocate(4 + (8 + 4) * n); byteBuffer.putInt(n); for (int i = 0; i < n; i++) { byteBuffer.putLong(exceptions.get(i).dialogId); byteBuffer.putInt(exceptions.get(i).keepMedia); } UserConfig.getInstance(currentAccount).getPreferences().edit().putString(key, Utilities.bytesToHex(byteBuffer.array())).apply(); byteBuffer.clear(); } } public int getKeepMedia(int type) { if (keepMediaByTypes[type] == -1) { return SharedConfig.keepMedia; } return keepMediaByTypes[type]; } public void setKeepMedia(int type, int keepMedia) { keepMediaByTypes[type] = keepMedia; SharedConfig.getPreferences().edit().putInt("keep_media_type_" + type, keepMedia).apply(); } public void lookupFiles(ArrayList<? extends KeepMediaFile> keepMediaFiles) { LongSparseArray<ArrayList<KeepMediaFile>> filesByDialogId = FileLoader.getInstance(currentAccount).getFileDatabase().lookupFiles(keepMediaFiles); LongSparseArray<KeepMediaException> exceptionsByType = getKeepMediaExceptionsByDialogs(); for (int i = 0; i < filesByDialogId.size(); i++) { long dialogId = filesByDialogId.keyAt(i); ArrayList<? extends KeepMediaFile> files = filesByDialogId.valueAt(i); int type; if (dialogId >= 0) { type = KEEP_MEDIA_TYPE_USER; } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat == null) { chat = MessagesStorage.getInstance(currentAccount).getChatSync(-dialogId); } if (chat == null) { type = -1; } else if (ChatObject.isChannel(chat)) { type = KEEP_MEDIA_TYPE_CHANNEL; } else { type = KEEP_MEDIA_TYPE_GROUP; } } KeepMediaException exception = exceptionsByType.get(dialogId); for (int k = 0; k < files.size(); k++) { KeepMediaFile file = files.get(k); if (type >= 0) { file.dialogType = type; } if (exception != null) { file.keepMedia = exception.keepMedia; } } } } public LongSparseArray<KeepMediaException> getKeepMediaExceptionsByDialogs() { LongSparseArray<KeepMediaException> sparseArray = new LongSparseArray<>(); for (int i = 0; i < 3; i++) { ArrayList<KeepMediaException> exceptions = getKeepMediaExceptions(i); if (exceptions != null) { for (int k = 0; k < exceptions.size(); k++) { sparseArray.put(exceptions.get(k).dialogId, exceptions.get(k)); } } } return sparseArray; } public static class KeepMediaException { public final long dialogId; public int keepMedia; public KeepMediaException(long dialogId, int keepMedia) { this.dialogId = dialogId; this.keepMedia = keepMedia; } } public static class KeepMediaFile { final File file; int keepMedia = -1; int dialogType = KEEP_MEDIA_TYPE_CHANNEL; boolean isStory; public KeepMediaFile(File file) { this.file = file; } } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/messenger/CacheByChatsController.java
2,335
package org.schabi.newpipe.fragments.detail; import static android.text.TextUtils.isEmpty; import static org.schabi.newpipe.extractor.StreamingService.ServiceInfo.MediaCapability.COMMENTS; import static org.schabi.newpipe.extractor.stream.StreamExtractor.NO_AGE_LIMIT; import static org.schabi.newpipe.ktx.ViewUtils.animate; import static org.schabi.newpipe.ktx.ViewUtils.animateRotation; import static org.schabi.newpipe.player.helper.PlayerHelper.globalScreenOrientationLocked; import static org.schabi.newpipe.player.helper.PlayerHelper.isClearingQueueConfirmationRequired; import static org.schabi.newpipe.util.DependentPreferenceHelper.getResumePlaybackEnabled; import static org.schabi.newpipe.util.ExtractorHelper.showMetaInfoInTextView; import static org.schabi.newpipe.util.ListHelper.getUrlAndNonTorrentStreams; import static org.schabi.newpipe.util.NavigationHelper.openPlayQueue; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.database.ContentObserver; import android.graphics.Color; import android.graphics.Rect; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.Settings; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.RelativeLayout; import android.widget.Toast; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.preference.PreferenceManager; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.tabs.TabLayout; import org.schabi.newpipe.App; import org.schabi.newpipe.R; import org.schabi.newpipe.database.stream.model.StreamEntity; import org.schabi.newpipe.databinding.FragmentVideoDetailBinding; import org.schabi.newpipe.download.DownloadDialog; import org.schabi.newpipe.error.ErrorInfo; import org.schabi.newpipe.error.ErrorUtil; import org.schabi.newpipe.error.ReCaptchaActivity; import org.schabi.newpipe.error.UserAction; import org.schabi.newpipe.extractor.Image; import org.schabi.newpipe.extractor.NewPipe; import org.schabi.newpipe.extractor.comments.CommentsInfoItem; import org.schabi.newpipe.extractor.exceptions.ContentNotSupportedException; import org.schabi.newpipe.extractor.exceptions.ExtractionException; import org.schabi.newpipe.extractor.stream.AudioStream; import org.schabi.newpipe.extractor.stream.Stream; import org.schabi.newpipe.extractor.stream.StreamInfo; import org.schabi.newpipe.extractor.stream.StreamType; import org.schabi.newpipe.extractor.stream.VideoStream; import org.schabi.newpipe.fragments.BackPressable; import org.schabi.newpipe.fragments.BaseStateFragment; import org.schabi.newpipe.fragments.EmptyFragment; import org.schabi.newpipe.fragments.MainFragment; import org.schabi.newpipe.fragments.list.comments.CommentsFragment; import org.schabi.newpipe.fragments.list.videos.RelatedItemsFragment; import org.schabi.newpipe.ktx.AnimationType; import org.schabi.newpipe.local.dialog.PlaylistDialog; import org.schabi.newpipe.local.history.HistoryRecordManager; import org.schabi.newpipe.local.playlist.LocalPlaylistFragment; import org.schabi.newpipe.player.Player; import org.schabi.newpipe.player.PlayerService; import org.schabi.newpipe.player.PlayerType; import org.schabi.newpipe.player.event.OnKeyDownListener; import org.schabi.newpipe.player.event.PlayerServiceExtendedEventListener; import org.schabi.newpipe.player.helper.PlayerHelper; import org.schabi.newpipe.player.helper.PlayerHolder; import org.schabi.newpipe.player.playqueue.PlayQueue; import org.schabi.newpipe.player.playqueue.PlayQueueItem; import org.schabi.newpipe.player.playqueue.SinglePlayQueue; import org.schabi.newpipe.player.ui.MainPlayerUi; import org.schabi.newpipe.player.ui.VideoPlayerUi; import org.schabi.newpipe.util.Constants; import org.schabi.newpipe.util.DeviceUtils; import org.schabi.newpipe.util.ExtractorHelper; import org.schabi.newpipe.util.InfoCache; import org.schabi.newpipe.util.ListHelper; import org.schabi.newpipe.util.Localization; import org.schabi.newpipe.util.NavigationHelper; import org.schabi.newpipe.util.PermissionHelper; import org.schabi.newpipe.util.PlayButtonHelper; import org.schabi.newpipe.util.StreamTypeUtil; import org.schabi.newpipe.util.ThemeHelper; import org.schabi.newpipe.util.external_communication.KoreUtils; import org.schabi.newpipe.util.external_communication.ShareUtils; import org.schabi.newpipe.util.image.PicassoHelper; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import icepick.State; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.schedulers.Schedulers; public final class VideoDetailFragment extends BaseStateFragment<StreamInfo> implements BackPressable, PlayerServiceExtendedEventListener, OnKeyDownListener { public static final String KEY_SWITCHING_PLAYERS = "switching_players"; private static final float MAX_OVERLAY_ALPHA = 0.9f; private static final float MAX_PLAYER_HEIGHT = 0.7f; public static final String ACTION_SHOW_MAIN_PLAYER = App.PACKAGE_NAME + ".VideoDetailFragment.ACTION_SHOW_MAIN_PLAYER"; public static final String ACTION_HIDE_MAIN_PLAYER = App.PACKAGE_NAME + ".VideoDetailFragment.ACTION_HIDE_MAIN_PLAYER"; public static final String ACTION_PLAYER_STARTED = App.PACKAGE_NAME + ".VideoDetailFragment.ACTION_PLAYER_STARTED"; public static final String ACTION_VIDEO_FRAGMENT_RESUMED = App.PACKAGE_NAME + ".VideoDetailFragment.ACTION_VIDEO_FRAGMENT_RESUMED"; public static final String ACTION_VIDEO_FRAGMENT_STOPPED = App.PACKAGE_NAME + ".VideoDetailFragment.ACTION_VIDEO_FRAGMENT_STOPPED"; private static final String COMMENTS_TAB_TAG = "COMMENTS"; private static final String RELATED_TAB_TAG = "NEXT VIDEO"; private static final String DESCRIPTION_TAB_TAG = "DESCRIPTION TAB"; private static final String EMPTY_TAB_TAG = "EMPTY TAB"; private static final String PICASSO_VIDEO_DETAILS_TAG = "PICASSO_VIDEO_DETAILS_TAG"; // tabs private boolean showComments; private boolean showRelatedItems; private boolean showDescription; private String selectedTabTag; @AttrRes @NonNull final List<Integer> tabIcons = new ArrayList<>(); @StringRes @NonNull final List<Integer> tabContentDescriptions = new ArrayList<>(); private boolean tabSettingsChanged = false; private int lastAppBarVerticalOffset = Integer.MAX_VALUE; // prevents useless updates private final SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = (sharedPreferences, key) -> { if (getString(R.string.show_comments_key).equals(key)) { showComments = sharedPreferences.getBoolean(key, true); tabSettingsChanged = true; } else if (getString(R.string.show_next_video_key).equals(key)) { showRelatedItems = sharedPreferences.getBoolean(key, true); tabSettingsChanged = true; } else if (getString(R.string.show_description_key).equals(key)) { showDescription = sharedPreferences.getBoolean(key, true); tabSettingsChanged = true; } }; @State protected int serviceId = Constants.NO_SERVICE_ID; @State @NonNull protected String title = ""; @State @Nullable protected String url = null; @Nullable protected PlayQueue playQueue = null; @State int bottomSheetState = BottomSheetBehavior.STATE_EXPANDED; @State int lastStableBottomSheetState = BottomSheetBehavior.STATE_EXPANDED; @State protected boolean autoPlayEnabled = true; @Nullable private StreamInfo currentInfo = null; private Disposable currentWorker; @NonNull private final CompositeDisposable disposables = new CompositeDisposable(); @Nullable private Disposable positionSubscriber = null; private BottomSheetBehavior<FrameLayout> bottomSheetBehavior; private BottomSheetBehavior.BottomSheetCallback bottomSheetCallback; private BroadcastReceiver broadcastReceiver; /*////////////////////////////////////////////////////////////////////////// // Views //////////////////////////////////////////////////////////////////////////*/ private FragmentVideoDetailBinding binding; private TabAdapter pageAdapter; private ContentObserver settingsContentObserver; @Nullable private PlayerService playerService; private Player player; private final PlayerHolder playerHolder = PlayerHolder.getInstance(); /*////////////////////////////////////////////////////////////////////////// // Service management //////////////////////////////////////////////////////////////////////////*/ @Override public void onServiceConnected(final Player connectedPlayer, final PlayerService connectedPlayerService, final boolean playAfterConnect) { player = connectedPlayer; playerService = connectedPlayerService; // It will do nothing if the player is not in fullscreen mode hideSystemUiIfNeeded(); final Optional<MainPlayerUi> playerUi = player.UIs().get(MainPlayerUi.class); if (!player.videoPlayerSelected() && !playAfterConnect) { return; } if (DeviceUtils.isLandscape(requireContext())) { // If the video is playing but orientation changed // let's make the video in fullscreen again checkLandscape(); } else if (playerUi.map(ui -> ui.isFullscreen() && !ui.isVerticalVideo()).orElse(false) // Tablet UI has orientation-independent fullscreen && !DeviceUtils.isTablet(activity)) { // Device is in portrait orientation after rotation but UI is in fullscreen. // Return back to non-fullscreen state playerUi.ifPresent(MainPlayerUi::toggleFullscreen); } if (playAfterConnect || (currentInfo != null && isAutoplayEnabled() && playerUi.isEmpty())) { autoPlayEnabled = true; // forcefully start playing openVideoPlayerAutoFullscreen(); } updateOverlayPlayQueueButtonVisibility(); } @Override public void onServiceDisconnected() { playerService = null; player = null; restoreDefaultBrightness(); } /*////////////////////////////////////////////////////////////////////////*/ public static VideoDetailFragment getInstance(final int serviceId, @Nullable final String videoUrl, @NonNull final String name, @Nullable final PlayQueue queue) { final VideoDetailFragment instance = new VideoDetailFragment(); instance.setInitialData(serviceId, videoUrl, name, queue); return instance; } public static VideoDetailFragment getInstanceInCollapsedState() { final VideoDetailFragment instance = new VideoDetailFragment(); instance.updateBottomSheetState(BottomSheetBehavior.STATE_COLLAPSED); return instance; } /*////////////////////////////////////////////////////////////////////////// // Fragment's Lifecycle //////////////////////////////////////////////////////////////////////////*/ @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); showComments = prefs.getBoolean(getString(R.string.show_comments_key), true); showRelatedItems = prefs.getBoolean(getString(R.string.show_next_video_key), true); showDescription = prefs.getBoolean(getString(R.string.show_description_key), true); selectedTabTag = prefs.getString( getString(R.string.stream_info_selected_tab_key), COMMENTS_TAB_TAG); prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener); setupBroadcastReceiver(); settingsContentObserver = new ContentObserver(new Handler()) { @Override public void onChange(final boolean selfChange) { if (activity != null && !globalScreenOrientationLocked(activity)) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } }; activity.getContentResolver().registerContentObserver( Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), false, settingsContentObserver); } @Override public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { binding = FragmentVideoDetailBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onPause() { super.onPause(); if (currentWorker != null) { currentWorker.dispose(); } restoreDefaultBrightness(); PreferenceManager.getDefaultSharedPreferences(requireContext()) .edit() .putString(getString(R.string.stream_info_selected_tab_key), pageAdapter.getItemTitle(binding.viewPager.getCurrentItem())) .apply(); } @Override public void onResume() { super.onResume(); if (DEBUG) { Log.d(TAG, "onResume() called"); } activity.sendBroadcast(new Intent(ACTION_VIDEO_FRAGMENT_RESUMED)); updateOverlayPlayQueueButtonVisibility(); setupBrightness(); if (tabSettingsChanged) { tabSettingsChanged = false; initTabs(); if (currentInfo != null) { updateTabs(currentInfo); } } // Check if it was loading when the fragment was stopped/paused if (wasLoading.getAndSet(false) && !wasCleared()) { startLoading(false); } } @Override public void onStop() { super.onStop(); if (!activity.isChangingConfigurations()) { activity.sendBroadcast(new Intent(ACTION_VIDEO_FRAGMENT_STOPPED)); } } @Override public void onDestroy() { super.onDestroy(); // Stop the service when user leaves the app with double back press // if video player is selected. Otherwise unbind if (activity.isFinishing() && isPlayerAvailable() && player.videoPlayerSelected()) { playerHolder.stopService(); } else { playerHolder.setListener(null); } PreferenceManager.getDefaultSharedPreferences(activity) .unregisterOnSharedPreferenceChangeListener(preferenceChangeListener); activity.unregisterReceiver(broadcastReceiver); activity.getContentResolver().unregisterContentObserver(settingsContentObserver); if (positionSubscriber != null) { positionSubscriber.dispose(); } if (currentWorker != null) { currentWorker.dispose(); } disposables.clear(); positionSubscriber = null; currentWorker = null; bottomSheetBehavior.removeBottomSheetCallback(bottomSheetCallback); if (activity.isFinishing()) { playQueue = null; currentInfo = null; stack = new LinkedList<>(); } } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case ReCaptchaActivity.RECAPTCHA_REQUEST: if (resultCode == Activity.RESULT_OK) { NavigationHelper.openVideoDetailFragment(requireContext(), getFM(), serviceId, url, title, null, false); } else { Log.e(TAG, "ReCaptcha failed"); } break; default: Log.e(TAG, "Request code from activity not supported [" + requestCode + "]"); break; } } /*////////////////////////////////////////////////////////////////////////// // OnClick //////////////////////////////////////////////////////////////////////////*/ private void setOnClickListeners() { binding.detailTitleRootLayout.setOnClickListener(v -> toggleTitleAndSecondaryControls()); binding.detailUploaderRootLayout.setOnClickListener(makeOnClickListener(info -> { if (isEmpty(info.getSubChannelUrl())) { if (!isEmpty(info.getUploaderUrl())) { openChannel(info.getUploaderUrl(), info.getUploaderName()); } if (DEBUG) { Log.i(TAG, "Can't open sub-channel because we got no channel URL"); } } else { openChannel(info.getSubChannelUrl(), info.getSubChannelName()); } })); binding.detailThumbnailRootLayout.setOnClickListener(v -> { autoPlayEnabled = true; // forcefully start playing // FIXME Workaround #7427 if (isPlayerAvailable()) { player.setRecovery(); } openVideoPlayerAutoFullscreen(); }); binding.detailControlsBackground.setOnClickListener(v -> openBackgroundPlayer(false)); binding.detailControlsPopup.setOnClickListener(v -> openPopupPlayer(false)); binding.detailControlsPlaylistAppend.setOnClickListener(makeOnClickListener(info -> { if (getFM() != null && currentInfo != null) { final Fragment fragment = getParentFragmentManager(). findFragmentById(R.id.fragment_holder); // commit previous pending changes to database if (fragment instanceof LocalPlaylistFragment) { ((LocalPlaylistFragment) fragment).saveImmediate(); } else if (fragment instanceof MainFragment) { ((MainFragment) fragment).commitPlaylistTabs(); } disposables.add(PlaylistDialog.createCorrespondingDialog(requireContext(), List.of(new StreamEntity(info)), dialog -> dialog.show(getParentFragmentManager(), TAG))); } })); binding.detailControlsDownload.setOnClickListener(v -> { if (PermissionHelper.checkStoragePermissions(activity, PermissionHelper.DOWNLOAD_DIALOG_REQUEST_CODE)) { openDownloadDialog(); } }); binding.detailControlsShare.setOnClickListener(makeOnClickListener(info -> ShareUtils.shareText(requireContext(), info.getName(), info.getUrl(), info.getThumbnails()))); binding.detailControlsOpenInBrowser.setOnClickListener(makeOnClickListener(info -> ShareUtils.openUrlInBrowser(requireContext(), info.getUrl()))); binding.detailControlsPlayWithKodi.setOnClickListener(makeOnClickListener(info -> KoreUtils.playWithKore(requireContext(), Uri.parse(info.getUrl())))); if (DEBUG) { binding.detailControlsCrashThePlayer.setOnClickListener(v -> VideoDetailPlayerCrasher.onCrashThePlayer(requireContext(), player)); } final View.OnClickListener overlayListener = v -> bottomSheetBehavior .setState(BottomSheetBehavior.STATE_EXPANDED); binding.overlayThumbnail.setOnClickListener(overlayListener); binding.overlayMetadataLayout.setOnClickListener(overlayListener); binding.overlayButtonsLayout.setOnClickListener(overlayListener); binding.overlayCloseButton.setOnClickListener(v -> bottomSheetBehavior .setState(BottomSheetBehavior.STATE_HIDDEN)); binding.overlayPlayQueueButton.setOnClickListener(v -> openPlayQueue(requireContext())); binding.overlayPlayPauseButton.setOnClickListener(v -> { if (playerIsNotStopped()) { player.playPause(); player.UIs().get(VideoPlayerUi.class).ifPresent(ui -> ui.hideControls(0, 0)); showSystemUi(); } else { autoPlayEnabled = true; // forcefully start playing openVideoPlayer(false); } setOverlayPlayPauseImage(isPlayerAvailable() && player.isPlaying()); }); } private View.OnClickListener makeOnClickListener(final Consumer<StreamInfo> consumer) { return v -> { if (!isLoading.get() && currentInfo != null) { consumer.accept(currentInfo); } }; } private void setOnLongClickListeners() { binding.detailTitleRootLayout.setOnLongClickListener(makeOnLongClickListener(info -> ShareUtils.copyToClipboard(requireContext(), binding.detailVideoTitleView.getText().toString()))); binding.detailUploaderRootLayout.setOnLongClickListener(makeOnLongClickListener(info -> { if (isEmpty(info.getSubChannelUrl())) { Log.w(TAG, "Can't open parent channel because we got no parent channel URL"); } else { openChannel(info.getUploaderUrl(), info.getUploaderName()); } })); binding.detailControlsBackground.setOnLongClickListener(makeOnLongClickListener(info -> openBackgroundPlayer(true) )); binding.detailControlsPopup.setOnLongClickListener(makeOnLongClickListener(info -> openPopupPlayer(true) )); binding.detailControlsDownload.setOnLongClickListener(makeOnLongClickListener(info -> NavigationHelper.openDownloads(activity))); final View.OnLongClickListener overlayListener = makeOnLongClickListener(info -> openChannel(info.getUploaderUrl(), info.getUploaderName())); binding.overlayThumbnail.setOnLongClickListener(overlayListener); binding.overlayMetadataLayout.setOnLongClickListener(overlayListener); } private View.OnLongClickListener makeOnLongClickListener(final Consumer<StreamInfo> consumer) { return v -> { if (isLoading.get() || currentInfo == null) { return false; } consumer.accept(currentInfo); return true; }; } private void openChannel(final String subChannelUrl, final String subChannelName) { try { NavigationHelper.openChannelFragment(getFM(), currentInfo.getServiceId(), subChannelUrl, subChannelName); } catch (final Exception e) { ErrorUtil.showUiErrorSnackbar(this, "Opening channel fragment", e); } } private void toggleTitleAndSecondaryControls() { if (binding.detailSecondaryControlPanel.getVisibility() == View.GONE) { binding.detailVideoTitleView.setMaxLines(10); animateRotation(binding.detailToggleSecondaryControlsView, VideoPlayerUi.DEFAULT_CONTROLS_DURATION, 180); binding.detailSecondaryControlPanel.setVisibility(View.VISIBLE); } else { binding.detailVideoTitleView.setMaxLines(1); animateRotation(binding.detailToggleSecondaryControlsView, VideoPlayerUi.DEFAULT_CONTROLS_DURATION, 0); binding.detailSecondaryControlPanel.setVisibility(View.GONE); } // view pager height has changed, update the tab layout updateTabLayoutVisibility(); } /*////////////////////////////////////////////////////////////////////////// // Init //////////////////////////////////////////////////////////////////////////*/ @Override // called from onViewCreated in {@link BaseFragment#onViewCreated} protected void initViews(final View rootView, final Bundle savedInstanceState) { super.initViews(rootView, savedInstanceState); pageAdapter = new TabAdapter(getChildFragmentManager()); binding.viewPager.setAdapter(pageAdapter); binding.tabLayout.setupWithViewPager(binding.viewPager); binding.detailThumbnailRootLayout.requestFocus(); binding.detailControlsPlayWithKodi.setVisibility( KoreUtils.shouldShowPlayWithKodi(requireContext(), serviceId) ? View.VISIBLE : View.GONE ); binding.detailControlsCrashThePlayer.setVisibility( DEBUG && PreferenceManager.getDefaultSharedPreferences(getContext()) .getBoolean(getString(R.string.show_crash_the_player_key), false) ? View.VISIBLE : View.GONE ); accommodateForTvAndDesktopMode(); } @Override @SuppressLint("ClickableViewAccessibility") protected void initListeners() { super.initListeners(); setOnClickListeners(); setOnLongClickListeners(); final View.OnTouchListener controlsTouchListener = (view, motionEvent) -> { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && PlayButtonHelper.shouldShowHoldToAppendTip(activity)) { animate(binding.touchAppendDetail, true, 250, AnimationType.ALPHA, 0, () -> animate(binding.touchAppendDetail, false, 1500, AnimationType.ALPHA, 1000)); } return false; }; binding.detailControlsBackground.setOnTouchListener(controlsTouchListener); binding.detailControlsPopup.setOnTouchListener(controlsTouchListener); binding.appBarLayout.addOnOffsetChangedListener((layout, verticalOffset) -> { // prevent useless updates to tab layout visibility if nothing changed if (verticalOffset != lastAppBarVerticalOffset) { lastAppBarVerticalOffset = verticalOffset; // the view was scrolled updateTabLayoutVisibility(); } }); setupBottomPlayer(); if (!playerHolder.isBound()) { setHeightThumbnail(); } else { playerHolder.startService(false, this); } } /*////////////////////////////////////////////////////////////////////////// // OwnStack //////////////////////////////////////////////////////////////////////////*/ /** * Stack that contains the "navigation history".<br> * The peek is the current video. */ private static LinkedList<StackItem> stack = new LinkedList<>(); @Override public boolean onKeyDown(final int keyCode) { return isPlayerAvailable() && player.UIs().get(VideoPlayerUi.class) .map(playerUi -> playerUi.onKeyDown(keyCode)).orElse(false); } @Override public boolean onBackPressed() { if (DEBUG) { Log.d(TAG, "onBackPressed() called"); } // If we are in fullscreen mode just exit from it via first back press if (isFullscreen()) { if (!DeviceUtils.isTablet(activity)) { player.pause(); } restoreDefaultOrientation(); setAutoPlay(false); return true; } // If we have something in history of played items we replay it here if (isPlayerAvailable() && player.getPlayQueue() != null && player.videoPlayerSelected() && player.getPlayQueue().previous()) { return true; // no code here, as previous() was used in the if } // That means that we are on the start of the stack, if (stack.size() <= 1) { restoreDefaultOrientation(); return false; // let MainActivity handle the onBack (e.g. to minimize the mini player) } // Remove top stack.pop(); // Get stack item from the new top setupFromHistoryItem(Objects.requireNonNull(stack.peek())); return true; } private void setupFromHistoryItem(final StackItem item) { setAutoPlay(false); hideMainPlayerOnLoadingNewStream(); setInitialData(item.getServiceId(), item.getUrl(), item.getTitle() == null ? "" : item.getTitle(), item.getPlayQueue()); startLoading(false); // Maybe an item was deleted in background activity if (item.getPlayQueue().getItem() == null) { return; } final PlayQueueItem playQueueItem = item.getPlayQueue().getItem(); // Update title, url, uploader from the last item in the stack (it's current now) final boolean isPlayerStopped = !isPlayerAvailable() || player.isStopped(); if (playQueueItem != null && isPlayerStopped) { updateOverlayData(playQueueItem.getTitle(), playQueueItem.getUploader(), playQueueItem.getThumbnails()); } } /*////////////////////////////////////////////////////////////////////////// // Info loading and handling //////////////////////////////////////////////////////////////////////////*/ @Override protected void doInitialLoadLogic() { if (wasCleared()) { return; } if (currentInfo == null) { prepareAndLoadInfo(); } else { prepareAndHandleInfoIfNeededAfterDelay(currentInfo, false, 50); } } public void selectAndLoadVideo(final int newServiceId, @Nullable final String newUrl, @NonNull final String newTitle, @Nullable final PlayQueue newQueue) { if (isPlayerAvailable() && newQueue != null && playQueue != null && playQueue.getItem() != null && !playQueue.getItem().getUrl().equals(newUrl)) { // Preloading can be disabled since playback is surely being replaced. player.disablePreloadingOfCurrentTrack(); } setInitialData(newServiceId, newUrl, newTitle, newQueue); startLoading(false, true); } private void prepareAndHandleInfoIfNeededAfterDelay(final StreamInfo info, final boolean scrollToTop, final long delay) { new Handler(Looper.getMainLooper()).postDelayed(() -> { if (activity == null) { return; } // Data can already be drawn, don't spend time twice if (info.getName().equals(binding.detailVideoTitleView.getText().toString())) { return; } prepareAndHandleInfo(info, scrollToTop); }, delay); } private void prepareAndHandleInfo(final StreamInfo info, final boolean scrollToTop) { if (DEBUG) { Log.d(TAG, "prepareAndHandleInfo() called with: " + "info = [" + info + "], scrollToTop = [" + scrollToTop + "]"); } showLoading(); initTabs(); if (scrollToTop) { scrollToTop(); } handleResult(info); showContent(); } protected void prepareAndLoadInfo() { scrollToTop(); startLoading(false); } @Override public void startLoading(final boolean forceLoad) { super.startLoading(forceLoad); initTabs(); currentInfo = null; if (currentWorker != null) { currentWorker.dispose(); } runWorker(forceLoad, stack.isEmpty()); } private void startLoading(final boolean forceLoad, final boolean addToBackStack) { super.startLoading(forceLoad); initTabs(); currentInfo = null; if (currentWorker != null) { currentWorker.dispose(); } runWorker(forceLoad, addToBackStack); } private void runWorker(final boolean forceLoad, final boolean addToBackStack) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); currentWorker = ExtractorHelper.getStreamInfo(serviceId, url, forceLoad) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { isLoading.set(false); hideMainPlayerOnLoadingNewStream(); if (result.getAgeLimit() != NO_AGE_LIMIT && !prefs.getBoolean( getString(R.string.show_age_restricted_content), false)) { hideAgeRestrictedContent(); } else { handleResult(result); showContent(); if (addToBackStack) { if (playQueue == null) { playQueue = new SinglePlayQueue(result); } if (stack.isEmpty() || !stack.peek().getPlayQueue() .equalStreams(playQueue)) { stack.push(new StackItem(serviceId, url, title, playQueue)); } } if (isAutoplayEnabled()) { openVideoPlayerAutoFullscreen(); } } }, throwable -> showError(new ErrorInfo(throwable, UserAction.REQUESTED_STREAM, url == null ? "no url" : url, serviceId))); } /*////////////////////////////////////////////////////////////////////////// // Tabs //////////////////////////////////////////////////////////////////////////*/ private void initTabs() { if (pageAdapter.getCount() != 0) { selectedTabTag = pageAdapter.getItemTitle(binding.viewPager.getCurrentItem()); } pageAdapter.clearAllItems(); tabIcons.clear(); tabContentDescriptions.clear(); if (shouldShowComments()) { pageAdapter.addFragment( CommentsFragment.getInstance(serviceId, url, title), COMMENTS_TAB_TAG); tabIcons.add(R.drawable.ic_comment); tabContentDescriptions.add(R.string.comments_tab_description); } if (showRelatedItems && binding.relatedItemsLayout == null) { // temp empty fragment. will be updated in handleResult pageAdapter.addFragment(EmptyFragment.newInstance(false), RELATED_TAB_TAG); tabIcons.add(R.drawable.ic_art_track); tabContentDescriptions.add(R.string.related_items_tab_description); } if (showDescription) { // temp empty fragment. will be updated in handleResult pageAdapter.addFragment(EmptyFragment.newInstance(false), DESCRIPTION_TAB_TAG); tabIcons.add(R.drawable.ic_description); tabContentDescriptions.add(R.string.description_tab_description); } if (pageAdapter.getCount() == 0) { pageAdapter.addFragment(EmptyFragment.newInstance(true), EMPTY_TAB_TAG); } pageAdapter.notifyDataSetUpdate(); if (pageAdapter.getCount() >= 2) { final int position = pageAdapter.getItemPositionByTitle(selectedTabTag); if (position != -1) { binding.viewPager.setCurrentItem(position); } updateTabIconsAndContentDescriptions(); } // the page adapter now contains tabs: show the tab layout updateTabLayoutVisibility(); } /** * To be called whenever {@link #pageAdapter} is modified, since that triggers a refresh in * {@link FragmentVideoDetailBinding#tabLayout} resetting all tab's icons and content * descriptions. This reads icons from {@link #tabIcons} and content descriptions from * {@link #tabContentDescriptions}, which are all set in {@link #initTabs()}. */ private void updateTabIconsAndContentDescriptions() { for (int i = 0; i < tabIcons.size(); ++i) { final TabLayout.Tab tab = binding.tabLayout.getTabAt(i); if (tab != null) { tab.setIcon(tabIcons.get(i)); tab.setContentDescription(tabContentDescriptions.get(i)); } } } private void updateTabs(@NonNull final StreamInfo info) { if (showRelatedItems) { if (binding.relatedItemsLayout == null) { // phone pageAdapter.updateItem(RELATED_TAB_TAG, RelatedItemsFragment.getInstance(info)); } else { // tablet + TV getChildFragmentManager().beginTransaction() .replace(R.id.relatedItemsLayout, RelatedItemsFragment.getInstance(info)) .commitAllowingStateLoss(); binding.relatedItemsLayout.setVisibility(isFullscreen() ? View.GONE : View.VISIBLE); } } if (showDescription) { pageAdapter.updateItem(DESCRIPTION_TAB_TAG, new DescriptionFragment(info)); } binding.viewPager.setVisibility(View.VISIBLE); // make sure the tab layout is visible updateTabLayoutVisibility(); pageAdapter.notifyDataSetUpdate(); updateTabIconsAndContentDescriptions(); } private boolean shouldShowComments() { try { return showComments && NewPipe.getService(serviceId) .getServiceInfo() .getMediaCapabilities() .contains(COMMENTS); } catch (final ExtractionException e) { return false; } } public void updateTabLayoutVisibility() { if (binding == null) { //If binding is null we do not need to and should not do anything with its object(s) return; } if (pageAdapter.getCount() < 2 || binding.viewPager.getVisibility() != View.VISIBLE) { // hide tab layout if there is only one tab or if the view pager is also hidden binding.tabLayout.setVisibility(View.GONE); } else { // call `post()` to be sure `viewPager.getHitRect()` // is up to date and not being currently recomputed binding.tabLayout.post(() -> { final var activity = getActivity(); if (activity != null) { final Rect pagerHitRect = new Rect(); binding.viewPager.getHitRect(pagerHitRect); final int height = DeviceUtils.getWindowHeight(activity.getWindowManager()); final int viewPagerVisibleHeight = height - pagerHitRect.top; // see TabLayout.DEFAULT_HEIGHT, which is equal to 48dp final float tabLayoutHeight = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()); if (viewPagerVisibleHeight > tabLayoutHeight * 2) { // no translation at all when viewPagerVisibleHeight > tabLayout.height * 3 binding.tabLayout.setTranslationY( Math.max(0, tabLayoutHeight * 3 - viewPagerVisibleHeight)); binding.tabLayout.setVisibility(View.VISIBLE); } else { // view pager is not visible enough binding.tabLayout.setVisibility(View.GONE); } } }); } } public void scrollToTop() { binding.appBarLayout.setExpanded(true, true); // notify tab layout of scrolling updateTabLayoutVisibility(); } public void scrollToComment(final CommentsInfoItem comment) { final int commentsTabPos = pageAdapter.getItemPositionByTitle(COMMENTS_TAB_TAG); final Fragment fragment = pageAdapter.getItem(commentsTabPos); if (!(fragment instanceof CommentsFragment)) { return; } // unexpand the app bar only if scrolling to the comment succeeded if (((CommentsFragment) fragment).scrollToComment(comment)) { binding.appBarLayout.setExpanded(false, false); binding.viewPager.setCurrentItem(commentsTabPos, false); } } /*////////////////////////////////////////////////////////////////////////// // Play Utils //////////////////////////////////////////////////////////////////////////*/ private void toggleFullscreenIfInFullscreenMode() { // If a user watched video inside fullscreen mode and than chose another player // return to non-fullscreen mode if (isPlayerAvailable()) { player.UIs().get(MainPlayerUi.class).ifPresent(playerUi -> { if (playerUi.isFullscreen()) { playerUi.toggleFullscreen(); } }); } } private void openBackgroundPlayer(final boolean append) { final boolean useExternalAudioPlayer = PreferenceManager .getDefaultSharedPreferences(activity) .getBoolean(activity.getString(R.string.use_external_audio_player_key), false); toggleFullscreenIfInFullscreenMode(); if (isPlayerAvailable()) { // FIXME Workaround #7427 player.setRecovery(); } if (useExternalAudioPlayer) { showExternalAudioPlaybackDialog(); } else { openNormalBackgroundPlayer(append); } } private void openPopupPlayer(final boolean append) { if (!PermissionHelper.isPopupEnabledElseAsk(activity)) { return; } // See UI changes while remote playQueue changes if (!isPlayerAvailable()) { playerHolder.startService(false, this); } else { // FIXME Workaround #7427 player.setRecovery(); } toggleFullscreenIfInFullscreenMode(); final PlayQueue queue = setupPlayQueueForIntent(append); if (append) { //resumePlayback: false NavigationHelper.enqueueOnPlayer(activity, queue, PlayerType.POPUP); } else { replaceQueueIfUserConfirms(() -> NavigationHelper .playOnPopupPlayer(activity, queue, true)); } } /** * Opens the video player, in fullscreen if needed. In order to open fullscreen, the activity * is toggled to landscape orientation (which will then cause fullscreen mode). * * @param directlyFullscreenIfApplicable whether to open fullscreen if we are not already * in landscape and screen orientation is locked */ public void openVideoPlayer(final boolean directlyFullscreenIfApplicable) { if (directlyFullscreenIfApplicable && !DeviceUtils.isLandscape(requireContext()) && PlayerHelper.globalScreenOrientationLocked(requireContext())) { // Make sure the bottom sheet turns out expanded. When this code kicks in the bottom // sheet could not have fully expanded yet, and thus be in the STATE_SETTLING state. // When the activity is rotated, and its state is saved and then restored, the bottom // sheet would forget what it was doing, since even if STATE_SETTLING is restored, it // doesn't tell which state it was settling to, and thus the bottom sheet settles to // STATE_COLLAPSED. This can be solved by manually setting the state that will be // restored (i.e. bottomSheetState) to STATE_EXPANDED. updateBottomSheetState(BottomSheetBehavior.STATE_EXPANDED); // toggle landscape in order to open directly in fullscreen onScreenRotationButtonClicked(); } if (PreferenceManager.getDefaultSharedPreferences(activity) .getBoolean(this.getString(R.string.use_external_video_player_key), false)) { showExternalVideoPlaybackDialog(); } else { replaceQueueIfUserConfirms(this::openMainPlayer); } } /** * If the option to start directly fullscreen is enabled, calls * {@link #openVideoPlayer(boolean)} with {@code directlyFullscreenIfApplicable = true}, so that * if the user is not already in landscape and he has screen orientation locked the activity * rotates and fullscreen starts. Otherwise, if the option to start directly fullscreen is * disabled, calls {@link #openVideoPlayer(boolean)} with {@code directlyFullscreenIfApplicable * = false}, hence preventing it from going directly fullscreen. */ public void openVideoPlayerAutoFullscreen() { openVideoPlayer(PlayerHelper.isStartMainPlayerFullscreenEnabled(requireContext())); } private void openNormalBackgroundPlayer(final boolean append) { // See UI changes while remote playQueue changes if (!isPlayerAvailable()) { playerHolder.startService(false, this); } final PlayQueue queue = setupPlayQueueForIntent(append); if (append) { NavigationHelper.enqueueOnPlayer(activity, queue, PlayerType.AUDIO); } else { replaceQueueIfUserConfirms(() -> NavigationHelper .playOnBackgroundPlayer(activity, queue, true)); } } private void openMainPlayer() { if (!isPlayerServiceAvailable()) { playerHolder.startService(autoPlayEnabled, this); return; } if (currentInfo == null) { return; } final PlayQueue queue = setupPlayQueueForIntent(false); tryAddVideoPlayerView(); final Intent playerIntent = NavigationHelper.getPlayerIntent(requireContext(), PlayerService.class, queue, true, autoPlayEnabled); ContextCompat.startForegroundService(activity, playerIntent); } /** * When the video detail fragment is already showing details for a video and the user opens a * new one, the video detail fragment changes all of its old data to the new stream, so if there * is a video player currently open it should be hidden. This method does exactly that. If * autoplay is enabled, the underlying player is not stopped completely, since it is going to * be reused in a few milliseconds and the flickering would be annoying. */ private void hideMainPlayerOnLoadingNewStream() { final var root = getRoot(); if (!isPlayerServiceAvailable() || root.isEmpty() || !player.videoPlayerSelected()) { return; } removeVideoPlayerView(); if (isAutoplayEnabled()) { playerService.stopForImmediateReusing(); root.ifPresent(view -> view.setVisibility(View.GONE)); } else { playerHolder.stopService(); } } private PlayQueue setupPlayQueueForIntent(final boolean append) { if (append) { return new SinglePlayQueue(currentInfo); } PlayQueue queue = playQueue; // Size can be 0 because queue removes bad stream automatically when error occurs if (queue == null || queue.isEmpty()) { queue = new SinglePlayQueue(currentInfo); } return queue; } /*////////////////////////////////////////////////////////////////////////// // Utils //////////////////////////////////////////////////////////////////////////*/ public void setAutoPlay(final boolean autoPlay) { this.autoPlayEnabled = autoPlay; } private void startOnExternalPlayer(@NonNull final Context context, @NonNull final StreamInfo info, @NonNull final Stream selectedStream) { NavigationHelper.playOnExternalPlayer(context, currentInfo.getName(), currentInfo.getSubChannelName(), selectedStream); final HistoryRecordManager recordManager = new HistoryRecordManager(requireContext()); disposables.add(recordManager.onViewed(info).onErrorComplete() .subscribe( ignored -> { /* successful */ }, error -> Log.e(TAG, "Register view failure: ", error) )); } private boolean isExternalPlayerEnabled() { return PreferenceManager.getDefaultSharedPreferences(requireContext()) .getBoolean(getString(R.string.use_external_video_player_key), false); } // This method overrides default behaviour when setAutoPlay() is called. // Don't auto play if the user selected an external player or disabled it in settings private boolean isAutoplayEnabled() { return autoPlayEnabled && !isExternalPlayerEnabled() && (!isPlayerAvailable() || player.videoPlayerSelected()) && bottomSheetState != BottomSheetBehavior.STATE_HIDDEN && PlayerHelper.isAutoplayAllowedByUser(requireContext()); } private void tryAddVideoPlayerView() { if (isPlayerAvailable() && getView() != null) { // Setup the surface view height, so that it fits the video correctly; this is done also // here, and not only in the Handler, to avoid a choppy fullscreen rotation animation. setHeightThumbnail(); } // do all the null checks in the posted lambda, too, since the player, the binding and the // view could be set or unset before the lambda gets executed on the next main thread cycle new Handler(Looper.getMainLooper()).post(() -> { if (!isPlayerAvailable() || getView() == null) { return; } // setup the surface view height, so that it fits the video correctly setHeightThumbnail(); player.UIs().get(MainPlayerUi.class).ifPresent(playerUi -> { // sometimes binding would be null here, even though getView() != null above u.u if (binding != null) { // prevent from re-adding a view multiple times playerUi.removeViewFromParent(); binding.playerPlaceholder.addView(playerUi.getBinding().getRoot()); playerUi.setupVideoSurfaceIfNeeded(); } }); }); } private void removeVideoPlayerView() { makeDefaultHeightForVideoPlaceholder(); if (player != null) { player.UIs().get(VideoPlayerUi.class).ifPresent(VideoPlayerUi::removeViewFromParent); } } private void makeDefaultHeightForVideoPlaceholder() { if (getView() == null) { return; } binding.playerPlaceholder.getLayoutParams().height = FrameLayout.LayoutParams.MATCH_PARENT; binding.playerPlaceholder.requestLayout(); } private final ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { final DisplayMetrics metrics = getResources().getDisplayMetrics(); if (getView() != null) { final int height = (DeviceUtils.isInMultiWindow(activity) ? requireView() : activity.getWindow().getDecorView()).getHeight(); setHeightThumbnail(height, metrics); getView().getViewTreeObserver().removeOnPreDrawListener(preDrawListener); } return false; } }; /** * Method which controls the size of thumbnail and the size of main player inside * a layout with thumbnail. It decides what height the player should have in both * screen orientations. It knows about multiWindow feature * and about videos with aspectRatio ZOOM (the height for them will be a bit higher, * {@link #MAX_PLAYER_HEIGHT}) */ private void setHeightThumbnail() { final DisplayMetrics metrics = getResources().getDisplayMetrics(); final boolean isPortrait = metrics.heightPixels > metrics.widthPixels; requireView().getViewTreeObserver().removeOnPreDrawListener(preDrawListener); if (isFullscreen()) { final int height = (DeviceUtils.isInMultiWindow(activity) ? requireView() : activity.getWindow().getDecorView()).getHeight(); // Height is zero when the view is not yet displayed like after orientation change if (height != 0) { setHeightThumbnail(height, metrics); } else { requireView().getViewTreeObserver().addOnPreDrawListener(preDrawListener); } } else { final int height = (int) (isPortrait ? metrics.widthPixels / (16.0f / 9.0f) : metrics.heightPixels / 2.0f); setHeightThumbnail(height, metrics); } } private void setHeightThumbnail(final int newHeight, final DisplayMetrics metrics) { binding.detailThumbnailImageView.setLayoutParams( new FrameLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, newHeight)); binding.detailThumbnailImageView.setMinimumHeight(newHeight); if (isPlayerAvailable()) { final int maxHeight = (int) (metrics.heightPixels * MAX_PLAYER_HEIGHT); player.UIs().get(VideoPlayerUi.class).ifPresent(ui -> ui.getBinding().surfaceView.setHeights(newHeight, ui.isFullscreen() ? newHeight : maxHeight)); } } private void showContent() { binding.detailContentRootHiding.setVisibility(View.VISIBLE); } protected void setInitialData(final int newServiceId, @Nullable final String newUrl, @NonNull final String newTitle, @Nullable final PlayQueue newPlayQueue) { this.serviceId = newServiceId; this.url = newUrl; this.title = newTitle; this.playQueue = newPlayQueue; } private void setErrorImage(final int imageResource) { if (binding == null || activity == null) { return; } binding.detailThumbnailImageView.setImageDrawable( AppCompatResources.getDrawable(requireContext(), imageResource)); animate(binding.detailThumbnailImageView, false, 0, AnimationType.ALPHA, 0, () -> animate(binding.detailThumbnailImageView, true, 500)); } @Override public void handleError() { super.handleError(); setErrorImage(R.drawable.not_available_monkey); if (binding.relatedItemsLayout != null) { // hide related streams for tablets binding.relatedItemsLayout.setVisibility(View.INVISIBLE); } // hide comments / related streams / description tabs binding.viewPager.setVisibility(View.GONE); binding.tabLayout.setVisibility(View.GONE); } private void hideAgeRestrictedContent() { showTextError(getString(R.string.restricted_video, getString(R.string.show_age_restricted_content_title))); } private void setupBroadcastReceiver() { broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { switch (intent.getAction()) { case ACTION_SHOW_MAIN_PLAYER: bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); break; case ACTION_HIDE_MAIN_PLAYER: bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); break; case ACTION_PLAYER_STARTED: // If the state is not hidden we don't need to show the mini player if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } // Rebound to the service if it was closed via notification or mini player if (!playerHolder.isBound()) { playerHolder.startService( false, VideoDetailFragment.this); } break; } } }; final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_SHOW_MAIN_PLAYER); intentFilter.addAction(ACTION_HIDE_MAIN_PLAYER); intentFilter.addAction(ACTION_PLAYER_STARTED); activity.registerReceiver(broadcastReceiver, intentFilter); } /*////////////////////////////////////////////////////////////////////////// // Orientation listener //////////////////////////////////////////////////////////////////////////*/ private void restoreDefaultOrientation() { if (isPlayerAvailable() && player.videoPlayerSelected()) { toggleFullscreenIfInFullscreenMode(); } // This will show systemUI and pause the player. // User can tap on Play button and video will be in fullscreen mode again // Note for tablet: trying to avoid orientation changes since it's not easy // to physically rotate the tablet every time if (activity != null && !DeviceUtils.isTablet(activity)) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } /*////////////////////////////////////////////////////////////////////////// // Contract //////////////////////////////////////////////////////////////////////////*/ @Override public void showLoading() { super.showLoading(); //if data is already cached, transition from VISIBLE -> INVISIBLE -> VISIBLE is not required if (!ExtractorHelper.isCached(serviceId, url, InfoCache.Type.STREAM)) { binding.detailContentRootHiding.setVisibility(View.INVISIBLE); } animate(binding.detailThumbnailPlayButton, false, 50); animate(binding.detailDurationView, false, 100); binding.detailPositionView.setVisibility(View.GONE); binding.positionView.setVisibility(View.GONE); binding.detailVideoTitleView.setText(title); binding.detailVideoTitleView.setMaxLines(1); animate(binding.detailVideoTitleView, true, 0); binding.detailToggleSecondaryControlsView.setVisibility(View.GONE); binding.detailTitleRootLayout.setClickable(false); binding.detailSecondaryControlPanel.setVisibility(View.GONE); if (binding.relatedItemsLayout != null) { if (showRelatedItems) { binding.relatedItemsLayout.setVisibility( isFullscreen() ? View.GONE : View.INVISIBLE); } else { binding.relatedItemsLayout.setVisibility(View.GONE); } } PicassoHelper.cancelTag(PICASSO_VIDEO_DETAILS_TAG); binding.detailThumbnailImageView.setImageBitmap(null); binding.detailSubChannelThumbnailView.setImageBitmap(null); } @Override public void handleResult(@NonNull final StreamInfo info) { super.handleResult(info); currentInfo = info; setInitialData(info.getServiceId(), info.getOriginalUrl(), info.getName(), playQueue); updateTabs(info); animate(binding.detailThumbnailPlayButton, true, 200); binding.detailVideoTitleView.setText(title); binding.detailSubChannelThumbnailView.setVisibility(View.GONE); if (!isEmpty(info.getSubChannelName())) { displayBothUploaderAndSubChannel(info); } else { displayUploaderAsSubChannel(info); } if (info.getViewCount() >= 0) { if (info.getStreamType().equals(StreamType.AUDIO_LIVE_STREAM)) { binding.detailViewCountView.setText(Localization.listeningCount(activity, info.getViewCount())); } else if (info.getStreamType().equals(StreamType.LIVE_STREAM)) { binding.detailViewCountView.setText(Localization .localizeWatchingCount(activity, info.getViewCount())); } else { binding.detailViewCountView.setText(Localization .localizeViewCount(activity, info.getViewCount())); } binding.detailViewCountView.setVisibility(View.VISIBLE); } else { binding.detailViewCountView.setVisibility(View.GONE); } if (info.getDislikeCount() == -1 && info.getLikeCount() == -1) { binding.detailThumbsDownImgView.setVisibility(View.VISIBLE); binding.detailThumbsUpImgView.setVisibility(View.VISIBLE); binding.detailThumbsUpCountView.setVisibility(View.GONE); binding.detailThumbsDownCountView.setVisibility(View.GONE); binding.detailThumbsDisabledView.setVisibility(View.VISIBLE); } else { if (info.getDislikeCount() >= 0) { binding.detailThumbsDownCountView.setText(Localization .shortCount(activity, info.getDislikeCount())); binding.detailThumbsDownCountView.setVisibility(View.VISIBLE); binding.detailThumbsDownImgView.setVisibility(View.VISIBLE); } else { binding.detailThumbsDownCountView.setVisibility(View.GONE); binding.detailThumbsDownImgView.setVisibility(View.GONE); } if (info.getLikeCount() >= 0) { binding.detailThumbsUpCountView.setText(Localization.shortCount(activity, info.getLikeCount())); binding.detailThumbsUpCountView.setVisibility(View.VISIBLE); binding.detailThumbsUpImgView.setVisibility(View.VISIBLE); } else { binding.detailThumbsUpCountView.setVisibility(View.GONE); binding.detailThumbsUpImgView.setVisibility(View.GONE); } binding.detailThumbsDisabledView.setVisibility(View.GONE); } if (info.getDuration() > 0) { binding.detailDurationView.setText(Localization.getDurationString(info.getDuration())); binding.detailDurationView.setBackgroundColor( ContextCompat.getColor(activity, R.color.duration_background_color)); animate(binding.detailDurationView, true, 100); } else if (info.getStreamType() == StreamType.LIVE_STREAM) { binding.detailDurationView.setText(R.string.duration_live); binding.detailDurationView.setBackgroundColor( ContextCompat.getColor(activity, R.color.live_duration_background_color)); animate(binding.detailDurationView, true, 100); } else { binding.detailDurationView.setVisibility(View.GONE); } binding.detailTitleRootLayout.setClickable(true); binding.detailToggleSecondaryControlsView.setRotation(0); binding.detailToggleSecondaryControlsView.setVisibility(View.VISIBLE); binding.detailSecondaryControlPanel.setVisibility(View.GONE); checkUpdateProgressInfo(info); PicassoHelper.loadDetailsThumbnail(info.getThumbnails()).tag(PICASSO_VIDEO_DETAILS_TAG) .into(binding.detailThumbnailImageView); showMetaInfoInTextView(info.getMetaInfo(), binding.detailMetaInfoTextView, binding.detailMetaInfoSeparator, disposables); if (!isPlayerAvailable() || player.isStopped()) { updateOverlayData(info.getName(), info.getUploaderName(), info.getThumbnails()); } if (!info.getErrors().isEmpty()) { // Bandcamp fan pages are not yet supported and thus a ContentNotAvailableException is // thrown. This is not an error and thus should not be shown to the user. for (final Throwable throwable : info.getErrors()) { if (throwable instanceof ContentNotSupportedException && "Fan pages are not supported".equals(throwable.getMessage())) { info.getErrors().remove(throwable); } } if (!info.getErrors().isEmpty()) { showSnackBarError(new ErrorInfo(info.getErrors(), UserAction.REQUESTED_STREAM, info.getUrl(), info)); } } binding.detailControlsDownload.setVisibility( StreamTypeUtil.isLiveStream(info.getStreamType()) ? View.GONE : View.VISIBLE); binding.detailControlsBackground.setVisibility( info.getAudioStreams().isEmpty() && info.getVideoStreams().isEmpty() ? View.GONE : View.VISIBLE); final boolean noVideoStreams = info.getVideoStreams().isEmpty() && info.getVideoOnlyStreams().isEmpty(); binding.detailControlsPopup.setVisibility(noVideoStreams ? View.GONE : View.VISIBLE); binding.detailThumbnailPlayButton.setImageResource( noVideoStreams ? R.drawable.ic_headset_shadow : R.drawable.ic_play_arrow_shadow); } private void displayUploaderAsSubChannel(final StreamInfo info) { binding.detailSubChannelTextView.setText(info.getUploaderName()); binding.detailSubChannelTextView.setVisibility(View.VISIBLE); binding.detailSubChannelTextView.setSelected(true); if (info.getUploaderSubscriberCount() > -1) { binding.detailUploaderTextView.setText( Localization.shortSubscriberCount(activity, info.getUploaderSubscriberCount())); binding.detailUploaderTextView.setVisibility(View.VISIBLE); } else { binding.detailUploaderTextView.setVisibility(View.GONE); } PicassoHelper.loadAvatar(info.getUploaderAvatars()).tag(PICASSO_VIDEO_DETAILS_TAG) .into(binding.detailSubChannelThumbnailView); binding.detailSubChannelThumbnailView.setVisibility(View.VISIBLE); binding.detailUploaderThumbnailView.setVisibility(View.GONE); } private void displayBothUploaderAndSubChannel(final StreamInfo info) { binding.detailSubChannelTextView.setText(info.getSubChannelName()); binding.detailSubChannelTextView.setVisibility(View.VISIBLE); binding.detailSubChannelTextView.setSelected(true); final StringBuilder subText = new StringBuilder(); if (!isEmpty(info.getUploaderName())) { subText.append( String.format(getString(R.string.video_detail_by), info.getUploaderName())); } if (info.getUploaderSubscriberCount() > -1) { if (subText.length() > 0) { subText.append(Localization.DOT_SEPARATOR); } subText.append( Localization.shortSubscriberCount(activity, info.getUploaderSubscriberCount())); } if (subText.length() > 0) { binding.detailUploaderTextView.setText(subText); binding.detailUploaderTextView.setVisibility(View.VISIBLE); binding.detailUploaderTextView.setSelected(true); } else { binding.detailUploaderTextView.setVisibility(View.GONE); } PicassoHelper.loadAvatar(info.getSubChannelAvatars()).tag(PICASSO_VIDEO_DETAILS_TAG) .into(binding.detailSubChannelThumbnailView); binding.detailSubChannelThumbnailView.setVisibility(View.VISIBLE); PicassoHelper.loadAvatar(info.getUploaderAvatars()).tag(PICASSO_VIDEO_DETAILS_TAG) .into(binding.detailUploaderThumbnailView); binding.detailUploaderThumbnailView.setVisibility(View.VISIBLE); } public void openDownloadDialog() { if (currentInfo == null) { return; } try { final DownloadDialog downloadDialog = new DownloadDialog(activity, currentInfo); downloadDialog.show(activity.getSupportFragmentManager(), "downloadDialog"); } catch (final Exception e) { ErrorUtil.showSnackbar(activity, new ErrorInfo(e, UserAction.DOWNLOAD_OPEN_DIALOG, "Showing download dialog", currentInfo)); } } /*////////////////////////////////////////////////////////////////////////// // Stream Results //////////////////////////////////////////////////////////////////////////*/ private void checkUpdateProgressInfo(@NonNull final StreamInfo info) { if (positionSubscriber != null) { positionSubscriber.dispose(); } if (!getResumePlaybackEnabled(activity)) { binding.positionView.setVisibility(View.GONE); binding.detailPositionView.setVisibility(View.GONE); return; } final HistoryRecordManager recordManager = new HistoryRecordManager(requireContext()); positionSubscriber = recordManager.loadStreamState(info) .subscribeOn(Schedulers.io()) .onErrorComplete() .observeOn(AndroidSchedulers.mainThread()) .subscribe(state -> { updatePlaybackProgress( state.getProgressMillis(), info.getDuration() * 1000); }, e -> { // impossible since the onErrorComplete() }, () -> { binding.positionView.setVisibility(View.GONE); binding.detailPositionView.setVisibility(View.GONE); }); } private void updatePlaybackProgress(final long progress, final long duration) { if (!getResumePlaybackEnabled(activity)) { return; } final int progressSeconds = (int) TimeUnit.MILLISECONDS.toSeconds(progress); final int durationSeconds = (int) TimeUnit.MILLISECONDS.toSeconds(duration); // If the old and the new progress values have a big difference then use animation. // Otherwise don't because it affects CPU final int progressDifference = Math.abs(binding.positionView.getProgress() - progressSeconds); binding.positionView.setMax(durationSeconds); if (progressDifference > 2) { binding.positionView.setProgressAnimated(progressSeconds); } else { binding.positionView.setProgress(progressSeconds); } final String position = Localization.getDurationString(progressSeconds); if (position != binding.detailPositionView.getText()) { binding.detailPositionView.setText(position); } if (binding.positionView.getVisibility() != View.VISIBLE) { animate(binding.positionView, true, 100); animate(binding.detailPositionView, true, 100); } } /*////////////////////////////////////////////////////////////////////////// // Player event listener //////////////////////////////////////////////////////////////////////////*/ @Override public void onViewCreated() { tryAddVideoPlayerView(); } @Override public void onQueueUpdate(final PlayQueue queue) { playQueue = queue; if (DEBUG) { Log.d(TAG, "onQueueUpdate() called with: serviceId = [" + serviceId + "], videoUrl = [" + url + "], name = [" + title + "], playQueue = [" + playQueue + "]"); } // Register broadcast receiver to listen to playQueue changes // and hide the overlayPlayQueueButton when the playQueue is empty / destroyed. if (playQueue != null && playQueue.getBroadcastReceiver() != null) { playQueue.getBroadcastReceiver().subscribe( event -> updateOverlayPlayQueueButtonVisibility() ); } // This should be the only place where we push data to stack. // It will allow to have live instance of PlayQueue with actual information about // deleted/added items inside Channel/Playlist queue and makes possible to have // a history of played items @Nullable final StackItem stackPeek = stack.peek(); if (stackPeek != null && !stackPeek.getPlayQueue().equalStreams(queue)) { @Nullable final PlayQueueItem playQueueItem = queue.getItem(); if (playQueueItem != null) { stack.push(new StackItem(playQueueItem.getServiceId(), playQueueItem.getUrl(), playQueueItem.getTitle(), queue)); return; } // else continue below } @Nullable final StackItem stackWithQueue = findQueueInStack(queue); if (stackWithQueue != null) { // On every MainPlayer service's destroy() playQueue gets disposed and // no longer able to track progress. That's why we update our cached disposed // queue with the new one that is active and have the same history. // Without that the cached playQueue will have an old recovery position stackWithQueue.setPlayQueue(queue); } } @Override public void onPlaybackUpdate(final int state, final int repeatMode, final boolean shuffled, final PlaybackParameters parameters) { setOverlayPlayPauseImage(player != null && player.isPlaying()); switch (state) { case Player.STATE_PLAYING: if (binding.positionView.getAlpha() != 1.0f && player.getPlayQueue() != null && player.getPlayQueue().getItem() != null && player.getPlayQueue().getItem().getUrl().equals(url)) { animate(binding.positionView, true, 100); animate(binding.detailPositionView, true, 100); } break; } } @Override public void onProgressUpdate(final int currentProgress, final int duration, final int bufferPercent) { // Progress updates every second even if media is paused. It's useless until playing if (!player.isPlaying() || playQueue == null) { return; } if (player.getPlayQueue().getItem().getUrl().equals(url)) { updatePlaybackProgress(currentProgress, duration); } } @Override public void onMetadataUpdate(final StreamInfo info, final PlayQueue queue) { final StackItem item = findQueueInStack(queue); if (item != null) { // When PlayQueue can have multiple streams (PlaylistPlayQueue or ChannelPlayQueue) // every new played stream gives new title and url. // StackItem contains information about first played stream. Let's update it here item.setTitle(info.getName()); item.setUrl(info.getUrl()); } // They are not equal when user watches something in popup while browsing in fragment and // then changes screen orientation. In that case the fragment will set itself as // a service listener and will receive initial call to onMetadataUpdate() if (!queue.equalStreams(playQueue)) { return; } updateOverlayData(info.getName(), info.getUploaderName(), info.getThumbnails()); if (currentInfo != null && info.getUrl().equals(currentInfo.getUrl())) { return; } currentInfo = info; setInitialData(info.getServiceId(), info.getUrl(), info.getName(), queue); setAutoPlay(false); // Delay execution just because it freezes the main thread, and while playing // next/previous video you see visual glitches // (when non-vertical video goes after vertical video) prepareAndHandleInfoIfNeededAfterDelay(info, true, 200); } @Override public void onPlayerError(final PlaybackException error, final boolean isCatchableException) { if (!isCatchableException) { // Properly exit from fullscreen toggleFullscreenIfInFullscreenMode(); hideMainPlayerOnLoadingNewStream(); } } @Override public void onServiceStopped() { setOverlayPlayPauseImage(false); if (currentInfo != null) { updateOverlayData(currentInfo.getName(), currentInfo.getUploaderName(), currentInfo.getThumbnails()); } updateOverlayPlayQueueButtonVisibility(); } @Override public void onFullscreenStateChanged(final boolean fullscreen) { setupBrightness(); if (!isPlayerAndPlayerServiceAvailable() || player.UIs().get(MainPlayerUi.class).isEmpty() || getRoot().map(View::getParent).isEmpty()) { return; } if (fullscreen) { hideSystemUiIfNeeded(); binding.overlayPlayPauseButton.requestFocus(); } else { showSystemUi(); } if (binding.relatedItemsLayout != null) { binding.relatedItemsLayout.setVisibility(fullscreen ? View.GONE : View.VISIBLE); } scrollToTop(); tryAddVideoPlayerView(); } @Override public void onScreenRotationButtonClicked() { // In tablet user experience will be better if screen will not be rotated // from landscape to portrait every time. // Just turn on fullscreen mode in landscape orientation // or portrait & unlocked global orientation final boolean isLandscape = DeviceUtils.isLandscape(requireContext()); if (DeviceUtils.isTablet(activity) && (!globalScreenOrientationLocked(activity) || isLandscape)) { player.UIs().get(MainPlayerUi.class).ifPresent(MainPlayerUi::toggleFullscreen); return; } final int newOrientation = isLandscape ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; activity.setRequestedOrientation(newOrientation); } /* * Will scroll down to description view after long click on moreOptionsButton * */ @Override public void onMoreOptionsLongClicked() { final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams(); final AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior(); final ValueAnimator valueAnimator = ValueAnimator .ofInt(0, -binding.playerPlaceholder.getHeight()); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.addUpdateListener(animation -> { behavior.setTopAndBottomOffset((int) animation.getAnimatedValue()); binding.appBarLayout.requestLayout(); }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(500); valueAnimator.start(); } /*////////////////////////////////////////////////////////////////////////// // Player related utils //////////////////////////////////////////////////////////////////////////*/ private void showSystemUi() { if (DEBUG) { Log.d(TAG, "showSystemUi() called"); } if (activity == null) { return; } // Prevent jumping of the player on devices with cutout if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { activity.getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT; } activity.getWindow().getDecorView().setSystemUiVisibility(0); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); activity.getWindow().setStatusBarColor(ThemeHelper.resolveColorFromAttr( requireContext(), android.R.attr.colorPrimary)); } private void hideSystemUi() { if (DEBUG) { Log.d(TAG, "hideSystemUi() called"); } if (activity == null) { return; } // Prevent jumping of the player on devices with cutout if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { activity.getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } int visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; // In multiWindow mode status bar is not transparent for devices with cutout // if I include this flag. So without it is better in this case final boolean isInMultiWindow = DeviceUtils.isInMultiWindow(activity); if (!isInMultiWindow) { visibility |= View.SYSTEM_UI_FLAG_FULLSCREEN; } activity.getWindow().getDecorView().setSystemUiVisibility(visibility); if (isInMultiWindow || isFullscreen()) { activity.getWindow().setStatusBarColor(Color.TRANSPARENT); activity.getWindow().setNavigationBarColor(Color.TRANSPARENT); } activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Listener implementation @Override public void hideSystemUiIfNeeded() { if (isFullscreen() && bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) { hideSystemUi(); } } private boolean isFullscreen() { return isPlayerAvailable() && player.UIs().get(VideoPlayerUi.class) .map(VideoPlayerUi::isFullscreen).orElse(false); } private boolean playerIsNotStopped() { return isPlayerAvailable() && !player.isStopped(); } private void restoreDefaultBrightness() { final WindowManager.LayoutParams lp = activity.getWindow().getAttributes(); if (lp.screenBrightness == -1) { return; } // Restore the old brightness when fragment.onPause() called or // when a player is in portrait lp.screenBrightness = -1; activity.getWindow().setAttributes(lp); } private void setupBrightness() { if (activity == null) { return; } final WindowManager.LayoutParams lp = activity.getWindow().getAttributes(); if (!isFullscreen() || bottomSheetState != BottomSheetBehavior.STATE_EXPANDED) { // Apply system brightness when the player is not in fullscreen restoreDefaultBrightness(); } else { // Do not restore if user has disabled brightness gesture if (!PlayerHelper.getActionForRightGestureSide(activity) .equals(getString(R.string.brightness_control_key)) && !PlayerHelper.getActionForLeftGestureSide(activity) .equals(getString(R.string.brightness_control_key))) { return; } // Restore already saved brightness level final float brightnessLevel = PlayerHelper.getScreenBrightness(activity); if (brightnessLevel == lp.screenBrightness) { return; } lp.screenBrightness = brightnessLevel; activity.getWindow().setAttributes(lp); } } /** * Make changes to the UI to accommodate for better usability on bigger screens such as TVs * or in Android's desktop mode (DeX etc). */ private void accommodateForTvAndDesktopMode() { if (DeviceUtils.isTv(getContext())) { // remove ripple effects from detail controls final int transparent = ContextCompat.getColor(requireContext(), R.color.transparent_background_color); binding.detailControlsPlaylistAppend.setBackgroundColor(transparent); binding.detailControlsBackground.setBackgroundColor(transparent); binding.detailControlsPopup.setBackgroundColor(transparent); binding.detailControlsDownload.setBackgroundColor(transparent); binding.detailControlsShare.setBackgroundColor(transparent); binding.detailControlsOpenInBrowser.setBackgroundColor(transparent); binding.detailControlsPlayWithKodi.setBackgroundColor(transparent); } if (DeviceUtils.isDesktopMode(getContext())) { // Remove the "hover" overlay (since it is visible on all mouse events and interferes // with the video content being played) binding.detailThumbnailRootLayout.setForeground(null); } } private void checkLandscape() { if ((!player.isPlaying() && player.getPlayQueue() != playQueue) || player.getPlayQueue() == null) { setAutoPlay(true); } player.UIs().get(MainPlayerUi.class).ifPresent(MainPlayerUi::checkLandscape); // Let's give a user time to look at video information page if video is not playing if (globalScreenOrientationLocked(activity) && !player.isPlaying()) { player.play(); } } /* * Means that the player fragment was swiped away via BottomSheetLayout * and is empty but ready for any new actions. See cleanUp() * */ private boolean wasCleared() { return url == null; } @Nullable private StackItem findQueueInStack(final PlayQueue queue) { StackItem item = null; final Iterator<StackItem> iterator = stack.descendingIterator(); while (iterator.hasNext()) { final StackItem next = iterator.next(); if (next.getPlayQueue().equalStreams(queue)) { item = next; break; } } return item; } private void replaceQueueIfUserConfirms(final Runnable onAllow) { @Nullable final PlayQueue activeQueue = isPlayerAvailable() ? player.getPlayQueue() : null; // Player will have STATE_IDLE when a user pressed back button if (isClearingQueueConfirmationRequired(activity) && playerIsNotStopped() && activeQueue != null && !activeQueue.equalStreams(playQueue)) { showClearingQueueConfirmation(onAllow); } else { onAllow.run(); } } private void showClearingQueueConfirmation(final Runnable onAllow) { new AlertDialog.Builder(activity) .setTitle(R.string.clear_queue_confirmation_description) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok, (dialog, which) -> { onAllow.run(); dialog.dismiss(); }) .show(); } private void showExternalVideoPlaybackDialog() { if (currentInfo == null) { return; } final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.select_quality_external_players); builder.setNeutralButton(R.string.open_in_browser, (dialog, i) -> ShareUtils.openUrlInBrowser(requireActivity(), url)); final List<VideoStream> videoStreamsForExternalPlayers = ListHelper.getSortedStreamVideosList( activity, getUrlAndNonTorrentStreams(currentInfo.getVideoStreams()), getUrlAndNonTorrentStreams(currentInfo.getVideoOnlyStreams()), false, false ); if (videoStreamsForExternalPlayers.isEmpty()) { builder.setMessage(R.string.no_video_streams_available_for_external_players); builder.setPositiveButton(R.string.ok, null); } else { final int selectedVideoStreamIndexForExternalPlayers = ListHelper.getDefaultResolutionIndex(activity, videoStreamsForExternalPlayers); final CharSequence[] resolutions = videoStreamsForExternalPlayers.stream() .map(VideoStream::getResolution).toArray(CharSequence[]::new); builder.setSingleChoiceItems(resolutions, selectedVideoStreamIndexForExternalPlayers, null); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.ok, (dialog, i) -> { final int index = ((AlertDialog) dialog).getListView().getCheckedItemPosition(); // We don't have to manage the index validity because if there is no stream // available for external players, this code will be not executed and if there is // no stream which matches the default resolution, 0 is returned by // ListHelper.getDefaultResolutionIndex. // The index cannot be outside the bounds of the list as its always between 0 and // the list size - 1, . startOnExternalPlayer(activity, currentInfo, videoStreamsForExternalPlayers.get(index)); }); } builder.show(); } private void showExternalAudioPlaybackDialog() { if (currentInfo == null) { return; } final List<AudioStream> audioStreams = getUrlAndNonTorrentStreams( currentInfo.getAudioStreams()); final List<AudioStream> audioTracks = ListHelper.getFilteredAudioStreams(activity, audioStreams); if (audioTracks.isEmpty()) { Toast.makeText(activity, R.string.no_audio_streams_available_for_external_players, Toast.LENGTH_SHORT).show(); } else if (audioTracks.size() == 1) { startOnExternalPlayer(activity, currentInfo, audioTracks.get(0)); } else { final int selectedAudioStream = ListHelper.getDefaultAudioFormat(activity, audioTracks); final CharSequence[] trackNames = audioTracks.stream() .map(audioStream -> Localization.audioTrackName(activity, audioStream)) .toArray(CharSequence[]::new); new AlertDialog.Builder(activity) .setTitle(R.string.select_audio_track_external_players) .setNeutralButton(R.string.open_in_browser, (dialog, i) -> ShareUtils.openUrlInBrowser(requireActivity(), url)) .setSingleChoiceItems(trackNames, selectedAudioStream, null) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok, (dialog, i) -> { final int index = ((AlertDialog) dialog).getListView() .getCheckedItemPosition(); startOnExternalPlayer(activity, currentInfo, audioTracks.get(index)); }) .show(); } } /* * Remove unneeded information while waiting for a next task * */ private void cleanUp() { // New beginning stack.clear(); if (currentWorker != null) { currentWorker.dispose(); } playerHolder.stopService(); setInitialData(0, null, "", null); currentInfo = null; updateOverlayData(null, null, List.of()); } /*////////////////////////////////////////////////////////////////////////// // Bottom mini player //////////////////////////////////////////////////////////////////////////*/ /** * That's for Android TV support. Move focus from main fragment to the player or back * based on what is currently selected * * @param toMain if true than the main fragment will be focused or the player otherwise */ private void moveFocusToMainFragment(final boolean toMain) { setupBrightness(); final ViewGroup mainFragment = requireActivity().findViewById(R.id.fragment_holder); // Hamburger button steels a focus even under bottomSheet final Toolbar toolbar = requireActivity().findViewById(R.id.toolbar); final int afterDescendants = ViewGroup.FOCUS_AFTER_DESCENDANTS; final int blockDescendants = ViewGroup.FOCUS_BLOCK_DESCENDANTS; if (toMain) { mainFragment.setDescendantFocusability(afterDescendants); toolbar.setDescendantFocusability(afterDescendants); ((ViewGroup) requireView()).setDescendantFocusability(blockDescendants); // Only focus the mainFragment if the mainFragment (e.g. search-results) // or the toolbar (e.g. Textfield for search) don't have focus. // This was done to fix problems with the keyboard input, see also #7490 if (!mainFragment.hasFocus() && !toolbar.hasFocus()) { mainFragment.requestFocus(); } } else { mainFragment.setDescendantFocusability(blockDescendants); toolbar.setDescendantFocusability(blockDescendants); ((ViewGroup) requireView()).setDescendantFocusability(afterDescendants); // Only focus the player if it not already has focus if (!binding.getRoot().hasFocus()) { binding.detailThumbnailRootLayout.requestFocus(); } } } /** * When the mini player exists the view underneath it is not touchable. * Bottom padding should be equal to the mini player's height in this case * * @param showMore whether main fragment should be expanded or not */ private void manageSpaceAtTheBottom(final boolean showMore) { final int peekHeight = getResources().getDimensionPixelSize(R.dimen.mini_player_height); final ViewGroup holder = requireActivity().findViewById(R.id.fragment_holder); final int newBottomPadding; if (showMore) { newBottomPadding = 0; } else { newBottomPadding = peekHeight; } if (holder.getPaddingBottom() == newBottomPadding) { return; } holder.setPadding(holder.getPaddingLeft(), holder.getPaddingTop(), holder.getPaddingRight(), newBottomPadding); } private void setupBottomPlayer() { final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams(); final AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior(); final FrameLayout bottomSheetLayout = activity.findViewById(R.id.fragment_player_holder); bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout); bottomSheetBehavior.setState(lastStableBottomSheetState); updateBottomSheetState(lastStableBottomSheetState); final int peekHeight = getResources().getDimensionPixelSize(R.dimen.mini_player_height); if (bottomSheetState != BottomSheetBehavior.STATE_HIDDEN) { manageSpaceAtTheBottom(false); bottomSheetBehavior.setPeekHeight(peekHeight); if (bottomSheetState == BottomSheetBehavior.STATE_COLLAPSED) { binding.overlayLayout.setAlpha(MAX_OVERLAY_ALPHA); } else if (bottomSheetState == BottomSheetBehavior.STATE_EXPANDED) { binding.overlayLayout.setAlpha(0); setOverlayElementsClickable(false); } } bottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull final View bottomSheet, final int newState) { updateBottomSheetState(newState); switch (newState) { case BottomSheetBehavior.STATE_HIDDEN: moveFocusToMainFragment(true); manageSpaceAtTheBottom(true); bottomSheetBehavior.setPeekHeight(0); cleanUp(); break; case BottomSheetBehavior.STATE_EXPANDED: moveFocusToMainFragment(false); manageSpaceAtTheBottom(false); bottomSheetBehavior.setPeekHeight(peekHeight); // Disable click because overlay buttons located on top of buttons // from the player setOverlayElementsClickable(false); hideSystemUiIfNeeded(); // Conditions when the player should be expanded to fullscreen if (DeviceUtils.isLandscape(requireContext()) && isPlayerAvailable() && player.isPlaying() && !isFullscreen() && !DeviceUtils.isTablet(activity)) { player.UIs().get(MainPlayerUi.class) .ifPresent(MainPlayerUi::toggleFullscreen); } setOverlayLook(binding.appBarLayout, behavior, 1); break; case BottomSheetBehavior.STATE_COLLAPSED: moveFocusToMainFragment(true); manageSpaceAtTheBottom(false); bottomSheetBehavior.setPeekHeight(peekHeight); // Re-enable clicks setOverlayElementsClickable(true); if (isPlayerAvailable()) { player.UIs().get(MainPlayerUi.class) .ifPresent(MainPlayerUi::closeItemsList); } setOverlayLook(binding.appBarLayout, behavior, 0); break; case BottomSheetBehavior.STATE_DRAGGING: case BottomSheetBehavior.STATE_SETTLING: if (isFullscreen()) { showSystemUi(); } if (isPlayerAvailable()) { player.UIs().get(MainPlayerUi.class).ifPresent(ui -> { if (ui.isControlsVisible()) { ui.hideControls(0, 0); } }); } break; case BottomSheetBehavior.STATE_HALF_EXPANDED: break; } } @Override public void onSlide(@NonNull final View bottomSheet, final float slideOffset) { setOverlayLook(binding.appBarLayout, behavior, slideOffset); } }; bottomSheetBehavior.addBottomSheetCallback(bottomSheetCallback); // User opened a new page and the player will hide itself activity.getSupportFragmentManager().addOnBackStackChangedListener(() -> { if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } }); } private void updateOverlayPlayQueueButtonVisibility() { final boolean isPlayQueueEmpty = player == null // no player => no play queue :) || player.getPlayQueue() == null || player.getPlayQueue().isEmpty(); if (binding != null) { // binding is null when rotating the device... binding.overlayPlayQueueButton.setVisibility( isPlayQueueEmpty ? View.GONE : View.VISIBLE); } } private void updateOverlayData(@Nullable final String overlayTitle, @Nullable final String uploader, @NonNull final List<Image> thumbnails) { binding.overlayTitleTextView.setText(isEmpty(overlayTitle) ? "" : overlayTitle); binding.overlayChannelTextView.setText(isEmpty(uploader) ? "" : uploader); binding.overlayThumbnail.setImageDrawable(null); PicassoHelper.loadDetailsThumbnail(thumbnails).tag(PICASSO_VIDEO_DETAILS_TAG) .into(binding.overlayThumbnail); } private void setOverlayPlayPauseImage(final boolean playerIsPlaying) { final int drawable = playerIsPlaying ? R.drawable.ic_pause : R.drawable.ic_play_arrow; binding.overlayPlayPauseButton.setImageResource(drawable); } private void setOverlayLook(final AppBarLayout appBar, final AppBarLayout.Behavior behavior, final float slideOffset) { // SlideOffset < 0 when mini player is about to close via swipe. // Stop animation in this case if (behavior == null || slideOffset < 0) { return; } binding.overlayLayout.setAlpha(Math.min(MAX_OVERLAY_ALPHA, 1 - slideOffset)); // These numbers are not special. They just do a cool transition behavior.setTopAndBottomOffset( (int) (-binding.detailThumbnailImageView.getHeight() * 2 * (1 - slideOffset) / 3)); appBar.requestLayout(); } private void setOverlayElementsClickable(final boolean enable) { binding.overlayThumbnail.setClickable(enable); binding.overlayThumbnail.setLongClickable(enable); binding.overlayMetadataLayout.setClickable(enable); binding.overlayMetadataLayout.setLongClickable(enable); binding.overlayButtonsLayout.setClickable(enable); binding.overlayPlayQueueButton.setClickable(enable); binding.overlayPlayPauseButton.setClickable(enable); binding.overlayCloseButton.setClickable(enable); } // helpers to check the state of player and playerService boolean isPlayerAvailable() { return player != null; } boolean isPlayerServiceAvailable() { return playerService != null; } boolean isPlayerAndPlayerServiceAvailable() { return player != null && playerService != null; } public Optional<View> getRoot() { return Optional.ofNullable(player) .flatMap(player1 -> player1.UIs().get(VideoPlayerUi.class)) .map(playerUi -> playerUi.getBinding().getRoot()); } private void updateBottomSheetState(final int newState) { bottomSheetState = newState; if (newState != BottomSheetBehavior.STATE_DRAGGING && newState != BottomSheetBehavior.STATE_SETTLING) { lastStableBottomSheetState = newState; } } }
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/fragments/detail/VideoDetailFragment.java
2,336
404: Not Found
halo-dev/halo
application/src/main/java/run/halo/app/cache/PageCacheWebFilter.java
2,337
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.cat.consumer.storage.builder; import java.util.Arrays; import java.util.List; import org.unidal.lookup.annotation.Named; import com.dianping.cat.message.Event; import com.dianping.cat.message.Message; import com.dianping.cat.message.Transaction; @Named(type = StorageBuilder.class, value = StorageCacheBuilder.ID) public class StorageCacheBuilder implements StorageBuilder { public final static String ID = "Cache"; public final static int LONG_THRESHOLD = 50; public final static List<String> DEFAULT_METHODS = Arrays.asList("add", "get", "mGet", "remove"); @Override public StorageItem build(Transaction t) { String ip = "default"; String id = t.getType(); int index = id.indexOf("."); if (index > -1) { id = id.substring(index + 1); } String name = t.getName(); String method = name.substring(name.lastIndexOf(":") + 1); List<Message> messages = t.getChildren(); for (Message message : messages) { if (message instanceof Event) { String type = message.getType(); if (type.endsWith(".server")) { ip = message.getName(); index = ip.indexOf(":"); if (index > -1) { ip = ip.substring(0, index); } } } } return new StorageItem(id, ID, method, ip, LONG_THRESHOLD); } @Override public List<String> getDefaultMethods() { return DEFAULT_METHODS; } @Override public String getType() { return ID; } @Override public boolean isEligable(Transaction t) { String type = t.getType(); return type != null && (type.startsWith("Cache.") || type.startsWith("Squirrel.")); } }
dianping/cat
cat-consumer/src/main/java/com/dianping/cat/consumer/storage/builder/StorageCacheBuilder.java
2,338
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package com.vaticle.typedb.core.database; import com.vaticle.typedb.common.collection.ConcurrentSet; import com.vaticle.typedb.common.collection.Pair; import com.vaticle.typedb.core.TypeDB; import com.vaticle.typedb.core.common.collection.ByteArray; import com.vaticle.typedb.core.common.exception.TypeDBException; import com.vaticle.typedb.core.common.iterator.FunctionalIterator; import com.vaticle.typedb.core.common.parameters.Arguments; import com.vaticle.typedb.core.common.parameters.Options; import com.vaticle.typedb.core.concept.type.Type; import com.vaticle.typedb.core.concurrent.executor.Executors; import com.vaticle.typedb.core.encoding.Encoding; import com.vaticle.typedb.core.encoding.iid.VertexIID; import com.vaticle.typedb.core.encoding.key.Key; import com.vaticle.typedb.core.encoding.key.KeyGenerator; import com.vaticle.typedb.core.encoding.key.StatisticsKey; import com.vaticle.typedb.core.graph.TypeGraph; import com.vaticle.typedb.core.graph.edge.ThingEdge; import com.vaticle.typedb.core.graph.vertex.AttributeVertex; import com.vaticle.typedb.core.graph.vertex.ThingVertex; import com.vaticle.typedb.core.graph.vertex.TypeVertex; import com.vaticle.typedb.core.logic.LogicCache; import com.vaticle.typedb.core.traversal.TraversalCache; import com.vaticle.typeql.lang.TypeQL; import org.rocksdb.ColumnFamilyDescriptor; import org.rocksdb.ColumnFamilyHandle; import org.rocksdb.OptimisticTransactionDB; import org.rocksdb.RocksDBException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; 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.concurrent.locks.StampedLock; import java.util.stream.Stream; import static com.vaticle.typedb.common.collection.Collections.pair; import static com.vaticle.typedb.common.collection.Collections.set; import static com.vaticle.typedb.core.common.collection.ByteArray.encodeLong; import static com.vaticle.typedb.core.common.collection.ByteArray.encodeLongs; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Database.DATABASE_CLOSED; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Database.INCOMPATIBLE_ENCODING; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Database.ROCKS_LOGGER_SHUTDOWN_TIMEOUT; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Database.STATISTICS_CORRECTOR_SHUTDOWN_TIMEOUT; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.DIRTY_INITIALISATION; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.ILLEGAL_STATE; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.JAVA_ERROR; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.STORAGE_ERROR; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Session.SCHEMA_ACQUIRE_LOCK_TIMEOUT; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Transaction.RESOURCE_CLOSED; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Transaction.TRANSACTION_ISOLATION_DELETE_MODIFY_VIOLATION; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Transaction.TRANSACTION_ISOLATION_EXCLUSIVE_CREATE_VIOLATION; import static com.vaticle.typedb.core.common.exception.ErrorMessage.Transaction.TRANSACTION_ISOLATION_MODIFY_DELETE_VIOLATION; import static com.vaticle.typedb.core.common.iterator.Iterators.iterate; import static com.vaticle.typedb.core.common.iterator.Iterators.link; import static com.vaticle.typedb.core.common.parameters.Arguments.Session.Type.DATA; import static com.vaticle.typedb.core.common.parameters.Arguments.Session.Type.SCHEMA; import static com.vaticle.typedb.core.common.parameters.Arguments.Transaction.Type.READ; import static com.vaticle.typedb.core.common.parameters.Arguments.Transaction.Type.WRITE; import static com.vaticle.typedb.core.concurrent.executor.Executors.serial; import static com.vaticle.typedb.core.encoding.Encoding.ENCODING_VERSION; import static com.vaticle.typedb.core.encoding.Encoding.System.ENCODING_VERSION_KEY; import static java.util.Collections.emptySet; import static java.util.Comparator.reverseOrder; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; public class CoreDatabase implements TypeDB.Database { private static final Logger LOG = LoggerFactory.getLogger(CoreDatabase.class); private static final int ROCKS_LOG_PERIOD = 300; private final CoreDatabaseManager databaseMgr; private final Factory.Session sessionFactory; protected final String name; protected final AtomicBoolean isOpen; private final AtomicLong nextTransactionID; private final AtomicInteger schemaLockWriteRequests; private final StampedLock schemaLock; protected final ConcurrentMap<UUID, Pair<CoreSession, Long>> sessions; protected final RocksConfiguration rocksConfiguration; protected final KeyGenerator.Schema.Persisted schemaKeyGenerator; protected final KeyGenerator.Data.Persisted dataKeyGenerator; private final IsolationManager isolationMgr; private final StatisticsCorrector statisticsCorrector; protected OptimisticTransactionDB rocksSchema; protected OptimisticTransactionDB rocksData; protected CorePartitionManager.Schema rocksSchemaPartitionMgr; protected CorePartitionManager.Data rocksDataPartitionMgr; protected CoreSession.Data statisticsBackgroundCounterSession; protected ScheduledExecutorService scheduledPropertiesLogger; protected RocksProperties.Reader rocksPropertiesReader; private Cache cache; protected CoreDatabase(CoreDatabaseManager databaseMgr, String name, Factory.Session sessionFactory) { this.databaseMgr = databaseMgr; this.name = name; this.sessionFactory = sessionFactory; schemaKeyGenerator = new KeyGenerator.Schema.Persisted(); dataKeyGenerator = new KeyGenerator.Data.Persisted(); isolationMgr = new IsolationManager(); statisticsCorrector = createStatisticsCorrector(); sessions = new ConcurrentHashMap<>(); rocksConfiguration = new RocksConfiguration(options().storageDataCacheSize(), options().storageIndexCacheSize(), LOG.isDebugEnabled() || LOG.isTraceEnabled(), ROCKS_LOG_PERIOD); schemaLock = new StampedLock(); schemaLockWriteRequests = new AtomicInteger(0); nextTransactionID = new AtomicLong(0); isOpen = new AtomicBoolean(false); } protected StatisticsCorrector createStatisticsCorrector() { return new StatisticsCorrector(this); } static CoreDatabase createAndOpen(CoreDatabaseManager databaseMgr, String name, Factory.Session sessionFactory) { try { Files.createDirectory(databaseMgr.directory().resolve(name)); } catch (IOException e) { throw TypeDBException.of(JAVA_ERROR, e); } CoreDatabase database = new CoreDatabase(databaseMgr, name, sessionFactory); database.initialise(); return database; } static CoreDatabase loadAndOpen(CoreDatabaseManager databaseMgr, String name, Factory.Session sessionFactory) { CoreDatabase database = new CoreDatabase(databaseMgr, name, sessionFactory); database.load(); return database; } protected void initialise() { try { openSchema(); initialiseEncodingVersion(); openData(); isOpen.set(true); try (CoreSession.Schema session = createAndOpenSession(SCHEMA, new Options.Session()).asSchema()) { try (CoreTransaction.Schema txn = session.initialisationTransaction()) { if (txn.graph().isInitialised()) throw TypeDBException.of(DIRTY_INITIALISATION); txn.graph().initialise(); txn.commit(); } } statisticsCorrector.markActivating(); statisticsCorrector.doActivate(); } catch (RocksDBException e) { closeResources(); throw TypeDBException.of(STORAGE_ERROR, e); } } protected void openSchema() throws RocksDBException { List<ColumnFamilyDescriptor> schemaDescriptors = CorePartitionManager.Schema.descriptors(rocksConfiguration.schema()); List<ColumnFamilyHandle> schemaHandles = new ArrayList<>(); rocksSchema = OptimisticTransactionDB.open( rocksConfiguration.schema().dbOptions(), directory().resolve(Encoding.ROCKS_SCHEMA).toString(), schemaDescriptors, schemaHandles ); rocksSchemaPartitionMgr = createPartitionMgrSchema(schemaDescriptors, schemaHandles); } protected CorePartitionManager.Schema createPartitionMgrSchema(List<ColumnFamilyDescriptor> schemaDescriptors, List<ColumnFamilyHandle> schemaHandles) { return new CorePartitionManager.Schema(schemaDescriptors, schemaHandles); } protected void openData() throws RocksDBException { List<ColumnFamilyDescriptor> dataDescriptors = CorePartitionManager.Data.descriptors(rocksConfiguration.data()); List<ColumnFamilyHandle> dataHandles = new ArrayList<>(); rocksData = OptimisticTransactionDB.open( rocksConfiguration.data().dbOptions(), directory().resolve(Encoding.ROCKS_DATA).toString(), dataDescriptors.subList(0, 1), dataHandles ); assert dataHandles.size() == 1; dataHandles.addAll(rocksData.createColumnFamilies(dataDescriptors.subList(1, dataDescriptors.size()))); rocksDataPartitionMgr = createPartitionMgrData(dataDescriptors, dataHandles); rocksPropertiesReader = new RocksProperties.Reader(rocksData, rocksDataPartitionMgr.handles); mayInitRocksDataLogger(); } protected CorePartitionManager.Data createPartitionMgrData(List<ColumnFamilyDescriptor> dataDescriptors, List<ColumnFamilyHandle> dataHandles) { return new CorePartitionManager.Data(dataDescriptors, dataHandles); } protected void load() { assert isExistingDatabaseDirectory(directory()); try { loadSchema(); validateEncodingVersion(); loadData(); isOpen.set(true); try (CoreSession.Schema session = createAndOpenSession(SCHEMA, new Options.Session()).asSchema()) { try (CoreTransaction.Schema txn = session.initialisationTransaction()) { schemaKeyGenerator.sync(txn.schemaStorage()); dataKeyGenerator.sync(txn.schemaStorage(), txn.dataStorage()); } } statisticsCorrector.markReactivating(); statisticsCorrector.doReactivate(); } catch (RocksDBException e) { closeResources(); throw TypeDBException.of(STORAGE_ERROR, e); } } public static boolean isExistingDatabaseDirectory(Path directory) { boolean dataExists = directory.resolve(Encoding.ROCKS_DATA).toFile().exists(); boolean schemaExists = directory.resolve(Encoding.ROCKS_SCHEMA).toFile().exists(); return dataExists && schemaExists; } protected void loadSchema() throws RocksDBException { openSchema(); } protected void loadData() throws RocksDBException { List<ColumnFamilyDescriptor> dataDescriptors = CorePartitionManager.Data.descriptors(rocksConfiguration.data()); List<ColumnFamilyHandle> dataHandles = new ArrayList<>(); rocksData = OptimisticTransactionDB.open( rocksConfiguration.data().dbOptions(), directory().resolve(Encoding.ROCKS_DATA).toString(), dataDescriptors, dataHandles ); assert dataDescriptors.size() == dataHandles.size(); rocksDataPartitionMgr = createPartitionMgrData(dataDescriptors, dataHandles); rocksPropertiesReader = new RocksProperties.Reader(rocksData, rocksDataPartitionMgr.handles); mayInitRocksDataLogger(); } private void mayInitRocksDataLogger() { if (rocksConfiguration.isLoggingEnabled()) { scheduledPropertiesLogger = java.util.concurrent.Executors.newScheduledThreadPool(1); scheduledPropertiesLogger.scheduleAtFixedRate( new RocksProperties.Logger(rocksPropertiesReader, name), 0, ROCKS_LOG_PERIOD, SECONDS ); } else { scheduledPropertiesLogger = null; } } protected void initialiseEncodingVersion() throws RocksDBException { rocksSchema.put( rocksSchemaPartitionMgr.get(Key.Partition.DEFAULT), ENCODING_VERSION_KEY.bytes().getBytes(), ByteArray.encodeInt(ENCODING_VERSION).getBytes() ); } protected void validateEncodingVersion() throws RocksDBException { byte[] encodingBytes = rocksSchema.get( rocksSchemaPartitionMgr.get(Key.Partition.DEFAULT), ENCODING_VERSION_KEY.bytes().getBytes() ); int encoding = encodingBytes == null || encodingBytes.length == 0 ? 0 : ByteArray.of(encodingBytes).decodeInt(); if (encoding != ENCODING_VERSION) { throw TypeDBException.of(INCOMPATIBLE_ENCODING, name(), directory().toAbsolutePath(), encoding, ENCODING_VERSION); } } public CoreSession createAndOpenSession(Arguments.Session.Type type, Options.Session options) { if (!isOpen.get()) throw TypeDBException.of(DATABASE_CLOSED, name); long lock = 0; CoreSession session; if (type.isSchema()) { try { schemaLockWriteRequests.incrementAndGet(); lock = schemaLock().tryWriteLock(options.schemaLockTimeoutMillis(), MILLISECONDS); if (lock == 0) throw TypeDBException.of(SCHEMA_ACQUIRE_LOCK_TIMEOUT); } catch (InterruptedException e) { throw TypeDBException.of(JAVA_ERROR, e); } finally { schemaLockWriteRequests.decrementAndGet(); } session = sessionFactory.sessionSchema(this, options); } else if (type.isData()) { session = sessionFactory.sessionData(this, options); } else { throw TypeDBException.of(ILLEGAL_STATE); } sessions.put(session.uuid(), new Pair<>(session, lock)); return session; } synchronized Cache cacheBorrow() { if (!isOpen.get()) throw TypeDBException.of(DATABASE_CLOSED, name); if (cache == null) cache = new Cache(this); cache.borrow(); return cache; } synchronized void cacheUnborrow(Cache cache) { cache.unborrow(); } public synchronized void cacheInvalidate() { if (!isOpen.get()) throw TypeDBException.of(DATABASE_CLOSED, name); if (cache != null) { cache.invalidate(); cache = null; } } protected synchronized void cacheClose() { if (cache != null) cache.close(); } long nextTransactionID() { return nextTransactionID.getAndIncrement(); } protected Path directory() { return databaseMgr.directory().resolve(name); } public Options.Database options() { return databaseMgr.options(); } KeyGenerator.Schema schemaKeyGenerator() { return schemaKeyGenerator; } KeyGenerator.Data dataKeyGenerator() { return dataKeyGenerator; } public IsolationManager isolationMgr() { return isolationMgr; } protected StatisticsCorrector statisticsCorrector() { return statisticsCorrector; } /** * Get the lock that guarantees that the schema is not modified at the same * time as data being written to the database. When a schema session is * opened (to modify the schema), all write transaction need to wait until * the schema session is completed. If there is a write transaction opened, * a schema session needs to wait until those transactions are completed. * * @return a {@code StampedLock} to protect data writes from concurrent schema modification */ protected StampedLock schemaLock() { return schemaLock; } @Override public String name() { return name; } @Override public boolean isEmpty() { try (TypeDB.Session session = databaseMgr.session(name, SCHEMA); TypeDB.Transaction tx = session.transaction(READ)) { return tx.concepts().getRootThingType().getSubtypes().allMatch(Type::isRoot); } } @Override public boolean contains(UUID sessionID) { return sessions.containsKey(sessionID); } @Override public TypeDB.Session session(UUID sessionID) { if (sessions.containsKey(sessionID)) return sessions.get(sessionID).first(); else return null; } @Override public Stream<TypeDB.Session> sessions() { return sessions.values().stream().map(Pair::first); } public long storageDataKeysEstimate() { return rocksPropertiesReader.getTotal(RocksProperties.properties.get("key-count")); } public long storageDataBytesEstimate() { return rocksPropertiesReader.getTotal(RocksProperties.properties.get("disk-size-live-bytes")); } public long typeCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().stats().typeCount(); } } } public long entityTypeCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().stats().entityTypeCount(); } } } public long relationTypeCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().stats().relationTypeCount(); } } } public long attributeTypeCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().stats().attributeTypeCount(); } } } public long roleTypeCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().stats().roleTypeCount(); } } } public long ownsCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().thingTypes().map(t -> t.outOwnsCount(false)) .reduce(0L, Long::sum); } } } public long thingCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.data().stats().thingVertexTransitiveCount(Encoding.Vertex.Type.Root.THING.properLabel()); } } } public long entityCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.data().stats().thingVertexTransitiveCount(Encoding.Vertex.Type.Root.ENTITY.properLabel()); } } } public long relationCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.data().stats().thingVertexTransitiveCount(Encoding.Vertex.Type.Root.RELATION.properLabel()); } } } public long attributeCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.data().stats().thingVertexTransitiveCount(Encoding.Vertex.Type.Root.ATTRIBUTE.properLabel()); } } } public long roleCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.data().stats().thingVertexTransitiveCount(Encoding.Vertex.Type.Root.ROLE.properLabel()); } } } public long hasCount() { try (CoreSession session = createAndOpenSession(DATA, new Options.Session())) { try (CoreTransaction txn = session.transaction(READ)) { return txn.graphMgr.schema().thingTypes().map(owner -> txn.graphMgr.data().stats().hasEdgeSum( owner, txn.graphMgr.schema().ownedAttributeTypes(owner, emptySet()) )).reduce(0L, Long::sum); } } } @Override public String schema() { try (TypeDB.Session session = databaseMgr.session(name, DATA); TypeDB.Transaction tx = session.transaction(READ)) { String syntax = tx.concepts().typesSyntax() + tx.logic().rulesSyntax(); if (syntax.trim().isEmpty()) return ""; else return TypeQL.parseQuery("define\n\n" + syntax).toString(true); } } @Override public String typeSchema() { try (TypeDB.Session session = databaseMgr.session(name, DATA); TypeDB.Transaction tx = session.transaction(READ)) { String syntax = tx.concepts().typesSyntax(); if (syntax.trim().isEmpty()) return ""; return TypeQL.parseQuery("define\n\n" + syntax).toString(true); } } @Override public String ruleSchema() { try (TypeDB.Session session = databaseMgr.session(name, DATA); TypeDB.Transaction tx = session.transaction(READ)) { String syntax = tx.logic().rulesSyntax(); if (syntax.trim().isEmpty()) return ""; else return TypeQL.parseQuery("define\n\n" + syntax).toString(true); } } void closed(CoreSession session) { if (session != statisticsBackgroundCounterSession) { long lock = sessions.remove(session.uuid()).second(); if (session.type().isSchema()) schemaLock().unlockWrite(lock); } } public void close() { if (isOpen.compareAndSet(true, false)) { if (scheduledPropertiesLogger != null) shutdownRocksPropertiesLogger(); closeResources(); } } private void shutdownRocksPropertiesLogger() { assert scheduledPropertiesLogger != null; try { scheduledPropertiesLogger.shutdown(); boolean terminated = scheduledPropertiesLogger.awaitTermination(Executors.SHUTDOWN_TIMEOUT_MS, MILLISECONDS); if (!terminated) throw TypeDBException.of(ROCKS_LOGGER_SHUTDOWN_TIMEOUT); } catch (InterruptedException e) { throw TypeDBException.of(JAVA_ERROR, e); } } protected void closeResources() { statisticsCorrector.close(); sessions.values().forEach(p -> p.first().close()); cacheClose(); if (rocksDataPartitionMgr != null) rocksDataPartitionMgr.close(); if (rocksData != null) rocksData.close(); if (rocksSchemaPartitionMgr != null) rocksSchemaPartitionMgr.close(); if (rocksSchema != null) rocksSchema.close(); } @Override public void delete() { close(); databaseMgr.remove(this); try { Files.walk(directory()).sorted(reverseOrder()).map(Path::toFile).forEach(File::delete); } catch (IOException e) { throw TypeDBException.of(JAVA_ERROR, e); } } public static class IsolationManager { private final ConcurrentSet<CoreTransaction.Data> uncommitted; private final ConcurrentSet<CoreTransaction.Data> committing; private final ConcurrentSet<CoreTransaction.Data> committed; private final AtomicBoolean cleanupRunning; IsolationManager() { uncommitted = new ConcurrentSet<>(); committing = new ConcurrentSet<>(); committed = new ConcurrentSet<>(); cleanupRunning = new AtomicBoolean(false); } void opened(CoreTransaction.Data transaction) { uncommitted.add(transaction); } public Set<CoreTransaction.Data> validateOverlappingAndStartCommit(CoreTransaction.Data txn) { Set<CoreTransaction.Data> transactions; synchronized (this) { transactions = commitMayConflict(txn); transactions.forEach(other -> validateIsolation(txn, other)); committing.add(txn); uncommitted.remove(txn); } return transactions; } private Set<CoreTransaction.Data> commitMayConflict(CoreTransaction.Data txn) { if (!txn.dataStorage.hasTrackedWrite()) return set(); Set<CoreTransaction.Data> mayConflict = new HashSet<>(committing); for (CoreTransaction.Data committedTxn : committed) { if (committedTxn.snapshotEnd().get() > txn.snapshotStart()) mayConflict.add(committedTxn); } return mayConflict; } private void validateIsolation(CoreTransaction.Data txn, CoreTransaction.Data mayConflict) { if (txn.dataStorage.modifyDeleteConflict(mayConflict.dataStorage)) { throw TypeDBException.of(TRANSACTION_ISOLATION_MODIFY_DELETE_VIOLATION); } else if (txn.dataStorage.deleteModifyConflict(mayConflict.dataStorage)) { throw TypeDBException.of(TRANSACTION_ISOLATION_DELETE_MODIFY_VIOLATION); } else if (txn.dataStorage.exclusiveCreateConflict(mayConflict.dataStorage)) { throw TypeDBException.of(TRANSACTION_ISOLATION_EXCLUSIVE_CREATE_VIOLATION); } } public void committed(CoreTransaction.Data txn) { assert committing.contains(txn) && txn.snapshotEnd().isPresent(); committed.add(txn); committing.remove(txn); } void closed(CoreTransaction.Data txn) { // txn closed with commit or without failed commit uncommitted.remove(txn); committing.remove(txn); cleanupCommitted(); } private void cleanupCommitted() { if (cleanupRunning.compareAndSet(false, true)) { long lastCommittedSnapshot = newestCommittedSnapshot(); Long cleanupUntil = oldestUncommittedSnapshot().orElse(lastCommittedSnapshot + 1); committed.forEach(txn -> { if (txn.snapshotEnd().get() < cleanupUntil) { txn.delete(); committed.remove(txn); } }); cleanupRunning.set(false); } } private Optional<Long> oldestUncommittedSnapshot() { return link(iterate(uncommitted), iterate(committing)).map(CoreTransaction.Data::snapshotStart) .stream().min(Comparator.naturalOrder()); } private long newestCommittedSnapshot() { return iterate(committed).map(txn -> txn.snapshotEnd().get()).stream().max(Comparator.naturalOrder()).orElse(0L); } FunctionalIterator<CoreTransaction.Data> getNotCommitted() { return link(iterate(uncommitted), iterate(committing)); } long committedEventCount() { return committed.size(); } } public static class StatisticsCorrector { private final CoreDatabase database; protected final AtomicReference<State> state; protected final ConcurrentSet<CompletableFuture<Void>> corrections; private final ConcurrentSet<Long> deletedTxnIDs; protected CoreSession.Data session; protected enum State {INACTIVE, ACTIVATING, REACTIVATING, WAITING, CORRECTION_QUEUED, CLOSED} protected StatisticsCorrector(CoreDatabase database) { this.database = database; corrections = new ConcurrentSet<>(); deletedTxnIDs = new ConcurrentSet<>(); state = new AtomicReference<>(State.INACTIVE); } public void markActivating() { assert state.get() == State.INACTIVE; state.set(State.ACTIVATING); } public void doActivate() { assert state.get() == State.ACTIVATING; session = database.createAndOpenSession(DATA, new Options.Session()).asData(); state.set(State.WAITING); } public void markReactivating() { assert state.get() == State.INACTIVE; state.set(State.REACTIVATING); } protected void doReactivate() { assert state.get() == State.REACTIVATING; session = database.createAndOpenSession(DATA, new Options.Session()).asData(); state.set(State.WAITING); LOG.trace("Cleaning up statistics metadata."); correctMiscounts(); deleteCorrectionMetadata(); LOG.trace("Statistics are ready and up to date."); if (LOG.isTraceEnabled()) logSummary(); } private void deleteCorrectionMetadata() { try (CoreTransaction.Data txn = session.transaction(WRITE)) { txn.dataStorage.iterate(StatisticsKey.txnCommittedPrefix()).forEachRemaining(kv -> txn.dataStorage.deleteUntracked(kv.key()) ); txn.commit(); } } private void logSummary() { try (CoreTransaction.Data txn = session.transaction(READ)) { LOG.trace("Total 'thing' count: " + txn.graphMgr.data().stats().thingVertexTransitiveCount(txn.graphMgr.schema().rootThingType()) ); long hasCount = 0; NavigableSet<TypeVertex> allTypes = txn.graphMgr.schema().getSubtypes(txn.graphMgr.schema().rootThingType()); Set<TypeVertex> attributes = txn.graphMgr.schema().getSubtypes(txn.graphMgr.schema().rootAttributeType()); for (TypeVertex attr : attributes) { hasCount += txn.graphMgr.data().stats().hasEdgeSum(allTypes, attr); } LOG.trace("Total 'role' count: " + txn.graphMgr.data().stats().thingVertexTransitiveCount(txn.graphMgr.schema().rootRoleType()) ); LOG.trace("Total 'has' count: " + hasCount); } } public void committed(CoreTransaction.Data transaction) { handleDeferredSetUp(); if (mayMiscount(transaction) && state.compareAndSet(State.WAITING, State.CORRECTION_QUEUED)) { submitCorrection(); } } private void handleDeferredSetUp() { if (state.get() == State.ACTIVATING) { synchronized (this) { if (state.get() == State.ACTIVATING) doActivate(); } } else if (state.get() == State.REACTIVATING) { synchronized (this) { if (state.get() == State.REACTIVATING) doReactivate(); } } } CompletableFuture<Void> submitCorrection() { CompletableFuture<Void> correction = CompletableFuture.runAsync(() -> { if (state.compareAndSet(State.CORRECTION_QUEUED, State.WAITING)) correctMiscounts(); }, serial()); corrections.add(correction); correction.exceptionally(exception -> { LOG.debug("StatisticsCorrection task failed with exception: " + exception.toString()); return null; }).thenRun(() -> corrections.remove(correction)); return correction; } private boolean mayMiscount(CoreTransaction.Data transaction) { return !transaction.graphMgr.data().attributesCreated().isEmpty() || !transaction.graphMgr.data().attributesDeleted().isEmpty() || !transaction.graphMgr.data().hasEdgeCreated().isEmpty() || !transaction.graphMgr.data().hasEdgeDeleted().isEmpty(); } void deleted(CoreTransaction.Data transaction) { deletedTxnIDs.add(transaction.id()); } /** * Scan through all attributes that may need to be corrected (eg. have been over/under counted), * and correct them if we have enough information to do so. */ protected void correctMiscounts() { if (state.get().equals(State.CLOSED)) return; try (CoreTransaction.Data txn = session.transaction(WRITE)) { if (mayCorrectMiscounts(txn)) database.cache.incrementStatisticsVersion(); } } protected boolean mayCorrectMiscounts(CoreTransaction.Data txn) { Set<Long> deletableTxnIDs = new HashSet<>(deletedTxnIDs); boolean[] modified = new boolean[]{false}; boolean[] miscountCorrected = new boolean[]{false}; Set<Long> openTxnIDs = database.isolationMgr.getNotCommitted().map(CoreTransaction::id).toSet(); txn.dataStorage.iterate(StatisticsKey.Miscountable.prefix()).forEachRemaining(kv -> { StatisticsKey.Miscountable item = kv.key(); List<Long> txnIDsCausingMiscount = kv.value().decodeLongs(); if (anyCommitted(txnIDsCausingMiscount, txn.dataStorage)) { correctMiscount(item, txn); miscountCorrected[0] = true; txn.dataStorage.deleteUntracked(item); modified[0] = true; } else if (noneOpen(txnIDsCausingMiscount, openTxnIDs)) { txn.dataStorage.deleteUntracked(item); modified[0] = true; } else { // transaction IDs causing miscount are not deletable deletableTxnIDs.removeAll(txnIDsCausingMiscount); } }); if (!deletableTxnIDs.isEmpty()) { for (Long txnID : deletableTxnIDs) { txn.dataStorage.deleteUntracked(StatisticsKey.txnCommitted(txnID)); } deletedTxnIDs.removeAll(deletableTxnIDs); modified[0] = true; } if (modified[0]) txn.commit(); return miscountCorrected[0]; } private void correctMiscount(StatisticsKey.Miscountable miscount, CoreTransaction.Data txn) { if (miscount.isAttrOvertcount()) { VertexIID.Type type = miscount.getMiscountableAttribute().type(); txn.dataStorage.mergeUntracked(StatisticsKey.vertexCount(type), encodeLong(-1)); } else if (miscount.isAttrUndercount()) { VertexIID.Type type = miscount.getMiscountableAttribute().type(); txn.dataStorage.mergeUntracked(StatisticsKey.vertexCount(type), encodeLong(1)); } else if (miscount.isHasEdgeOvercount()) { Pair<VertexIID.Thing, VertexIID.Attribute<?>> has = miscount.getMiscountableHasEdge(); txn.dataStorage.mergeUntracked( StatisticsKey.hasEdgeCount(has.first().type(), has.second().type()), encodeLong(-1) ); } else if (miscount.isHasEdgeUndercount()) { Pair<VertexIID.Thing, VertexIID.Attribute<?>> has = miscount.getMiscountableHasEdge(); txn.dataStorage.mergeUntracked( StatisticsKey.hasEdgeCount(has.first().type(), has.second().type()), encodeLong(1) ); } } private boolean anyCommitted(List<Long> txnIDsToCheck, RocksStorage.Data storage) { for (Long txnID : txnIDsToCheck) { if (storage.get(StatisticsKey.txnCommitted(txnID)) != null) return true; } return false; } private boolean noneOpen(List<Long> txnIDs, Set<Long> openTxnIDs) { return iterate(txnIDs).noneMatch(openTxnIDs::contains); } public void recordCorrectionMetadata(CoreTransaction.Data txn, Set<CoreTransaction.Data> overlappingTxn) { recordMiscountableCauses(txn, overlappingTxn); txn.dataStorage.putUntracked(StatisticsKey.txnCommitted(txn.id())); } private void recordMiscountableCauses(CoreTransaction.Data txn, Set<CoreTransaction.Data> overlappingTxn) { Map<AttributeVertex<?>, List<Long>> attrOvercount = new HashMap<>(); Map<AttributeVertex<?>, List<Long>> attrUndercount = new HashMap<>(); Map<Pair<ThingVertex, AttributeVertex<?>>, List<Long>> hasEdgeOvercount = new HashMap<>(); Map<Pair<ThingVertex, AttributeVertex<?>>, List<Long>> hasEdgeUndercount = new HashMap<>(); for (CoreTransaction.Data overlapping : overlappingTxn) { attrMiscountableCauses(attrOvercount, overlapping.id(), txn.graphMgr.data().attributesCreated(), overlapping.graphMgr.data().attributesCreated()); attrMiscountableCauses(attrUndercount, overlapping.id(), txn.graphMgr.data().attributesDeleted(), overlapping.graphMgr.data().attributesDeleted()); hasEdgeMiscountableCauses(hasEdgeOvercount, overlapping.id(), txn.graphMgr.data().hasEdgeCreated(), overlapping.graphMgr.data().hasEdgeCreated()); hasEdgeMiscountableCauses(hasEdgeUndercount, overlapping.id(), txn.graphMgr.data().hasEdgeDeleted(), overlapping.graphMgr.data().hasEdgeDeleted()); } attrOvercount.forEach((attr, txns) -> txn.dataStorage.putUntracked( StatisticsKey.Miscountable.attrOvercount(txn.id(), attr.iid()), encodeLongs(txns) )); attrUndercount.forEach((attr, txs) -> txn.dataStorage.putUntracked( StatisticsKey.Miscountable.attrUndercount(txn.id(), attr.iid()), encodeLongs(txs) )); hasEdgeOvercount.forEach((has, txs) -> txn.dataStorage.putUntracked( StatisticsKey.Miscountable.hasEdgeOvercount(txn.id(), has.first().iid(), has.second().iid()), encodeLongs(txs) )); hasEdgeUndercount.forEach((has, txs) -> txn.dataStorage.putUntracked( StatisticsKey.Miscountable.hasEdgeUndercount(txn.id(), has.first().iid(), has.second().iid()), encodeLongs(txs) )); } private void attrMiscountableCauses(Map<AttributeVertex<?>, List<Long>> miscountableCauses, long cause, Set<? extends AttributeVertex<?>> attrs1, Set<? extends AttributeVertex<?>> attrs2) { // note: fail-fast if checks are much faster than using empty iterators (due to concurrent data structures) if (!attrs1.isEmpty() && !attrs2.isEmpty()) { iterate(attrs1).filter(attrs2::contains).forEachRemaining(attribute -> miscountableCauses.computeIfAbsent(attribute, (key) -> new ArrayList<>()).add(cause) ); } } private void hasEdgeMiscountableCauses(Map<Pair<ThingVertex, AttributeVertex<?>>, List<Long>> miscountableCauses, long cause, Set<ThingEdge> hasEdge1, Set<ThingEdge> hasEdge2) { // note: fail-fast if checks are much faster than using empty iterators (due to concurrent data structures) if (!hasEdge1.isEmpty() && !hasEdge2.isEmpty()) { iterate(hasEdge1).filter(hasEdge2::contains).forEachRemaining(edge -> miscountableCauses.computeIfAbsent( pair(edge.from(), edge.to().asAttribute()), (key) -> new ArrayList<>() ).add(cause) ); } } protected void close() { try { state.set(State.CLOSED); for (CompletableFuture<Void> correction : corrections) { correction.get(Executors.SHUTDOWN_TIMEOUT_MS, MILLISECONDS); } corrections.clear(); } catch (InterruptedException | TimeoutException e) { LOG.warn(STATISTICS_CORRECTOR_SHUTDOWN_TIMEOUT.message()); throw TypeDBException.of(JAVA_ERROR, e); } catch (ExecutionException e) { if (!((e.getCause() instanceof TypeDBException) && ( ((TypeDBException) e.getCause()).errorMessage().code().equals(RESOURCE_CLOSED.code()) || ((TypeDBException) e.getCause()).errorMessage().code().equals(DATABASE_CLOSED.code()) ))) { throw TypeDBException.of(JAVA_ERROR, e); } } finally { if (session != null) session.close(); } } } static class Cache { private final TraversalCache traversalCache; private final LogicCache logicCache; private final TypeGraph typeGraph; private final RocksStorage schemaStorage; private final AtomicLong statisticsVersion; private long borrowerCount; private boolean invalidated; private Cache(CoreDatabase database) { schemaStorage = new RocksStorage.Cache(database.rocksSchema, database.rocksSchemaPartitionMgr); typeGraph = new TypeGraph(schemaStorage, true); traversalCache = new TraversalCache(); logicCache = new LogicCache(); borrowerCount = 0L; invalidated = false; statisticsVersion = new AtomicLong(0); } public TraversalCache traversal() { return traversalCache; } public LogicCache logic() { return logicCache; } public TypeGraph typeGraph() { return typeGraph; } private void borrow() { borrowerCount++; } private void unborrow() { borrowerCount--; mayClose(); } private void invalidate() { invalidated = true; mayClose(); } private void mayClose() { if (borrowerCount == 0 && invalidated) { schemaStorage.close(); } } AtomicLong statisticsVersion() { return statisticsVersion; } void incrementStatisticsVersion() { statisticsVersion.incrementAndGet(); } private void close() { schemaStorage.close(); } } private static class SchemaExporter { } }
vaticle/typedb
database/CoreDatabase.java
2,339
/* * 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.druid.client.cache; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import org.apache.druid.query.Query; import javax.validation.constraints.Min; import java.util.List; public class CacheConfig { public static final String POPULATE_CACHE = "populateCache"; // The defaults defined here for cache related parameters are different from the QueryContext defaults due to legacy reasons. // They should be made the same at some point in the future. @JsonProperty private boolean useCache = false; @JsonProperty private boolean populateCache = false; @JsonProperty private boolean useResultLevelCache = false; @JsonProperty private boolean populateResultLevelCache = false; @JsonProperty @Min(0) private int numBackgroundThreads = 0; @JsonProperty @Min(0) private int cacheBulkMergeLimit = Integer.MAX_VALUE; @JsonProperty private int maxEntrySize = 1_000_000; @JsonProperty private List<String> unCacheable = ImmutableList.of(); @JsonProperty private int resultLevelCacheLimit = Integer.MAX_VALUE; public boolean isPopulateCache() { return populateCache; } public boolean isUseCache() { return useCache; } public boolean isPopulateResultLevelCache() { return populateResultLevelCache; } public boolean isUseResultLevelCache() { return useResultLevelCache; } public int getNumBackgroundThreads() { return numBackgroundThreads; } public int getCacheBulkMergeLimit() { return cacheBulkMergeLimit; } public int getMaxEntrySize() { return maxEntrySize; } public int getResultLevelCacheLimit() { return resultLevelCacheLimit; } public boolean isQueryCacheable(Query query) { return isQueryCacheable(query.getType()); } public boolean isQueryCacheable(String queryType) { // O(n) impl, but I don't think we'll ever have a million query types here return !unCacheable.contains(queryType); } }
apache/druid
server/src/main/java/org/apache/druid/client/cache/CacheConfig.java
2,340
package com.u9porn.data; import android.graphics.Bitmap; import com.danikula.videocache.HttpProxyCacheServer; import com.u9porn.cookie.CookieManager; import com.u9porn.data.db.DbHelper; import com.u9porn.data.model.BaseResult; import com.u9porn.data.db.entity.Category; import com.u9porn.data.model.F9PronItem; import com.u9porn.data.model.HuaBan; import com.u9porn.data.model.MeiZiTu; import com.u9porn.data.model.Mm99; import com.u9porn.data.model.Notice; import com.u9porn.data.model.pxgav.PxgavResultWithBlockId; import com.u9porn.data.model.pxgav.PxgavVideoParserJsonResult; import com.u9porn.data.model.PinnedHeaderEntity; import com.u9porn.data.model.F9PornContent; import com.u9porn.data.model.ProxyModel; import com.u9porn.data.db.entity.V9PornItem; import com.u9porn.data.model.UpdateVersion; import com.u9porn.data.model.User; import com.u9porn.data.model.VideoComment; import com.u9porn.data.db.entity.VideoResult; import com.u9porn.data.model.axgle.AxgleResponse; import com.u9porn.data.network.ApiHelper; import com.u9porn.data.prefs.PreferencesHelper; import com.u9porn.utils.UserHelper; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import io.reactivex.Observable; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Response; /** * @author flymegoc * @date 2017/11/22 * @describe */ @Singleton public class AppDataManager implements DataManager { private final DbHelper mDbHelper; private final PreferencesHelper mPreferencesHelper; private final ApiHelper mApiHelper; private final HttpProxyCacheServer httpProxyCacheServer; private CookieManager cookieManager; private User user; @Inject AppDataManager(DbHelper mDbHelper, PreferencesHelper mPreferencesHelper, ApiHelper mApiHelper, HttpProxyCacheServer httpProxyCacheServer, CookieManager cookieManager, User user) { this.mDbHelper = mDbHelper; this.mPreferencesHelper = mPreferencesHelper; this.mApiHelper = mApiHelper; this.httpProxyCacheServer = httpProxyCacheServer; this.cookieManager = cookieManager; this.user = user; } @Override public void initCategory(int type, String[] value, String[] name) { mDbHelper.initCategory(type, value, name); } @Override public void updateV9PornItem(V9PornItem v9PornItem) { mDbHelper.updateV9PornItem(v9PornItem); } @Override public List<V9PornItem> loadDownloadingData() { return mDbHelper.loadDownloadingData(); } @Override public List<V9PornItem> loadFinishedData() { return mDbHelper.loadFinishedData(); } @Override public List<V9PornItem> loadHistoryData(int page, int pageSize) { return mDbHelper.loadHistoryData(page, pageSize); } @Override public long saveV9PornItem(V9PornItem v9PornItem) { return mDbHelper.saveV9PornItem(v9PornItem); } @Override public long saveVideoResult(VideoResult videoResult) { return mDbHelper.saveVideoResult(videoResult); } @Override public V9PornItem findV9PornItemByViewKey(String viewKey) { return mDbHelper.findV9PornItemByViewKey(viewKey); } @Override public V9PornItem findV9PornItemByDownloadId(int downloadId) { return mDbHelper.findV9PornItemByDownloadId(downloadId); } @Override public List<V9PornItem> loadV9PornItems() { return mDbHelper.loadV9PornItems(); } @Override public List<V9PornItem> findV9PornItemByDownloadStatus(int status) { return mDbHelper.findV9PornItemByDownloadStatus(status); } @Override public List<Category> loadAllCategoryDataByType(int type) { return mDbHelper.loadAllCategoryDataByType(type); } @Override public List<Category> loadCategoryDataByType(int type) { return mDbHelper.loadCategoryDataByType(type); } @Override public void updateCategoryData(List<Category> categoryList) { mDbHelper.updateCategoryData(categoryList); } @Override public Category findCategoryById(Long id) { return mDbHelper.findCategoryById(id); } @Override public Observable<List<V9PornItem>> loadPorn9VideoIndex(boolean cleanCache) { return mApiHelper.loadPorn9VideoIndex(cleanCache); } @Override public Observable<BaseResult<List<V9PornItem>>> loadPorn9VideoByCategory(String category, String viewType, int page, String m, boolean cleanCache, boolean isLoadMoreCleanCache) { return mApiHelper.loadPorn9VideoByCategory(category, viewType, page, m, cleanCache, isLoadMoreCleanCache); } @Override public Observable<BaseResult<List<V9PornItem>>> loadPorn9authorVideos(String uid, String type, int page, boolean cleanCache) { return mApiHelper.loadPorn9authorVideos(uid, type, page, cleanCache); } @Override public Observable<BaseResult<List<V9PornItem>>> loadPorn9VideoRecentUpdates(String next, int page, boolean cleanCache, boolean isLoadMoreCleanCache) { return mApiHelper.loadPorn9VideoRecentUpdates(next, page, cleanCache, isLoadMoreCleanCache); } @Override public Observable<VideoResult> loadPorn9VideoUrl(String viewKey) { return mApiHelper.loadPorn9VideoUrl(viewKey); } @Override public Observable<List<VideoComment>> loadPorn9VideoComments(String videoId, int page, String viewKey) { return mApiHelper.loadPorn9VideoComments(videoId, page, viewKey); } @Override public Observable<String> commentPorn9Video(String cpaintFunction, String comment, String uid, String vid, String viewKey, String responseType) { return mApiHelper.commentPorn9Video(cpaintFunction, comment, uid, vid, viewKey, responseType); } @Override public Observable<String> replyPorn9VideoComment(String comment, String username, String vid, String commentId, String viewKey) { return mApiHelper.replyPorn9VideoComment(comment, username, vid, commentId, viewKey); } @Override public Observable<BaseResult<List<V9PornItem>>> searchPorn9Videos(String viewType, int page, String searchType, String searchId, String sort) { return mApiHelper.searchPorn9Videos(viewType, page, searchType, searchId, sort); } @Override public Observable<String> favoritePorn9Video(String uId, String videoId, String uvid) { return mApiHelper.favoritePorn9Video(uId, videoId, uvid); } @Override public Observable<BaseResult<List<V9PornItem>>> loadPorn9MyFavoriteVideos(String userName, int page, boolean cleanCache) { return mApiHelper.loadPorn9MyFavoriteVideos(userName, page, cleanCache); } @Override public Observable<List<V9PornItem>> deletePorn9MyFavoriteVideo(String rvid) { return mApiHelper.deletePorn9MyFavoriteVideo(rvid); } @Override public Observable<Bitmap> porn9VideoLoginCaptcha() { return mApiHelper.porn9VideoLoginCaptcha(); } @Override public Observable<User> userLoginPorn9Video(String username, String password, String captcha) { return mApiHelper.userLoginPorn9Video(username, password, captcha); } @Override public Observable<User> userRegisterPorn9Video(String username, String password1, String password2, String email, String captchaInput) { return mApiHelper.userRegisterPorn9Video(username, password1, password2, email, captchaInput); } @Override public Observable<List<PinnedHeaderEntity<F9PronItem>>> loadPorn9ForumIndex() { return mApiHelper.loadPorn9ForumIndex(); } @Override public Observable<BaseResult<List<F9PronItem>>> loadPorn9ForumListData(String fid, int page) { return mApiHelper.loadPorn9ForumListData(fid, page); } @Override public Observable<F9PornContent> loadPorn9ForumContent(Long tid, boolean isNightModel) { return mApiHelper.loadPorn9ForumContent(tid, isNightModel); } @Override public Observable<UpdateVersion> checkUpdate() { return mApiHelper.checkUpdate(); } @Override public Observable<Notice> checkNewNotice() { return mApiHelper.checkNewNotice(); } @Override public Observable<String> commonQuestions() { return mApiHelper.commonQuestions(); } @Override public Observable<BaseResult<List<MeiZiTu>>> listMeiZiTu(String tag, int page, boolean pullToRefresh) { return mApiHelper.listMeiZiTu(tag, page, pullToRefresh); } @Override public Observable<List<String>> meiZiTuImageList(int id, boolean pullToRefresh) { return mApiHelper.meiZiTuImageList(id, pullToRefresh); } @Override public Observable<BaseResult<List<Mm99>>> list99Mm(String category, int page, boolean cleanCache) { return mApiHelper.list99Mm(category, page, cleanCache); } @Override public Observable<List<String>> mm99ImageList(int id, String imageUrl, boolean pullToRefresh) { return mApiHelper.mm99ImageList(id, imageUrl, pullToRefresh); } @Override public Observable<PxgavResultWithBlockId> loadPxgavListByCategory(String category, boolean pullToRefresh) { return mApiHelper.loadPxgavListByCategory(category, pullToRefresh); } @Override public Observable<PxgavResultWithBlockId> loadMorePxgavListByCategory(String category, int page, String lastBlockId, boolean pullToRefresh) { return mApiHelper.loadMorePxgavListByCategory(category, page, lastBlockId, pullToRefresh); } @Override public Observable<PxgavVideoParserJsonResult> loadPxgavVideoUrl(String url, String pId, boolean pullToRefresh) { return mApiHelper.loadPxgavVideoUrl(url, pId, pullToRefresh); } @Override public Observable<BaseResult<List<ProxyModel>>> loadXiCiDaiLiProxyData(int page) { return mApiHelper.loadXiCiDaiLiProxyData(page); } @Override public Observable<Boolean> testProxy(String proxyIpAddress, int proxyPort) { return mApiHelper.testProxy(proxyIpAddress, proxyPort); } @Override public void setPorn9VideoAddress(String address) { mPreferencesHelper.setPorn9VideoAddress(address); } @Override public String getPorn9VideoAddress() { return mPreferencesHelper.getPorn9VideoAddress(); } @Override public void setPorn9ForumAddress(String address) { mPreferencesHelper.setPorn9ForumAddress(address); } @Override public String getPorn9ForumAddress() { return mPreferencesHelper.getPorn9ForumAddress(); } @Override public void setPavAddress(String address) { mPreferencesHelper.setPavAddress(address); } @Override public String getPavAddress() { return mPreferencesHelper.getPavAddress(); } @Override public void setPorn9VideoLoginUserName(String userName) { mPreferencesHelper.setPorn9VideoLoginUserName(userName); } @Override public String getPorn9VideoLoginUserName() { return mPreferencesHelper.getPorn9VideoLoginUserName(); } @Override public void setPorn9VideoLoginUserPassWord(String passWord) { mPreferencesHelper.setPorn9VideoLoginUserPassWord(passWord); } @Override public String getPorn9VideoLoginUserPassword() { return mPreferencesHelper.getPorn9VideoLoginUserPassword(); } @Override public void setPorn9VideoUserAutoLogin(boolean autoLogin) { mPreferencesHelper.setPorn9VideoUserAutoLogin(autoLogin); } @Override public boolean isPorn9VideoUserAutoLogin() { return mPreferencesHelper.isPorn9VideoUserAutoLogin(); } @Override public void setFavoriteNeedRefresh(boolean needRefresh) { mPreferencesHelper.setFavoriteNeedRefresh(needRefresh); } @Override public boolean isFavoriteNeedRefresh() { return mPreferencesHelper.isFavoriteNeedRefresh(); } @Override public void setPlaybackEngine(int playbackEngine) { mPreferencesHelper.setPlaybackEngine(playbackEngine); } @Override public int getPlaybackEngine() { return mPreferencesHelper.getPlaybackEngine(); } @Override public void setFirstInSearchPorn91Video(boolean firstInSearchPorn91Video) { mPreferencesHelper.setFirstInSearchPorn91Video(firstInSearchPorn91Video); } @Override public boolean isFirstInSearchPorn91Video() { return mPreferencesHelper.isFirstInSearchPorn91Video(); } @Override public void setDownloadVideoNeedWifi(boolean downloadVideoNeedWifi) { mPreferencesHelper.setDownloadVideoNeedWifi(downloadVideoNeedWifi); } @Override public boolean isDownloadVideoNeedWifi() { return mPreferencesHelper.isDownloadVideoNeedWifi(); } @Override public void setOpenHttpProxy(boolean openHttpProxy) { mPreferencesHelper.setOpenHttpProxy(openHttpProxy); } @Override public boolean isOpenHttpProxy() { return mPreferencesHelper.isOpenHttpProxy(); } @Override public void setOpenNightMode(boolean openNightMode) { mPreferencesHelper.setOpenNightMode(openNightMode); } @Override public boolean isOpenNightMode() { return mPreferencesHelper.isOpenNightMode(); } @Override public void setProxyIpAddress(String proxyIpAddress) { mPreferencesHelper.setProxyIpAddress(proxyIpAddress); } @Override public String getProxyIpAddress() { return mPreferencesHelper.getProxyIpAddress(); } @Override public void setProxyPort(int port) { mPreferencesHelper.setProxyPort(port); } @Override public int getProxyPort() { return mPreferencesHelper.getProxyPort(); } @Override public void setIgnoreUpdateVersionCode(int versionCode) { mPreferencesHelper.setIgnoreUpdateVersionCode(versionCode); } @Override public int getIgnoreUpdateVersionCode() { return mPreferencesHelper.getIgnoreUpdateVersionCode(); } @Override public void setForbiddenAutoReleaseMemory(boolean autoReleaseMemory) { mPreferencesHelper.setForbiddenAutoReleaseMemory(autoReleaseMemory); } @Override public boolean isForbiddenAutoReleaseMemory() { return mPreferencesHelper.isForbiddenAutoReleaseMemory(); } @Override public void setNeedShowTipFirstViewForum9Content(boolean contentShowTip) { mPreferencesHelper.setNeedShowTipFirstViewForum9Content(contentShowTip); } @Override public boolean isNeedShowTipFirstViewForum9Content() { return mPreferencesHelper.isNeedShowTipFirstViewForum9Content(); } @Override public void setNoticeVersionCode(int noticeVersionCode) { mPreferencesHelper.setNoticeVersionCode(noticeVersionCode); } @Override public int getNoticeVersionCode() { return mPreferencesHelper.getNoticeVersionCode(); } @Override public void setMainFirstTabShow(String firstTabShow) { mPreferencesHelper.setMainFirstTabShow(firstTabShow); } @Override public String getMainFirstTabShow() { return mPreferencesHelper.getMainFirstTabShow(); } @Override public void setMainSecondTabShow(String secondTabShow) { mPreferencesHelper.setMainSecondTabShow(secondTabShow); } @Override public String getMainSecondTabShow() { return mPreferencesHelper.getMainSecondTabShow(); } @Override public void setSettingScrollViewScrollPosition(int position) { mPreferencesHelper.setSettingScrollViewScrollPosition(position); } @Override public int getSettingScrollViewScrollPosition() { return mPreferencesHelper.getSettingScrollViewScrollPosition(); } @Override public void setOpenSkipPage(boolean openSkipPage) { mPreferencesHelper.setOpenSkipPage(openSkipPage); } @Override public boolean isOpenSkipPage() { return mPreferencesHelper.isOpenSkipPage(); } @Override public void setCustomDownloadVideoDirPath(String customDirPath) { mPreferencesHelper.setCustomDownloadVideoDirPath(customDirPath); } @Override public String getCustomDownloadVideoDirPath() { return mPreferencesHelper.getCustomDownloadVideoDirPath(); } @Override public boolean isShowUrlRedirectTipDialog() { return mPreferencesHelper.isShowUrlRedirectTipDialog(); } @Override public void setShowUrlRedirectTipDialog(boolean showUrlRedirectTipDialog) { mPreferencesHelper.setShowUrlRedirectTipDialog(showUrlRedirectTipDialog); } @Override public void setAxgleAddress(String address) { mPreferencesHelper.setAxgleAddress(address); } @Override public String getAxgleAddress() { return mPreferencesHelper.getAxgleAddress(); } @Override public boolean isFixMainNavigation() { return mPreferencesHelper.isFixMainNavigation(); } @Override public void setFixMainNavigation(boolean fixMainNavigation) { mPreferencesHelper.setFixMainNavigation(fixMainNavigation); } @Override public void existProxyTest() { mApiHelper.existProxyTest(); } @Override public Observable<Boolean> testPorn9VideoAddress() { return mApiHelper.testPorn9VideoAddress(); } @Override public Observable<Boolean> testPorn9ForumAddress() { return mApiHelper.testPorn9ForumAddress(); } @Override public Observable<Boolean> testPavAddress(String url) { return mApiHelper.testPavAddress(url); } @Override public Observable<Boolean> testAxgle() { return mApiHelper.testAxgle(); } @Override public Observable<List<HuaBan.Picture>> findPictures(int categoryId, int page) { return mApiHelper.findPictures(categoryId, page); } @Override public Observable<AxgleResponse> axgleVideos(int page, String o, String t, String type, String c, int limit) { return mApiHelper.axgleVideos(page, o, t, type, c, limit); } @Override public Observable<AxgleResponse> searchAxgleVideo(String keyWord, int page) { return mApiHelper.searchAxgleVideo(keyWord, page); } @Override public Observable<AxgleResponse> searchAxgleJavVideo(String keyWord, int page) { return mApiHelper.searchAxgleJavVideo(keyWord, page); } @Override public Call<ResponseBody> getPlayVideoUrl(String url) { return mApiHelper.getPlayVideoUrl(url); } @Override public Observable<Response<ResponseBody>> testV9Porn(String url) { return mApiHelper.testV9Porn(url); } @Override public Observable<Response<ResponseBody>> verifyGoogleRecaptcha(String action, String r, String id, String recaptcha) { return mApiHelper.verifyGoogleRecaptcha(action, r, id, recaptcha); } @Override public String getVideoCacheProxyUrl(String originalVideoUrl) { return httpProxyCacheServer.getProxyUrl(originalVideoUrl, true); } @Override public boolean isVideoCacheByProxy(String originalVideoUrl) { return httpProxyCacheServer.isCached(originalVideoUrl); } @Override public void existLogin() { cookieManager.cleanAllCookies(); user.cleanProperties(); } @Override public void resetPorn91VideoWatchTime(boolean reset) { cookieManager.resetPorn91VideoWatchTime(reset); } @Override public User getUser() { return user; } @Override public boolean isUserLogin() { return UserHelper.isUserInfoComplete(user); } }
techGay/v9porn
app/src/main/java/com/u9porn/data/AppDataManager.java
2,341
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.cache; import jodd.buffer.FastCharBuffer; import jodd.io.FastByteArrayOutputStream; import jodd.io.FastCharArrayWriter; import jodd.io.FileNameUtil; import jodd.io.IOUtil; import jodd.io.NetUtil; import jodd.io.PathUtil; import jodd.io.ZipUtil; import jodd.mutable.MutableBoolean; import jodd.mutable.MutableByte; import jodd.mutable.MutableInteger; import jodd.mutable.MutableLong; import jodd.util.TypeCache; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import java.util.HashMap; import java.util.Map; import java.util.Random; /** TypeCacheBenchmark.map thrpt 20 47135.079 ± 968.012 ops/s TypeCacheBenchmark.simpleHashMap thrpt 20 45526.617 ± 797.989 ops/s TypeCacheBenchmark.smoothieMap thrpt 20 39182.106 ± 545.616 ops/s TypeCacheBenchmark.syncMap thrpt 20 40134.180 ± 1308.250 ops/s TypeCacheBenchmark.timedCache thrpt 20 13929.643 ± 95.971 ops/s TypeCacheBenchmark.weakMap thrpt 20 36468.661 ± 1612.440 ops/s TypeCacheBenchmark.weakSyncMap thrpt 20 26196.027 ± 252.894 ops/s */ @Fork(2) @Warmup(iterations = 10) @Measurement(iterations = 10) @State(Scope.Benchmark) public class TypeCacheBenchmark { private static final Class[] TYPES = { Long.class, Integer.class, Float.class, Double.class, Byte.class, Short.class, Boolean.class, Enum.class, InternalError.class, Math.class, Long.class, Number.class, Object.class, Package.class, Class.class, Cloneable.class, ClassLoader.class, Compiler.class, Comparable.class, IllegalArgumentException.class, Appendable.class, String.class, AssertionError.class, CharSequence.class, OutOfMemoryError.class, ProcessBuilder.class, NullPointerException.class, Void.class, VerifyError.class, Throwable.class, Thread.class, System.class, AbstractCacheMap.class, Cache.class, FIFOCache.class, FileCache.class, NoCache.class, FastByteArrayOutputStream.class, FastCharArrayWriter.class, FileNameUtil.class, NetUtil.class, PathUtil.class, IOUtil.class, ZipUtil.class, MutableInteger.class, MutableLong.class, MutableBoolean.class, MutableByte.class }; { System.out.println("Total types: " + TYPES.length); } private static final int TOTAL_READS = 1024; private final TypeCache<String> map = TypeCache.<String>create().get(); private final TypeCache<String> syncMap = TypeCache.<String>create().threadsafe(true).get(); private final TypeCache<String> weakMap = TypeCache.<String>create().weak(true).get(); private final TypeCache<String> weakSyncMap = TypeCache.<String>create().weak(true).threadsafe(true).get(); private final Map<Class, String> smoothieMap = new net.openhft.smoothie.SmoothieMap<>(); private final Map<Class, String> simpleHashMap = new HashMap<>(); private final Cache<Class, String> timedCache = new TimedCache<>(0); private final int[] indexes = new int[TOTAL_READS]; @Setup public void prepare() { for (final Class type : TYPES) { final String typeName = type.getName(); map.put(type, typeName); syncMap.put(type, typeName); weakMap.put(type, typeName); weakSyncMap.put(type, typeName); smoothieMap.put(type, typeName); simpleHashMap.put(type, typeName); timedCache.put(type, typeName); } final Random rnd = new Random(); for (int i = 0; i < TOTAL_READS; i++) { indexes[i] = rnd.nextInt(TYPES.length); } } // ---------------------------------------------------------------- benchmark @Benchmark public Object map() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(map.get(TYPES[index])); } return sb; } @Benchmark public Object syncMap() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(syncMap.get(TYPES[index])); } return sb; } @Benchmark public Object weakMap() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(weakMap.get(TYPES[index])); } return sb; } @Benchmark public Object weakSyncMap() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(weakSyncMap.get(TYPES[index])); } return sb; } @Benchmark public Object smoothieMap() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(smoothieMap.get(TYPES[index])); } return sb; } @Benchmark public Object simpleHashMap() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(simpleHashMap.get(TYPES[index])); } return sb; } @Benchmark public Object timedCache() { final FastCharBuffer sb = new FastCharBuffer(); for (final int index : indexes) { sb.append(timedCache.get(TYPES[index])); } return sb; } }
oblac/jodd
jodd-core/src/jmh/java/jodd/cache/TypeCacheBenchmark.java
2,342
// 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.qe.cache; import org.apache.doris.common.Status; import org.apache.doris.proto.InternalService; import org.apache.doris.proto.Types; import org.apache.doris.qe.SimpleScheduler; import org.apache.doris.rpc.BackendServiceProxy; import org.apache.doris.rpc.RpcException; import org.apache.doris.system.Backend; import org.apache.doris.thrift.TNetworkAddress; import org.apache.doris.thrift.TStatusCode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Encapsulates access to BE, including network and other exception handling */ public class CacheBeProxy extends CacheProxy { private static final Logger LOG = LogManager.getLogger(CacheBeProxy.class); public void updateCache(InternalService.PUpdateCacheRequest request, int timeoutMs, Status status) { Types.PUniqueId sqlKey = request.getSqlKey(); Backend backend = CacheCoordinator.getInstance().findBackend(sqlKey); if (backend == null) { LOG.warn("update cache can't find backend, sqlKey {}", sqlKey); return; } TNetworkAddress address = new TNetworkAddress(backend.getHost(), backend.getBrpcPort()); try { Future<InternalService.PCacheResponse> future = BackendServiceProxy.getInstance() .updateCache(address, request); InternalService.PCacheResponse response = future.get(timeoutMs, TimeUnit.MILLISECONDS); if (response.getStatus() == InternalService.PCacheStatus.CACHE_OK) { status.updateStatus(TStatusCode.OK, "CACHE_OK"); } else { status.updateStatus(TStatusCode.INTERNAL_ERROR, response.getStatus().toString()); } } catch (Exception e) { LOG.warn("update cache exception, sqlKey {}", sqlKey, e); status.updateStatus(TStatusCode.THRIFT_RPC_ERROR, e.getMessage()); SimpleScheduler.addToBlacklist(backend.getId(), e.getMessage()); } } public InternalService.PFetchCacheResult fetchCache(InternalService.PFetchCacheRequest request, int timeoutMs, Status status) { Types.PUniqueId sqlKey = request.getSqlKey(); Backend backend = CacheCoordinator.getInstance().findBackend(sqlKey); if (backend == null) { return null; } TNetworkAddress address = new TNetworkAddress(backend.getHost(), backend.getBrpcPort()); try { Future<InternalService.PFetchCacheResult> future = BackendServiceProxy.getInstance() .fetchCache(address, request); return future.get(timeoutMs, TimeUnit.MILLISECONDS); } catch (RpcException e) { LOG.warn("fetch catch rpc exception, sqlKey {}, backend {}", sqlKey, backend.getId(), e); status.updateStatus(TStatusCode.THRIFT_RPC_ERROR, e.getMessage()); SimpleScheduler.addToBlacklist(backend.getId(), e.getMessage()); } catch (InterruptedException e) { LOG.warn("future get interrupted exception, sqlKey {}, backend {}", sqlKey, backend.getId(), e); status.updateStatus(TStatusCode.INTERNAL_ERROR, "interrupted exception"); } catch (ExecutionException e) { LOG.warn("future get execution exception, sqlKey {}, backend {}", sqlKey, backend.getId(), e); status.updateStatus(TStatusCode.INTERNAL_ERROR, "execution exception"); } catch (TimeoutException e) { LOG.warn("fetch result timeout, sqlKey {}, backend {}", sqlKey, backend.getId(), e); status.updateStatus(TStatusCode.TIMEOUT, "query timeout"); } return null; } public void clearCache(InternalService.PClearCacheRequest request) { this.clearCache(request, CacheCoordinator.getInstance().getBackendList()); } public void clearCache(InternalService.PClearCacheRequest request, List<Backend> beList) { int retry; Status status = new Status(); for (Backend backend : beList) { retry = 1; while (retry < 3 && !this.clearCache(request, backend, CLEAR_TIMEOUT, status)) { retry++; try { Thread.sleep(1000); //sleep 1 second } catch (Exception e) { // CHECKSTYLE IGNORE THIS LINE } } if (retry >= 3) { String errMsg = "clear cache timeout, backend " + backend.getId(); LOG.warn(errMsg); SimpleScheduler.addToBlacklist(backend.getId(), errMsg); } } } protected boolean clearCache(InternalService.PClearCacheRequest request, Backend backend, int timeoutMs, Status status) { TNetworkAddress address = new TNetworkAddress(backend.getHost(), backend.getBrpcPort()); try { request = request.toBuilder().setClearType(InternalService.PClearType.CLEAR_ALL).build(); LOG.info("clear all backend cache, backendId {}", backend.getId()); Future<InternalService.PCacheResponse> future = BackendServiceProxy.getInstance().clearCache(address, request); InternalService.PCacheResponse response = future.get(timeoutMs, TimeUnit.MILLISECONDS); if (response.getStatus() == InternalService.PCacheStatus.CACHE_OK) { status.updateStatus(TStatusCode.OK, "CACHE_OK"); return true; } else { status.updateStatus(TStatusCode.INTERNAL_ERROR, response.getStatus().toString()); return false; } } catch (Exception e) { LOG.warn("clear cache exception, backendId {}", backend.getId(), e); } return false; } }
apache/doris
fe/fe-core/src/main/java/org/apache/doris/qe/cache/CacheBeProxy.java
2,343
/******************************************************************************* * ___ _ ____ ____ * / _ \ _ _ ___ ___| |_| _ \| __ ) * | | | | | | |/ _ \/ __| __| | | | _ \ * | |_| | |_| | __/\__ \ |_| |_| | |_) | * \__\_\\__,_|\___||___/\__|____/|____/ * * Copyright (c) 2014-2019 Appsicle * Copyright (c) 2019-2024 QuestDB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package io.questdb; import io.questdb.cairo.*; import io.questdb.cairo.sql.SqlExecutionCircuitBreakerConfiguration; import io.questdb.cutlass.http.*; import io.questdb.cutlass.http.processors.JsonQueryProcessorConfiguration; import io.questdb.cutlass.http.processors.LineHttpProcessorConfiguration; import io.questdb.cutlass.http.processors.StaticContentProcessorConfiguration; import io.questdb.cutlass.json.JsonException; import io.questdb.cutlass.json.JsonLexer; import io.questdb.cutlass.line.*; import io.questdb.cutlass.line.tcp.LineTcpReceiverConfiguration; import io.questdb.cutlass.line.tcp.LineTcpReceiverConfigurationHelper; import io.questdb.cutlass.line.udp.LineUdpReceiverConfiguration; import io.questdb.cutlass.pgwire.PGWireConfiguration; import io.questdb.cutlass.text.CsvFileIndexer; import io.questdb.cutlass.text.TextConfiguration; import io.questdb.cutlass.text.types.InputFormatConfiguration; import io.questdb.log.Log; import io.questdb.metrics.MetricsConfiguration; import io.questdb.mp.WorkerPoolConfiguration; import io.questdb.network.*; import io.questdb.std.*; import io.questdb.std.datetime.DateFormat; import io.questdb.std.datetime.DateLocale; import io.questdb.std.datetime.DateLocaleFactory; import io.questdb.std.datetime.microtime.*; import io.questdb.std.datetime.millitime.DateFormatFactory; import io.questdb.std.datetime.millitime.Dates; import io.questdb.std.datetime.millitime.MillisecondClock; import io.questdb.std.datetime.millitime.MillisecondClockImpl; import io.questdb.std.str.Path; import io.questdb.std.str.StringSink; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.function.LongSupplier; import static io.questdb.PropServerConfiguration.JsonPropertyValueFormatter.str; public class PropServerConfiguration implements ServerConfiguration { public static final long COMMIT_INTERVAL_DEFAULT = 2000; public static final String CONFIG_DIRECTORY = "conf"; public static final String DB_DIRECTORY = "db"; public static final String SNAPSHOT_DIRECTORY = "snapshot"; public static final String TMP_DIRECTORY = "tmp"; private static final String RELEASE_TYPE = "release.type"; private static final String RELEASE_VERSION = "release.version"; private static final LowerCaseCharSequenceIntHashMap WRITE_FO_OPTS = new LowerCaseCharSequenceIntHashMap(); protected final byte httpHealthCheckAuthType; private final ObjObjHashMap<ConfigPropertyKey, ConfigPropertyValue> allPairs = new ObjObjHashMap<>(); private final boolean allowTableRegistrySharedWrite; private final DateFormat backupDirTimestampFormat; private final int backupMkdirMode; private final String backupRoot; private final CharSequence backupTempDirName; private final int binaryEncodingMaxLength; private final BuildInformation buildInformation; private final boolean cairoAttachPartitionCopy; private final String cairoAttachPartitionSuffix; private final CairoConfiguration cairoConfiguration = new PropCairoConfiguration(); private final int cairoGroupByMergeShardQueueCapacity; private final int cairoGroupByShardingThreshold; private final int cairoMaxCrashFiles; private final int cairoPageFrameReduceColumnListCapacity; private final int cairoPageFrameReduceQueueCapacity; private final int cairoPageFrameReduceRowIdListCapacity; private final int cairoPageFrameReduceShardCount; private final int cairoSQLCopyIdSupplier; private final int cairoSqlCopyLogRetentionDays; private final int cairoSqlCopyQueueCapacity; private final String cairoSqlCopyRoot; private final String cairoSqlCopyWorkRoot; private final long cairoTableRegistryAutoReloadFrequency; private final int cairoTableRegistryCompactionThreshold; private final PropSqlExecutionCircuitBreakerConfiguration circuitBreakerConfiguration = new PropSqlExecutionCircuitBreakerConfiguration(); private final int circuitBreakerThrottle; private final int columnIndexerQueueCapacity; private final int columnPurgeQueueCapacity; private final long columnPurgeRetryDelay; private final long columnPurgeRetryDelayLimit; private final double columnPurgeRetryDelayMultiplier; private final int columnPurgeTaskPoolCapacity; private final int commitMode; private final TimestampFormatCompiler compiler = new TimestampFormatCompiler(); private final String confRoot; private final int connectionPoolInitialCapacity; private final int connectionStringPoolCapacity; private final int createAsSelectRetryCount; private final int dateAdapterPoolCapacity; private final String dbDirectory; private final int defaultSeqPartTxnCount; private final boolean defaultSymbolCacheFlag; private final int defaultSymbolCapacity; private final int detachedMkdirMode; private final boolean enableTestFactories; private final int fileOperationRetryCount; private final FilesFacade filesFacade; private final FactoryProviderFactory fpf; private final boolean httpAllowDeflateBeforeSend; private final PropHttpContextConfiguration httpContextConfiguration = new PropHttpContextConfiguration(); private final int httpForceRecvFragmentationChunkSize; private final int httpForceSendFragmentationChunkSize; private final boolean httpFrozenClock; private final IODispatcherConfiguration httpIODispatcherConfiguration = new PropHttpIODispatcherConfiguration(); private final PropHttpMinIODispatcherConfiguration httpMinIODispatcherConfiguration = new PropHttpMinIODispatcherConfiguration(); private final boolean httpMinServerEnabled; private final boolean httpNetConnectionHint; private final boolean httpPessimisticHealthCheckEnabled; private final boolean httpReadOnlySecurityContext; private final int httpRecvBufferSize; private final int httpSendBufferSize; private final boolean httpServerCookiesEnabled; private final boolean httpServerEnabled; private final boolean httpServerKeepAlive; private final int httpSqlCacheBlockCount; private final boolean httpSqlCacheEnabled; private final int httpSqlCacheRowCount; private final WaitProcessorConfiguration httpWaitProcessorConfiguration = new PropWaitProcessorConfiguration(); private final int[] httpWorkerAffinity; private final int httpWorkerCount; private final boolean httpWorkerHaltOnError; private final long httpWorkerNapThreshold; private final long httpWorkerSleepThreshold; private final long httpWorkerSleepTimeout; private final long httpWorkerYieldThreshold; private final long idleCheckInterval; private final boolean ilpAutoCreateNewColumns; private final boolean ilpAutoCreateNewTables; private final int inactiveReaderMaxOpenPartitions; private final long inactiveReaderTTL; private final long inactiveWalWriterTTL; private final long inactiveWriterTTL; private final CharSequence indexFileName; private final int indexValueBlockSize; private final InputFormatConfiguration inputFormatConfiguration; private final long instanceHashHi; private final long instanceHashLo; private final boolean interruptOnClosedConnection; private final boolean ioURingEnabled; private final boolean isReadOnlyInstance; private final int jsonCacheLimit; private final int jsonCacheSize; private final String keepAliveHeader; private final int latestByQueueCapacity; private final boolean lineHttpEnabled; private final CharSequence lineHttpPingVersion; private final LineHttpProcessorConfiguration lineHttpProcessorConfiguration = new PropLineHttpProcessorConfiguration(); private final String lineTcpAuthDB; private final boolean lineTcpEnabled; private final WorkerPoolConfiguration lineTcpIOWorkerPoolConfiguration = new PropLineTcpIOWorkerPoolConfiguration(); private final LineTcpReceiverConfiguration lineTcpReceiverConfiguration = new PropLineTcpReceiverConfiguration(); private final IODispatcherConfiguration lineTcpReceiverDispatcherConfiguration = new PropLineTcpReceiverIODispatcherConfiguration(); private final WorkerPoolConfiguration lineTcpWriterWorkerPoolConfiguration = new PropLineTcpWriterWorkerPoolConfiguration(); private final int lineUdpCommitMode; private final int lineUdpCommitRate; private final boolean lineUdpEnabled; private final int lineUdpGroupIPv4Address; private final int lineUdpMsgBufferSize; private final int lineUdpMsgCount; private final boolean lineUdpOwnThread; private final int lineUdpOwnThreadAffinity; private final int lineUdpReceiveBufferSize; private final LineUdpReceiverConfiguration lineUdpReceiverConfiguration = new PropLineUdpReceiverConfiguration(); private final LineTimestampAdapter lineUdpTimestampAdapter; private final boolean lineUdpUnicast; private final DateLocale locale; private final Log log; private final int maxFileNameLength; private final long maxHttpQueryResponseRowLimit; private final double maxRequiredDelimiterStdDev; private final double maxRequiredLineLengthStdDev; private final long maxRerunWaitCapMs; private final int maxSqlRecompileAttempts; private final int maxSwapFileCount; private final int maxUncommittedRows; private final int metadataStringPoolCapacity; private final MetricsConfiguration metricsConfiguration = new PropMetricsConfiguration(); private final boolean metricsEnabled; private final MicrosecondClock microsecondClock; private final int mkdirMode; private final int multipartHeaderBufferSize; private final long multipartIdleSpinCount; private final int o3CallbackQueueCapacity; private final int o3ColumnMemorySize; private final int o3CopyQueueCapacity; private final int o3LagCalculationWindowsSize; private final int o3LastPartitionMaxSplits; private final long o3MaxLag; private final long o3MinLagUs; private final int o3OpenColumnQueueCapacity; private final int o3PartitionPurgeListCapacity; private final int o3PartitionQueueCapacity; private final long o3PartitionSplitMinSize; private final int o3PurgeDiscoveryQueueCapacity; private final boolean o3QuickSortEnabled; private final int parallelIndexThreshold; private final boolean parallelIndexingEnabled; private final boolean pgEnabled; private final PGWireConfiguration pgWireConfiguration = new PropPGWireConfiguration(); private final PropPGWireDispatcherConfiguration propPGWireDispatcherConfiguration = new PropPGWireDispatcherConfiguration(); private final String publicDirectory; private final long queryTimeout; private final int readerPoolMaxSegments; private final int repeatMigrationFromVersion; private final int requestHeaderBufferSize; private final double rerunExponentialWaitMultiplier; private final int rerunInitialWaitQueueSize; private final int rerunMaxProcessingQueueSize; private final int rndFunctionMemoryMaxPages; private final int rndFunctionMemoryPageSize; private final int rollBufferLimit; private final int rollBufferSize; private final String root; private final int[] sharedWorkerAffinity; private final int sharedWorkerCount; private final boolean sharedWorkerHaltOnError; private final long sharedWorkerNapThreshold; private final WorkerPoolConfiguration sharedWorkerPoolConfiguration = new PropWorkerPoolConfiguration(); private final long sharedWorkerSleepThreshold; private final long sharedWorkerSleepTimeout; private final long sharedWorkerYieldThreshold; private final boolean simulateCrashEnabled; private final String snapshotInstanceId; private final boolean snapshotRecoveryEnabled; private final String snapshotRoot; private final long spinLockTimeout; private final int sqlAsOfJoinLookahead; private final int sqlBindVariablePoolSize; private final int sqlCharacterStoreCapacity; private final int sqlCharacterStoreSequencePoolCapacity; private final int sqlColumnCastModelPoolCapacity; private final int sqlColumnPoolCapacity; private final int sqlCompilerPoolCapacity; private final int sqlCopyBufferSize; private final int sqlCopyModelPoolCapacity; private final int sqlCountDistinctCapacity; private final double sqlCountDistinctLoadFactor; private final long sqlCreateTableModelBatchSize; private final int sqlCreateTableModelPoolCapacity; private final int sqlDistinctTimestampKeyCapacity; private final double sqlDistinctTimestampLoadFactor; private final int sqlDoubleToStrCastScale; private final int sqlExplainModelPoolCapacity; private final int sqlExpressionPoolCapacity; private final double sqlFastMapLoadFactor; private final int sqlFloatToStrCastScale; private final long sqlGroupByAllocatorChunkSize; private final long sqlGroupByAllocatorMaxChunkSize; private final int sqlGroupByMapCapacity; private final int sqlGroupByPoolCapacity; private final int sqlHashJoinLightValueMaxPages; private final int sqlHashJoinLightValuePageSize; private final int sqlHashJoinValueMaxPages; private final int sqlHashJoinValuePageSize; private final long sqlInsertModelBatchSize; private final int sqlInsertModelPoolCapacity; private final int sqlJitBindVarsMemoryMaxPages; private final int sqlJitBindVarsMemoryPageSize; private final boolean sqlJitDebugEnabled; private final int sqlJitIRMemoryMaxPages; private final int sqlJitIRMemoryPageSize; private final int sqlJitMode; private final int sqlJitPageAddressCacheThreshold; private final int sqlJoinContextPoolCapacity; private final int sqlJoinMetadataMaxResizes; private final int sqlJoinMetadataPageSize; private final long sqlLatestByRowCount; private final int sqlLexerPoolCapacity; private final int sqlMapMaxPages; private final int sqlMapMaxResizes; private final int sqlMaxNegativeLimit; private final int sqlMaxSymbolNotEqualsCount; private final int sqlModelPoolCapacity; private final int sqlPageFrameMaxRows; private final int sqlPageFrameMinRows; private final boolean sqlParallelFilterEnabled; private final boolean sqlParallelFilterPreTouchEnabled; private final boolean sqlParallelGroupByEnabled; private final int sqlQueryRegistryPoolSize; private final int sqlRenameTableModelPoolCapacity; private final boolean sqlSampleByDefaultAlignment; private final int sqlSampleByIndexSearchPageSize; private final int sqlSmallMapKeyCapacity; private final int sqlSmallMapPageSize; private final int sqlSortKeyMaxPages; private final long sqlSortKeyPageSize; private final int sqlSortLightValueMaxPages; private final long sqlSortLightValuePageSize; private final int sqlSortValueMaxPages; private final int sqlSortValuePageSize; private final int sqlStrFunctionBufferMaxSize; private final int sqlTxnScoreboardEntryCount; private final int sqlUnorderedMapMaxEntrySize; private final int sqlWindowColumnPoolCapacity; private final int sqlWindowInitialRangeBufferSize; private final int sqlWindowMaxRecursion; private final int sqlWindowRowIdMaxPages; private final int sqlWindowRowIdPageSize; private final int sqlWindowStoreMaxPages; private final int sqlWindowStorePageSize; private final int sqlWindowTreeKeyMaxPages; private final int sqlWindowTreeKeyPageSize; private final int sqlWithClauseModelPoolCapacity; private final int systemO3ColumnMemorySize; private final String systemTableNamePrefix; private final long systemWalWriterDataAppendPageSize; private final long systemWalWriterEventAppendPageSize; private final long systemWriterDataAppendPageSize; private final boolean tableTypeConversionEnabled; private final TelemetryConfiguration telemetryConfiguration = new PropTelemetryConfiguration(); private final boolean telemetryDisableCompletely; private final boolean telemetryEnabled; private final boolean telemetryHideTables; private final int telemetryQueueCapacity; private final CharSequence tempRenamePendingTablePrefix; private final int textAnalysisMaxLines; private final TextConfiguration textConfiguration = new PropTextConfiguration(); private final int textLexerStringPoolCapacity; private final int timestampAdapterPoolCapacity; private final boolean useLegacyStringDefault; private final int utf8SinkSize; private final PropertyValidator validator; private final int vectorAggregateQueueCapacity; private final VolumeDefinitions volumeDefinitions = new VolumeDefinitions(); private final boolean walApplyEnabled; private final int walApplyLookAheadTransactionCount; private final WorkerPoolConfiguration walApplyPoolConfiguration = new PropWalApplyPoolConfiguration(); private final long walApplySleepTimeout; private final long walApplyTableTimeQuota; private final int[] walApplyWorkerAffinity; private final int walApplyWorkerCount; private final boolean walApplyWorkerHaltOnError; private final long walApplyWorkerNapThreshold; private final long walApplyWorkerSleepThreshold; private final long walApplyWorkerYieldThreshold; private final boolean walEnabledDefault; private final long walMaxLagSize; private final int walMaxLagTxnCount; private final int walMaxSegmentFileDescriptorsCache; private final long walPurgeInterval; private final int walPurgeWaitBeforeDelete; private final int walRecreateDistressedSequencerAttempts; private final long walSegmentRolloverRowCount; private final double walSquashUncommittedRowsMultiplier; private final boolean walSupported; private final int walTxnNotificationQueueCapacity; private final long walWriterDataAppendPageSize; private final long walWriterEventAppendPageSize; private final int walWriterPoolMaxSegments; private final long workStealTimeoutNanos; private final long writerAsyncCommandBusyWaitTimeout; private final long writerAsyncCommandMaxWaitTimeout; private final int writerAsyncCommandQueueCapacity; private final long writerAsyncCommandQueueSlotSize; private final long writerDataAppendPageSize; private final long writerDataIndexKeyAppendPageSize; private final long writerDataIndexValueAppendPageSize; private final long writerFileOpenOpts; private final long writerMemoryLimit; private final long writerMiscAppendPageSize; private final boolean writerMixedIOEnabled; private final int writerTickRowsCountMod; protected HttpMinServerConfiguration httpMinServerConfiguration = new PropHttpMinServerConfiguration(); protected HttpServerConfiguration httpServerConfiguration = new PropHttpServerConfiguration(); protected JsonQueryProcessorConfiguration jsonQueryProcessorConfiguration = new PropJsonQueryProcessorConfiguration(); protected StaticContentProcessorConfiguration staticContentProcessorConfiguration; protected long walSegmentRolloverSize; private long cairoSqlCopyMaxIndexChunkSize; private FactoryProvider factoryProvider; private short floatDefaultColumnType; private int httpMinBindIPv4Address; private int httpMinBindPort; private boolean httpMinNetConnectionHint; private int httpMinNetConnectionLimit; private long httpMinNetConnectionQueueTimeout; private int httpMinNetConnectionRcvBuf; private int httpMinNetConnectionSndBuf; private long httpMinNetConnectionTimeout; private int[] httpMinWorkerAffinity; private int httpMinWorkerCount; private boolean httpMinWorkerHaltOnError; private long httpMinWorkerNapThreshold; private long httpMinWorkerSleepThreshold; private long httpMinWorkerSleepTimeout; private long httpMinWorkerYieldThreshold; private int httpNetBindIPv4Address; private int httpNetBindPort; private int httpNetConnectionLimit; private long httpNetConnectionQueueTimeout; private int httpNetConnectionRcvBuf; private int httpNetConnectionSndBuf; private long httpNetConnectionTimeout; private String httpVersion; private short integerDefaultColumnType; private int jsonQueryConnectionCheckFrequency; private int jsonQueryDoubleScale; private int jsonQueryFloatScale; private long lineTcpCommitIntervalDefault; private double lineTcpCommitIntervalFraction; private int lineTcpConnectionPoolInitialCapacity; private int lineTcpDefaultPartitionBy; private boolean lineTcpDisconnectOnError; private int[] lineTcpIOWorkerAffinity; private int lineTcpIOWorkerCount; private long lineTcpIOWorkerNapThreshold; private boolean lineTcpIOWorkerPoolHaltOnError; private long lineTcpIOWorkerSleepThreshold; private long lineTcpIOWorkerYieldThreshold; private long lineTcpMaintenanceInterval; private int lineTcpMaxMeasurementSize; private int lineTcpMsgBufferSize; private int lineTcpNetBindIPv4Address; private int lineTcpNetBindPort; private long lineTcpNetConnectionHeartbeatInterval; private boolean lineTcpNetConnectionHint; private int lineTcpNetConnectionLimit; private long lineTcpNetConnectionQueueTimeout; private int lineTcpNetConnectionRcvBuf; private long lineTcpNetConnectionTimeout; private LineTcpTimestampAdapter lineTcpTimestampAdapter; private int lineTcpWriterQueueCapacity; private int[] lineTcpWriterWorkerAffinity; private int lineTcpWriterWorkerCount; private long lineTcpWriterWorkerNapThreshold; private boolean lineTcpWriterWorkerPoolHaltOnError; private long lineTcpWriterWorkerSleepThreshold; private long lineTcpWriterWorkerYieldThreshold; private int lineUdpBindIPV4Address; private int lineUdpDefaultPartitionBy; private int lineUdpPort; private MimeTypesCache mimeTypesCache; private long minIdleMsBeforeWriterRelease; private int netTestConnectionBufferSize; private int pgBinaryParamsCapacity; private int pgCharacterStoreCapacity; private int pgCharacterStorePoolCapacity; private int pgConnectionPoolInitialCapacity; private boolean pgDaemonPool; private DateLocale pgDefaultLocale; private int pgForceRecvFragmentationChunkSize; private int pgForceSendFragmentationChunkSize; private boolean pgHaltOnError; private int pgInsertCacheBlockCount; private boolean pgInsertCacheEnabled; private int pgInsertCacheRowCount; private int pgMaxBlobSizeOnQuery; private int pgNamedStatementCacheCapacity; private int pgNamesStatementPoolCapacity; private int pgNetBindIPv4Address; private int pgNetBindPort; private boolean pgNetConnectionHint; private int pgNetConnectionLimit; private long pgNetConnectionQueueTimeout; private int pgNetConnectionRcvBuf; private int pgNetConnectionSndBuf; private long pgNetIdleConnectionTimeout; private String pgPassword; private int pgPendingWritersCacheCapacity; private String pgReadOnlyPassword; private boolean pgReadOnlySecurityContext; private boolean pgReadOnlyUserEnabled; private String pgReadOnlyUsername; private int pgRecvBufferSize; private int pgSelectCacheBlockCount; private boolean pgSelectCacheEnabled; private int pgSelectCacheRowCount; private int pgSendBufferSize; private int pgUpdateCacheBlockCount; private boolean pgUpdateCacheEnabled; private int pgUpdateCacheRowCount; private String pgUsername; private int[] pgWorkerAffinity; private int pgWorkerCount; private long pgWorkerNapThreshold; private long pgWorkerSleepThreshold; private long pgWorkerYieldThreshold; private final long sequencerCheckInterval; private boolean stringToCharCastAllowed; private long symbolCacheWaitUsBeforeReload; public PropServerConfiguration( String root, Properties properties, @Nullable Map<String, String> env, Log log, final BuildInformation buildInformation ) throws ServerConfigurationException, JsonException { this( root, properties, env, log, buildInformation, FilesFacadeImpl.INSTANCE, MicrosecondClockImpl.INSTANCE, (configuration, engine, freeOnExitList) -> DefaultFactoryProvider.INSTANCE, true ); } public PropServerConfiguration( String root, Properties properties, @Nullable Map<String, String> env, Log log, final BuildInformation buildInformation, FilesFacade filesFacade, MicrosecondClock microsecondClock, FactoryProviderFactory fpf ) throws ServerConfigurationException, JsonException { this( root, properties, env, log, buildInformation, filesFacade, microsecondClock, fpf, true ); } public PropServerConfiguration( String root, Properties properties, @Nullable Map<String, String> env, Log log, final BuildInformation buildInformation, FilesFacade filesFacade, MicrosecondClock microsecondClock, FactoryProviderFactory fpf, boolean loadAdditionalConfigurations ) throws ServerConfigurationException, JsonException { this.log = log; this.filesFacade = filesFacade; this.fpf = fpf; this.microsecondClock = microsecondClock; this.validator = newValidator(); this.staticContentProcessorConfiguration = new PropStaticContentProcessorConfiguration(); boolean configValidationStrict = getBoolean(properties, env, PropertyKey.CONFIG_VALIDATION_STRICT, false); validateProperties(properties, configValidationStrict); this.writerMemoryLimit = getLongSize(properties, env, PropertyKey.WRITER_MEMORY_LIMIT, 0); this.isReadOnlyInstance = getBoolean(properties, env, PropertyKey.READ_ONLY_INSTANCE, false); this.cairoTableRegistryAutoReloadFrequency = getLong(properties, env, PropertyKey.CAIRO_TABLE_REGISTRY_AUTO_RELOAD_FREQUENCY, 500); this.cairoTableRegistryCompactionThreshold = getInt(properties, env, PropertyKey.CAIRO_TABLE_REGISTRY_COMPACTION_THRESHOLD, 30); this.repeatMigrationFromVersion = getInt(properties, env, PropertyKey.CAIRO_REPEAT_MIGRATION_FROM_VERSION, 426); this.mkdirMode = getInt(properties, env, PropertyKey.CAIRO_MKDIR_MODE, 509); this.maxFileNameLength = getInt(properties, env, PropertyKey.CAIRO_MAX_FILE_NAME_LENGTH, 127); // changing the default value of walEnabledDefault to true would mean that QuestDB instances upgraded from // a pre-WAL version suddenly would start to create WAL tables by default, this could come as a surprise to users // instead cairo.wal.enabled.default=true is added to the config, so only new QuestDB installations have WAL enabled by default this.walEnabledDefault = getBoolean(properties, env, PropertyKey.CAIRO_WAL_ENABLED_DEFAULT, true); this.walPurgeInterval = getLong(properties, env, PropertyKey.CAIRO_WAL_PURGE_INTERVAL, 30_000); this.walPurgeWaitBeforeDelete = getInt(properties, env, PropertyKey.DEBUG_WAL_PURGE_WAIT_BEFORE_DELETE, 0); this.walTxnNotificationQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_WAL_TXN_NOTIFICATION_QUEUE_CAPACITY, 4096); this.walRecreateDistressedSequencerAttempts = getInt(properties, env, PropertyKey.CAIRO_WAL_RECREATE_DISTRESSED_SEQUENCER_ATTEMPTS, 3); this.walSupported = getBoolean(properties, env, PropertyKey.CAIRO_WAL_SUPPORTED, true); walApplyEnabled = getBoolean(properties, env, PropertyKey.CAIRO_WAL_APPLY_ENABLED, true); this.walSegmentRolloverRowCount = getLong(properties, env, PropertyKey.CAIRO_WAL_SEGMENT_ROLLOVER_ROW_COUNT, 200_000); this.walSegmentRolloverSize = getLong(properties, env, PropertyKey.CAIRO_WAL_SEGMENT_ROLLOVER_SIZE, 0); // disabled by default. if ((this.walSegmentRolloverSize != 0) && (this.walSegmentRolloverSize < 1024)) { // 1KiB segments minimum throw CairoException.critical(0).put("cairo.wal.segment.rollover.size must be 0 (disabled) or >= 1024 (1KiB)"); } this.walWriterDataAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_WAL_WRITER_DATA_APPEND_PAGE_SIZE, Numbers.SIZE_1MB)); this.walWriterEventAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_WAL_WRITER_EVENT_APPEND_PAGE_SIZE, 128 * 1024)); this.systemWalWriterDataAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_SYSTEM_WAL_WRITER_DATA_APPEND_PAGE_SIZE, 256 * 1024)); this.systemWalWriterEventAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_SYSTEM_WAL_WRITER_EVENT_APPEND_PAGE_SIZE, 16 * 1024)); this.walSquashUncommittedRowsMultiplier = getDouble(properties, env, PropertyKey.CAIRO_WAL_SQUASH_UNCOMMITTED_ROWS_MULTIPLIER, "20.0"); this.walMaxLagTxnCount = getInt(properties, env, PropertyKey.CAIRO_WAL_MAX_LAG_TXN_COUNT, -1); this.walMaxLagSize = getLongSize(properties, env, PropertyKey.CAIRO_WAL_MAX_LAG_SIZE, 75 * Numbers.SIZE_1MB); this.walMaxSegmentFileDescriptorsCache = getInt(properties, env, PropertyKey.CAIRO_WAL_MAX_SEGMENT_FILE_DESCRIPTORS_CACHE, 30); this.walApplyTableTimeQuota = getLong(properties, env, PropertyKey.CAIRO_WAL_APPLY_TABLE_TIME_QUOTA, 1000); this.walApplyLookAheadTransactionCount = getInt(properties, env, PropertyKey.CAIRO_WAL_APPLY_LOOK_AHEAD_TXN_COUNT, 20); this.tableTypeConversionEnabled = getBoolean(properties, env, PropertyKey.TABLE_TYPE_CONVERSION_ENABLED, true); this.tempRenamePendingTablePrefix = getString(properties, env, PropertyKey.CAIRO_WAL_TEMP_PENDING_RENAME_TABLE_PREFIX, "temp_5822f658-31f6-11ee-be56-0242ac120002"); this.sequencerCheckInterval = getLong(properties, env, PropertyKey.CAIRO_WAL_SEQUENCER_CHECK_INTERVAL, 10_000); if (tempRenamePendingTablePrefix.length() > maxFileNameLength - 4) { throw CairoException.critical(0).put("Temp pending table prefix is too long [") .put(PropertyKey.CAIRO_MAX_FILE_NAME_LENGTH.toString()).put("=") .put(maxFileNameLength).put(", ") .put(PropertyKey.CAIRO_WAL_TEMP_PENDING_RENAME_TABLE_PREFIX.toString()).put("=") .put(tempRenamePendingTablePrefix).put(']'); } if (!TableUtils.isValidTableName(tempRenamePendingTablePrefix, maxFileNameLength)) { throw CairoException.critical(0).put("Invalid temp pending table prefix [") .put(PropertyKey.CAIRO_WAL_TEMP_PENDING_RENAME_TABLE_PREFIX.toString()).put("=") .put(tempRenamePendingTablePrefix).put(']'); } this.dbDirectory = getString(properties, env, PropertyKey.CAIRO_ROOT, DB_DIRECTORY); String tmpRoot; if (new File(this.dbDirectory).isAbsolute()) { this.root = this.dbDirectory; this.confRoot = rootSubdir(this.root, CONFIG_DIRECTORY); // ../conf this.snapshotRoot = rootSubdir(this.root, SNAPSHOT_DIRECTORY); // ../snapshot tmpRoot = rootSubdir(this.root, TMP_DIRECTORY); // ../tmp } else { this.root = new File(root, this.dbDirectory).getAbsolutePath(); this.confRoot = new File(root, CONFIG_DIRECTORY).getAbsolutePath(); this.snapshotRoot = new File(root, SNAPSHOT_DIRECTORY).getAbsolutePath(); tmpRoot = new File(root, TMP_DIRECTORY).getAbsolutePath(); } this.cairoAttachPartitionSuffix = getString(properties, env, PropertyKey.CAIRO_ATTACH_PARTITION_SUFFIX, TableUtils.ATTACHABLE_DIR_MARKER); this.cairoAttachPartitionCopy = getBoolean(properties, env, PropertyKey.CAIRO_ATTACH_PARTITION_COPY, false); this.snapshotInstanceId = getString(properties, env, PropertyKey.CAIRO_SNAPSHOT_INSTANCE_ID, ""); this.snapshotRecoveryEnabled = getBoolean(properties, env, PropertyKey.CAIRO_SNAPSHOT_RECOVERY_ENABLED, true); this.simulateCrashEnabled = getBoolean(properties, env, PropertyKey.CAIRO_SIMULATE_CRASH_ENABLED, false); int cpuAvailable = Runtime.getRuntime().availableProcessors(); int cpuUsed = 0; int cpuSpare = 0; int cpuIoWorkers = 0; int cpuWalApplyWorkers = 2; if (cpuAvailable > 8) { cpuWalApplyWorkers = 3; } else if (cpuAvailable > 16) { cpuWalApplyWorkers = 4; cpuSpare = 1; // tested on 4/32/48 core servers cpuIoWorkers = cpuAvailable / 2; } else if (cpuAvailable > 32) { cpuWalApplyWorkers = 4; cpuSpare = 2; // tested on 4/32/48 core servers cpuIoWorkers = cpuAvailable / 2; } final FilesFacade ff = cairoConfiguration.getFilesFacade(); try (Path path = new Path()) { volumeDefinitions.of(getString(properties, env, PropertyKey.CAIRO_VOLUMES, null), path, root); ff.mkdirs(path.of(this.root).slash$(), this.mkdirMode); path.of(this.root).concat(TableUtils.TAB_INDEX_FILE_NAME).$(); final int tableIndexFd = TableUtils.openFileRWOrFail(ff, path, CairoConfiguration.O_NONE); final long fileSize = ff.length(tableIndexFd); if (fileSize < Long.BYTES) { if (!ff.allocate(tableIndexFd, Files.PAGE_SIZE)) { ff.close(tableIndexFd); throw CairoException.critical(ff.errno()).put("Could not allocate [file=").put(path).put(", actual=").put(fileSize).put(", desired=").put(Files.PAGE_SIZE).put(']'); } } final long tableIndexMem = TableUtils.mapRWOrClose(ff, tableIndexFd, Files.PAGE_SIZE, MemoryTag.MMAP_DEFAULT); Rnd rnd = new Rnd(cairoConfiguration.getMicrosecondClock().getTicks(), cairoConfiguration.getMillisecondClock().getTicks()); if (Os.compareAndSwap(tableIndexMem + Long.BYTES, 0, rnd.nextLong()) == 0) { Unsafe.getUnsafe().putLong(tableIndexMem + Long.BYTES * 2, rnd.nextLong()); } this.instanceHashLo = Unsafe.getUnsafe().getLong(tableIndexMem + Long.BYTES); this.instanceHashHi = Unsafe.getUnsafe().getLong(tableIndexMem + Long.BYTES * 2); ff.munmap(tableIndexMem, Files.PAGE_SIZE, MemoryTag.MMAP_DEFAULT); ff.close(tableIndexFd); this.httpMinServerEnabled = getBoolean(properties, env, PropertyKey.HTTP_MIN_ENABLED, true); if (httpMinServerEnabled) { this.httpMinWorkerHaltOnError = getBoolean(properties, env, PropertyKey.HTTP_MIN_WORKER_HALT_ON_ERROR, false); this.httpMinWorkerCount = getInt(properties, env, PropertyKey.HTTP_MIN_WORKER_COUNT, 1); this.httpMinWorkerAffinity = getAffinity(properties, env, PropertyKey.HTTP_MIN_WORKER_AFFINITY, httpMinWorkerCount); this.httpMinWorkerYieldThreshold = getLong(properties, env, PropertyKey.HTTP_MIN_WORKER_YIELD_THRESHOLD, 10); this.httpMinWorkerNapThreshold = getLong(properties, env, PropertyKey.HTTP_MIN_WORKER_NAP_THRESHOLD, 100); this.httpMinWorkerSleepThreshold = getLong(properties, env, PropertyKey.HTTP_MIN_WORKER_SLEEP_THRESHOLD, 100); this.httpMinWorkerSleepTimeout = getLong(properties, env, PropertyKey.HTTP_MIN_WORKER_SLEEP_TIMEOUT, 50); // deprecated String httpMinBindTo = getString(properties, env, PropertyKey.HTTP_MIN_BIND_TO, "0.0.0.0:9003"); parseBindTo(properties, env, PropertyKey.HTTP_MIN_NET_BIND_TO, httpMinBindTo, (a, p) -> { httpMinBindIPv4Address = a; httpMinBindPort = p; }); this.httpMinNetConnectionLimit = getInt(properties, env, PropertyKey.HTTP_MIN_NET_CONNECTION_LIMIT, 4); // deprecated this.httpMinNetConnectionTimeout = getLong(properties, env, PropertyKey.HTTP_MIN_NET_IDLE_CONNECTION_TIMEOUT, 5 * 60 * 1000L); this.httpMinNetConnectionTimeout = getLong(properties, env, PropertyKey.HTTP_MIN_NET_CONNECTION_TIMEOUT, this.httpMinNetConnectionTimeout); // deprecated this.httpMinNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.HTTP_MIN_NET_QUEUED_CONNECTION_TIMEOUT, 5 * 1000L); this.httpMinNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.HTTP_MIN_NET_CONNECTION_QUEUE_TIMEOUT, this.httpMinNetConnectionQueueTimeout); // deprecated this.httpMinNetConnectionSndBuf = getIntSize(properties, env, PropertyKey.HTTP_MIN_NET_SND_BUF_SIZE, 1024); this.httpMinNetConnectionSndBuf = getIntSize(properties, env, PropertyKey.HTTP_MIN_NET_CONNECTION_SNDBUF, this.httpMinNetConnectionSndBuf); // deprecated this.httpMinNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.HTTP_NET_RCV_BUF_SIZE, 1024); this.httpMinNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.HTTP_MIN_NET_CONNECTION_RCVBUF, this.httpMinNetConnectionRcvBuf); this.httpMinNetConnectionHint = getBoolean(properties, env, PropertyKey.HTTP_MIN_NET_CONNECTION_HINT, false); } this.httpRecvBufferSize = getIntSize(properties, env, PropertyKey.HTTP_RECEIVE_BUFFER_SIZE, Numbers.SIZE_1MB); this.requestHeaderBufferSize = getIntSize(properties, env, PropertyKey.HTTP_REQUEST_HEADER_BUFFER_SIZE, 32 * 2014); this.httpSendBufferSize = getIntSize(properties, env, PropertyKey.HTTP_SEND_BUFFER_SIZE, 2 * Numbers.SIZE_1MB); if (httpSendBufferSize < HttpServerConfiguration.MIN_SEND_BUFFER_SIZE) { throw new ServerConfigurationException("invalid configuration value [key=" + PropertyKey.HTTP_SEND_BUFFER_SIZE.getPropertyPath() + ", description=http response send buffer should be at least " + HttpServerConfiguration.MIN_SEND_BUFFER_SIZE + " bytes]"); } this.httpServerEnabled = getBoolean(properties, env, PropertyKey.HTTP_ENABLED, true); this.connectionStringPoolCapacity = getInt(properties, env, PropertyKey.HTTP_CONNECTION_STRING_POOL_CAPACITY, 128); this.connectionPoolInitialCapacity = getInt(properties, env, PropertyKey.HTTP_CONNECTION_POOL_INITIAL_CAPACITY, 4); this.multipartHeaderBufferSize = getIntSize(properties, env, PropertyKey.HTTP_MULTIPART_HEADER_BUFFER_SIZE, 512); this.multipartIdleSpinCount = getLong(properties, env, PropertyKey.HTTP_MULTIPART_IDLE_SPIN_COUNT, 10_000); this.httpWorkerCount = getInt(properties, env, PropertyKey.HTTP_WORKER_COUNT, 0); cpuUsed += this.httpWorkerCount; this.httpWorkerAffinity = getAffinity(properties, env, PropertyKey.HTTP_WORKER_AFFINITY, httpWorkerCount); this.httpWorkerHaltOnError = getBoolean(properties, env, PropertyKey.HTTP_WORKER_HALT_ON_ERROR, false); this.httpWorkerYieldThreshold = getLong(properties, env, PropertyKey.HTTP_WORKER_YIELD_THRESHOLD, 10); this.httpWorkerNapThreshold = getLong(properties, env, PropertyKey.HTTP_WORKER_NAP_THRESHOLD, 7_000); this.httpWorkerSleepThreshold = getLong(properties, env, PropertyKey.HTTP_WORKER_SLEEP_THRESHOLD, 10_000); this.httpWorkerSleepTimeout = getLong(properties, env, PropertyKey.HTTP_WORKER_SLEEP_TIMEOUT, 10); this.indexFileName = getString(properties, env, PropertyKey.HTTP_STATIC_INDEX_FILE_NAME, "index.html"); this.httpFrozenClock = getBoolean(properties, env, PropertyKey.HTTP_FROZEN_CLOCK, false); this.httpAllowDeflateBeforeSend = getBoolean(properties, env, PropertyKey.HTTP_ALLOW_DEFLATE_BEFORE_SEND, false); this.httpServerKeepAlive = getBoolean(properties, env, PropertyKey.HTTP_SERVER_KEEP_ALIVE, true); this.httpServerCookiesEnabled = getBoolean(properties, env, PropertyKey.HTTP_SERVER_KEEP_ALIVE, true); this.httpVersion = getString(properties, env, PropertyKey.HTTP_VERSION, "HTTP/1.1"); if (!httpVersion.endsWith(" ")) { httpVersion += ' '; } int keepAliveTimeout = getInt(properties, env, PropertyKey.HTTP_KEEP_ALIVE_TIMEOUT, 5); int keepAliveMax = getInt(properties, env, PropertyKey.HTTP_KEEP_ALIVE_MAX, 10_000); if (keepAliveTimeout > 0 && keepAliveMax > 0) { this.keepAliveHeader = "Keep-Alive: timeout=" + keepAliveTimeout + ", max=" + keepAliveMax + Misc.EOL; } else { this.keepAliveHeader = null; } final String publicDirectory = getString(properties, env, PropertyKey.HTTP_STATIC_PUBLIC_DIRECTORY, "public"); // translate public directory into absolute path // this will generate some garbage, but this is ok - we're just doing this once on startup if (new File(publicDirectory).isAbsolute()) { this.publicDirectory = publicDirectory; } else { this.publicDirectory = new File(root, publicDirectory).getAbsolutePath(); } this.defaultSeqPartTxnCount = getInt(properties, env, PropertyKey.CAIRO_DEFAULT_SEQ_PART_TXN_COUNT, 0); // maintain deprecated property name for the time being this.httpNetConnectionLimit = getInt(properties, env, PropertyKey.HTTP_NET_ACTIVE_CONNECTION_LIMIT, 256); this.httpNetConnectionLimit = getInt(properties, env, PropertyKey.HTTP_NET_CONNECTION_LIMIT, this.httpNetConnectionLimit); this.httpNetConnectionHint = getBoolean(properties, env, PropertyKey.HTTP_NET_CONNECTION_HINT, false); // deprecated this.httpNetConnectionTimeout = getLong(properties, env, PropertyKey.HTTP_NET_IDLE_CONNECTION_TIMEOUT, 5 * 60 * 1000L); this.httpNetConnectionTimeout = getLong(properties, env, PropertyKey.HTTP_NET_CONNECTION_TIMEOUT, this.httpNetConnectionTimeout); // deprecated this.httpNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.HTTP_NET_QUEUED_CONNECTION_TIMEOUT, 5 * 1000L); this.httpNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.HTTP_NET_CONNECTION_QUEUE_TIMEOUT, this.httpNetConnectionQueueTimeout); // deprecated this.httpNetConnectionSndBuf = getIntSize(properties, env, PropertyKey.HTTP_NET_SND_BUF_SIZE, 2 * Numbers.SIZE_1MB); this.httpNetConnectionSndBuf = getIntSize(properties, env, PropertyKey.HTTP_NET_CONNECTION_SNDBUF, this.httpNetConnectionSndBuf); // deprecated this.httpNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.HTTP_NET_RCV_BUF_SIZE, 2 * Numbers.SIZE_1MB); this.httpNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.HTTP_NET_CONNECTION_RCVBUF, this.httpNetConnectionRcvBuf); this.dateAdapterPoolCapacity = getInt(properties, env, PropertyKey.HTTP_TEXT_DATE_ADAPTER_POOL_CAPACITY, 16); this.jsonCacheLimit = getIntSize(properties, env, PropertyKey.HTTP_TEXT_JSON_CACHE_LIMIT, 16384); this.jsonCacheSize = getIntSize(properties, env, PropertyKey.HTTP_TEXT_JSON_CACHE_SIZE, 8192); this.maxRequiredDelimiterStdDev = getDouble(properties, env, PropertyKey.HTTP_TEXT_MAX_REQUIRED_DELIMITER_STDDEV, "0.1222"); this.maxRequiredLineLengthStdDev = getDouble(properties, env, PropertyKey.HTTP_TEXT_MAX_REQUIRED_LINE_LENGTH_STDDEV, "0.8"); this.metadataStringPoolCapacity = getInt(properties, env, PropertyKey.HTTP_TEXT_METADATA_STRING_POOL_CAPACITY, 128); this.rollBufferLimit = getIntSize(properties, env, PropertyKey.HTTP_TEXT_ROLL_BUFFER_LIMIT, 1024 * 4096); this.rollBufferSize = getIntSize(properties, env, PropertyKey.HTTP_TEXT_ROLL_BUFFER_SIZE, 1024); this.textAnalysisMaxLines = getInt(properties, env, PropertyKey.HTTP_TEXT_ANALYSIS_MAX_LINES, 1000); this.textLexerStringPoolCapacity = getInt(properties, env, PropertyKey.HTTP_TEXT_LEXER_STRING_POOL_CAPACITY, 64); this.timestampAdapterPoolCapacity = getInt(properties, env, PropertyKey.HTTP_TEXT_TIMESTAMP_ADAPTER_POOL_CAPACITY, 64); this.utf8SinkSize = getIntSize(properties, env, PropertyKey.HTTP_TEXT_UTF8_SINK_SIZE, 4096); this.httpPessimisticHealthCheckEnabled = getBoolean(properties, env, PropertyKey.HTTP_PESSIMISTIC_HEALTH_CHECK, false); final boolean httpHealthCheckAuthRequired = getBoolean(properties, env, PropertyKey.HTTP_HEALTH_CHECK_AUTHENTICATION_REQUIRED, true); this.httpHealthCheckAuthType = httpHealthCheckAuthRequired ? SecurityContext.AUTH_TYPE_CREDENTIALS : SecurityContext.AUTH_TYPE_NONE; this.httpReadOnlySecurityContext = getBoolean(properties, env, PropertyKey.HTTP_SECURITY_READONLY, false); this.maxHttpQueryResponseRowLimit = getLong(properties, env, PropertyKey.HTTP_SECURITY_MAX_RESPONSE_ROWS, Long.MAX_VALUE); this.interruptOnClosedConnection = getBoolean(properties, env, PropertyKey.HTTP_SECURITY_INTERRUPT_ON_CLOSED_CONNECTION, true); if (loadAdditionalConfigurations && httpServerEnabled) { this.jsonQueryConnectionCheckFrequency = getInt(properties, env, PropertyKey.HTTP_JSON_QUERY_CONNECTION_CHECK_FREQUENCY, 1_000_000); this.jsonQueryFloatScale = getInt(properties, env, PropertyKey.HTTP_JSON_QUERY_FLOAT_SCALE, 4); this.jsonQueryDoubleScale = getInt(properties, env, PropertyKey.HTTP_JSON_QUERY_DOUBLE_SCALE, 12); String httpBindTo = getString(properties, env, PropertyKey.HTTP_BIND_TO, "0.0.0.0:9000"); parseBindTo(properties, env, PropertyKey.HTTP_NET_BIND_TO, httpBindTo, (a, p) -> { httpNetBindIPv4Address = a; httpNetBindPort = p; }); // load mime types path.of(new File(new File(root, CONFIG_DIRECTORY), "mime.types").getAbsolutePath()).$(); this.mimeTypesCache = new MimeTypesCache(FilesFacadeImpl.INSTANCE, path); } this.maxRerunWaitCapMs = getLong(properties, env, PropertyKey.HTTP_BUSY_RETRY_MAXIMUM_WAIT_BEFORE_RETRY, 1000); this.rerunExponentialWaitMultiplier = getDouble(properties, env, PropertyKey.HTTP_BUSY_RETRY_EXPONENTIAL_WAIT_MULTIPLIER, "2.0"); this.rerunInitialWaitQueueSize = getIntSize(properties, env, PropertyKey.HTTP_BUSY_RETRY_INITIAL_WAIT_QUEUE_SIZE, 64); this.rerunMaxProcessingQueueSize = getIntSize(properties, env, PropertyKey.HTTP_BUSY_RETRY_MAX_PROCESSING_QUEUE_SIZE, 4096); this.circuitBreakerThrottle = getInt(properties, env, PropertyKey.CIRCUIT_BREAKER_THROTTLE, 2_000_000); this.queryTimeout = (long) (getDouble(properties, env, PropertyKey.QUERY_TIMEOUT_SEC, "60") * Timestamps.SECOND_MILLIS); this.netTestConnectionBufferSize = getInt(properties, env, PropertyKey.CIRCUIT_BREAKER_BUFFER_SIZE, 64); this.netTestConnectionBufferSize = getInt(properties, env, PropertyKey.NET_TEST_CONNECTION_BUFFER_SIZE, netTestConnectionBufferSize); final int forceSendFragmentationChunkSize = getInt(properties, env, PropertyKey.DEBUG_FORCE_SEND_FRAGMENTATION_CHUNK_SIZE, Integer.MAX_VALUE); final int forceRecvFragmentationChunkSize = getInt(properties, env, PropertyKey.DEBUG_FORCE_RECV_FRAGMENTATION_CHUNK_SIZE, Integer.MAX_VALUE); this.httpForceSendFragmentationChunkSize = getInt(properties, env, PropertyKey.DEBUG_HTTP_FORCE_SEND_FRAGMENTATION_CHUNK_SIZE, forceSendFragmentationChunkSize); this.httpForceRecvFragmentationChunkSize = getInt(properties, env, PropertyKey.DEBUG_HTTP_FORCE_RECV_FRAGMENTATION_CHUNK_SIZE, forceRecvFragmentationChunkSize); this.pgEnabled = getBoolean(properties, env, PropertyKey.PG_ENABLED, true); if (pgEnabled) { this.pgForceSendFragmentationChunkSize = getInt(properties, env, PropertyKey.DEBUG_PG_FORCE_SEND_FRAGMENTATION_CHUNK_SIZE, forceSendFragmentationChunkSize); this.pgForceRecvFragmentationChunkSize = getInt(properties, env, PropertyKey.DEBUG_PG_FORCE_RECV_FRAGMENTATION_CHUNK_SIZE, forceRecvFragmentationChunkSize); // deprecated pgNetConnectionLimit = getInt(properties, env, PropertyKey.PG_NET_ACTIVE_CONNECTION_LIMIT, 64); pgNetConnectionLimit = getInt(properties, env, PropertyKey.PG_NET_CONNECTION_LIMIT, pgNetConnectionLimit); pgNetConnectionHint = getBoolean(properties, env, PropertyKey.PG_NET_CONNECTION_HINT, false); parseBindTo(properties, env, PropertyKey.PG_NET_BIND_TO, "0.0.0.0:8812", (a, p) -> { pgNetBindIPv4Address = a; pgNetBindPort = p; }); // deprecated this.pgNetIdleConnectionTimeout = getLong(properties, env, PropertyKey.PG_NET_IDLE_TIMEOUT, 300_000); this.pgNetIdleConnectionTimeout = getLong(properties, env, PropertyKey.PG_NET_CONNECTION_TIMEOUT, this.pgNetIdleConnectionTimeout); this.pgNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.PG_NET_CONNECTION_QUEUE_TIMEOUT, 300_000); // deprecated this.pgNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.PG_NET_RECV_BUF_SIZE, -1); this.pgNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.PG_NET_CONNECTION_RCVBUF, this.pgNetConnectionRcvBuf); // deprecated this.pgNetConnectionSndBuf = getIntSize(properties, env, PropertyKey.PG_NET_SEND_BUF_SIZE, -1); this.pgNetConnectionSndBuf = getIntSize(properties, env, PropertyKey.PG_NET_CONNECTION_SNDBUF, this.pgNetConnectionSndBuf); this.pgCharacterStoreCapacity = getInt(properties, env, PropertyKey.PG_CHARACTER_STORE_CAPACITY, 4096); this.pgBinaryParamsCapacity = getInt(properties, env, PropertyKey.PG_BINARY_PARAM_COUNT_CAPACITY, 2); this.pgCharacterStorePoolCapacity = getInt(properties, env, PropertyKey.PG_CHARACTER_STORE_POOL_CAPACITY, 64); this.pgConnectionPoolInitialCapacity = getInt(properties, env, PropertyKey.PG_CONNECTION_POOL_CAPACITY, 4); this.pgPassword = getString(properties, env, PropertyKey.PG_PASSWORD, "quest"); this.pgUsername = getString(properties, env, PropertyKey.PG_USER, "admin"); this.pgReadOnlyPassword = getString(properties, env, PropertyKey.PG_RO_PASSWORD, "quest"); this.pgReadOnlyUsername = getString(properties, env, PropertyKey.PG_RO_USER, "user"); this.pgReadOnlyUserEnabled = getBoolean(properties, env, PropertyKey.PG_RO_USER_ENABLED, false); this.pgReadOnlySecurityContext = getBoolean(properties, env, PropertyKey.PG_SECURITY_READONLY, false); this.pgMaxBlobSizeOnQuery = getIntSize(properties, env, PropertyKey.PG_MAX_BLOB_SIZE_ON_QUERY, 512 * 1024); this.pgRecvBufferSize = getIntSize(properties, env, PropertyKey.PG_RECV_BUFFER_SIZE, Numbers.SIZE_1MB); this.pgSendBufferSize = getIntSize(properties, env, PropertyKey.PG_SEND_BUFFER_SIZE, Numbers.SIZE_1MB); final String dateLocale = getString(properties, env, PropertyKey.PG_DATE_LOCALE, "en"); this.pgDefaultLocale = DateLocaleFactory.INSTANCE.getLocale(dateLocale); if (this.pgDefaultLocale == null) { throw ServerConfigurationException.forInvalidKey(PropertyKey.PG_DATE_LOCALE.getPropertyPath(), dateLocale); } this.pgWorkerCount = getInt(properties, env, PropertyKey.PG_WORKER_COUNT, 0); cpuUsed += this.pgWorkerCount; this.pgWorkerAffinity = getAffinity(properties, env, PropertyKey.PG_WORKER_AFFINITY, pgWorkerCount); this.pgHaltOnError = getBoolean(properties, env, PropertyKey.PG_HALT_ON_ERROR, false); this.pgWorkerYieldThreshold = getLong(properties, env, PropertyKey.PG_WORKER_YIELD_THRESHOLD, 10); this.pgWorkerNapThreshold = getLong(properties, env, PropertyKey.PG_WORKER_NAP_THRESHOLD, 7_000); this.pgWorkerSleepThreshold = getLong(properties, env, PropertyKey.PG_WORKER_SLEEP_THRESHOLD, 10_000); this.pgDaemonPool = getBoolean(properties, env, PropertyKey.PG_DAEMON_POOL, true); this.pgSelectCacheEnabled = getBoolean(properties, env, PropertyKey.PG_SELECT_CACHE_ENABLED, true); this.pgSelectCacheBlockCount = getInt(properties, env, PropertyKey.PG_SELECT_CACHE_BLOCK_COUNT, 4); this.pgSelectCacheRowCount = getInt(properties, env, PropertyKey.PG_SELECT_CACHE_ROW_COUNT, 4); this.pgInsertCacheEnabled = getBoolean(properties, env, PropertyKey.PG_INSERT_CACHE_ENABLED, true); this.pgInsertCacheBlockCount = getInt(properties, env, PropertyKey.PG_INSERT_CACHE_BLOCK_COUNT, 4); this.pgInsertCacheRowCount = getInt(properties, env, PropertyKey.PG_INSERT_CACHE_ROW_COUNT, 4); this.pgUpdateCacheEnabled = getBoolean(properties, env, PropertyKey.PG_UPDATE_CACHE_ENABLED, true); this.pgUpdateCacheBlockCount = getInt(properties, env, PropertyKey.PG_UPDATE_CACHE_BLOCK_COUNT, 4); this.pgUpdateCacheRowCount = getInt(properties, env, PropertyKey.PG_UPDATE_CACHE_ROW_COUNT, 4); this.pgNamedStatementCacheCapacity = getInt(properties, env, PropertyKey.PG_NAMED_STATEMENT_CACHE_CAPACITY, 32); this.pgNamesStatementPoolCapacity = getInt(properties, env, PropertyKey.PG_NAMED_STATEMENT_POOL_CAPACITY, 32); this.pgPendingWritersCacheCapacity = getInt(properties, env, PropertyKey.PG_PENDING_WRITERS_CACHE_CAPACITY, 16); } this.walApplyWorkerCount = getInt(properties, env, PropertyKey.WAL_APPLY_WORKER_COUNT, cpuWalApplyWorkers); this.walApplyWorkerAffinity = getAffinity(properties, env, PropertyKey.WAL_APPLY_WORKER_AFFINITY, walApplyWorkerCount); this.walApplyWorkerHaltOnError = getBoolean(properties, env, PropertyKey.WAL_APPLY_WORKER_HALT_ON_ERROR, false); this.walApplyWorkerNapThreshold = getLong(properties, env, PropertyKey.WAL_APPLY_WORKER_NAP_THRESHOLD, 7_000); this.walApplyWorkerSleepThreshold = getLong(properties, env, PropertyKey.WAL_APPLY_WORKER_SLEEP_THRESHOLD, 10_000); this.walApplySleepTimeout = getLong(properties, env, PropertyKey.WAL_APPLY_WORKER_SLEEP_TIMEOUT, 10); this.walApplyWorkerYieldThreshold = getLong(properties, env, PropertyKey.WAL_APPLY_WORKER_YIELD_THRESHOLD, 1000); this.commitMode = getCommitMode(properties, env, PropertyKey.CAIRO_COMMIT_MODE); this.createAsSelectRetryCount = getInt(properties, env, PropertyKey.CAIRO_CREATE_AS_SELECT_RETRY_COUNT, 5); this.defaultSymbolCacheFlag = getBoolean(properties, env, PropertyKey.CAIRO_DEFAULT_SYMBOL_CACHE_FLAG, true); this.defaultSymbolCapacity = getInt(properties, env, PropertyKey.CAIRO_DEFAULT_SYMBOL_CAPACITY, 256); this.fileOperationRetryCount = getInt(properties, env, PropertyKey.CAIRO_FILE_OPERATION_RETRY_COUNT, 30); this.idleCheckInterval = getLong(properties, env, PropertyKey.CAIRO_IDLE_CHECK_INTERVAL, 5 * 60 * 1000L); this.inactiveReaderMaxOpenPartitions = getInt(properties, env, PropertyKey.CAIRO_INACTIVE_READER_MAX_OPEN_PARTITIONS, 128); this.inactiveReaderTTL = getLong(properties, env, PropertyKey.CAIRO_INACTIVE_READER_TTL, 120_000); this.inactiveWriterTTL = getLong(properties, env, PropertyKey.CAIRO_INACTIVE_WRITER_TTL, 600_000); this.inactiveWalWriterTTL = getLong(properties, env, PropertyKey.CAIRO_WAL_INACTIVE_WRITER_TTL, 120_000); this.indexValueBlockSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_INDEX_VALUE_BLOCK_SIZE, 256)); this.maxSwapFileCount = getInt(properties, env, PropertyKey.CAIRO_MAX_SWAP_FILE_COUNT, 30); this.parallelIndexThreshold = getInt(properties, env, PropertyKey.CAIRO_PARALLEL_INDEX_THRESHOLD, 100000); this.readerPoolMaxSegments = getInt(properties, env, PropertyKey.CAIRO_READER_POOL_MAX_SEGMENTS, 10); this.walWriterPoolMaxSegments = getInt(properties, env, PropertyKey.CAIRO_WAL_WRITER_POOL_MAX_SEGMENTS, 10); this.spinLockTimeout = getLong(properties, env, PropertyKey.CAIRO_SPIN_LOCK_TIMEOUT, 1_000); this.httpSqlCacheEnabled = getBoolean(properties, env, PropertyKey.HTTP_QUERY_CACHE_ENABLED, true); this.httpSqlCacheBlockCount = getInt(properties, env, PropertyKey.HTTP_QUERY_CACHE_BLOCK_COUNT, 4); this.httpSqlCacheRowCount = getInt(properties, env, PropertyKey.HTTP_QUERY_CACHE_ROW_COUNT, 4); this.sqlCharacterStoreCapacity = getInt(properties, env, PropertyKey.CAIRO_CHARACTER_STORE_CAPACITY, 1024); this.sqlCharacterStoreSequencePoolCapacity = getInt(properties, env, PropertyKey.CAIRO_CHARACTER_STORE_SEQUENCE_POOL_CAPACITY, 64); this.sqlColumnPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_COLUMN_POOL_CAPACITY, 4096); this.sqlExpressionPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_EXPRESSION_POOL_CAPACITY, 8192); this.sqlFastMapLoadFactor = getDouble(properties, env, PropertyKey.CAIRO_FAST_MAP_LOAD_FACTOR, "0.7"); this.sqlJoinContextPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_JOIN_CONTEXT_POOL_CAPACITY, 64); this.sqlLexerPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_LEXER_POOL_CAPACITY, 2048); this.sqlSmallMapKeyCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_SMALL_MAP_KEY_CAPACITY, 32); this.sqlSmallMapPageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_SMALL_MAP_PAGE_SIZE, 32 * 1024); this.sqlUnorderedMapMaxEntrySize = getInt(properties, env, PropertyKey.CAIRO_SQL_UNORDERED_MAP_MAX_ENTRY_SIZE, 32); this.sqlMapMaxPages = getIntSize(properties, env, PropertyKey.CAIRO_SQL_MAP_MAX_PAGES, Integer.MAX_VALUE); this.sqlMapMaxResizes = getIntSize(properties, env, PropertyKey.CAIRO_SQL_MAP_MAX_RESIZES, Integer.MAX_VALUE); this.sqlExplainModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_EXPLAIN_MODEL_POOL_CAPACITY, 32); this.sqlModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_MODEL_POOL_CAPACITY, 1024); this.sqlMaxNegativeLimit = getInt(properties, env, PropertyKey.CAIRO_SQL_MAX_NEGATIVE_LIMIT, 10_000); this.sqlSortKeyPageSize = getLongSize(properties, env, PropertyKey.CAIRO_SQL_SORT_KEY_PAGE_SIZE, 4 * Numbers.SIZE_1MB); this.sqlSortKeyMaxPages = getIntSize(properties, env, PropertyKey.CAIRO_SQL_SORT_KEY_MAX_PAGES, Integer.MAX_VALUE); this.sqlSortLightValuePageSize = getLongSize(properties, env, PropertyKey.CAIRO_SQL_SORT_LIGHT_VALUE_PAGE_SIZE, 8 * 1048576); this.sqlSortLightValueMaxPages = getIntSize(properties, env, PropertyKey.CAIRO_SQL_SORT_LIGHT_VALUE_MAX_PAGES, Integer.MAX_VALUE); this.sqlHashJoinValuePageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_HASH_JOIN_VALUE_PAGE_SIZE, 16777216); this.sqlHashJoinValueMaxPages = getIntSize(properties, env, PropertyKey.CAIRO_SQL_HASH_JOIN_VALUE_MAX_PAGES, Integer.MAX_VALUE); this.sqlLatestByRowCount = getInt(properties, env, PropertyKey.CAIRO_SQL_LATEST_BY_ROW_COUNT, 1000); this.sqlHashJoinLightValuePageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_HASH_JOIN_LIGHT_VALUE_PAGE_SIZE, 1048576); this.sqlHashJoinLightValueMaxPages = getIntSize(properties, env, PropertyKey.CAIRO_SQL_HASH_JOIN_LIGHT_VALUE_MAX_PAGES, Integer.MAX_VALUE); this.sqlAsOfJoinLookahead = getInt(properties, env, PropertyKey.CAIRO_SQL_ASOF_JOIN_LOOKAHEAD, 100); this.sqlSortValuePageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_SORT_VALUE_PAGE_SIZE, 16777216); this.sqlSortValueMaxPages = getIntSize(properties, env, PropertyKey.CAIRO_SQL_SORT_VALUE_MAX_PAGES, Integer.MAX_VALUE); this.workStealTimeoutNanos = getLong(properties, env, PropertyKey.CAIRO_WORK_STEAL_TIMEOUT_NANOS, 10_000); this.parallelIndexingEnabled = getBoolean(properties, env, PropertyKey.CAIRO_PARALLEL_INDEXING_ENABLED, true); this.sqlJoinMetadataPageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_JOIN_METADATA_PAGE_SIZE, 16384); this.sqlJoinMetadataMaxResizes = getIntSize(properties, env, PropertyKey.CAIRO_SQL_JOIN_METADATA_MAX_RESIZES, Integer.MAX_VALUE); int sqlWindowColumnPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_COLUMN_POOL_CAPACITY, 64); this.sqlWindowColumnPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_WINDOW_COLUMN_POOL_CAPACITY, sqlWindowColumnPoolCapacity); this.sqlCreateTableModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_CREATE_TABLE_MODEL_POOL_CAPACITY, 16); this.sqlCreateTableModelBatchSize = getLong(properties, env, PropertyKey.CAIRO_SQL_CREATE_TABLE_MODEL_BATCH_SIZE, 1_000_000); this.sqlColumnCastModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_COLUMN_CAST_MODEL_POOL_CAPACITY, 16); this.sqlRenameTableModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_RENAME_TABLE_MODEL_POOL_CAPACITY, 16); this.sqlWithClauseModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_WITH_CLAUSE_MODEL_POOL_CAPACITY, 128); this.sqlInsertModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_INSERT_MODEL_POOL_CAPACITY, 64); this.sqlInsertModelBatchSize = getLong(properties, env, PropertyKey.CAIRO_SQL_INSERT_MODEL_BATCH_SIZE, 1_000_000); this.sqlCopyBufferSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_COPY_BUFFER_SIZE, 2 * Numbers.SIZE_1MB); this.columnPurgeQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_SQL_COLUMN_PURGE_QUEUE_CAPACITY, 128); this.columnPurgeTaskPoolCapacity = getIntSize(properties, env, PropertyKey.CAIRO_SQL_COLUMN_PURGE_TASK_POOL_CAPACITY, 256); this.columnPurgeRetryDelayLimit = getLong(properties, env, PropertyKey.CAIRO_SQL_COLUMN_PURGE_RETRY_DELAY_LIMIT, 60_000_000L); this.columnPurgeRetryDelay = getLong(properties, env, PropertyKey.CAIRO_SQL_COLUMN_PURGE_RETRY_DELAY, 10_000); this.columnPurgeRetryDelayMultiplier = getDouble(properties, env, PropertyKey.CAIRO_SQL_COLUMN_PURGE_RETRY_DELAY_MULTIPLIER, "10.0"); this.systemTableNamePrefix = getString(properties, env, PropertyKey.CAIRO_SQL_SYSTEM_TABLE_PREFIX, "sys."); this.writerDataIndexKeyAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_WRITER_DATA_INDEX_KEY_APPEND_PAGE_SIZE, 512 * 1024)); this.writerDataIndexValueAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_WRITER_DATA_INDEX_VALUE_APPEND_PAGE_SIZE, 16 * Numbers.SIZE_1MB)); this.writerDataAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_WRITER_DATA_APPEND_PAGE_SIZE, 16 * Numbers.SIZE_1MB)); this.systemWriterDataAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_SYSTEM_WRITER_DATA_APPEND_PAGE_SIZE, 256 * 1024)); this.writerMiscAppendPageSize = Files.ceilPageSize(getLongSize(properties, env, PropertyKey.CAIRO_WRITER_MISC_APPEND_PAGE_SIZE, Files.PAGE_SIZE)); this.sqlSampleByIndexSearchPageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_SAMPLEBY_PAGE_SIZE, 0); this.sqlSampleByDefaultAlignment = getBoolean(properties, env, PropertyKey.CAIRO_SQL_SAMPLEBY_DEFAULT_ALIGNMENT_CALENDAR, true); this.sqlDoubleToStrCastScale = getInt(properties, env, PropertyKey.CAIRO_SQL_DOUBLE_CAST_SCALE, 12); this.sqlFloatToStrCastScale = getInt(properties, env, PropertyKey.CAIRO_SQL_FLOAT_CAST_SCALE, 4); this.sqlGroupByMapCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_GROUPBY_MAP_CAPACITY, 1024); this.sqlGroupByAllocatorChunkSize = getLongSize(properties, env, PropertyKey.CAIRO_SQL_GROUPBY_ALLOCATOR_DEFAULT_CHUNK_SIZE, 128 * 1024); this.sqlGroupByAllocatorMaxChunkSize = getLongSize(properties, env, PropertyKey.CAIRO_SQL_GROUPBY_ALLOCATOR_MAX_CHUNK_SIZE, 4 * Numbers.SIZE_1GB); this.sqlGroupByPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_GROUPBY_POOL_CAPACITY, 1024); this.sqlMaxSymbolNotEqualsCount = getInt(properties, env, PropertyKey.CAIRO_SQL_MAX_SYMBOL_NOT_EQUALS_COUNT, 100); this.sqlBindVariablePoolSize = getInt(properties, env, PropertyKey.CAIRO_SQL_BIND_VARIABLE_POOL_SIZE, 8); this.sqlQueryRegistryPoolSize = getInt(properties, env, PropertyKey.CAIRO_SQL_QUERY_REGISTRY_POOL_SIZE, 32); this.sqlCountDistinctCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_COUNT_DISTINCT_CAPACITY, 16); this.sqlCountDistinctLoadFactor = getDouble(properties, env, PropertyKey.CAIRO_SQL_COUNT_DISTINCT_LOAD_FACTOR, "0.7"); final String sqlCopyFormatsFile = getString(properties, env, PropertyKey.CAIRO_SQL_COPY_FORMATS_FILE, "/text_loader.json"); final String dateLocale = getString(properties, env, PropertyKey.CAIRO_DATE_LOCALE, "en"); this.locale = DateLocaleFactory.INSTANCE.getLocale(dateLocale); if (this.locale == null) { throw ServerConfigurationException.forInvalidKey(PropertyKey.CAIRO_DATE_LOCALE.getPropertyPath(), dateLocale); } this.sqlDistinctTimestampKeyCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_DISTINCT_TIMESTAMP_KEY_CAPACITY, 512); this.sqlDistinctTimestampLoadFactor = getDouble(properties, env, PropertyKey.CAIRO_SQL_DISTINCT_TIMESTAMP_LOAD_FACTOR, "0.5"); this.sqlPageFrameMinRows = getInt(properties, env, PropertyKey.CAIRO_SQL_PAGE_FRAME_MIN_ROWS, 100_000); this.sqlPageFrameMaxRows = getInt(properties, env, PropertyKey.CAIRO_SQL_PAGE_FRAME_MAX_ROWS, 1_000_000); this.sqlJitMode = getSqlJitMode(properties, env); this.sqlJitIRMemoryPageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_JIT_IR_MEMORY_PAGE_SIZE, 8 * 1024); this.sqlJitIRMemoryMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_JIT_IR_MEMORY_MAX_PAGES, 8); this.sqlJitBindVarsMemoryPageSize = getIntSize(properties, env, PropertyKey.CAIRO_SQL_JIT_BIND_VARS_MEMORY_PAGE_SIZE, 4 * 1024); this.sqlJitBindVarsMemoryMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_JIT_BIND_VARS_MEMORY_MAX_PAGES, 8); this.sqlJitPageAddressCacheThreshold = getIntSize(properties, env, PropertyKey.CAIRO_SQL_JIT_PAGE_ADDRESS_CACHE_THRESHOLD, 1024 * 1024); this.sqlJitDebugEnabled = getBoolean(properties, env, PropertyKey.CAIRO_SQL_JIT_DEBUG_ENABLED, false); this.maxSqlRecompileAttempts = getInt(properties, env, PropertyKey.CAIRO_SQL_MAX_RECOMPILE_ATTEMPTS, 10); String value = getString(properties, env, PropertyKey.CAIRO_WRITER_FO_OPTS, "o_none"); long lopts = CairoConfiguration.O_NONE; String[] opts = value.split("\\|"); for (String opt : opts) { int index = WRITE_FO_OPTS.keyIndex(opt.trim()); if (index < 0) { lopts |= WRITE_FO_OPTS.valueAt(index); } } this.writerFileOpenOpts = lopts; this.writerMixedIOEnabled = getBoolean(properties, env, PropertyKey.DEBUG_CAIRO_ALLOW_MIXED_IO, ff.allowMixedIO(this.root)); this.inputFormatConfiguration = new InputFormatConfiguration( new DateFormatFactory(), DateLocaleFactory.INSTANCE, new TimestampFormatFactory(), this.locale ); try (JsonLexer lexer = new JsonLexer(1024, 1024)) { inputFormatConfiguration.parseConfiguration(PropServerConfiguration.class, lexer, confRoot, sqlCopyFormatsFile); } this.cairoSqlCopyRoot = getString(properties, env, PropertyKey.CAIRO_SQL_COPY_ROOT, null); String cairoSqlCopyWorkRoot = getString(properties, env, PropertyKey.CAIRO_SQL_COPY_WORK_ROOT, tmpRoot); if (cairoSqlCopyRoot != null) { this.cairoSqlCopyWorkRoot = getCanonicalPath(cairoSqlCopyWorkRoot); } else { this.cairoSqlCopyWorkRoot = null; } if (pathEquals(root, this.cairoSqlCopyWorkRoot) || pathEquals(this.root, this.cairoSqlCopyWorkRoot) || pathEquals(this.confRoot, this.cairoSqlCopyWorkRoot) || pathEquals(this.snapshotRoot, this.cairoSqlCopyWorkRoot)) { throw new ServerConfigurationException("Configuration value for " + PropertyKey.CAIRO_SQL_COPY_WORK_ROOT.getPropertyPath() + " can't point to root, data, conf or snapshot dirs. "); } String cairoSQLCopyIdSupplier = getString(properties, env, PropertyKey.CAIRO_SQL_COPY_ID_SUPPLIER, "random"); this.cairoSQLCopyIdSupplier = Chars.equalsLowerCaseAscii(cairoSQLCopyIdSupplier, "sequential") ? 1 : 0; this.cairoSqlCopyMaxIndexChunkSize = getLongSize(properties, env, PropertyKey.CAIRO_SQL_COPY_MAX_INDEX_CHUNK_SIZE, 100 * Numbers.SIZE_1MB); this.cairoSqlCopyMaxIndexChunkSize -= (cairoSqlCopyMaxIndexChunkSize % CsvFileIndexer.INDEX_ENTRY_SIZE); if (this.cairoSqlCopyMaxIndexChunkSize < 16) { throw new ServerConfigurationException("invalid configuration value [key=" + PropertyKey.CAIRO_SQL_COPY_MAX_INDEX_CHUNK_SIZE.getPropertyPath() + ", description=max import chunk size can't be smaller than 16]"); } this.cairoSqlCopyQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_SQL_COPY_QUEUE_CAPACITY, 32)); this.cairoSqlCopyLogRetentionDays = getInt(properties, env, PropertyKey.CAIRO_SQL_COPY_LOG_RETENTION_DAYS, 3); this.o3MinLagUs = getLong(properties, env, PropertyKey.CAIRO_O3_MIN_LAG, 1_000) * 1_000L; this.backupRoot = getString(properties, env, PropertyKey.CAIRO_SQL_BACKUP_ROOT, null); this.backupDirTimestampFormat = getTimestampFormat(properties, env); this.backupTempDirName = getString(properties, env, PropertyKey.CAIRO_SQL_BACKUP_DIR_TMP_NAME, "tmp"); this.backupMkdirMode = getInt(properties, env, PropertyKey.CAIRO_SQL_BACKUP_MKDIR_MODE, 509); this.detachedMkdirMode = getInt(properties, env, PropertyKey.CAIRO_DETACHED_MKDIR_MODE, 509); this.columnIndexerQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_COLUMN_INDEXER_QUEUE_CAPACITY, 64); this.vectorAggregateQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_VECTOR_AGGREGATE_QUEUE_CAPACITY, 128); this.o3CallbackQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_O3_CALLBACK_QUEUE_CAPACITY, 128); this.o3PartitionQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_O3_PARTITION_QUEUE_CAPACITY, 128); this.o3OpenColumnQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_O3_OPEN_COLUMN_QUEUE_CAPACITY, 128); this.o3CopyQueueCapacity = getQueueCapacity(properties, env, PropertyKey.CAIRO_O3_COPY_QUEUE_CAPACITY, 128); this.o3LagCalculationWindowsSize = getIntSize(properties, env, PropertyKey.CAIRO_O3_LAG_CALCULATION_WINDOW_SIZE, 4); this.o3PurgeDiscoveryQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_O3_PURGE_DISCOVERY_QUEUE_CAPACITY, 128)); int debugO3MemSize = getInt(properties, env, PropertyKey.DEBUG_CAIRO_O3_COLUMN_MEMORY_SIZE, 0); if (debugO3MemSize != 0) { this.o3ColumnMemorySize = debugO3MemSize; } else { this.o3ColumnMemorySize = (int) Files.ceilPageSize(getIntSize(properties, env, PropertyKey.CAIRO_O3_COLUMN_MEMORY_SIZE, 8 * Numbers.SIZE_1MB)); } this.systemO3ColumnMemorySize = (int) Files.ceilPageSize(getIntSize(properties, env, PropertyKey.CAIRO_SYSTEM_O3_COLUMN_MEMORY_SIZE, 256 * 1024)); this.maxUncommittedRows = getInt(properties, env, PropertyKey.CAIRO_MAX_UNCOMMITTED_ROWS, 500_000); long o3MaxLag = getLong(properties, env, PropertyKey.CAIRO_COMMIT_LAG, 10 * Dates.MINUTE_MILLIS); this.o3MaxLag = getLong(properties, env, PropertyKey.CAIRO_O3_MAX_LAG, o3MaxLag) * 1_000; this.o3QuickSortEnabled = getBoolean(properties, env, PropertyKey.CAIRO_O3_QUICKSORT_ENABLED, false); this.rndFunctionMemoryPageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_RND_MEMORY_PAGE_SIZE, 8192)); this.rndFunctionMemoryMaxPages = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_RND_MEMORY_MAX_PAGES, 128)); this.sqlStrFunctionBufferMaxSize = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_SQL_STR_FUNCTION_BUFFER_MAX_SIZE, Numbers.SIZE_1MB)); this.sqlWindowMaxRecursion = getInt(properties, env, PropertyKey.CAIRO_SQL_WINDOW_MAX_RECURSION, 128); int sqlWindowStorePageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_STORE_PAGE_SIZE, Numbers.SIZE_1MB)); this.sqlWindowStorePageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_SQL_WINDOW_STORE_PAGE_SIZE, sqlWindowStorePageSize)); int sqlWindowStoreMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_STORE_MAX_PAGES, Integer.MAX_VALUE); this.sqlWindowStoreMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_WINDOW_STORE_MAX_PAGES, sqlWindowStoreMaxPages); int sqlWindowRowIdPageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_ROWID_PAGE_SIZE, 512 * 1024)); this.sqlWindowRowIdPageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_SQL_WINDOW_ROWID_PAGE_SIZE, sqlWindowRowIdPageSize)); int sqlWindowRowIdMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_ROWID_MAX_PAGES, Integer.MAX_VALUE); this.sqlWindowRowIdMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_WINDOW_ROWID_MAX_PAGES, sqlWindowRowIdMaxPages); int sqlWindowTreeKeyPageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_TREE_PAGE_SIZE, 512 * 1024)); this.sqlWindowTreeKeyPageSize = Numbers.ceilPow2(getIntSize(properties, env, PropertyKey.CAIRO_SQL_WINDOW_TREE_PAGE_SIZE, sqlWindowTreeKeyPageSize)); int sqlWindowTreeKeyMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_TREE_MAX_PAGES, Integer.MAX_VALUE); this.sqlWindowTreeKeyMaxPages = getInt(properties, env, PropertyKey.CAIRO_SQL_WINDOW_TREE_MAX_PAGES, sqlWindowTreeKeyMaxPages); this.sqlWindowInitialRangeBufferSize = getInt(properties, env, PropertyKey.CAIRO_SQL_ANALYTIC_INITIAL_RANGE_BUFFER_SIZE, 32); this.sqlTxnScoreboardEntryCount = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_O3_TXN_SCOREBOARD_ENTRY_COUNT, 16384)); this.latestByQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_LATESTBY_QUEUE_CAPACITY, 32)); this.telemetryEnabled = getBoolean(properties, env, PropertyKey.TELEMETRY_ENABLED, true); this.telemetryDisableCompletely = getBoolean(properties, env, PropertyKey.TELEMETRY_DISABLE_COMPLETELY, false); this.telemetryQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.TELEMETRY_QUEUE_CAPACITY, 512)); this.telemetryHideTables = getBoolean(properties, env, PropertyKey.TELEMETRY_HIDE_TABLES, true); this.o3PartitionPurgeListCapacity = getInt(properties, env, PropertyKey.CAIRO_O3_PARTITION_PURGE_LIST_INITIAL_CAPACITY, 1); this.ioURingEnabled = getBoolean(properties, env, PropertyKey.CAIRO_IO_URING_ENABLED, true); this.cairoMaxCrashFiles = getInt(properties, env, PropertyKey.CAIRO_MAX_CRASH_FILES, 100); this.o3LastPartitionMaxSplits = Math.max(1, getInt(properties, env, PropertyKey.CAIRO_O3_LAST_PARTITION_MAX_SPLITS, 20)); this.o3PartitionSplitMinSize = getLongSize(properties, env, PropertyKey.CAIRO_O3_PARTITION_SPLIT_MIN_SIZE, 50 * Numbers.SIZE_1MB); parseBindTo(properties, env, PropertyKey.LINE_UDP_BIND_TO, "0.0.0.0:9009", (a, p) -> { this.lineUdpBindIPV4Address = a; this.lineUdpPort = p; }); this.lineUdpGroupIPv4Address = getIPv4Address(properties, env, PropertyKey.LINE_UDP_JOIN, "232.1.2.3"); this.lineUdpCommitRate = getInt(properties, env, PropertyKey.LINE_UDP_COMMIT_RATE, 1_000_000); this.lineUdpMsgBufferSize = getIntSize(properties, env, PropertyKey.LINE_UDP_MSG_BUFFER_SIZE, 2048); this.lineUdpMsgCount = getInt(properties, env, PropertyKey.LINE_UDP_MSG_COUNT, 10_000); this.lineUdpReceiveBufferSize = getIntSize(properties, env, PropertyKey.LINE_UDP_RECEIVE_BUFFER_SIZE, 8 * Numbers.SIZE_1MB); this.lineUdpEnabled = getBoolean(properties, env, PropertyKey.LINE_UDP_ENABLED, false); this.lineUdpOwnThreadAffinity = getInt(properties, env, PropertyKey.LINE_UDP_OWN_THREAD_AFFINITY, -1); this.lineUdpOwnThread = getBoolean(properties, env, PropertyKey.LINE_UDP_OWN_THREAD, false); this.lineUdpUnicast = getBoolean(properties, env, PropertyKey.LINE_UDP_UNICAST, false); this.lineUdpCommitMode = getCommitMode(properties, env, PropertyKey.LINE_UDP_COMMIT_MODE); this.lineUdpTimestampAdapter = getLineTimestampAdaptor(properties, env, PropertyKey.LINE_UDP_TIMESTAMP); String defaultUdpPartitionByProperty = getString(properties, env, PropertyKey.LINE_DEFAULT_PARTITION_BY, "DAY"); this.lineUdpDefaultPartitionBy = PartitionBy.fromString(defaultUdpPartitionByProperty); if (this.lineUdpDefaultPartitionBy == -1) { log.info().$("invalid partition by ").$(lineUdpDefaultPartitionBy).$("), will use DAY for UDP").$(); this.lineUdpDefaultPartitionBy = PartitionBy.DAY; } this.lineTcpEnabled = getBoolean(properties, env, PropertyKey.LINE_TCP_ENABLED, true); this.lineHttpEnabled = getBoolean(properties, env, PropertyKey.LINE_HTTP_ENABLED, true); this.lineHttpPingVersion = getString(properties, env, PropertyKey.LINE_HTTP_PING_VERSION, "v2.7.4"); if (lineTcpEnabled || lineHttpEnabled) { // obsolete lineTcpNetConnectionLimit = getInt(properties, env, PropertyKey.LINE_TCP_NET_ACTIVE_CONNECTION_LIMIT, 256); lineTcpNetConnectionLimit = getInt(properties, env, PropertyKey.LINE_TCP_NET_CONNECTION_LIMIT, lineTcpNetConnectionLimit); lineTcpNetConnectionHint = getBoolean(properties, env, PropertyKey.LINE_TCP_NET_CONNECTION_HINT, false); parseBindTo(properties, env, PropertyKey.LINE_TCP_NET_BIND_TO, "0.0.0.0:9009", (a, p) -> { lineTcpNetBindIPv4Address = a; lineTcpNetBindPort = p; }); // deprecated this.lineTcpNetConnectionTimeout = getLong(properties, env, PropertyKey.LINE_TCP_NET_IDLE_TIMEOUT, 0); this.lineTcpNetConnectionTimeout = getLong(properties, env, PropertyKey.LINE_TCP_NET_CONNECTION_TIMEOUT, this.lineTcpNetConnectionTimeout); // deprecated this.lineTcpNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.LINE_TCP_NET_QUEUED_TIMEOUT, 5_000); this.lineTcpNetConnectionQueueTimeout = getLong(properties, env, PropertyKey.LINE_TCP_NET_CONNECTION_QUEUE_TIMEOUT, this.lineTcpNetConnectionQueueTimeout); // deprecated this.lineTcpNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.LINE_TCP_NET_RECV_BUF_SIZE, -1); this.lineTcpNetConnectionRcvBuf = getIntSize(properties, env, PropertyKey.LINE_TCP_NET_CONNECTION_RCVBUF, this.lineTcpNetConnectionRcvBuf); this.lineTcpConnectionPoolInitialCapacity = getInt(properties, env, PropertyKey.LINE_TCP_CONNECTION_POOL_CAPACITY, 8); this.lineTcpMsgBufferSize = getIntSize(properties, env, PropertyKey.LINE_TCP_MSG_BUFFER_SIZE, 32768); this.lineTcpMaxMeasurementSize = getIntSize(properties, env, PropertyKey.LINE_TCP_MAX_MEASUREMENT_SIZE, 32768); if (lineTcpMaxMeasurementSize > lineTcpMsgBufferSize) { lineTcpMsgBufferSize = lineTcpMaxMeasurementSize; } this.lineTcpWriterQueueCapacity = getQueueCapacity(properties, env, PropertyKey.LINE_TCP_WRITER_QUEUE_CAPACITY, 128); this.lineTcpWriterWorkerCount = getInt(properties, env, PropertyKey.LINE_TCP_WRITER_WORKER_COUNT, 0); cpuUsed += this.lineTcpWriterWorkerCount; this.lineTcpWriterWorkerAffinity = getAffinity(properties, env, PropertyKey.LINE_TCP_WRITER_WORKER_AFFINITY, lineTcpWriterWorkerCount); this.lineTcpWriterWorkerPoolHaltOnError = getBoolean(properties, env, PropertyKey.LINE_TCP_WRITER_HALT_ON_ERROR, false); this.lineTcpWriterWorkerYieldThreshold = getLong(properties, env, PropertyKey.LINE_TCP_WRITER_WORKER_YIELD_THRESHOLD, 10); this.lineTcpWriterWorkerNapThreshold = getLong(properties, env, PropertyKey.LINE_TCP_WRITER_WORKER_NAP_THRESHOLD, 7_000); this.lineTcpWriterWorkerSleepThreshold = getLong(properties, env, PropertyKey.LINE_TCP_WRITER_WORKER_SLEEP_THRESHOLD, 10_000); this.symbolCacheWaitUsBeforeReload = getLong(properties, env, PropertyKey.LINE_TCP_SYMBOL_CACHE_WAIT_US_BEFORE_RELOAD, 500_000); this.lineTcpIOWorkerCount = getInt(properties, env, PropertyKey.LINE_TCP_IO_WORKER_COUNT, cpuIoWorkers); this.lineTcpIOWorkerAffinity = getAffinity(properties, env, PropertyKey.LINE_TCP_IO_WORKER_AFFINITY, lineTcpIOWorkerCount); this.lineTcpIOWorkerPoolHaltOnError = getBoolean(properties, env, PropertyKey.LINE_TCP_IO_HALT_ON_ERROR, false); this.lineTcpIOWorkerYieldThreshold = getLong(properties, env, PropertyKey.LINE_TCP_IO_WORKER_YIELD_THRESHOLD, 10); this.lineTcpIOWorkerNapThreshold = getLong(properties, env, PropertyKey.LINE_TCP_IO_WORKER_NAP_THRESHOLD, 7_000); this.lineTcpIOWorkerSleepThreshold = getLong(properties, env, PropertyKey.LINE_TCP_IO_WORKER_SLEEP_THRESHOLD, 10_000); this.lineTcpMaintenanceInterval = getLong(properties, env, PropertyKey.LINE_TCP_MAINTENANCE_JOB_INTERVAL, 1000); this.lineTcpCommitIntervalFraction = getDouble(properties, env, PropertyKey.LINE_TCP_COMMIT_INTERVAL_FRACTION, "0.5"); this.lineTcpCommitIntervalDefault = getLong(properties, env, PropertyKey.LINE_TCP_COMMIT_INTERVAL_DEFAULT, COMMIT_INTERVAL_DEFAULT); if (this.lineTcpCommitIntervalDefault < 1L) { log.info().$("invalid default commit interval ").$(lineTcpCommitIntervalDefault).$("), will use ").$(COMMIT_INTERVAL_DEFAULT).$(); this.lineTcpCommitIntervalDefault = COMMIT_INTERVAL_DEFAULT; } this.lineTcpAuthDB = getString(properties, env, PropertyKey.LINE_TCP_AUTH_DB_PATH, null); // deprecated String defaultTcpPartitionByProperty = getString(properties, env, PropertyKey.LINE_TCP_DEFAULT_PARTITION_BY, "DAY"); defaultTcpPartitionByProperty = getString(properties, env, PropertyKey.LINE_DEFAULT_PARTITION_BY, defaultTcpPartitionByProperty); this.lineTcpDefaultPartitionBy = PartitionBy.fromString(defaultTcpPartitionByProperty); if (this.lineTcpDefaultPartitionBy == -1) { log.info().$("invalid partition by ").$(defaultTcpPartitionByProperty).$("), will use DAY for TCP").$(); this.lineTcpDefaultPartitionBy = PartitionBy.DAY; } this.minIdleMsBeforeWriterRelease = getLong(properties, env, PropertyKey.LINE_TCP_MIN_IDLE_MS_BEFORE_WRITER_RELEASE, 500); this.lineTcpDisconnectOnError = getBoolean(properties, env, PropertyKey.LINE_TCP_DISCONNECT_ON_ERROR, true); final long heartbeatInterval = LineTcpReceiverConfigurationHelper.calcCommitInterval( this.o3MinLagUs, this.lineTcpCommitIntervalFraction, this.lineTcpCommitIntervalDefault ); this.lineTcpNetConnectionHeartbeatInterval = getLong(properties, env, PropertyKey.LINE_TCP_NET_CONNECTION_HEARTBEAT_INTERVAL, heartbeatInterval); } else { this.lineTcpAuthDB = null; } this.useLegacyStringDefault = getBoolean(properties, env, PropertyKey.CAIRO_LEGACY_STRING_COLUMN_TYPE_DEFAULT, false); if (lineTcpEnabled || (lineHttpEnabled && httpServerEnabled)) { LineTimestampAdapter timestampAdapter = getLineTimestampAdaptor(properties, env, PropertyKey.LINE_TCP_TIMESTAMP); this.lineTcpTimestampAdapter = new LineTcpTimestampAdapter(timestampAdapter); this.stringToCharCastAllowed = getBoolean(properties, env, PropertyKey.LINE_TCP_UNDOCUMENTED_STRING_TO_CHAR_CAST_ALLOWED, false); String floatDefaultColumnTypeName = getString(properties, env, PropertyKey.LINE_FLOAT_DEFAULT_COLUMN_TYPE, ColumnType.nameOf(ColumnType.DOUBLE)); this.floatDefaultColumnType = ColumnType.tagOf(floatDefaultColumnTypeName); if (floatDefaultColumnType != ColumnType.DOUBLE && floatDefaultColumnType != ColumnType.FLOAT) { log.info().$("invalid default column type for float ").$(floatDefaultColumnTypeName).$(", will use DOUBLE").$(); this.floatDefaultColumnType = ColumnType.DOUBLE; } String integerDefaultColumnTypeName = getString(properties, env, PropertyKey.LINE_INTEGER_DEFAULT_COLUMN_TYPE, ColumnType.nameOf(ColumnType.LONG)); this.integerDefaultColumnType = ColumnType.tagOf(integerDefaultColumnTypeName); if (integerDefaultColumnType != ColumnType.LONG && integerDefaultColumnType != ColumnType.INT && integerDefaultColumnType != ColumnType.SHORT && integerDefaultColumnType != ColumnType.BYTE) { log.info().$("invalid default column type for integer ").$(integerDefaultColumnTypeName).$(", will use LONG").$(); this.integerDefaultColumnType = ColumnType.LONG; } } this.ilpAutoCreateNewColumns = getBoolean(properties, env, PropertyKey.LINE_AUTO_CREATE_NEW_COLUMNS, true); this.ilpAutoCreateNewTables = getBoolean(properties, env, PropertyKey.LINE_AUTO_CREATE_NEW_TABLES, true); this.sharedWorkerCount = getInt(properties, env, PropertyKey.SHARED_WORKER_COUNT, Math.max(4, cpuAvailable - cpuSpare - cpuUsed)); this.sharedWorkerAffinity = getAffinity(properties, env, PropertyKey.SHARED_WORKER_AFFINITY, sharedWorkerCount); this.sharedWorkerHaltOnError = getBoolean(properties, env, PropertyKey.SHARED_WORKER_HALT_ON_ERROR, false); this.sharedWorkerYieldThreshold = getLong(properties, env, PropertyKey.SHARED_WORKER_YIELD_THRESHOLD, 10); this.sharedWorkerNapThreshold = getLong(properties, env, PropertyKey.SHARED_WORKER_NAP_THRESHOLD, 7_000); this.sharedWorkerSleepThreshold = getLong(properties, env, PropertyKey.SHARED_WORKER_SLEEP_THRESHOLD, 10_000); this.sharedWorkerSleepTimeout = getLong(properties, env, PropertyKey.SHARED_WORKER_SLEEP_TIMEOUT, 10); this.sqlCompilerPoolCapacity = 2 * (httpWorkerCount + pgWorkerCount + sharedWorkerCount + walApplyWorkerCount); final int defaultReduceQueueCapacity = Math.min(2 * sharedWorkerCount, 64); this.cairoPageFrameReduceQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_PAGE_FRAME_REDUCE_QUEUE_CAPACITY, defaultReduceQueueCapacity)); this.cairoGroupByMergeShardQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_SQL_PARALLEL_GROUPBY_MERGE_QUEUE_CAPACITY, defaultReduceQueueCapacity)); this.cairoGroupByShardingThreshold = getInt(properties, env, PropertyKey.CAIRO_SQL_PARALLEL_GROUPBY_SHARDING_THRESHOLD, 100_000); this.cairoPageFrameReduceRowIdListCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_PAGE_FRAME_ROWID_LIST_CAPACITY, 256)); this.cairoPageFrameReduceColumnListCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_PAGE_FRAME_COLUMN_LIST_CAPACITY, 16)); final int defaultReduceShardCount = Math.min(sharedWorkerCount, 4); this.cairoPageFrameReduceShardCount = getInt(properties, env, PropertyKey.CAIRO_PAGE_FRAME_SHARD_COUNT, defaultReduceShardCount); this.sqlParallelFilterPreTouchEnabled = getBoolean(properties, env, PropertyKey.CAIRO_SQL_PARALLEL_FILTER_PRETOUCH_ENABLED, true); this.sqlCopyModelPoolCapacity = getInt(properties, env, PropertyKey.CAIRO_SQL_COPY_MODEL_POOL_CAPACITY, 32); boolean defaultParallelSqlEnabled = sharedWorkerCount >= 4; this.sqlParallelFilterEnabled = getBoolean(properties, env, PropertyKey.CAIRO_SQL_PARALLEL_FILTER_ENABLED, defaultParallelSqlEnabled); this.sqlParallelGroupByEnabled = getBoolean(properties, env, PropertyKey.CAIRO_SQL_PARALLEL_GROUPBY_ENABLED, defaultParallelSqlEnabled); this.metricsEnabled = getBoolean(properties, env, PropertyKey.METRICS_ENABLED, false); this.writerAsyncCommandBusyWaitTimeout = getLong(properties, env, PropertyKey.CAIRO_WRITER_ALTER_BUSY_WAIT_TIMEOUT, 500); this.writerAsyncCommandMaxWaitTimeout = getLong(properties, env, PropertyKey.CAIRO_WRITER_ALTER_MAX_WAIT_TIMEOUT, 30_000); this.writerTickRowsCountMod = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_WRITER_TICK_ROWS_COUNT, 1024)) - 1; this.writerAsyncCommandQueueCapacity = Numbers.ceilPow2(getInt(properties, env, PropertyKey.CAIRO_WRITER_COMMAND_QUEUE_CAPACITY, 32)); this.writerAsyncCommandQueueSlotSize = Numbers.ceilPow2(getLongSize(properties, env, PropertyKey.CAIRO_WRITER_COMMAND_QUEUE_SLOT_SIZE, 2048)); this.buildInformation = buildInformation; this.binaryEncodingMaxLength = getInt(properties, env, PropertyKey.BINARYDATA_ENCODING_MAXLENGTH, 32768); } this.allowTableRegistrySharedWrite = getBoolean(properties, env, PropertyKey.DEBUG_ALLOW_TABLE_REGISTRY_SHARED_WRITE, false); this.enableTestFactories = getBoolean(properties, env, PropertyKey.DEBUG_ENABLE_TEST_FACTORIES, false); } public static String rootSubdir(CharSequence dbRoot, CharSequence subdir) { if (dbRoot != null) { int len = dbRoot.length(); int end = len; boolean needsSlash = true; for (int i = len - 1; i > -1; --i) { if (dbRoot.charAt(i) == Files.SEPARATOR) { if (i == len - 1) { continue; } end = i + 1; needsSlash = false; break; } } StringSink sink = Misc.getThreadLocalSink(); sink.put(dbRoot, 0, end); if (needsSlash) { sink.put(Files.SEPARATOR); } return sink.put(subdir).toString(); } return null; } @Override public CairoConfiguration getCairoConfiguration() { return cairoConfiguration; } @Override public FactoryProvider getFactoryProvider() { if (factoryProvider == null) { throw new IllegalStateException("configuration.init() has not been invoked"); } return factoryProvider; } @Override public HttpMinServerConfiguration getHttpMinServerConfiguration() { return httpMinServerConfiguration; } @Override public HttpServerConfiguration getHttpServerConfiguration() { return httpServerConfiguration; } @Override public LineTcpReceiverConfiguration getLineTcpReceiverConfiguration() { return lineTcpReceiverConfiguration; } @Override public LineUdpReceiverConfiguration getLineUdpReceiverConfiguration() { return lineUdpReceiverConfiguration; } @Override public MetricsConfiguration getMetricsConfiguration() { return metricsConfiguration; } @Override public PGWireConfiguration getPGWireConfiguration() { return pgWireConfiguration; } @Override public WorkerPoolConfiguration getWalApplyPoolConfiguration() { return walApplyPoolConfiguration; } @Override public WorkerPoolConfiguration getWorkerPoolConfiguration() { return sharedWorkerPoolConfiguration; } @Override public void init(CairoEngine engine, FreeOnExit freeOnExit) { this.factoryProvider = fpf.getInstance(this, engine, freeOnExit); } private int[] getAffinity(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, int workerCount) throws ServerConfigurationException { final int[] result = new int[workerCount]; String value = getString(properties, env, key, null); if (value == null) { Arrays.fill(result, -1); } else { String[] affinity = value.split(","); if (affinity.length != workerCount) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), "wrong number of affinity values"); } for (int i = 0; i < workerCount; i++) { try { result[i] = Numbers.parseInt(affinity[i]); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), "Invalid affinity value: " + affinity[i]); } } } return result; } private int getCommitMode(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key) { final String commitMode = getString(properties, env, key, "nosync"); // must not be null because we provided non-null default value assert commitMode != null; if (Chars.equalsLowerCaseAscii(commitMode, "nosync")) { return CommitMode.NOSYNC; } if (Chars.equalsLowerCaseAscii(commitMode, "async")) { return CommitMode.ASYNC; } if (Chars.equalsLowerCaseAscii(commitMode, "sync")) { return CommitMode.SYNC; } return CommitMode.NOSYNC; } private LineTimestampAdapter getLineTimestampAdaptor(Properties properties, Map<String, String> env, ConfigPropertyKey propNm) { final String lineUdpTimestampSwitch = getString(properties, env, propNm, "n"); switch (lineUdpTimestampSwitch) { case "u": return LineMicroTimestampAdapter.INSTANCE; case "ms": return LineMilliTimestampAdapter.INSTANCE; case "s": return LineSecondTimestampAdapter.INSTANCE; case "m": return LineMinuteTimestampAdapter.INSTANCE; case "h": return LineHourTimestampAdapter.INSTANCE; default: return LineNanoTimestampAdapter.INSTANCE; } } private int getSqlJitMode(Properties properties, @Nullable Map<String, String> env) { final String jitMode = getString(properties, env, PropertyKey.CAIRO_SQL_JIT_MODE, "on"); assert jitMode != null; if (Chars.equalsLowerCaseAscii(jitMode, "on")) { return SqlJitMode.JIT_MODE_ENABLED; } if (Chars.equalsLowerCaseAscii(jitMode, "off")) { return SqlJitMode.JIT_MODE_DISABLED; } if (Chars.equalsLowerCaseAscii(jitMode, "scalar")) { return SqlJitMode.JIT_MODE_FORCE_SCALAR; } return SqlJitMode.JIT_MODE_ENABLED; } private DateFormat getTimestampFormat(Properties properties, @Nullable Map<String, String> env) { return compiler.compile(getString(properties, env, PropertyKey.CAIRO_SQL_BACKUP_DIR_DATETIME_FORMAT, "yyyy-MM-dd")); } private boolean pathEquals(String p1, String p2) { try { if (p1 == null || p2 == null) { return false; } //unfortunately java.io.Files.isSameFile() doesn't work on files that don't exist return new File(p1).getCanonicalPath().replace(File.separatorChar, '/') .equals(new File(p2).getCanonicalPath().replace(File.separatorChar, '/')); } catch (IOException e) { log.info().$("Can't validate configuration property [key=").$(PropertyKey.CAIRO_SQL_COPY_WORK_ROOT.getPropertyPath()) .$(", value=").$(p2).$("]"); return false; } } private void validateProperties(Properties properties, boolean configValidationStrict) throws ServerConfigurationException { ValidationResult validation = validator.validate(properties); if (validation != null) { if (validation.isError && configValidationStrict) { throw new ServerConfigurationException(validation.message); } else { log.advisory().$(validation.message).$(); } } } protected boolean getBoolean(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, boolean defaultValue) { return Boolean.parseBoolean(getString(properties, env, key, Boolean.toString(defaultValue))); } String getCanonicalPath(String path) throws ServerConfigurationException { try { return new File(path).getCanonicalPath(); } catch (IOException e) { throw new ServerConfigurationException("Cannot calculate canonical path for configuration property [key=" + PropertyKey.CAIRO_SQL_COPY_WORK_ROOT.getPropertyPath() + ",value=" + path + "]"); } } protected double getDouble(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, String defaultValue) throws ServerConfigurationException { final String value = getString(properties, env, key, defaultValue); try { return Numbers.parseDouble(value); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), value); } } @SuppressWarnings("SameParameterValue") protected int getIPv4Address(Properties properties, Map<String, String> env, ConfigPropertyKey key, String defaultValue) throws ServerConfigurationException { final String value = getString(properties, env, key, defaultValue); try { return Net.parseIPv4(value); } catch (NetworkError e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), value); } } protected int getInt(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, int defaultValue) throws ServerConfigurationException { final String value = getString(properties, env, key, Integer.toString(defaultValue)); try { return Numbers.parseInt(value); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), value); } } protected int getIntSize(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, int defaultValue) throws ServerConfigurationException { final String value = getString(properties, env, key, Integer.toString(defaultValue)); try { return Numbers.parseIntSize(value); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), value); } } protected long getLong(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, long defaultValue) throws ServerConfigurationException { final String value = getString(properties, env, key, Long.toString(defaultValue)); try { return Numbers.parseLong(value); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), value); } } protected long getLongSize(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, long defaultValue) throws ServerConfigurationException { final String value = getString(properties, env, key, Long.toString(defaultValue)); try { return Numbers.parseLongSize(value); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), value); } } protected int getQueueCapacity(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, int defaultValue) throws ServerConfigurationException { final int value = getInt(properties, env, key, defaultValue); if (!Numbers.isPow2(value)) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), "Value must be power of 2, e.g. 1,2,4,8,16,32,64..."); } return value; } protected String getString(Properties properties, @Nullable Map<String, String> env, ConfigPropertyKey key, String defaultValue) { String envCandidate = key.getEnvVarName(); String result = env != null ? env.get(envCandidate) : null; final int valueSource; if (result != null) { log.info().$("env config [key=").$(envCandidate).I$(); valueSource = ConfigPropertyValue.VALUE_SOURCE_ENV; } else { result = properties.getProperty(key.getPropertyPath()); if (result == null) { result = defaultValue; valueSource = ConfigPropertyValue.VALUE_SOURCE_DEFAULT; } else { valueSource = ConfigPropertyValue.VALUE_SOURCE_CONF; } } if (!key.isDebug()) { allPairs.put(key, new ConfigPropertyValueImpl(result, valueSource, false)); } return result; } protected PropertyValidator newValidator() { return new PropertyValidator(); } protected void parseBindTo( Properties properties, Map<String, String> env, ConfigPropertyKey key, String defaultValue, BindToParser parser ) throws ServerConfigurationException { final String bindTo = getString(properties, env, key, defaultValue); final int colonIndex = bindTo.indexOf(':'); if (colonIndex == -1) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), bindTo); } final String ipv4Str = bindTo.substring(0, colonIndex); final int ipv4; try { ipv4 = Net.parseIPv4(ipv4Str); } catch (NetworkError e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), ipv4Str); } final String portStr = bindTo.substring(colonIndex + 1); final int port; try { port = Numbers.parseInt(portStr); } catch (NumericException e) { throw ServerConfigurationException.forInvalidKey(key.getPropertyPath(), portStr); } parser.onReady(ipv4, port); } @FunctionalInterface protected interface BindToParser { void onReady(int address, int port); } public static class JsonPropertyValueFormatter { public static String bool(boolean value) { return Boolean.toString(value); } public static String integer(int value) { return Integer.toString(value); } public static String str(String value) { return value != null ? '"' + value + '"' : "null"; } } public static class PropertyValidator { protected final Map<ConfigPropertyKey, String> deprecatedSettings = new HashMap<>(); protected final Map<String, String> obsoleteSettings = new HashMap<>(); public PropertyValidator() { registerObsolete( "line.tcp.commit.timeout", PropertyKey.LINE_TCP_COMMIT_INTERVAL_DEFAULT, PropertyKey.LINE_TCP_COMMIT_INTERVAL_FRACTION ); registerObsolete( "cairo.timestamp.locale", PropertyKey.CAIRO_DATE_LOCALE ); registerObsolete( "pg.timestamp.locale", PropertyKey.PG_DATE_LOCALE ); registerObsolete( "cairo.sql.append.page.size", PropertyKey.CAIRO_WRITER_DATA_APPEND_PAGE_SIZE ); registerDeprecated( PropertyKey.HTTP_MIN_BIND_TO, PropertyKey.HTTP_MIN_NET_BIND_TO ); registerDeprecated( PropertyKey.HTTP_MIN_NET_IDLE_CONNECTION_TIMEOUT, PropertyKey.HTTP_MIN_NET_CONNECTION_TIMEOUT ); registerDeprecated( PropertyKey.HTTP_MIN_NET_QUEUED_CONNECTION_TIMEOUT, PropertyKey.HTTP_MIN_NET_CONNECTION_QUEUE_TIMEOUT ); registerDeprecated( PropertyKey.HTTP_MIN_NET_SND_BUF_SIZE, PropertyKey.HTTP_MIN_NET_CONNECTION_SNDBUF ); registerDeprecated( PropertyKey.HTTP_NET_RCV_BUF_SIZE, PropertyKey.HTTP_MIN_NET_CONNECTION_RCVBUF, PropertyKey.HTTP_NET_CONNECTION_RCVBUF ); registerDeprecated( PropertyKey.HTTP_NET_ACTIVE_CONNECTION_LIMIT, PropertyKey.HTTP_NET_CONNECTION_LIMIT ); registerDeprecated( PropertyKey.HTTP_NET_IDLE_CONNECTION_TIMEOUT, PropertyKey.HTTP_NET_CONNECTION_TIMEOUT ); registerDeprecated( PropertyKey.HTTP_NET_QUEUED_CONNECTION_TIMEOUT, PropertyKey.HTTP_NET_CONNECTION_QUEUE_TIMEOUT ); registerDeprecated( PropertyKey.HTTP_NET_SND_BUF_SIZE, PropertyKey.HTTP_NET_CONNECTION_SNDBUF ); registerDeprecated( PropertyKey.PG_NET_ACTIVE_CONNECTION_LIMIT, PropertyKey.PG_NET_CONNECTION_LIMIT ); registerDeprecated( PropertyKey.PG_NET_IDLE_TIMEOUT, PropertyKey.PG_NET_CONNECTION_TIMEOUT ); registerDeprecated( PropertyKey.PG_NET_RECV_BUF_SIZE, PropertyKey.PG_NET_CONNECTION_RCVBUF ); registerDeprecated( PropertyKey.LINE_TCP_NET_ACTIVE_CONNECTION_LIMIT, PropertyKey.LINE_TCP_NET_CONNECTION_LIMIT ); registerDeprecated( PropertyKey.LINE_TCP_NET_IDLE_TIMEOUT, PropertyKey.LINE_TCP_NET_CONNECTION_TIMEOUT ); registerDeprecated( PropertyKey.LINE_TCP_NET_QUEUED_TIMEOUT, PropertyKey.LINE_TCP_NET_CONNECTION_QUEUE_TIMEOUT ); registerDeprecated( PropertyKey.LINE_TCP_NET_RECV_BUF_SIZE, PropertyKey.LINE_TCP_NET_CONNECTION_RCVBUF ); registerDeprecated( PropertyKey.LINE_TCP_DEFAULT_PARTITION_BY, PropertyKey.LINE_DEFAULT_PARTITION_BY ); registerDeprecated( PropertyKey.CAIRO_REPLACE_BUFFER_MAX_SIZE, PropertyKey.CAIRO_SQL_STR_FUNCTION_BUFFER_MAX_SIZE ); registerDeprecated( PropertyKey.CIRCUIT_BREAKER_BUFFER_SIZE, PropertyKey.NET_TEST_CONNECTION_BUFFER_SIZE ); registerDeprecated( PropertyKey.CAIRO_PAGE_FRAME_TASK_POOL_CAPACITY ); registerDeprecated( PropertyKey.CAIRO_SQL_MAP_PAGE_SIZE, PropertyKey.CAIRO_SQL_SMALL_MAP_PAGE_SIZE ); registerDeprecated( PropertyKey.CAIRO_SQL_MAP_KEY_CAPACITY, PropertyKey.CAIRO_SQL_SMALL_MAP_KEY_CAPACITY ); registerDeprecated(PropertyKey.PG_INSERT_POOL_CAPACITY); registerDeprecated(PropertyKey.LINE_UDP_TIMESTAMP); registerDeprecated(PropertyKey.LINE_TCP_TIMESTAMP); registerDeprecated(PropertyKey.CAIRO_QUERY_CACHE_EVENT_QUEUE_CAPACITY); registerDeprecated(PropertyKey.CAIRO_SQL_JIT_ROWS_THRESHOLD); registerDeprecated(PropertyKey.CAIRO_COMPACT_MAP_LOAD_FACTOR); registerDeprecated(PropertyKey.CAIRO_DEFAULT_MAP_TYPE); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_COLUMN_POOL_CAPACITY, PropertyKey.CAIRO_SQL_WINDOW_COLUMN_POOL_CAPACITY ); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_STORE_PAGE_SIZE, PropertyKey.CAIRO_SQL_WINDOW_STORE_PAGE_SIZE ); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_STORE_MAX_PAGES, PropertyKey.CAIRO_SQL_WINDOW_STORE_MAX_PAGES ); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_ROWID_PAGE_SIZE, PropertyKey.CAIRO_SQL_WINDOW_ROWID_PAGE_SIZE ); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_ROWID_MAX_PAGES, PropertyKey.CAIRO_SQL_WINDOW_ROWID_MAX_PAGES ); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_TREE_PAGE_SIZE, PropertyKey.CAIRO_SQL_WINDOW_TREE_PAGE_SIZE ); registerDeprecated( PropertyKey.CAIRO_SQL_ANALYTIC_TREE_MAX_PAGES, PropertyKey.CAIRO_SQL_WINDOW_TREE_MAX_PAGES ); } public ValidationResult validate(Properties properties) { // Settings that used to be valid but no longer are. Map<String, String> obsolete = new HashMap<>(); // Settings that are still valid but are now superseded by newer ones. Map<String, String> deprecated = new HashMap<>(); // Settings that are not recognized. Set<String> incorrect = new HashSet<>(); for (String propName : properties.stringPropertyNames()) { Optional<ConfigPropertyKey> prop = lookupConfigProperty(propName); if (prop.isPresent()) { String deprecationMsg = deprecatedSettings.get(prop.get()); if (deprecationMsg != null) { deprecated.put(propName, deprecationMsg); } } else { String obsoleteMsg = obsoleteSettings.get(propName); if (obsoleteMsg != null) { obsolete.put(propName, obsoleteMsg); } else { incorrect.add(propName); } } } if (obsolete.isEmpty() && deprecated.isEmpty() && incorrect.isEmpty()) { return null; } boolean isError = false; StringBuilder sb = new StringBuilder("Configuration issues:\n"); if (!incorrect.isEmpty()) { isError = true; sb.append(" Invalid settings (not recognized, probable typos):\n"); for (String key : incorrect) { sb.append(" * "); sb.append(key); sb.append('\n'); } } if (!obsolete.isEmpty()) { isError = true; sb.append(" Obsolete settings (no longer recognized):\n"); for (Map.Entry<String, String> entry : obsolete.entrySet()) { sb.append(" * "); sb.append(entry.getKey()); sb.append(": "); sb.append(entry.getValue()); sb.append('\n'); } } if (!deprecated.isEmpty()) { sb.append(" Deprecated settings (recognized but superseded by newer settings):\n"); for (Map.Entry<String, String> entry : deprecated.entrySet()) { sb.append(" * "); sb.append(entry.getKey()); sb.append(": "); sb.append(entry.getValue()); sb.append('\n'); } } return new ValidationResult(isError, sb.toString()); } private static <KeyT> void registerReplacements( Map<KeyT, String> map, KeyT old, ConfigPropertyKey... replacements ) { if (replacements.length > 0) { final StringBuilder sb = new StringBuilder("Replaced by "); for (int index = 0; index < replacements.length; index++) { if (index > 0) { sb.append(index < (replacements.length - 1) ? ", " : " and "); } String replacement = replacements[index].getPropertyPath(); sb.append('`'); sb.append(replacement); sb.append('`'); } map.put(old, sb.toString()); } else { map.put(old, "No longer used"); } } protected Optional<ConfigPropertyKey> lookupConfigProperty(String propName) { return PropertyKey.getByString(propName).map(prop -> prop); } protected void registerDeprecated(ConfigPropertyKey old, ConfigPropertyKey... replacements) { registerReplacements(deprecatedSettings, old, replacements); } protected void registerObsolete(String old, ConfigPropertyKey... replacements) { registerReplacements(obsoleteSettings, old, replacements); } } public static class ValidationResult { public final boolean isError; public final String message; private ValidationResult(boolean isError, String message) { this.isError = isError; this.message = message; } } class PropCairoConfiguration implements CairoConfiguration { private final LongSupplier randomIDSupplier = () -> getRandom().nextPositiveLong(); private final LongSupplier sequentialIDSupplier = new LongSupplier() { final AtomicLong value = new AtomicLong(); @Override public long getAsLong() { return value.incrementAndGet(); } }; @Override public boolean attachPartitionCopy() { return cairoAttachPartitionCopy; } @Override public boolean enableTestFactories() { return enableTestFactories; } @Override public @Nullable ObjObjHashMap<ConfigPropertyKey, ConfigPropertyValue> getAllPairs() { return allPairs; } @Override public boolean getAllowTableRegistrySharedWrite() { return allowTableRegistrySharedWrite; } @Override public @NotNull String getAttachPartitionSuffix() { return cairoAttachPartitionSuffix; } @Override public DateFormat getBackupDirTimestampFormat() { return backupDirTimestampFormat; } @Override public int getBackupMkDirMode() { return backupMkdirMode; } @Override public CharSequence getBackupRoot() { return backupRoot; } @Override public @NotNull CharSequence getBackupTempDirName() { return backupTempDirName; } @Override public int getBinaryEncodingMaxLength() { return binaryEncodingMaxLength; } @Override public int getBindVariablePoolSize() { return sqlBindVariablePoolSize; } @Override public @NotNull BuildInformation getBuildInformation() { return buildInformation; } @Override public @NotNull SqlExecutionCircuitBreakerConfiguration getCircuitBreakerConfiguration() { return circuitBreakerConfiguration; } @Override public int getColumnCastModelPoolCapacity() { return sqlColumnCastModelPoolCapacity; } @Override public int getColumnIndexerQueueCapacity() { return columnIndexerQueueCapacity; } @Override public int getColumnPurgeQueueCapacity() { return columnPurgeQueueCapacity; } @Override public long getColumnPurgeRetryDelay() { return columnPurgeRetryDelay; } @Override public long getColumnPurgeRetryDelayLimit() { return columnPurgeRetryDelayLimit; } @Override public double getColumnPurgeRetryDelayMultiplier() { return columnPurgeRetryDelayMultiplier; } @Override public int getColumnPurgeTaskPoolCapacity() { return columnPurgeTaskPoolCapacity; } @Override public int getCommitMode() { return commitMode; } @Override public @NotNull CharSequence getConfRoot() { return confRoot; } @Override public @NotNull LongSupplier getCopyIDSupplier() { if (cairoSQLCopyIdSupplier == 0) { return randomIDSupplier; } return sequentialIDSupplier; } @Override public int getCopyPoolCapacity() { return sqlCopyModelPoolCapacity; } @Override public int getCountDistinctCapacity() { return sqlCountDistinctCapacity; } @Override public double getCountDistinctLoadFactor() { return sqlCountDistinctLoadFactor; } @Override public int getCreateAsSelectRetryCount() { return createAsSelectRetryCount; } @Override public long getCreateTableModelBatchSize() { return sqlCreateTableModelBatchSize; } @Override public int getCreateTableModelPoolCapacity() { return sqlCreateTableModelPoolCapacity; } @Override public long getDataAppendPageSize() { return writerDataAppendPageSize; } @Override public long getDataIndexKeyAppendPageSize() { return writerDataIndexKeyAppendPageSize; } @Override public long getDataIndexValueAppendPageSize() { return writerDataIndexValueAppendPageSize; } @Override public long getDatabaseIdHi() { return instanceHashHi; } @Override public long getDatabaseIdLo() { return instanceHashLo; } @Override public @NotNull CharSequence getDbDirectory() { return dbDirectory; } @Override public @NotNull DateLocale getDefaultDateLocale() { return locale; } @Override public int getDefaultSeqPartTxnCount() { return defaultSeqPartTxnCount; } @Override public boolean getDefaultSymbolCacheFlag() { return defaultSymbolCacheFlag; } @Override public int getDefaultSymbolCapacity() { return defaultSymbolCapacity; } @Override public int getDetachedMkDirMode() { return detachedMkdirMode; } @Override public int getDoubleToStrCastScale() { return sqlDoubleToStrCastScale; } @Override public int getExplainPoolCapacity() { return sqlExplainModelPoolCapacity; } @Override public @NotNull FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public int getFileOperationRetryCount() { return fileOperationRetryCount; } @Override public @NotNull FilesFacade getFilesFacade() { return filesFacade; } @Override public int getFloatToStrCastScale() { return sqlFloatToStrCastScale; } @Override public long getGroupByAllocatorDefaultChunkSize() { return sqlGroupByAllocatorChunkSize; } @Override public long getGroupByAllocatorMaxChunkSize() { return sqlGroupByAllocatorMaxChunkSize; } @Override public int getGroupByMapCapacity() { return sqlGroupByMapCapacity; } @Override public int getGroupByMergeShardQueueCapacity() { return cairoGroupByMergeShardQueueCapacity; } @Override public int getGroupByPoolCapacity() { return sqlGroupByPoolCapacity; } @Override public int getGroupByShardingThreshold() { return cairoGroupByShardingThreshold; } @Override public long getIdleCheckInterval() { return idleCheckInterval; } @Override public int getInactiveReaderMaxOpenPartitions() { return inactiveReaderMaxOpenPartitions; } @Override public long getInactiveReaderTTL() { return inactiveReaderTTL; } @Override public long getInactiveWalWriterTTL() { return inactiveWalWriterTTL; } @Override public long getInactiveWriterTTL() { return inactiveWriterTTL; } @Override public int getIndexValueBlockSize() { return indexValueBlockSize; } @Override public long getInsertModelBatchSize() { return sqlInsertModelBatchSize; } @Override public int getInsertModelPoolCapacity() { return sqlInsertModelPoolCapacity; } @Override public int getLatestByQueueCapacity() { return latestByQueueCapacity; } @Override public int getMaxCrashFiles() { return cairoMaxCrashFiles; } @Override public int getMaxFileNameLength() { return maxFileNameLength; } @Override public int getMaxSqlRecompileAttempts() { return maxSqlRecompileAttempts; } @Override public int getMaxSwapFileCount() { return maxSwapFileCount; } @Override public int getMaxSymbolNotEqualsCount() { return sqlMaxSymbolNotEqualsCount; } @Override public int getMaxUncommittedRows() { return maxUncommittedRows; } @Override public int getMetadataPoolCapacity() { return sqlModelPoolCapacity; } @Override public @NotNull MicrosecondClock getMicrosecondClock() { return microsecondClock; } @Override public long getMiscAppendPageSize() { return writerMiscAppendPageSize; } @Override public int getMkDirMode() { return mkdirMode; } @Override public int getO3CallbackQueueCapacity() { return o3CallbackQueueCapacity; } @Override public int getO3ColumnMemorySize() { return o3ColumnMemorySize; } @Override public int getO3CopyQueueCapacity() { return o3CopyQueueCapacity; } @Override public int getO3LagCalculationWindowsSize() { return o3LagCalculationWindowsSize; } @Override public int getO3LastPartitionMaxSplits() { return o3LastPartitionMaxSplits; } @Override public long getO3MaxLag() { return o3MaxLag; } @Override public int getO3MemMaxPages() { return Integer.MAX_VALUE; } @Override public long getO3MinLag() { return o3MinLagUs; } @Override public int getO3OpenColumnQueueCapacity() { return o3OpenColumnQueueCapacity; } @Override public int getO3PartitionQueueCapacity() { return o3PartitionQueueCapacity; } @Override public int getO3PurgeDiscoveryQueueCapacity() { return o3PurgeDiscoveryQueueCapacity; } @Override public int getPageFrameReduceColumnListCapacity() { return cairoPageFrameReduceColumnListCapacity; } @Override public int getPageFrameReduceQueueCapacity() { return cairoPageFrameReduceQueueCapacity; } @Override public int getPageFrameReduceRowIdListCapacity() { return cairoPageFrameReduceRowIdListCapacity; } @Override public int getPageFrameReduceShardCount() { return cairoPageFrameReduceShardCount; } @Override public int getParallelIndexThreshold() { return parallelIndexThreshold; } @Override public long getPartitionO3SplitMinSize() { return o3PartitionSplitMinSize; } @Override public int getPartitionPurgeListCapacity() { return o3PartitionPurgeListCapacity; } @Override public int getQueryRegistryPoolSize() { return sqlQueryRegistryPoolSize; } @Override public int getReaderPoolMaxSegments() { return readerPoolMaxSegments; } @Override public int getRenameTableModelPoolCapacity() { return sqlRenameTableModelPoolCapacity; } @Override public int getRepeatMigrationsFromVersion() { return repeatMigrationFromVersion; } @Override public int getRndFunctionMemoryMaxPages() { return rndFunctionMemoryMaxPages; } @Override public int getRndFunctionMemoryPageSize() { return rndFunctionMemoryPageSize; } @Override public @NotNull String getRoot() { return root; } @Override public boolean getSampleByDefaultAlignmentCalendar() { return sqlSampleByDefaultAlignment; } @Override public int getSampleByIndexSearchPageSize() { return sqlSampleByIndexSearchPageSize; } @Override public boolean getSimulateCrashEnabled() { return simulateCrashEnabled; } @Override public @NotNull CharSequence getSnapshotInstanceId() { return snapshotInstanceId; } @Override public @NotNull CharSequence getSnapshotRoot() { return snapshotRoot; } @Override public long getSpinLockTimeout() { return spinLockTimeout; } @Override public int getSqlAsOfJoinLookAhead() { return sqlAsOfJoinLookahead; } @Override public int getSqlCharacterStoreCapacity() { return sqlCharacterStoreCapacity; } @Override public int getSqlCharacterStoreSequencePoolCapacity() { return sqlCharacterStoreSequencePoolCapacity; } @Override public int getSqlColumnPoolCapacity() { return sqlColumnPoolCapacity; } @Override public int getSqlCompilerPoolCapacity() { return sqlCompilerPoolCapacity; } @Override public int getSqlCopyBufferSize() { return sqlCopyBufferSize; } @Override public CharSequence getSqlCopyInputRoot() { return cairoSqlCopyRoot; } @Override public CharSequence getSqlCopyInputWorkRoot() { return cairoSqlCopyWorkRoot; } @Override public int getSqlCopyLogRetentionDays() { return cairoSqlCopyLogRetentionDays; } @Override public long getSqlCopyMaxIndexChunkSize() { return cairoSqlCopyMaxIndexChunkSize; } @Override public int getSqlCopyQueueCapacity() { return cairoSqlCopyQueueCapacity; } @Override public int getSqlDistinctTimestampKeyCapacity() { return sqlDistinctTimestampKeyCapacity; } @Override public double getSqlDistinctTimestampLoadFactor() { return sqlDistinctTimestampLoadFactor; } @Override public int getSqlExpressionPoolCapacity() { return sqlExpressionPoolCapacity; } @Override public double getSqlFastMapLoadFactor() { return sqlFastMapLoadFactor; } @Override public int getSqlHashJoinLightValueMaxPages() { return sqlHashJoinLightValueMaxPages; } @Override public int getSqlHashJoinLightValuePageSize() { return sqlHashJoinLightValuePageSize; } @Override public int getSqlHashJoinValueMaxPages() { return sqlHashJoinValueMaxPages; } @Override public int getSqlHashJoinValuePageSize() { return sqlHashJoinValuePageSize; } @Override public int getSqlJitBindVarsMemoryMaxPages() { return sqlJitBindVarsMemoryMaxPages; } @Override public int getSqlJitBindVarsMemoryPageSize() { return sqlJitBindVarsMemoryPageSize; } @Override public int getSqlJitIRMemoryMaxPages() { return sqlJitIRMemoryMaxPages; } @Override public int getSqlJitIRMemoryPageSize() { return sqlJitIRMemoryPageSize; } @Override public int getSqlJitMode() { return sqlJitMode; } @Override public int getSqlJitPageAddressCacheThreshold() { return sqlJitPageAddressCacheThreshold; } @Override public int getSqlJoinContextPoolCapacity() { return sqlJoinContextPoolCapacity; } @Override public int getSqlJoinMetadataMaxResizes() { return sqlJoinMetadataMaxResizes; } @Override public int getSqlJoinMetadataPageSize() { return sqlJoinMetadataPageSize; } @Override public long getSqlLatestByRowCount() { return sqlLatestByRowCount; } @Override public int getSqlLexerPoolCapacity() { return sqlLexerPoolCapacity; } @Override public int getSqlMapMaxPages() { return sqlMapMaxPages; } @Override public int getSqlMapMaxResizes() { return sqlMapMaxResizes; } @Override public int getSqlMaxNegativeLimit() { return sqlMaxNegativeLimit; } @Override public int getSqlModelPoolCapacity() { return sqlModelPoolCapacity; } @Override public int getSqlPageFrameMaxRows() { return sqlPageFrameMaxRows; } @Override public int getSqlPageFrameMinRows() { return sqlPageFrameMinRows; } @Override public int getSqlSmallMapKeyCapacity() { return sqlSmallMapKeyCapacity; } @Override public int getSqlSmallMapPageSize() { return sqlSmallMapPageSize; } @Override public int getSqlSortKeyMaxPages() { return sqlSortKeyMaxPages; } @Override public long getSqlSortKeyPageSize() { return sqlSortKeyPageSize; } @Override public int getSqlSortLightValueMaxPages() { return sqlSortLightValueMaxPages; } @Override public long getSqlSortLightValuePageSize() { return sqlSortLightValuePageSize; } @Override public int getSqlSortValueMaxPages() { return sqlSortValueMaxPages; } @Override public int getSqlSortValuePageSize() { return sqlSortValuePageSize; } @Override public int getSqlUnorderedMapMaxEntrySize() { return sqlUnorderedMapMaxEntrySize; } @Override public int getSqlWindowInitialRangeBufferSize() { return sqlWindowInitialRangeBufferSize; } @Override public int getSqlWindowMaxRecursion() { return sqlWindowMaxRecursion; } @Override public int getSqlWindowRowIdMaxPages() { return sqlWindowRowIdMaxPages; } @Override public int getSqlWindowRowIdPageSize() { return sqlWindowRowIdPageSize; } @Override public int getSqlWindowStoreMaxPages() { return sqlWindowStoreMaxPages; } @Override public int getSqlWindowStorePageSize() { return sqlWindowStorePageSize; } @Override public int getSqlWindowTreeKeyMaxPages() { return sqlWindowTreeKeyMaxPages; } @Override public int getSqlWindowTreeKeyPageSize() { return sqlWindowTreeKeyPageSize; } @Override public int getStrFunctionMaxBufferLength() { return sqlStrFunctionBufferMaxSize; } @Override public long getSystemDataAppendPageSize() { return systemWriterDataAppendPageSize; } @Override public int getSystemO3ColumnMemorySize() { return systemO3ColumnMemorySize; } @Override public @NotNull CharSequence getSystemTableNamePrefix() { return systemTableNamePrefix; } @Override public long getSystemWalDataAppendPageSize() { return systemWalWriterDataAppendPageSize; } @Override public long getSystemWalEventAppendPageSize() { return systemWalWriterEventAppendPageSize; } @Override public long getTableRegistryAutoReloadFrequency() { return cairoTableRegistryAutoReloadFrequency; } @Override public int getTableRegistryCompactionThreshold() { return cairoTableRegistryCompactionThreshold; } public @NotNull TelemetryConfiguration getTelemetryConfiguration() { return telemetryConfiguration; } @Override public CharSequence getTempRenamePendingTablePrefix() { return tempRenamePendingTablePrefix; } @Override public @NotNull TextConfiguration getTextConfiguration() { return textConfiguration; } @Override public int getTxnScoreboardEntryCount() { return sqlTxnScoreboardEntryCount; } @Override public int getVectorAggregateQueueCapacity() { return vectorAggregateQueueCapacity; } @Override public @NotNull VolumeDefinitions getVolumeDefinitions() { return volumeDefinitions; } @Override public int getWalApplyLookAheadTransactionCount() { return walApplyLookAheadTransactionCount; } @Override public long getWalApplyTableTimeQuota() { return walApplyTableTimeQuota; } @Override public long getWalDataAppendPageSize() { return walWriterDataAppendPageSize; } @Override public boolean getWalEnabledDefault() { return walEnabledDefault; } @Override public long getWalEventAppendPageSize() { return walWriterEventAppendPageSize; } @Override public long getWalMaxLagSize() { return walMaxLagSize; } @Override public int getWalMaxLagTxnCount() { return walMaxLagTxnCount; } @Override public int getWalMaxSegmentFileDescriptorsCache() { return walMaxSegmentFileDescriptorsCache; } @Override public long getWalPurgeInterval() { return walPurgeInterval; } @Override public long getSequencerCheckInterval() { return sequencerCheckInterval; } @Override public int getWalPurgeWaitBeforeDelete() { return walPurgeWaitBeforeDelete; } @Override public int getWalRecreateDistressedSequencerAttempts() { return walRecreateDistressedSequencerAttempts; } @Override public long getWalSegmentRolloverRowCount() { return walSegmentRolloverRowCount; } @Override public long getWalSegmentRolloverSize() { return walSegmentRolloverSize; } @Override public double getWalSquashUncommittedRowsMultiplier() { return walSquashUncommittedRowsMultiplier; } @Override public int getWalTxnNotificationQueueCapacity() { return walTxnNotificationQueueCapacity; } @Override public int getWalWriterPoolMaxSegments() { return walWriterPoolMaxSegments; } @Override public int getWindowColumnPoolCapacity() { return sqlWindowColumnPoolCapacity; } @Override public int getWithClauseModelPoolCapacity() { return sqlWithClauseModelPoolCapacity; } @Override public long getWorkStealTimeoutNanos() { return workStealTimeoutNanos; } @Override public long getWriterAsyncCommandBusyWaitTimeout() { return writerAsyncCommandBusyWaitTimeout; } @Override public long getWriterAsyncCommandMaxTimeout() { return writerAsyncCommandMaxWaitTimeout; } @Override public int getWriterCommandQueueCapacity() { return writerAsyncCommandQueueCapacity; } @Override public long getWriterCommandQueueSlotSize() { return writerAsyncCommandQueueSlotSize; } @Override public long getWriterFileOpenOpts() { return writerFileOpenOpts; } @Override public long getWriterMemoryLimit() { return writerMemoryLimit; } @Override public int getWriterTickRowsCountMod() { return writerTickRowsCountMod; } @Override public boolean isIOURingEnabled() { return ioURingEnabled; } @Override public boolean isMultiKeyDedupEnabled() { return false; } @Override public boolean isO3QuickSortEnabled() { return o3QuickSortEnabled; } @Override public boolean isParallelIndexingEnabled() { return parallelIndexingEnabled; } @Override public boolean isReadOnlyInstance() { return isReadOnlyInstance; } @Override public boolean isSnapshotRecoveryEnabled() { return snapshotRecoveryEnabled; } @Override public boolean isSqlJitDebugEnabled() { return sqlJitDebugEnabled; } @Override public boolean isSqlParallelFilterEnabled() { return sqlParallelFilterEnabled; } @Override public boolean isSqlParallelFilterPreTouchEnabled() { return sqlParallelFilterPreTouchEnabled; } @Override public boolean isSqlParallelGroupByEnabled() { return sqlParallelGroupByEnabled; } @Override public boolean isTableTypeConversionEnabled() { return tableTypeConversionEnabled; } @Override public boolean isWalApplyEnabled() { return walApplyEnabled; } public boolean isWalSupported() { return walSupported; } @Override public boolean isWriterMixedIOEnabled() { return writerMixedIOEnabled; } @Override public boolean mangleTableDirNames() { return false; } @Override public void populateSettings(CharSequenceObjHashMap<CharSequence> settings) { settings.put(RELEASE_TYPE, str(getReleaseType())); settings.put(RELEASE_VERSION, str(getBuildInformation().getSwVersion())); } } private class PropHttpContextConfiguration implements HttpContextConfiguration { @Override public boolean allowDeflateBeforeSend() { return httpAllowDeflateBeforeSend; } @Override public boolean areCookiesEnabled() { return httpServerCookiesEnabled; } @Override public int getConnectionPoolInitialCapacity() { return connectionPoolInitialCapacity; } @Override public int getConnectionStringPoolCapacity() { return connectionStringPoolCapacity; } @Override public boolean getDumpNetworkTraffic() { return false; } @Override public FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public int getForceRecvFragmentationChunkSize() { return httpForceRecvFragmentationChunkSize; } @Override public int getForceSendFragmentationChunkSize() { return httpForceSendFragmentationChunkSize; } @Override public String getHttpVersion() { return httpVersion; } @Override public MillisecondClock getMillisecondClock() { return httpFrozenClock ? StationaryMillisClock.INSTANCE : MillisecondClockImpl.INSTANCE; } @Override public int getMultipartHeaderBufferSize() { return multipartHeaderBufferSize; } @Override public long getMultipartIdleSpinCount() { return multipartIdleSpinCount; } @Override public NanosecondClock getNanosecondClock() { return httpFrozenClock ? StationaryNanosClock.INSTANCE : NanosecondClockImpl.INSTANCE; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public int getRecvBufferSize() { return httpRecvBufferSize; } @Override public int getRequestHeaderBufferSize() { return requestHeaderBufferSize; } @Override public int getSendBufferSize() { return httpSendBufferSize; } @Override public boolean getServerKeepAlive() { return httpServerKeepAlive; } @Override public boolean readOnlySecurityContext() { return httpReadOnlySecurityContext || isReadOnlyInstance; } } private class PropHttpIODispatcherConfiguration implements IODispatcherConfiguration { @Override public int getBindIPv4Address() { return httpNetBindIPv4Address; } @Override public int getBindPort() { return httpNetBindPort; } @Override public MillisecondClock getClock() { return MillisecondClockImpl.INSTANCE; } @Override public String getDispatcherLogName() { return "http-server"; } @Override public EpollFacade getEpollFacade() { return EpollFacadeImpl.INSTANCE; } @Override public long getHeartbeatInterval() { return -1L; } @Override public boolean getHint() { return httpNetConnectionHint; } @Override public KqueueFacade getKqueueFacade() { return KqueueFacadeImpl.INSTANCE; } @Override public int getLimit() { return httpNetConnectionLimit; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public long getQueueTimeout() { return httpNetConnectionQueueTimeout; } @Override public int getRcvBufSize() { return httpNetConnectionRcvBuf; } @Override public SelectFacade getSelectFacade() { return SelectFacadeImpl.INSTANCE; } @Override public int getSndBufSize() { return httpNetConnectionSndBuf; } @Override public int getTestConnectionBufferSize() { return netTestConnectionBufferSize; } @Override public long getTimeout() { return httpNetConnectionTimeout; } } private class PropHttpMinIODispatcherConfiguration implements IODispatcherConfiguration { @Override public int getBindIPv4Address() { return httpMinBindIPv4Address; } @Override public int getBindPort() { return httpMinBindPort; } @Override public MillisecondClock getClock() { return MillisecondClockImpl.INSTANCE; } @Override public String getDispatcherLogName() { return "http-min-server"; } @Override public EpollFacade getEpollFacade() { return EpollFacadeImpl.INSTANCE; } @Override public long getHeartbeatInterval() { return -1L; } @Override public boolean getHint() { return httpMinNetConnectionHint; } @Override public KqueueFacade getKqueueFacade() { return KqueueFacadeImpl.INSTANCE; } @Override public int getLimit() { return httpMinNetConnectionLimit; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public long getQueueTimeout() { return httpMinNetConnectionQueueTimeout; } @Override public int getRcvBufSize() { return httpMinNetConnectionRcvBuf; } @Override public SelectFacade getSelectFacade() { return SelectFacadeImpl.INSTANCE; } @Override public int getSndBufSize() { return httpMinNetConnectionSndBuf; } @Override public int getTestConnectionBufferSize() { return netTestConnectionBufferSize; } @Override public long getTimeout() { return httpMinNetConnectionTimeout; } } public class PropHttpMinServerConfiguration implements HttpMinServerConfiguration { @Override public IODispatcherConfiguration getDispatcherConfiguration() { return httpMinIODispatcherConfiguration; } @Override public FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public HttpContextConfiguration getHttpContextConfiguration() { return httpContextConfiguration; } @Override public long getNapThreshold() { return httpMinWorkerNapThreshold; } @Override public String getPoolName() { return "minhttp"; } @Override public byte getRequiredAuthType() { return httpHealthCheckAuthType; } @Override public long getSleepThreshold() { return httpMinWorkerSleepThreshold; } @Override public long getSleepTimeout() { return httpMinWorkerSleepTimeout; } @Override public WaitProcessorConfiguration getWaitProcessorConfiguration() { return httpWaitProcessorConfiguration; } @Override public int[] getWorkerAffinity() { return httpMinWorkerAffinity; } @Override public int getWorkerCount() { return httpMinWorkerCount; } @Override public long getYieldThreshold() { return httpMinWorkerYieldThreshold; } @Override public boolean haltOnError() { return httpMinWorkerHaltOnError; } @Override public boolean isEnabled() { return httpMinServerEnabled; } @Override public boolean isPessimisticHealthCheckEnabled() { return httpPessimisticHealthCheckEnabled; } } public class PropHttpServerConfiguration implements HttpServerConfiguration { @Override public IODispatcherConfiguration getDispatcherConfiguration() { return httpIODispatcherConfiguration; } @Override public FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public HttpContextConfiguration getHttpContextConfiguration() { return httpContextConfiguration; } @Override public JsonQueryProcessorConfiguration getJsonQueryProcessorConfiguration() { return jsonQueryProcessorConfiguration; } @Override public LineHttpProcessorConfiguration getLineHttpProcessorConfiguration() { return lineHttpProcessorConfiguration; } @Override public long getNapThreshold() { return httpWorkerNapThreshold; } @Override public String getPoolName() { return "http"; } @Override public int getQueryCacheBlockCount() { return httpSqlCacheBlockCount; } @Override public int getQueryCacheRowCount() { return httpSqlCacheRowCount; } @Override public byte getRequiredAuthType() { return httpHealthCheckAuthType; } @Override public long getSleepThreshold() { return httpWorkerSleepThreshold; } @Override public long getSleepTimeout() { return httpWorkerSleepTimeout; } @Override public StaticContentProcessorConfiguration getStaticContentProcessorConfiguration() { return staticContentProcessorConfiguration; } @Override public WaitProcessorConfiguration getWaitProcessorConfiguration() { return httpWaitProcessorConfiguration; } @Override public int[] getWorkerAffinity() { return httpWorkerAffinity; } @Override public int getWorkerCount() { return httpWorkerCount; } @Override public long getYieldThreshold() { return httpWorkerYieldThreshold; } @Override public boolean haltOnError() { return httpWorkerHaltOnError; } @Override public boolean isEnabled() { return httpServerEnabled; } @Override public boolean isPessimisticHealthCheckEnabled() { return httpPessimisticHealthCheckEnabled; } @Override public boolean isQueryCacheEnabled() { return httpSqlCacheEnabled; } } public class PropJsonQueryProcessorConfiguration implements JsonQueryProcessorConfiguration { @Override public int getConnectionCheckFrequency() { return jsonQueryConnectionCheckFrequency; } @Override public int getDoubleScale() { return jsonQueryDoubleScale; } @Override public FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public FilesFacade getFilesFacade() { return FilesFacadeImpl.INSTANCE; } @Override public int getFloatScale() { return jsonQueryFloatScale; } @Override public CharSequence getKeepAliveHeader() { return keepAliveHeader; } @Override public long getMaxQueryResponseRowLimit() { return maxHttpQueryResponseRowLimit; } @Override public MillisecondClock getMillisecondClock() { return httpFrozenClock ? StationaryMillisClock.INSTANCE : MillisecondClockImpl.INSTANCE; } @Override public NanosecondClock getNanosecondClock() { return httpFrozenClock ? StationaryNanosClock.INSTANCE : NanosecondClockImpl.INSTANCE; } } private class PropLineHttpProcessorConfiguration implements LineHttpProcessorConfiguration { @Override public boolean autoCreateNewColumns() { return ilpAutoCreateNewColumns; } @Override public boolean autoCreateNewTables() { return ilpAutoCreateNewTables; } @Override public short getDefaultColumnTypeForFloat() { return floatDefaultColumnType; } @Override public short getDefaultColumnTypeForInteger() { return integerDefaultColumnType; } @Override public int getDefaultPartitionBy() { return lineTcpDefaultPartitionBy; } @Override public CharSequence getInfluxPingVersion() { return lineHttpPingVersion; } @Override public MicrosecondClock getMicrosecondClock() { return microsecondClock; } @Override public long getSymbolCacheWaitUsBeforeReload() { return symbolCacheWaitUsBeforeReload; } @Override public LineTcpTimestampAdapter getTimestampAdapter() { return lineTcpTimestampAdapter; } @Override public boolean isEnabled() { return lineHttpEnabled; } @Override public boolean isStringToCharCastAllowed() { return stringToCharCastAllowed; } @Override public boolean isUseLegacyStringDefault() { return useLegacyStringDefault; } } private class PropLineTcpIOWorkerPoolConfiguration implements WorkerPoolConfiguration { @Override public long getNapThreshold() { return lineTcpIOWorkerNapThreshold; } @Override public String getPoolName() { return "ilpio"; } @Override public long getSleepThreshold() { return lineTcpIOWorkerSleepThreshold; } @Override public int[] getWorkerAffinity() { return lineTcpIOWorkerAffinity; } @Override public int getWorkerCount() { return lineTcpIOWorkerCount; } @Override public long getYieldThreshold() { return lineTcpIOWorkerYieldThreshold; } @Override public boolean haltOnError() { return lineTcpIOWorkerPoolHaltOnError; } } private class PropLineTcpReceiverConfiguration implements LineTcpReceiverConfiguration { @Override public String getAuthDB() { return lineTcpAuthDB; } @Override public boolean getAutoCreateNewColumns() { return ilpAutoCreateNewColumns; } @Override public boolean getAutoCreateNewTables() { return ilpAutoCreateNewTables; } @Override public long getCommitInterval() { return LineTcpReceiverConfigurationHelper.calcCommitInterval( cairoConfiguration.getO3MinLag(), getCommitIntervalFraction(), getCommitIntervalDefault() ); } public long getCommitIntervalDefault() { return lineTcpCommitIntervalDefault; } @Override public double getCommitIntervalFraction() { return lineTcpCommitIntervalFraction; } @Override public int getConnectionPoolInitialCapacity() { return lineTcpConnectionPoolInitialCapacity; } @Override public short getDefaultColumnTypeForFloat() { return floatDefaultColumnType; } @Override public short getDefaultColumnTypeForInteger() { return integerDefaultColumnType; } @Override public int getDefaultPartitionBy() { return lineTcpDefaultPartitionBy; } @Override public boolean getDisconnectOnError() { return lineTcpDisconnectOnError; } @Override public IODispatcherConfiguration getDispatcherConfiguration() { return lineTcpReceiverDispatcherConfiguration; } @Override public FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public FilesFacade getFilesFacade() { return FilesFacadeImpl.INSTANCE; } @Override public WorkerPoolConfiguration getIOWorkerPoolConfiguration() { return lineTcpIOWorkerPoolConfiguration; } @Override public long getMaintenanceInterval() { return lineTcpMaintenanceInterval; } @Override public int getMaxFileNameLength() { return maxFileNameLength; } @Override public int getMaxMeasurementSize() { return lineTcpMaxMeasurementSize; } @Override public MicrosecondClock getMicrosecondClock() { return MicrosecondClockImpl.INSTANCE; } @Override public MillisecondClock getMillisecondClock() { return MillisecondClockImpl.INSTANCE; } @Override public int getNetMsgBufferSize() { return lineTcpMsgBufferSize; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public long getSymbolCacheWaitUsBeforeReload() { return symbolCacheWaitUsBeforeReload; } @Override public LineTcpTimestampAdapter getTimestampAdapter() { return lineTcpTimestampAdapter; } @Override public long getWriterIdleTimeout() { return minIdleMsBeforeWriterRelease; } @Override public int getWriterQueueCapacity() { return lineTcpWriterQueueCapacity; } @Override public WorkerPoolConfiguration getWriterWorkerPoolConfiguration() { return lineTcpWriterWorkerPoolConfiguration; } @Override public boolean isEnabled() { return lineTcpEnabled; } @Override public boolean isStringToCharCastAllowed() { return stringToCharCastAllowed; } @Override public boolean isUseLegacyStringDefault() { return useLegacyStringDefault; } } private class PropLineTcpReceiverIODispatcherConfiguration implements IODispatcherConfiguration { @Override public int getBindIPv4Address() { return lineTcpNetBindIPv4Address; } @Override public int getBindPort() { return lineTcpNetBindPort; } @Override public MillisecondClock getClock() { return MillisecondClockImpl.INSTANCE; } @Override public String getDispatcherLogName() { return "tcp-line-server"; } @Override public EpollFacade getEpollFacade() { return EpollFacadeImpl.INSTANCE; } @Override public long getHeartbeatInterval() { return lineTcpNetConnectionHeartbeatInterval; } @Override public boolean getHint() { return lineTcpNetConnectionHint; } @Override public KqueueFacade getKqueueFacade() { return KqueueFacadeImpl.INSTANCE; } @Override public int getLimit() { return lineTcpNetConnectionLimit; } public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public long getQueueTimeout() { return lineTcpNetConnectionQueueTimeout; } @Override public int getRcvBufSize() { return lineTcpNetConnectionRcvBuf; } @Override public SelectFacade getSelectFacade() { return SelectFacadeImpl.INSTANCE; } @Override public int getSndBufSize() { return -1; } @Override public int getTestConnectionBufferSize() { return netTestConnectionBufferSize; } @Override public long getTimeout() { return lineTcpNetConnectionTimeout; } } private class PropLineTcpWriterWorkerPoolConfiguration implements WorkerPoolConfiguration { @Override public long getNapThreshold() { return lineTcpWriterWorkerNapThreshold; } @Override public String getPoolName() { return "ilpwriter"; } @Override public long getSleepThreshold() { return lineTcpWriterWorkerSleepThreshold; } @Override public int[] getWorkerAffinity() { return lineTcpWriterWorkerAffinity; } @Override public int getWorkerCount() { return lineTcpWriterWorkerCount; } @Override public long getYieldThreshold() { return lineTcpWriterWorkerYieldThreshold; } @Override public boolean haltOnError() { return lineTcpWriterWorkerPoolHaltOnError; } } private class PropLineUdpReceiverConfiguration implements LineUdpReceiverConfiguration { @Override public boolean getAutoCreateNewColumns() { return ilpAutoCreateNewColumns; } @Override public boolean getAutoCreateNewTables() { return ilpAutoCreateNewTables; } @Override public int getBindIPv4Address() { return lineUdpBindIPV4Address; } @Override public int getCommitMode() { return lineUdpCommitMode; } @Override public int getCommitRate() { return lineUdpCommitRate; } @Override public short getDefaultColumnTypeForFloat() { return floatDefaultColumnType; } @Override public short getDefaultColumnTypeForInteger() { return integerDefaultColumnType; } @Override public int getDefaultPartitionBy() { return lineUdpDefaultPartitionBy; } @Override public int getGroupIPv4Address() { return lineUdpGroupIPv4Address; } @Override public int getMaxFileNameLength() { return maxFileNameLength; } @Override public int getMsgBufferSize() { return lineUdpMsgBufferSize; } @Override public int getMsgCount() { return lineUdpMsgCount; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public int getPort() { return lineUdpPort; } @Override public int getReceiveBufferSize() { return lineUdpReceiveBufferSize; } @Override public LineTimestampAdapter getTimestampAdapter() { return lineUdpTimestampAdapter; } @Override public boolean isEnabled() { return lineUdpEnabled; } @Override public boolean isUnicast() { return lineUdpUnicast; } @Override public boolean isUseLegacyStringDefault() { return useLegacyStringDefault; } @Override public boolean ownThread() { return lineUdpOwnThread; } @Override public int ownThreadAffinity() { return lineUdpOwnThreadAffinity; } } private class PropMetricsConfiguration implements MetricsConfiguration { @Override public boolean isEnabled() { return metricsEnabled; } } private class PropPGWireConfiguration implements PGWireConfiguration { @Override public int getBinParamCountCapacity() { return pgBinaryParamsCapacity; } @Override public int getCharacterStoreCapacity() { return pgCharacterStoreCapacity; } @Override public int getCharacterStorePoolCapacity() { return pgCharacterStorePoolCapacity; } @Override public SqlExecutionCircuitBreakerConfiguration getCircuitBreakerConfiguration() { return circuitBreakerConfiguration; } @Override public int getConnectionPoolInitialCapacity() { return pgConnectionPoolInitialCapacity; } @Override public DateLocale getDefaultDateLocale() { return pgDefaultLocale; } @Override public String getDefaultPassword() { return pgPassword; } @Override public String getDefaultUsername() { return pgUsername; } @Override public IODispatcherConfiguration getDispatcherConfiguration() { return propPGWireDispatcherConfiguration; } @Override public FactoryProvider getFactoryProvider() { return factoryProvider; } @Override public int getForceRecvFragmentationChunkSize() { return pgForceRecvFragmentationChunkSize; } @Override public int getForceSendFragmentationChunkSize() { return pgForceSendFragmentationChunkSize; } @Override public int getInsertCacheBlockCount() { return pgInsertCacheBlockCount; } @Override public int getInsertCacheRowCount() { return pgInsertCacheRowCount; } @Override public int getMaxBlobSizeOnQuery() { return pgMaxBlobSizeOnQuery; } @Override public int getNamedStatementCacheCapacity() { return pgNamedStatementCacheCapacity; } @Override public int getNamesStatementPoolCapacity() { return pgNamesStatementPoolCapacity; } @Override public long getNapThreshold() { return pgWorkerNapThreshold; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public int getPendingWritersCacheSize() { return pgPendingWritersCacheCapacity; } @Override public String getPoolName() { return "pgwire"; } @Override public String getReadOnlyPassword() { return pgReadOnlyPassword; } @Override public String getReadOnlyUsername() { return pgReadOnlyUsername; } @Override public int getRecvBufferSize() { return pgRecvBufferSize; } @Override public int getSelectCacheBlockCount() { return pgSelectCacheBlockCount; } @Override public int getSelectCacheRowCount() { return pgSelectCacheRowCount; } @Override public int getSendBufferSize() { return pgSendBufferSize; } @Override public String getServerVersion() { return "11.3"; } @Override public long getSleepThreshold() { return pgWorkerSleepThreshold; } @Override public int getUpdateCacheBlockCount() { return pgUpdateCacheBlockCount; } @Override public int getUpdateCacheRowCount() { return pgUpdateCacheRowCount; } @Override public int[] getWorkerAffinity() { return pgWorkerAffinity; } @Override public int getWorkerCount() { return pgWorkerCount; } @Override public long getYieldThreshold() { return pgWorkerYieldThreshold; } @Override public boolean haltOnError() { return pgHaltOnError; } @Override public boolean isDaemonPool() { return pgDaemonPool; } @Override public boolean isEnabled() { return pgEnabled; } @Override public boolean isInsertCacheEnabled() { return pgInsertCacheEnabled; } @Override public boolean isReadOnlyUserEnabled() { return pgReadOnlyUserEnabled; } @Override public boolean isSelectCacheEnabled() { return pgSelectCacheEnabled; } @Override public boolean isUpdateCacheEnabled() { return pgUpdateCacheEnabled; } @Override public boolean readOnlySecurityContext() { return pgReadOnlySecurityContext || isReadOnlyInstance; } } private class PropPGWireDispatcherConfiguration implements IODispatcherConfiguration { @Override public int getBindIPv4Address() { return pgNetBindIPv4Address; } @Override public int getBindPort() { return pgNetBindPort; } @Override public MillisecondClock getClock() { return MillisecondClockImpl.INSTANCE; } @Override public String getDispatcherLogName() { return "pg-server"; } @Override public EpollFacade getEpollFacade() { return EpollFacadeImpl.INSTANCE; } @Override public long getHeartbeatInterval() { return -1L; } @Override public boolean getHint() { return pgNetConnectionHint; } @Override public KqueueFacade getKqueueFacade() { return KqueueFacadeImpl.INSTANCE; } @Override public int getLimit() { return pgNetConnectionLimit; } @Override public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public long getQueueTimeout() { return pgNetConnectionQueueTimeout; } @Override public int getRcvBufSize() { return pgNetConnectionRcvBuf; } @Override public SelectFacade getSelectFacade() { return SelectFacadeImpl.INSTANCE; } @Override public int getSndBufSize() { return pgNetConnectionSndBuf; } @Override public int getTestConnectionBufferSize() { return netTestConnectionBufferSize; } @Override public long getTimeout() { return pgNetIdleConnectionTimeout; } } private class PropSqlExecutionCircuitBreakerConfiguration implements SqlExecutionCircuitBreakerConfiguration { @Override public boolean checkConnection() { return true; } @Override public int getBufferSize() { return netTestConnectionBufferSize; } @Override public int getCircuitBreakerThrottle() { return circuitBreakerThrottle; } @Override @NotNull public MillisecondClock getClock() { return MillisecondClockImpl.INSTANCE; } @Override @NotNull public NetworkFacade getNetworkFacade() { return NetworkFacadeImpl.INSTANCE; } @Override public long getQueryTimeout() { return queryTimeout; } @Override public boolean isEnabled() { return interruptOnClosedConnection; } } public class PropStaticContentProcessorConfiguration implements StaticContentProcessorConfiguration { @Override public FilesFacade getFilesFacade() { return FilesFacadeImpl.INSTANCE; } @Override public CharSequence getIndexFileName() { return indexFileName; } @Override public String getKeepAliveHeader() { return keepAliveHeader; } @Override public MimeTypesCache getMimeTypesCache() { return mimeTypesCache; } /** * Absolute path to HTTP public directory. * * @return path to public directory */ @Override public CharSequence getPublicDirectory() { return publicDirectory; } @Override public byte getRequiredAuthType() { return SecurityContext.AUTH_TYPE_NONE; } } private class PropTelemetryConfiguration implements TelemetryConfiguration { @Override public boolean getDisableCompletely() { return telemetryDisableCompletely; } @Override public boolean getEnabled() { return telemetryEnabled; } @Override public int getQueueCapacity() { return telemetryQueueCapacity; } @Override public boolean hideTables() { return telemetryHideTables; } } private class PropTextConfiguration implements TextConfiguration { @Override public int getDateAdapterPoolCapacity() { return dateAdapterPoolCapacity; } @Override public DateLocale getDefaultDateLocale() { return locale; } @Override public InputFormatConfiguration getInputFormatConfiguration() { return inputFormatConfiguration; } @Override public int getJsonCacheLimit() { return jsonCacheLimit; } @Override public int getJsonCacheSize() { return jsonCacheSize; } @Override public double getMaxRequiredDelimiterStdDev() { return maxRequiredDelimiterStdDev; } @Override public double getMaxRequiredLineLengthStdDev() { return maxRequiredLineLengthStdDev; } @Override public int getMetadataStringPoolCapacity() { return metadataStringPoolCapacity; } @Override public int getRollBufferLimit() { return rollBufferLimit; } @Override public int getRollBufferSize() { return rollBufferSize; } @Override public int getTextAnalysisMaxLines() { return textAnalysisMaxLines; } @Override public int getTextLexerStringPoolCapacity() { return textLexerStringPoolCapacity; } @Override public int getTimestampAdapterPoolCapacity() { return timestampAdapterPoolCapacity; } @Override public int getUtf8SinkSize() { return utf8SinkSize; } @Override public boolean isUseLegacyStringDefault() { return useLegacyStringDefault; } } private class PropWaitProcessorConfiguration implements WaitProcessorConfiguration { @Override public MillisecondClock getClock() { return MillisecondClockImpl.INSTANCE; } @Override public double getExponentialWaitMultiplier() { return rerunExponentialWaitMultiplier; } @Override public int getInitialWaitQueueSize() { return rerunInitialWaitQueueSize; } @Override public int getMaxProcessingQueueSize() { return rerunMaxProcessingQueueSize; } @Override public long getMaxWaitCapMs() { return maxRerunWaitCapMs; } } private class PropWalApplyPoolConfiguration implements WorkerPoolConfiguration { @Override public long getNapThreshold() { return walApplyWorkerNapThreshold; } @Override public String getPoolName() { return "wal-apply"; } @Override public long getSleepThreshold() { return walApplyWorkerSleepThreshold; } @Override public long getSleepTimeout() { return walApplySleepTimeout; } @Override public int[] getWorkerAffinity() { return walApplyWorkerAffinity; } @Override public int getWorkerCount() { return walApplyWorkerCount; } @Override public long getYieldThreshold() { return walApplyWorkerYieldThreshold; } @Override public boolean haltOnError() { return walApplyWorkerHaltOnError; } @Override public boolean isEnabled() { return walApplyWorkerCount > 0; } } private class PropWorkerPoolConfiguration implements WorkerPoolConfiguration { @Override public long getNapThreshold() { return sharedWorkerNapThreshold; } @Override public String getPoolName() { return "shared"; } @Override public long getSleepThreshold() { return sharedWorkerSleepThreshold; } @Override public long getSleepTimeout() { return sharedWorkerSleepTimeout; } @Override public int[] getWorkerAffinity() { return sharedWorkerAffinity; } @Override public int getWorkerCount() { return sharedWorkerCount; } @Override public long getYieldThreshold() { return sharedWorkerYieldThreshold; } @Override public boolean haltOnError() { return sharedWorkerHaltOnError; } } static { WRITE_FO_OPTS.put("o_direct", (int) CairoConfiguration.O_DIRECT); WRITE_FO_OPTS.put("o_sync", (int) CairoConfiguration.O_SYNC); WRITE_FO_OPTS.put("o_async", (int) CairoConfiguration.O_ASYNC); WRITE_FO_OPTS.put("o_none", (int) CairoConfiguration.O_NONE); } }
questdb/questdb
core/src/main/java/io/questdb/PropServerConfiguration.java
2,344
/* * Copyright (C) 2016 The Android Open Source Project * * 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.android.exoplayer2.util; import static android.content.Context.UI_MODE_SERVICE; import static com.google.android.exoplayer2.Player.COMMAND_PLAY_PAUSE; import static com.google.android.exoplayer2.Player.COMMAND_PREPARE; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_BACK; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_FORWARD; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_DEFAULT_POSITION; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_NEXT; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_PREVIOUS; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM; import static com.google.android.exoplayer2.util.Assertions.checkArgument; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import android.Manifest.permission; import android.annotation.SuppressLint; import android.app.Activity; import android.app.UiModeManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.hardware.display.DisplayManager; import android.media.AudioFormat; import android.media.AudioManager; import android.media.MediaCodec; import android.media.MediaDrm; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.SystemClock; import android.provider.MediaStore; import android.security.NetworkSecurityPolicy; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Base64; import android.util.SparseLongArray; import android.view.Display; import android.view.SurfaceView; import android.view.WindowManager; import androidx.annotation.DoNotInline; import androidx.annotation.DrawableRes; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C.ContentType; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.ParserException; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.Commands; import com.google.common.base.Ascii; import com.google.common.base.Charsets; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Formatter; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.NoSuchElementException; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.DataFormatException; import java.util.zip.GZIPOutputStream; import java.util.zip.Inflater; import org.checkerframework.checker.initialization.qual.UnknownInitialization; import org.checkerframework.checker.nullness.compatqual.NullableType; import org.checkerframework.checker.nullness.qual.EnsuresNonNull; import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.PolyNull; /** * Miscellaneous utility methods. * * @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which * contains the same ExoPlayer code). See <a * href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the * migration guide</a> for more details, including a script to help with the migration. */ @Deprecated public final class Util { /** * Like {@link Build.VERSION#SDK_INT}, but in a place where it can be conveniently overridden for * local testing. */ public static final int SDK_INT = Build.VERSION.SDK_INT; /** * Like {@link Build#DEVICE}, but in a place where it can be conveniently overridden for local * testing. */ public static final String DEVICE = Build.DEVICE; /** * Like {@link Build#MANUFACTURER}, but in a place where it can be conveniently overridden for * local testing. */ public static final String MANUFACTURER = Build.MANUFACTURER; /** * Like {@link Build#MODEL}, but in a place where it can be conveniently overridden for local * testing. */ public static final String MODEL = Build.MODEL; /** A concise description of the device that it can be useful to log for debugging purposes. */ public static final String DEVICE_DEBUG_INFO = DEVICE + ", " + MODEL + ", " + MANUFACTURER + ", " + SDK_INT; /** An empty byte array. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String TAG = "Util"; private static final Pattern XS_DATE_TIME_PATTERN = Pattern.compile( "(\\d\\d\\d\\d)\\-(\\d\\d)\\-(\\d\\d)[Tt]" + "(\\d\\d):(\\d\\d):(\\d\\d)([\\.,](\\d+))?" + "([Zz]|((\\+|\\-)(\\d?\\d):?(\\d\\d)))?"); private static final Pattern XS_DURATION_PATTERN = Pattern.compile( "^(-)?P(([0-9]*)Y)?(([0-9]*)M)?(([0-9]*)D)?" + "(T(([0-9]*)H)?(([0-9]*)M)?(([0-9.]*)S)?)?$"); private static final Pattern ESCAPED_CHARACTER_PATTERN = Pattern.compile("%([A-Fa-f0-9]{2})"); // https://docs.microsoft.com/en-us/azure/media-services/previous/media-services-deliver-content-overview#URLs private static final Pattern ISM_PATH_PATTERN = Pattern.compile("(?:.*\\.)?isml?(?:/(manifest(.*))?)?", Pattern.CASE_INSENSITIVE); private static final String ISM_HLS_FORMAT_EXTENSION = "format=m3u8-aapl"; private static final String ISM_DASH_FORMAT_EXTENSION = "format=mpd-time-csf"; // Replacement map of ISO language codes used for normalization. @Nullable private static HashMap<String, String> languageTagReplacementMap; private Util() {} /** * Converts the entirety of an {@link InputStream} to a byte array. * * @param inputStream the {@link InputStream} to be read. The input stream is not closed by this * method. * @return a byte array containing all of the inputStream's bytes. * @throws IOException if an error occurs reading from the stream. */ public static byte[] toByteArray(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024 * 4]; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } return outputStream.toByteArray(); } /** Converts an integer into an equivalent byte array. */ public static byte[] toByteArray(int value) { return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; } /** * Converts an array of integers into an equivalent byte array. * * <p>Each integer is converted into 4 sequential bytes. */ public static byte[] toByteArray(int... values) { byte[] array = new byte[values.length * 4]; int index = 0; for (int value : values) { byte[] byteArray = toByteArray(value); array[index++] = byteArray[0]; array[index++] = byteArray[1]; array[index++] = byteArray[2]; array[index++] = byteArray[3]; } return array; } /** Converts a float into an equivalent byte array. */ public static byte[] toByteArray(float value) { return toByteArray(Float.floatToIntBits(value)); } /** Converts a byte array into a float. */ public static float toFloat(byte[] bytes) { checkArgument(bytes.length == 4); int intBits = bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF); return Float.intBitsToFloat(intBits); } /** Converts a byte array into an integer. */ public static int toInteger(byte[] bytes) { checkArgument(bytes.length == 4); return bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]; } /** * Registers a {@link BroadcastReceiver} that's not intended to receive broadcasts from other * apps. This will be enforced by specifying {@link Context#RECEIVER_NOT_EXPORTED} if {@link * #SDK_INT} is 33 or above. * * <p>Do not use this method if registering a receiver for a <a * href="https://android.googlesource.com/platform/frameworks/base/+/master/core/res/AndroidManifest.xml">protected * system broadcast</a>. * * @param context The context on which {@link Context#registerReceiver} will be called. * @param receiver The {@link BroadcastReceiver} to register. This value may be null. * @param filter Selects the Intent broadcasts to be received. * @return The first sticky intent found that matches {@code filter}, or null if there are none. */ @Nullable public static Intent registerReceiverNotExported( Context context, @Nullable BroadcastReceiver receiver, IntentFilter filter) { if (SDK_INT < 33) { return context.registerReceiver(receiver, filter); } else { return context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED); } } /** * Calls {@link Context#startForegroundService(Intent)} if {@link #SDK_INT} is 26 or higher, or * {@link Context#startService(Intent)} otherwise. * * @param context The context to call. * @param intent The intent to pass to the called method. * @return The result of the called method. */ @Nullable public static ComponentName startForegroundService(Context context, Intent intent) { if (SDK_INT >= 26) { return context.startForegroundService(intent); } else { return context.startService(intent); } } /** * Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE} * permission read the specified {@link Uri}s, requesting the permission if necessary. * * @param activity The host activity for checking and requesting the permission. * @param uris {@link Uri}s that may require {@link permission#READ_EXTERNAL_STORAGE} to read. * @return Whether a permission request was made. */ public static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris) { if (SDK_INT < 23) { return false; } for (Uri uri : uris) { if (maybeRequestReadExternalStoragePermission(activity, uri)) { return true; } } return false; } /** * Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE} * permission for the specified {@link MediaItem media items}, requesting the permission if * necessary. * * @param activity The host activity for checking and requesting the permission. * @param mediaItems {@link MediaItem Media items}s that may require {@link * permission#READ_EXTERNAL_STORAGE} to read. * @return Whether a permission request was made. */ public static boolean maybeRequestReadExternalStoragePermission( Activity activity, MediaItem... mediaItems) { if (SDK_INT < 23) { return false; } for (MediaItem mediaItem : mediaItems) { if (mediaItem.localConfiguration == null) { continue; } if (maybeRequestReadExternalStoragePermission(activity, mediaItem.localConfiguration.uri)) { return true; } List<MediaItem.SubtitleConfiguration> subtitleConfigs = mediaItem.localConfiguration.subtitleConfigurations; for (int i = 0; i < subtitleConfigs.size(); i++) { if (maybeRequestReadExternalStoragePermission(activity, subtitleConfigs.get(i).uri)) { return true; } } } return false; } private static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri uri) { return SDK_INT >= 23 && (isLocalFileUri(uri) || isMediaStoreExternalContentUri(uri)) && requestExternalStoragePermission(activity); } private static boolean isMediaStoreExternalContentUri(Uri uri) { if (!"content".equals(uri.getScheme()) || !MediaStore.AUTHORITY.equals(uri.getAuthority())) { return false; } List<String> pathSegments = uri.getPathSegments(); if (pathSegments.isEmpty()) { return false; } String firstPathSegment = pathSegments.get(0); return MediaStore.VOLUME_EXTERNAL.equals(firstPathSegment) || MediaStore.VOLUME_EXTERNAL_PRIMARY.equals(firstPathSegment); } /** * Returns whether it may be possible to load the URIs of the given media items based on the * network security policy's cleartext traffic permissions. * * @param mediaItems A list of {@link MediaItem media items}. * @return Whether it may be possible to load the URIs of the given media items. */ public static boolean checkCleartextTrafficPermitted(MediaItem... mediaItems) { if (SDK_INT < 24) { // We assume cleartext traffic is permitted. return true; } for (MediaItem mediaItem : mediaItems) { if (mediaItem.localConfiguration == null) { continue; } if (isTrafficRestricted(mediaItem.localConfiguration.uri)) { return false; } for (int i = 0; i < mediaItem.localConfiguration.subtitleConfigurations.size(); i++) { if (isTrafficRestricted(mediaItem.localConfiguration.subtitleConfigurations.get(i).uri)) { return false; } } } return true; } /** * Returns true if the URI is a path to a local file or a reference to a local file. * * @param uri The uri to test. */ public static boolean isLocalFileUri(Uri uri) { String scheme = uri.getScheme(); return TextUtils.isEmpty(scheme) || "file".equals(scheme); } /** * Tests two objects for {@link Object#equals(Object)} equality, handling the case where one or * both may be null. * * @param o1 The first object. * @param o2 The second object. * @return {@code o1 == null ? o2 == null : o1.equals(o2)}. */ public static boolean areEqual(@Nullable Object o1, @Nullable Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } /** * Tests whether an {@code items} array contains an object equal to {@code item}, according to * {@link Object#equals(Object)}. * * <p>If {@code item} is null then true is returned if and only if {@code items} contains null. * * @param items The array of items to search. * @param item The item to search for. * @return True if the array contains an object equal to the item being searched for. */ public static boolean contains(@NullableType Object[] items, @Nullable Object item) { for (Object arrayItem : items) { if (areEqual(arrayItem, item)) { return true; } } return false; } /** * Removes an indexed range from a List. * * <p>Does nothing if the provided range is valid and {@code fromIndex == toIndex}. * * @param list The List to remove the range from. * @param fromIndex The first index to be removed (inclusive). * @param toIndex The last index to be removed (exclusive). * @throws IllegalArgumentException If {@code fromIndex} &lt; 0, {@code toIndex} &gt; {@code * list.size()}, or {@code fromIndex} &gt; {@code toIndex}. */ public static <T> void removeRange(List<T> list, int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > list.size() || fromIndex > toIndex) { throw new IllegalArgumentException(); } else if (fromIndex != toIndex) { // Checking index inequality prevents an unnecessary allocation. list.subList(fromIndex, toIndex).clear(); } } /** * Casts a nullable variable to a non-null variable without runtime null check. * * <p>Use {@link Assertions#checkNotNull(Object)} to throw if the value is null. */ @SuppressWarnings({"nullness:contracts.postcondition", "nullness:return"}) @EnsuresNonNull("#1") public static <T> T castNonNull(@Nullable T value) { return value; } /** Casts a nullable type array to a non-null type array without runtime null check. */ @SuppressWarnings({"nullness:contracts.postcondition", "nullness:return"}) @EnsuresNonNull("#1") public static <T> T[] castNonNullTypeArray(@NullableType T[] value) { return value; } /** * Copies and optionally truncates an array. Prevents null array elements created by {@link * Arrays#copyOf(Object[], int)} by ensuring the new length does not exceed the current length. * * @param input The input array. * @param length The output array length. Must be less or equal to the length of the input array. * @return The copied array. */ @SuppressWarnings({"nullness:argument", "nullness:return"}) public static <T> T[] nullSafeArrayCopy(T[] input, int length) { checkArgument(length <= input.length); return Arrays.copyOf(input, length); } /** * Copies a subset of an array. * * @param input The input array. * @param from The start the range to be copied, inclusive * @param to The end of the range to be copied, exclusive. * @return The copied array. */ @SuppressWarnings({"nullness:argument", "nullness:return"}) public static <T> T[] nullSafeArrayCopyOfRange(T[] input, int from, int to) { checkArgument(0 <= from); checkArgument(to <= input.length); return Arrays.copyOfRange(input, from, to); } /** * Creates a new array containing {@code original} with {@code newElement} appended. * * @param original The input array. * @param newElement The element to append. * @return The new array. */ public static <T> T[] nullSafeArrayAppend(T[] original, T newElement) { @NullableType T[] result = Arrays.copyOf(original, original.length + 1); result[original.length] = newElement; return castNonNullTypeArray(result); } /** * Creates a new array containing the concatenation of two non-null type arrays. * * @param first The first array. * @param second The second array. * @return The concatenated result. */ @SuppressWarnings("nullness:assignment") public static <T> T[] nullSafeArrayConcatenation(T[] first, T[] second) { T[] concatenation = Arrays.copyOf(first, first.length + second.length); System.arraycopy( /* src= */ second, /* srcPos= */ 0, /* dest= */ concatenation, /* destPos= */ first.length, /* length= */ second.length); return concatenation; } /** * Copies the contents of {@code list} into {@code array}. * * <p>{@code list.size()} must be the same as {@code array.length} to ensure the contents can be * copied into {@code array} without leaving any nulls at the end. * * @param list The list to copy items from. * @param array The array to copy items to. */ @SuppressWarnings("nullness:toArray.nullable.elements.not.newarray") public static <T> void nullSafeListToArray(List<T> list, T[] array) { Assertions.checkState(list.size() == array.length); list.toArray(array); } /** * Creates a {@link Handler} on the current {@link Looper} thread. * * @throws IllegalStateException If the current thread doesn't have a {@link Looper}. */ public static Handler createHandlerForCurrentLooper() { return createHandlerForCurrentLooper(/* callback= */ null); } /** * Creates a {@link Handler} with the specified {@link Handler.Callback} on the current {@link * Looper} thread. * * <p>The method accepts partially initialized objects as callback under the assumption that the * Handler won't be used to send messages until the callback is fully initialized. * * @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no * callback is required. * @return A {@link Handler} with the specified callback on the current {@link Looper} thread. * @throws IllegalStateException If the current thread doesn't have a {@link Looper}. */ public static Handler createHandlerForCurrentLooper( @Nullable Handler.@UnknownInitialization Callback callback) { return createHandler(Assertions.checkStateNotNull(Looper.myLooper()), callback); } /** * Creates a {@link Handler} on the current {@link Looper} thread. * * <p>If the current thread doesn't have a {@link Looper}, the application's main thread {@link * Looper} is used. */ public static Handler createHandlerForCurrentOrMainLooper() { return createHandlerForCurrentOrMainLooper(/* callback= */ null); } /** * Creates a {@link Handler} with the specified {@link Handler.Callback} on the current {@link * Looper} thread. * * <p>The method accepts partially initialized objects as callback under the assumption that the * Handler won't be used to send messages until the callback is fully initialized. * * <p>If the current thread doesn't have a {@link Looper}, the application's main thread {@link * Looper} is used. * * @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no * callback is required. * @return A {@link Handler} with the specified callback on the current {@link Looper} thread. */ public static Handler createHandlerForCurrentOrMainLooper( @Nullable Handler.@UnknownInitialization Callback callback) { return createHandler(getCurrentOrMainLooper(), callback); } /** * Creates a {@link Handler} with the specified {@link Handler.Callback} on the specified {@link * Looper} thread. * * <p>The method accepts partially initialized objects as callback under the assumption that the * Handler won't be used to send messages until the callback is fully initialized. * * @param looper A {@link Looper} to run the callback on. * @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no * callback is required. * @return A {@link Handler} with the specified callback on the current {@link Looper} thread. */ @SuppressWarnings({"nullness:argument", "nullness:return"}) public static Handler createHandler( Looper looper, @Nullable Handler.@UnknownInitialization Callback callback) { return new Handler(looper, callback); } /** * Posts the {@link Runnable} if the calling thread differs with the {@link Looper} of the {@link * Handler}. Otherwise, runs the {@link Runnable} directly. * * @param handler The handler to which the {@link Runnable} will be posted. * @param runnable The runnable to either post or run. * @return {@code true} if the {@link Runnable} was successfully posted to the {@link Handler} or * run. {@code false} otherwise. */ public static boolean postOrRun(Handler handler, Runnable runnable) { Looper looper = handler.getLooper(); if (!looper.getThread().isAlive()) { return false; } if (handler.getLooper() == Looper.myLooper()) { runnable.run(); return true; } else { return handler.post(runnable); } } /** * Posts the {@link Runnable} if the calling thread differs with the {@link Looper} of the {@link * Handler}. Otherwise, runs the {@link Runnable} directly. Also returns a {@link * ListenableFuture} for when the {@link Runnable} has run. * * @param handler The handler to which the {@link Runnable} will be posted. * @param runnable The runnable to either post or run. * @param successValue The value to set in the {@link ListenableFuture} once the runnable * completes. * @param <T> The type of {@code successValue}. * @return A {@link ListenableFuture} for when the {@link Runnable} has run. */ public static <T> ListenableFuture<T> postOrRunWithCompletion( Handler handler, Runnable runnable, T successValue) { SettableFuture<T> outputFuture = SettableFuture.create(); postOrRun( handler, () -> { try { if (outputFuture.isCancelled()) { return; } runnable.run(); outputFuture.set(successValue); } catch (Throwable e) { outputFuture.setException(e); } }); return outputFuture; } /** * Asynchronously transforms the result of a {@link ListenableFuture}. * * <p>The transformation function is called using a {@linkplain MoreExecutors#directExecutor() * direct executor}. * * <p>The returned Future attempts to keep its cancellation state in sync with that of the input * future and that of the future returned by the transform function. That is, if the returned * Future is cancelled, it will attempt to cancel the other two, and if either of the other two is * cancelled, the returned Future will also be cancelled. All forwarded cancellations will not * attempt to interrupt. * * @param future The input {@link ListenableFuture}. * @param transformFunction The function transforming the result of the input future. * @param <T> The result type of the input future. * @param <U> The result type of the transformation function. * @return A {@link ListenableFuture} for the transformed result. */ public static <T, U> ListenableFuture<T> transformFutureAsync( ListenableFuture<U> future, AsyncFunction<U, T> transformFunction) { // This is a simplified copy of Guava's Futures.transformAsync. SettableFuture<T> outputFuture = SettableFuture.create(); outputFuture.addListener( () -> { if (outputFuture.isCancelled()) { future.cancel(/* mayInterruptIfRunning= */ false); } }, MoreExecutors.directExecutor()); future.addListener( () -> { U inputFutureResult; try { inputFutureResult = Futures.getDone(future); } catch (CancellationException cancellationException) { outputFuture.cancel(/* mayInterruptIfRunning= */ false); return; } catch (ExecutionException exception) { @Nullable Throwable cause = exception.getCause(); outputFuture.setException(cause == null ? exception : cause); return; } catch (RuntimeException | Error error) { outputFuture.setException(error); return; } try { outputFuture.setFuture(transformFunction.apply(inputFutureResult)); } catch (Throwable exception) { outputFuture.setException(exception); } }, MoreExecutors.directExecutor()); return outputFuture; } /** * Returns the {@link Looper} associated with the current thread, or the {@link Looper} of the * application's main thread if the current thread doesn't have a {@link Looper}. */ public static Looper getCurrentOrMainLooper() { @Nullable Looper myLooper = Looper.myLooper(); return myLooper != null ? myLooper : Looper.getMainLooper(); } /** * Instantiates a new single threaded executor whose thread has the specified name. * * @param threadName The name of the thread. * @return The executor. */ public static ExecutorService newSingleThreadExecutor(String threadName) { return Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, threadName)); } /** * Instantiates a new single threaded scheduled executor whose thread has the specified name. * * @param threadName The name of the thread. * @return The executor. */ public static ScheduledExecutorService newSingleThreadScheduledExecutor(String threadName) { return Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, threadName)); } /** * Closes a {@link Closeable}, suppressing any {@link IOException} that may occur. Both {@link * java.io.OutputStream} and {@link InputStream} are {@code Closeable}. * * @param closeable The {@link Closeable} to close. */ public static void closeQuietly(@Nullable Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { // Ignore. } } /** * Reads an integer from a {@link Parcel} and interprets it as a boolean, with 0 mapping to false * and all other values mapping to true. * * @param parcel The {@link Parcel} to read from. * @return The read value. */ public static boolean readBoolean(Parcel parcel) { return parcel.readInt() != 0; } /** * Writes a boolean to a {@link Parcel}. The boolean is written as an integer with value 1 (true) * or 0 (false). * * @param parcel The {@link Parcel} to write to. * @param value The value to write. */ public static void writeBoolean(Parcel parcel, boolean value) { parcel.writeInt(value ? 1 : 0); } /** * Returns the language tag for a {@link Locale}. * * <p>For API levels &ge; 21, this tag is IETF BCP 47 compliant. Use {@link * #normalizeLanguageCode(String)} to retrieve a normalized IETF BCP 47 language tag for all API * levels if needed. * * @param locale A {@link Locale}. * @return The language tag. */ public static String getLocaleLanguageTag(Locale locale) { return SDK_INT >= 21 ? getLocaleLanguageTagV21(locale) : locale.toString(); } /** * Returns a normalized IETF BCP 47 language tag for {@code language}. * * @param language A case-insensitive language code supported by {@link * Locale#forLanguageTag(String)}. * @return The all-lowercase normalized code, or null if the input was null, or {@code * language.toLowerCase()} if the language could not be normalized. */ public static @PolyNull String normalizeLanguageCode(@PolyNull String language) { if (language == null) { return null; } // Locale data (especially for API < 21) may produce tags with '_' instead of the // standard-conformant '-'. String normalizedTag = language.replace('_', '-'); if (normalizedTag.isEmpty() || normalizedTag.equals(C.LANGUAGE_UNDETERMINED)) { // Tag isn't valid, keep using the original. normalizedTag = language; } normalizedTag = Ascii.toLowerCase(normalizedTag); String mainLanguage = splitAtFirst(normalizedTag, "-")[0]; if (languageTagReplacementMap == null) { languageTagReplacementMap = createIsoLanguageReplacementMap(); } @Nullable String replacedLanguage = languageTagReplacementMap.get(mainLanguage); if (replacedLanguage != null) { normalizedTag = replacedLanguage + normalizedTag.substring(/* beginIndex= */ mainLanguage.length()); mainLanguage = replacedLanguage; } if ("no".equals(mainLanguage) || "i".equals(mainLanguage) || "zh".equals(mainLanguage)) { normalizedTag = maybeReplaceLegacyLanguageTags(normalizedTag); } return normalizedTag; } /** * Returns a new {@link String} constructed by decoding UTF-8 encoded bytes. * * @param bytes The UTF-8 encoded bytes to decode. * @return The string. */ public static String fromUtf8Bytes(byte[] bytes) { return new String(bytes, Charsets.UTF_8); } /** * Returns a new {@link String} constructed by decoding UTF-8 encoded bytes in a subarray. * * @param bytes The UTF-8 encoded bytes to decode. * @param offset The index of the first byte to decode. * @param length The number of bytes to decode. * @return The string. */ public static String fromUtf8Bytes(byte[] bytes, int offset, int length) { return new String(bytes, offset, length, Charsets.UTF_8); } /** * Returns a new byte array containing the code points of a {@link String} encoded using UTF-8. * * @param value The {@link String} whose bytes should be obtained. * @return The code points encoding using UTF-8. */ public static byte[] getUtf8Bytes(String value) { return value.getBytes(Charsets.UTF_8); } /** * Splits a string using {@code value.split(regex, -1}). Note: this is is similar to {@link * String#split(String)} but empty matches at the end of the string will not be omitted from the * returned array. * * @param value The string to split. * @param regex A delimiting regular expression. * @return The array of strings resulting from splitting the string. */ public static String[] split(String value, String regex) { return value.split(regex, /* limit= */ -1); } /** * Splits the string at the first occurrence of the delimiter {@code regex}. If the delimiter does * not match, returns an array with one element which is the input string. If the delimiter does * match, returns an array with the portion of the string before the delimiter and the rest of the * string. * * @param value The string. * @param regex A delimiting regular expression. * @return The string split by the first occurrence of the delimiter. */ public static String[] splitAtFirst(String value, String regex) { return value.split(regex, /* limit= */ 2); } /** * Returns whether the given character is a carriage return ('\r') or a line feed ('\n'). * * @param c The character. * @return Whether the given character is a linebreak. */ public static boolean isLinebreak(int c) { return c == '\n' || c == '\r'; } /** * Formats a string using {@link Locale#US}. * * @see String#format(String, Object...) */ public static String formatInvariant(String format, Object... args) { return String.format(Locale.US, format, args); } /** * Divides a {@code numerator} by a {@code denominator}, returning the ceiled result. * * @param numerator The numerator to divide. * @param denominator The denominator to divide by. * @return The ceiled result of the division. */ public static int ceilDivide(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } /** * Divides a {@code numerator} by a {@code denominator}, returning the ceiled result. * * @param numerator The numerator to divide. * @param denominator The denominator to divide by. * @return The ceiled result of the division. */ public static long ceilDivide(long numerator, long denominator) { return (numerator + denominator - 1) / denominator; } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ public static int constrainValue(int value, int min, int max) { return max(min, min(value, max)); } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ public static long constrainValue(long value, long min, long max) { return max(min, min(value, max)); } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ public static float constrainValue(float value, float min, float max) { return max(min, min(value, max)); } /** * Returns the sum of two arguments, or a third argument if the result overflows. * * @param x The first value. * @param y The second value. * @param overflowResult The return value if {@code x + y} overflows. * @return {@code x + y}, or {@code overflowResult} if the result overflows. */ public static long addWithOverflowDefault(long x, long y, long overflowResult) { long result = x + y; // See Hacker's Delight 2-13 (H. Warren Jr). if (((x ^ result) & (y ^ result)) < 0) { return overflowResult; } return result; } /** * Returns the difference between two arguments, or a third argument if the result overflows. * * @param x The first value. * @param y The second value. * @param overflowResult The return value if {@code x - y} overflows. * @return {@code x - y}, or {@code overflowResult} if the result overflows. */ public static long subtractWithOverflowDefault(long x, long y, long overflowResult) { long result = x - y; // See Hacker's Delight 2-13 (H. Warren Jr). if (((x ^ y) & (x ^ result)) < 0) { return overflowResult; } return result; } /** * Returns the index of the first occurrence of {@code value} in {@code array}, or {@link * C#INDEX_UNSET} if {@code value} is not contained in {@code array}. * * @param array The array to search. * @param value The value to search for. * @return The index of the first occurrence of value in {@code array}, or {@link C#INDEX_UNSET} * if {@code value} is not contained in {@code array}. */ public static int linearSearch(int[] array, int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return C.INDEX_UNSET; } /** * Returns the index of the first occurrence of {@code value} in {@code array}, or {@link * C#INDEX_UNSET} if {@code value} is not contained in {@code array}. * * @param array The array to search. * @param value The value to search for. * @return The index of the first occurrence of value in {@code array}, or {@link C#INDEX_UNSET} * if {@code value} is not contained in {@code array}. */ public static int linearSearch(long[] array, long value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return C.INDEX_UNSET; } /** * Returns the index of the largest element in {@code array} that is less than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the first one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the array. If false then -1 will be returned. * @return The index of the largest element in {@code array} that is less than (or optionally * equal to) {@code value}. */ public static int binarySearchFloor( int[] array, int value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = -(index + 2); } else { while (--index >= 0 && array[index] == value) {} if (inclusive) { index++; } } return stayInBounds ? max(0, index) : index; } /** * Returns the index of the largest element in {@code array} that is less than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the first one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the array. If false then -1 will be returned. * @return The index of the largest element in {@code array} that is less than (or optionally * equal to) {@code value}. */ public static int binarySearchFloor( long[] array, long value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = -(index + 2); } else { while (--index >= 0 && array[index] == value) {} if (inclusive) { index++; } } return stayInBounds ? max(0, index) : index; } /** * Returns the index of the largest element in {@code list} that is less than (or optionally equal * to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the list must be sorted. If the * list contains multiple elements equal to {@code value} and {@code inclusive} is true, the index * of the first one will be returned. * * @param <T> The type of values being searched. * @param list The list to search. * @param value The value being searched for. * @param inclusive If the value is present in the list, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the list. If false then -1 will be returned. * @return The index of the largest element in {@code list} that is less than (or optionally equal * to) {@code value}. */ public static <T extends Comparable<? super T>> int binarySearchFloor( List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds) { int index = Collections.binarySearch(list, value); if (index < 0) { index = -(index + 2); } else { while (--index >= 0 && list.get(index).compareTo(value) == 0) {} if (inclusive) { index++; } } return stayInBounds ? max(0, index) : index; } /** * Returns the index of the largest element in {@code longArray} that is less than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the first one will be returned. * * @param longArray The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the array. If false then -1 will be returned. * @return The index of the largest element in {@code array} that is less than (or optionally * equal to) {@code value}. */ public static int binarySearchFloor( LongArray longArray, long value, boolean inclusive, boolean stayInBounds) { int lowIndex = 0; int highIndex = longArray.size() - 1; while (lowIndex <= highIndex) { int midIndex = (lowIndex + highIndex) >>> 1; if (longArray.get(midIndex) < value) { lowIndex = midIndex + 1; } else { highIndex = midIndex - 1; } } if (inclusive && highIndex + 1 < longArray.size() && longArray.get(highIndex + 1) == value) { highIndex++; } else if (stayInBounds && highIndex == -1) { highIndex = 0; } return highIndex; } /** * Returns the index of the smallest element in {@code array} that is greater than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the last one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the smallest element strictly * greater than the value. * @param stayInBounds If true, then {@code (a.length - 1)} will be returned in the case that the * value is greater than the largest element in the array. If false then {@code a.length} will * be returned. * @return The index of the smallest element in {@code array} that is greater than (or optionally * equal to) {@code value}. */ public static int binarySearchCeil( int[] array, int value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = ~index; } else { while (++index < array.length && array[index] == value) {} if (inclusive) { index--; } } return stayInBounds ? min(array.length - 1, index) : index; } /** * Returns the index of the smallest element in {@code array} that is greater than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the last one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the smallest element strictly * greater than the value. * @param stayInBounds If true, then {@code (a.length - 1)} will be returned in the case that the * value is greater than the largest element in the array. If false then {@code a.length} will * be returned. * @return The index of the smallest element in {@code array} that is greater than (or optionally * equal to) {@code value}. */ public static int binarySearchCeil( long[] array, long value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = ~index; } else { while (++index < array.length && array[index] == value) {} if (inclusive) { index--; } } return stayInBounds ? min(array.length - 1, index) : index; } /** * Returns the index of the smallest element in {@code list} that is greater than (or optionally * equal to) a specified value. * * <p>The search is performed using a binary search algorithm, so the list must be sorted. If the * list contains multiple elements equal to {@code value} and {@code inclusive} is true, the index * of the last one will be returned. * * @param <T> The type of values being searched. * @param list The list to search. * @param value The value being searched for. * @param inclusive If the value is present in the list, whether to return the corresponding * index. If false then the returned index corresponds to the smallest element strictly * greater than the value. * @param stayInBounds If true, then {@code (list.size() - 1)} will be returned in the case that * the value is greater than the largest element in the list. If false then {@code * list.size()} will be returned. * @return The index of the smallest element in {@code list} that is greater than (or optionally * equal to) {@code value}. */ public static <T extends Comparable<? super T>> int binarySearchCeil( List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds) { int index = Collections.binarySearch(list, value); if (index < 0) { index = ~index; } else { int listSize = list.size(); while (++index < listSize && list.get(index).compareTo(value) == 0) {} if (inclusive) { index--; } } return stayInBounds ? min(list.size() - 1, index) : index; } /** * Compares two long values and returns the same value as {@code Long.compare(long, long)}. * * @param left The left operand. * @param right The right operand. * @return 0, if left == right, a negative value if left &lt; right, or a positive value if left * &gt; right. */ public static int compareLong(long left, long right) { return left < right ? -1 : left == right ? 0 : 1; } /** * Returns the minimum value in the given {@link SparseLongArray}. * * @param sparseLongArray The {@link SparseLongArray}. * @return The minimum value. * @throws NoSuchElementException If the array is empty. */ @RequiresApi(18) public static long minValue(SparseLongArray sparseLongArray) { if (sparseLongArray.size() == 0) { throw new NoSuchElementException(); } long min = Long.MAX_VALUE; for (int i = 0; i < sparseLongArray.size(); i++) { min = min(min, sparseLongArray.valueAt(i)); } return min; } /** * Returns the maximum value in the given {@link SparseLongArray}. * * @param sparseLongArray The {@link SparseLongArray}. * @return The maximum value. * @throws NoSuchElementException If the array is empty. */ @RequiresApi(18) public static long maxValue(SparseLongArray sparseLongArray) { if (sparseLongArray.size() == 0) { throw new NoSuchElementException(); } long max = Long.MIN_VALUE; for (int i = 0; i < sparseLongArray.size(); i++) { max = max(max, sparseLongArray.valueAt(i)); } return max; } /** * Converts a time in microseconds to the corresponding time in milliseconds, preserving {@link * C#TIME_UNSET} and {@link C#TIME_END_OF_SOURCE} values. * * @param timeUs The time in microseconds. * @return The corresponding time in milliseconds. */ public static long usToMs(long timeUs) { return (timeUs == C.TIME_UNSET || timeUs == C.TIME_END_OF_SOURCE) ? timeUs : (timeUs / 1000); } /** * Converts a time in milliseconds to the corresponding time in microseconds, preserving {@link * C#TIME_UNSET} values and {@link C#TIME_END_OF_SOURCE} values. * * @param timeMs The time in milliseconds. * @return The corresponding time in microseconds. */ public static long msToUs(long timeMs) { return (timeMs == C.TIME_UNSET || timeMs == C.TIME_END_OF_SOURCE) ? timeMs : (timeMs * 1000); } /** * Returns the total duration (in microseconds) of {@code sampleCount} samples of equal duration * at {@code sampleRate}. * * <p>If {@code sampleRate} is less than {@link C#MICROS_PER_SECOND}, the duration produced by * this method can be reversed to the original sample count using {@link * #durationUsToSampleCount(long, int)}. * * @param sampleCount The number of samples. * @param sampleRate The sample rate, in samples per second. * @return The total duration, in microseconds, of {@code sampleCount} samples. */ public static long sampleCountToDurationUs(long sampleCount, int sampleRate) { return (sampleCount * C.MICROS_PER_SECOND) / sampleRate; } /** * Returns the number of samples required to represent {@code durationUs} of media at {@code * sampleRate}, assuming all samples are equal duration except the last one which may be shorter. * * <p>The result of this method <b>cannot</b> be generally reversed to the original duration with * {@link #sampleCountToDurationUs(long, int)}, due to information lost when rounding to a whole * number of samples. * * @param durationUs The duration in microseconds. * @param sampleRate The sample rate in samples per second. * @return The number of samples required to represent {@code durationUs}. */ public static long durationUsToSampleCount(long durationUs, int sampleRate) { return Util.ceilDivide(durationUs * sampleRate, C.MICROS_PER_SECOND); } /** * Parses an xs:duration attribute value, returning the parsed duration in milliseconds. * * @param value The attribute value to decode. * @return The parsed duration in milliseconds. */ public static long parseXsDuration(String value) { Matcher matcher = XS_DURATION_PATTERN.matcher(value); if (matcher.matches()) { boolean negated = !TextUtils.isEmpty(matcher.group(1)); // Durations containing years and months aren't completely defined. We assume there are // 30.4368 days in a month, and 365.242 days in a year. String years = matcher.group(3); double durationSeconds = (years != null) ? Double.parseDouble(years) * 31556908 : 0; String months = matcher.group(5); durationSeconds += (months != null) ? Double.parseDouble(months) * 2629739 : 0; String days = matcher.group(7); durationSeconds += (days != null) ? Double.parseDouble(days) * 86400 : 0; String hours = matcher.group(10); durationSeconds += (hours != null) ? Double.parseDouble(hours) * 3600 : 0; String minutes = matcher.group(12); durationSeconds += (minutes != null) ? Double.parseDouble(minutes) * 60 : 0; String seconds = matcher.group(14); durationSeconds += (seconds != null) ? Double.parseDouble(seconds) : 0; long durationMillis = (long) (durationSeconds * 1000); return negated ? -durationMillis : durationMillis; } else { return (long) (Double.parseDouble(value) * 3600 * 1000); } } /** * Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the * epoch. * * @param value The attribute value to decode. * @return The parsed timestamp in milliseconds since the epoch. * @throws ParserException if an error occurs parsing the dateTime attribute value. */ // incompatible types in argument. // dereference of possibly-null reference matcher.group(9) @SuppressWarnings({"nullness:argument", "nullness:dereference.of.nullable"}) public static long parseXsDateTime(String value) throws ParserException { Matcher matcher = XS_DATE_TIME_PATTERN.matcher(value); if (!matcher.matches()) { throw ParserException.createForMalformedContainer( "Invalid date/time format: " + value, /* cause= */ null); } int timezoneShift; if (matcher.group(9) == null) { // No time zone specified. timezoneShift = 0; } else if (matcher.group(9).equalsIgnoreCase("Z")) { timezoneShift = 0; } else { timezoneShift = ((Integer.parseInt(matcher.group(12)) * 60 + Integer.parseInt(matcher.group(13)))); if ("-".equals(matcher.group(11))) { timezoneShift *= -1; } } Calendar dateTime = new GregorianCalendar(TimeZone.getTimeZone("GMT")); dateTime.clear(); // Note: The month value is 0-based, hence the -1 on group(2) dateTime.set( Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)) - 1, Integer.parseInt(matcher.group(3)), Integer.parseInt(matcher.group(4)), Integer.parseInt(matcher.group(5)), Integer.parseInt(matcher.group(6))); if (!TextUtils.isEmpty(matcher.group(8))) { final BigDecimal bd = new BigDecimal("0." + matcher.group(8)); // we care only for milliseconds, so movePointRight(3) dateTime.set(Calendar.MILLISECOND, bd.movePointRight(3).intValue()); } long time = dateTime.getTimeInMillis(); if (timezoneShift != 0) { time -= timezoneShift * 60000L; } return time; } /** * Scales a large timestamp. * * <p>Logically, scaling consists of a multiplication followed by a division. The actual * operations performed are designed to minimize the probability of overflow. * * @param timestamp The timestamp to scale. * @param multiplier The multiplier. * @param divisor The divisor. * @return The scaled timestamp. */ public static long scaleLargeTimestamp(long timestamp, long multiplier, long divisor) { if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; return timestamp / divisionFactor; } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; return timestamp * multiplicationFactor; } else { double multiplicationFactor = (double) multiplier / divisor; return (long) (timestamp * multiplicationFactor); } } /** * Applies {@link #scaleLargeTimestamp(long, long, long)} to a list of unscaled timestamps. * * @param timestamps The timestamps to scale. * @param multiplier The multiplier. * @param divisor The divisor. * @return The scaled timestamps. */ public static long[] scaleLargeTimestamps(List<Long> timestamps, long multiplier, long divisor) { long[] scaledTimestamps = new long[timestamps.size()]; if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; for (int i = 0; i < scaledTimestamps.length; i++) { scaledTimestamps[i] = timestamps.get(i) / divisionFactor; } } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; for (int i = 0; i < scaledTimestamps.length; i++) { scaledTimestamps[i] = timestamps.get(i) * multiplicationFactor; } } else { double multiplicationFactor = (double) multiplier / divisor; for (int i = 0; i < scaledTimestamps.length; i++) { scaledTimestamps[i] = (long) (timestamps.get(i) * multiplicationFactor); } } return scaledTimestamps; } /** * Applies {@link #scaleLargeTimestamp(long, long, long)} to an array of unscaled timestamps. * * @param timestamps The timestamps to scale. * @param multiplier The multiplier. * @param divisor The divisor. */ public static void scaleLargeTimestampsInPlace(long[] timestamps, long multiplier, long divisor) { if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; for (int i = 0; i < timestamps.length; i++) { timestamps[i] /= divisionFactor; } } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; for (int i = 0; i < timestamps.length; i++) { timestamps[i] *= multiplicationFactor; } } else { double multiplicationFactor = (double) multiplier / divisor; for (int i = 0; i < timestamps.length; i++) { timestamps[i] = (long) (timestamps[i] * multiplicationFactor); } } } /** * Returns the duration of media that will elapse in {@code playoutDuration}. * * @param playoutDuration The duration to scale. * @param speed The factor by which playback is sped up. * @return The scaled duration, in the same units as {@code playoutDuration}. */ public static long getMediaDurationForPlayoutDuration(long playoutDuration, float speed) { if (speed == 1f) { return playoutDuration; } return Math.round((double) playoutDuration * speed); } /** * Returns the playout duration of {@code mediaDuration} of media. * * @param mediaDuration The duration to scale. * @param speed The factor by which playback is sped up. * @return The scaled duration, in the same units as {@code mediaDuration}. */ public static long getPlayoutDurationForMediaDuration(long mediaDuration, float speed) { if (speed == 1f) { return mediaDuration; } return Math.round((double) mediaDuration / speed); } /** * Returns the integer equal to the big-endian concatenation of the characters in {@code string} * as bytes. The string must be no more than four characters long. * * @param string A string no more than four characters long. */ public static int getIntegerCodeForString(String string) { int length = string.length(); checkArgument(length <= 4); int result = 0; for (int i = 0; i < length; i++) { result <<= 8; result |= string.charAt(i); } return result; } /** * Converts an integer to a long by unsigned conversion. * * <p>This method is equivalent to {@link Integer#toUnsignedLong(int)} for API 26+. */ public static long toUnsignedLong(int x) { // x is implicitly casted to a long before the bit operation is executed but this does not // impact the method correctness. return x & 0xFFFFFFFFL; } /** * Returns the long that is composed of the bits of the 2 specified integers. * * @param mostSignificantBits The 32 most significant bits of the long to return. * @param leastSignificantBits The 32 least significant bits of the long to return. * @return a long where its 32 most significant bits are {@code mostSignificantBits} bits and its * 32 least significant bits are {@code leastSignificantBits}. */ public static long toLong(int mostSignificantBits, int leastSignificantBits) { return (toUnsignedLong(mostSignificantBits) << 32) | toUnsignedLong(leastSignificantBits); } /** * Returns a byte array containing values parsed from the hex string provided. * * @param hexString The hex string to convert to bytes. * @return A byte array containing values parsed from the hex string provided. */ public static byte[] getBytesFromHexString(String hexString) { byte[] data = new byte[hexString.length() / 2]; for (int i = 0; i < data.length; i++) { int stringOffset = i * 2; data[i] = (byte) ((Character.digit(hexString.charAt(stringOffset), 16) << 4) + Character.digit(hexString.charAt(stringOffset + 1), 16)); } return data; } /** * Returns a string containing a lower-case hex representation of the bytes provided. * * @param bytes The byte data to convert to hex. * @return A String containing the hex representation of {@code bytes}. */ public static String toHexString(byte[] bytes) { StringBuilder result = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { result .append(Character.forDigit((bytes[i] >> 4) & 0xF, 16)) .append(Character.forDigit(bytes[i] & 0xF, 16)); } return result.toString(); } /** * Returns a string with comma delimited simple names of each object's class. * * @param objects The objects whose simple class names should be comma delimited and returned. * @return A string with comma delimited simple names of each object's class. */ public static String getCommaDelimitedSimpleClassNames(Object[] objects) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < objects.length; i++) { stringBuilder.append(objects[i].getClass().getSimpleName()); if (i < objects.length - 1) { stringBuilder.append(", "); } } return stringBuilder.toString(); } /** * Returns a user agent string based on the given application name and the library version. * * @param context A valid context of the calling application. * @param applicationName String that will be prefix'ed to the generated user agent. * @return A user agent string generated using the applicationName and the library version. */ public static String getUserAgent(Context context, String applicationName) { String versionName; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); versionName = info.versionName; } catch (NameNotFoundException e) { versionName = "?"; } return applicationName + "/" + versionName + " (Linux;Android " + Build.VERSION.RELEASE + ") " + ExoPlayerLibraryInfo.VERSION_SLASHY; } /** Returns the number of codec strings in {@code codecs} whose type matches {@code trackType}. */ public static int getCodecCountOfType(@Nullable String codecs, @C.TrackType int trackType) { String[] codecArray = splitCodecs(codecs); int count = 0; for (String codec : codecArray) { if (trackType == MimeTypes.getTrackTypeOfCodec(codec)) { count++; } } return count; } /** * Returns a copy of {@code codecs} without the codecs whose track type doesn't match {@code * trackType}. * * @param codecs A codec sequence string, as defined in RFC 6381. * @param trackType The {@link C.TrackType track type}. * @return A copy of {@code codecs} without the codecs whose track type doesn't match {@code * trackType}. If this ends up empty, or {@code codecs} is null, returns null. */ @Nullable public static String getCodecsOfType(@Nullable String codecs, @C.TrackType int trackType) { String[] codecArray = splitCodecs(codecs); if (codecArray.length == 0) { return null; } StringBuilder builder = new StringBuilder(); for (String codec : codecArray) { if (trackType == MimeTypes.getTrackTypeOfCodec(codec)) { if (builder.length() > 0) { builder.append(","); } builder.append(codec); } } return builder.length() > 0 ? builder.toString() : null; } /** * Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings. * * @param codecs A codec sequence string, as defined in RFC 6381. * @return The split codecs, or an array of length zero if the input was empty or null. */ public static String[] splitCodecs(@Nullable String codecs) { if (TextUtils.isEmpty(codecs)) { return new String[0]; } return split(codecs.trim(), "(\\s*,\\s*)"); } /** * Gets a PCM {@link Format} with the specified parameters. * * @param pcmEncoding The {@link C.PcmEncoding}. * @param channels The number of channels, or {@link Format#NO_VALUE} if unknown. * @param sampleRate The sample rate in Hz, or {@link Format#NO_VALUE} if unknown. * @return The PCM format. */ public static Format getPcmFormat(@C.PcmEncoding int pcmEncoding, int channels, int sampleRate) { return new Format.Builder() .setSampleMimeType(MimeTypes.AUDIO_RAW) .setChannelCount(channels) .setSampleRate(sampleRate) .setPcmEncoding(pcmEncoding) .build(); } /** * Converts a sample bit depth to a corresponding PCM encoding constant. * * @param bitDepth The bit depth. Supported values are 8, 16, 24 and 32. * @return The corresponding encoding. One of {@link C#ENCODING_PCM_8BIT}, {@link * C#ENCODING_PCM_16BIT}, {@link C#ENCODING_PCM_24BIT} and {@link C#ENCODING_PCM_32BIT}. If * the bit depth is unsupported then {@link C#ENCODING_INVALID} is returned. */ public static @C.PcmEncoding int getPcmEncoding(int bitDepth) { switch (bitDepth) { case 8: return C.ENCODING_PCM_8BIT; case 16: return C.ENCODING_PCM_16BIT; case 24: return C.ENCODING_PCM_24BIT; case 32: return C.ENCODING_PCM_32BIT; default: return C.ENCODING_INVALID; } } /** * Returns whether {@code encoding} is one of the linear PCM encodings. * * @param encoding The encoding of the audio data. * @return Whether the encoding is one of the PCM encodings. */ public static boolean isEncodingLinearPcm(@C.Encoding int encoding) { return encoding == C.ENCODING_PCM_8BIT || encoding == C.ENCODING_PCM_16BIT || encoding == C.ENCODING_PCM_16BIT_BIG_ENDIAN || encoding == C.ENCODING_PCM_24BIT || encoding == C.ENCODING_PCM_32BIT || encoding == C.ENCODING_PCM_FLOAT; } /** * Returns whether {@code encoding} is high resolution (&gt; 16-bit) PCM. * * @param encoding The encoding of the audio data. * @return Whether the encoding is high resolution PCM. */ public static boolean isEncodingHighResolutionPcm(@C.PcmEncoding int encoding) { return encoding == C.ENCODING_PCM_24BIT || encoding == C.ENCODING_PCM_32BIT || encoding == C.ENCODING_PCM_FLOAT; } /** * Returns the audio track channel configuration for the given channel count, or {@link * AudioFormat#CHANNEL_INVALID} if output is not possible. * * @param channelCount The number of channels in the input audio. * @return The channel configuration or {@link AudioFormat#CHANNEL_INVALID} if output is not * possible. */ @SuppressLint("InlinedApi") // Inlined AudioFormat constants. public static int getAudioTrackChannelConfig(int channelCount) { switch (channelCount) { case 1: return AudioFormat.CHANNEL_OUT_MONO; case 2: return AudioFormat.CHANNEL_OUT_STEREO; case 3: return AudioFormat.CHANNEL_OUT_STEREO | AudioFormat.CHANNEL_OUT_FRONT_CENTER; case 4: return AudioFormat.CHANNEL_OUT_QUAD; case 5: return AudioFormat.CHANNEL_OUT_QUAD | AudioFormat.CHANNEL_OUT_FRONT_CENTER; case 6: return AudioFormat.CHANNEL_OUT_5POINT1; case 7: return AudioFormat.CHANNEL_OUT_5POINT1 | AudioFormat.CHANNEL_OUT_BACK_CENTER; case 8: return AudioFormat.CHANNEL_OUT_7POINT1_SURROUND; case 10: if (Util.SDK_INT >= 32) { return AudioFormat.CHANNEL_OUT_5POINT1POINT4; } else { // Before API 32, height channel masks are not available. For those 10-channel streams // supported on the audio output devices (e.g. DTS:X P2), we use 7.1-surround instead. return AudioFormat.CHANNEL_OUT_7POINT1_SURROUND; } case 12: return AudioFormat.CHANNEL_OUT_7POINT1POINT4; default: return AudioFormat.CHANNEL_INVALID; } } /** * Returns the frame size for audio with {@code channelCount} channels in the specified encoding. * * @param pcmEncoding The encoding of the audio data. * @param channelCount The channel count. * @return The size of one audio frame in bytes. */ public static int getPcmFrameSize(@C.PcmEncoding int pcmEncoding, int channelCount) { switch (pcmEncoding) { case C.ENCODING_PCM_8BIT: return channelCount; case C.ENCODING_PCM_16BIT: case C.ENCODING_PCM_16BIT_BIG_ENDIAN: return channelCount * 2; case C.ENCODING_PCM_24BIT: return channelCount * 3; case C.ENCODING_PCM_32BIT: case C.ENCODING_PCM_FLOAT: return channelCount * 4; case C.ENCODING_INVALID: case Format.NO_VALUE: default: throw new IllegalArgumentException(); } } /** Returns the {@link C.AudioUsage} corresponding to the specified {@link C.StreamType}. */ public static @C.AudioUsage int getAudioUsageForStreamType(@C.StreamType int streamType) { switch (streamType) { case C.STREAM_TYPE_ALARM: return C.USAGE_ALARM; case C.STREAM_TYPE_DTMF: return C.USAGE_VOICE_COMMUNICATION_SIGNALLING; case C.STREAM_TYPE_NOTIFICATION: return C.USAGE_NOTIFICATION; case C.STREAM_TYPE_RING: return C.USAGE_NOTIFICATION_RINGTONE; case C.STREAM_TYPE_SYSTEM: return C.USAGE_ASSISTANCE_SONIFICATION; case C.STREAM_TYPE_VOICE_CALL: return C.USAGE_VOICE_COMMUNICATION; case C.STREAM_TYPE_MUSIC: default: return C.USAGE_MEDIA; } } /** Returns the {@link C.AudioContentType} corresponding to the specified {@link C.StreamType}. */ public static @C.AudioContentType int getAudioContentTypeForStreamType( @C.StreamType int streamType) { switch (streamType) { case C.STREAM_TYPE_ALARM: case C.STREAM_TYPE_DTMF: case C.STREAM_TYPE_NOTIFICATION: case C.STREAM_TYPE_RING: case C.STREAM_TYPE_SYSTEM: return C.AUDIO_CONTENT_TYPE_SONIFICATION; case C.STREAM_TYPE_VOICE_CALL: return C.AUDIO_CONTENT_TYPE_SPEECH; case C.STREAM_TYPE_MUSIC: default: return C.AUDIO_CONTENT_TYPE_MUSIC; } } /** Returns the {@link C.StreamType} corresponding to the specified {@link C.AudioUsage}. */ public static @C.StreamType int getStreamTypeForAudioUsage(@C.AudioUsage int usage) { switch (usage) { case C.USAGE_MEDIA: case C.USAGE_GAME: case C.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: return C.STREAM_TYPE_MUSIC; case C.USAGE_ASSISTANCE_SONIFICATION: return C.STREAM_TYPE_SYSTEM; case C.USAGE_VOICE_COMMUNICATION: return C.STREAM_TYPE_VOICE_CALL; case C.USAGE_VOICE_COMMUNICATION_SIGNALLING: return C.STREAM_TYPE_DTMF; case C.USAGE_ALARM: return C.STREAM_TYPE_ALARM; case C.USAGE_NOTIFICATION_RINGTONE: return C.STREAM_TYPE_RING; case C.USAGE_NOTIFICATION: case C.USAGE_NOTIFICATION_COMMUNICATION_REQUEST: case C.USAGE_NOTIFICATION_COMMUNICATION_INSTANT: case C.USAGE_NOTIFICATION_COMMUNICATION_DELAYED: case C.USAGE_NOTIFICATION_EVENT: return C.STREAM_TYPE_NOTIFICATION; case C.USAGE_ASSISTANCE_ACCESSIBILITY: case C.USAGE_ASSISTANT: case C.USAGE_UNKNOWN: default: return C.STREAM_TYPE_DEFAULT; } } /** * Returns a newly generated audio session identifier, or {@link AudioManager#ERROR} if an error * occurred in which case audio playback may fail. * * @see AudioManager#generateAudioSessionId() */ @RequiresApi(21) public static int generateAudioSessionIdV21(Context context) { @Nullable AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)); return audioManager == null ? AudioManager.ERROR : audioManager.generateAudioSessionId(); } /** * Derives a DRM {@link UUID} from {@code drmScheme}. * * @param drmScheme A UUID string, or {@code "widevine"}, {@code "playready"} or {@code * "clearkey"}. * @return The derived {@link UUID}, or {@code null} if one could not be derived. */ @Nullable public static UUID getDrmUuid(String drmScheme) { switch (Ascii.toLowerCase(drmScheme)) { case "widevine": return C.WIDEVINE_UUID; case "playready": return C.PLAYREADY_UUID; case "clearkey": return C.CLEARKEY_UUID; default: try { return UUID.fromString(drmScheme); } catch (RuntimeException e) { return null; } } } /** * Returns a {@link PlaybackException.ErrorCode} value that corresponds to the provided {@link * MediaDrm.ErrorCodes} value. Returns {@link PlaybackException#ERROR_CODE_DRM_SYSTEM_ERROR} if * the provided error code isn't recognised. */ public static @PlaybackException.ErrorCode int getErrorCodeForMediaDrmErrorCode( int mediaDrmErrorCode) { switch (mediaDrmErrorCode) { case MediaDrm.ErrorCodes.ERROR_PROVISIONING_CONFIG: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_PARSE: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_REQUEST_REJECTED: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_CERTIFICATE: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_RETRY: return PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED; case MediaDrm.ErrorCodes.ERROR_LICENSE_PARSE: case MediaDrm.ErrorCodes.ERROR_LICENSE_RELEASE: case MediaDrm.ErrorCodes.ERROR_LICENSE_REQUEST_REJECTED: case MediaDrm.ErrorCodes.ERROR_LICENSE_RESTORE: case MediaDrm.ErrorCodes.ERROR_LICENSE_STATE: case MediaDrm.ErrorCodes.ERROR_CERTIFICATE_MALFORMED: return PlaybackException.ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED; case MediaDrm.ErrorCodes.ERROR_LICENSE_POLICY: case MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_OUTPUT_PROTECTION: case MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_SECURITY: case MediaDrm.ErrorCodes.ERROR_KEY_EXPIRED: case MediaDrm.ErrorCodes.ERROR_KEY_NOT_LOADED: return PlaybackException.ERROR_CODE_DRM_DISALLOWED_OPERATION; case MediaDrm.ErrorCodes.ERROR_INIT_DATA: case MediaDrm.ErrorCodes.ERROR_FRAME_TOO_LARGE: return PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR; default: return PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR; } } /** * @deprecated Use {@link #inferContentTypeForExtension(String)} when {@code overrideExtension} is * non-empty, and {@link #inferContentType(Uri)} otherwise. */ @Deprecated public static @ContentType int inferContentType(Uri uri, @Nullable String overrideExtension) { return TextUtils.isEmpty(overrideExtension) ? inferContentType(uri) : inferContentTypeForExtension(overrideExtension); } /** * Makes a best guess to infer the {@link ContentType} from a {@link Uri}. * * @param uri The {@link Uri}. * @return The content type. */ public static @ContentType int inferContentType(Uri uri) { @Nullable String scheme = uri.getScheme(); if (scheme != null && Ascii.equalsIgnoreCase("rtsp", scheme)) { return C.CONTENT_TYPE_RTSP; } @Nullable String lastPathSegment = uri.getLastPathSegment(); if (lastPathSegment == null) { return C.CONTENT_TYPE_OTHER; } int lastDotIndex = lastPathSegment.lastIndexOf('.'); if (lastDotIndex >= 0) { @C.ContentType int contentType = inferContentTypeForExtension(lastPathSegment.substring(lastDotIndex + 1)); if (contentType != C.CONTENT_TYPE_OTHER) { // If contentType is TYPE_SS that indicates the extension is .ism or .isml and shows the ISM // URI is missing the "/manifest" suffix, which contains the information used to // disambiguate between Smooth Streaming, HLS and DASH below - so we can just return TYPE_SS // here without further checks. return contentType; } } Matcher ismMatcher = ISM_PATH_PATTERN.matcher(checkNotNull(uri.getPath())); if (ismMatcher.matches()) { @Nullable String extensions = ismMatcher.group(2); if (extensions != null) { if (extensions.contains(ISM_DASH_FORMAT_EXTENSION)) { return C.CONTENT_TYPE_DASH; } else if (extensions.contains(ISM_HLS_FORMAT_EXTENSION)) { return C.CONTENT_TYPE_HLS; } } return C.CONTENT_TYPE_SS; } return C.CONTENT_TYPE_OTHER; } /** * @deprecated Use {@link Uri#parse(String)} and {@link #inferContentType(Uri)} for full file * paths or {@link #inferContentTypeForExtension(String)} for extensions. */ @Deprecated public static @ContentType int inferContentType(String fileName) { return inferContentType(Uri.parse("file:///" + fileName)); } /** * Makes a best guess to infer the {@link ContentType} from a file extension. * * @param fileExtension The extension of the file (excluding the '.'). * @return The content type. */ public static @ContentType int inferContentTypeForExtension(String fileExtension) { fileExtension = Ascii.toLowerCase(fileExtension); switch (fileExtension) { case "mpd": return C.CONTENT_TYPE_DASH; case "m3u8": return C.CONTENT_TYPE_HLS; case "ism": case "isml": return C.TYPE_SS; default: return C.CONTENT_TYPE_OTHER; } } /** * Makes a best guess to infer the {@link ContentType} from a {@link Uri} and optional MIME type. * * @param uri The {@link Uri}. * @param mimeType If MIME type, or {@code null}. * @return The content type. */ public static @ContentType int inferContentTypeForUriAndMimeType( Uri uri, @Nullable String mimeType) { if (mimeType == null) { return inferContentType(uri); } switch (mimeType) { case MimeTypes.APPLICATION_MPD: return C.CONTENT_TYPE_DASH; case MimeTypes.APPLICATION_M3U8: return C.CONTENT_TYPE_HLS; case MimeTypes.APPLICATION_SS: return C.CONTENT_TYPE_SS; case MimeTypes.APPLICATION_RTSP: return C.CONTENT_TYPE_RTSP; default: return C.CONTENT_TYPE_OTHER; } } /** * Returns the MIME type corresponding to the given adaptive {@link ContentType}, or {@code null} * if the content type is not adaptive. */ @Nullable public static String getAdaptiveMimeTypeForContentType(@ContentType int contentType) { switch (contentType) { case C.CONTENT_TYPE_DASH: return MimeTypes.APPLICATION_MPD; case C.CONTENT_TYPE_HLS: return MimeTypes.APPLICATION_M3U8; case C.CONTENT_TYPE_SS: return MimeTypes.APPLICATION_SS; case C.CONTENT_TYPE_RTSP: case C.CONTENT_TYPE_OTHER: default: return null; } } /** * If the provided URI is an ISM Presentation URI, returns the URI with "Manifest" appended to its * path (i.e., the corresponding default manifest URI). Else returns the provided URI without * modification. See [MS-SSTR] v20180912, section 2.2.1. * * @param uri The original URI. * @return The fixed URI. */ public static Uri fixSmoothStreamingIsmManifestUri(Uri uri) { @Nullable String path = uri.getPath(); if (path == null) { return uri; } Matcher ismMatcher = ISM_PATH_PATTERN.matcher(path); if (ismMatcher.matches() && ismMatcher.group(1) == null) { // Add missing "Manifest" suffix. return Uri.withAppendedPath(uri, "Manifest"); } return uri; } /** * Returns the specified millisecond time formatted as a string. * * @param builder The builder that {@code formatter} will write to. * @param formatter The formatter. * @param timeMs The time to format as a string, in milliseconds. * @return The time formatted as a string. */ public static String getStringForTime(StringBuilder builder, Formatter formatter, long timeMs) { if (timeMs == C.TIME_UNSET) { timeMs = 0; } String prefix = timeMs < 0 ? "-" : ""; timeMs = abs(timeMs); long totalSeconds = (timeMs + 500) / 1000; long seconds = totalSeconds % 60; long minutes = (totalSeconds / 60) % 60; long hours = totalSeconds / 3600; builder.setLength(0); return hours > 0 ? formatter.format("%s%d:%02d:%02d", prefix, hours, minutes, seconds).toString() : formatter.format("%s%02d:%02d", prefix, minutes, seconds).toString(); } /** * Escapes a string so that it's safe for use as a file or directory name on at least FAT32 * filesystems. FAT32 is the most restrictive of all filesystems still commonly used today. * * <p>For simplicity, this only handles common characters known to be illegal on FAT32: &lt;, * &gt;, :, ", /, \, |, ?, and *. % is also escaped since it is used as the escape character. * Escaping is performed in a consistent way so that no collisions occur and {@link * #unescapeFileName(String)} can be used to retrieve the original file name. * * @param fileName File name to be escaped. * @return An escaped file name which will be safe for use on at least FAT32 filesystems. */ public static String escapeFileName(String fileName) { int length = fileName.length(); int charactersToEscapeCount = 0; for (int i = 0; i < length; i++) { if (shouldEscapeCharacter(fileName.charAt(i))) { charactersToEscapeCount++; } } if (charactersToEscapeCount == 0) { return fileName; } int i = 0; StringBuilder builder = new StringBuilder(length + charactersToEscapeCount * 2); while (charactersToEscapeCount > 0) { char c = fileName.charAt(i++); if (shouldEscapeCharacter(c)) { builder.append('%').append(Integer.toHexString(c)); charactersToEscapeCount--; } else { builder.append(c); } } if (i < length) { builder.append(fileName, i, length); } return builder.toString(); } private static boolean shouldEscapeCharacter(char c) { switch (c) { case '<': case '>': case ':': case '"': case '/': case '\\': case '|': case '?': case '*': case '%': return true; default: return false; } } /** * Unescapes an escaped file or directory name back to its original value. * * <p>See {@link #escapeFileName(String)} for more information. * * @param fileName File name to be unescaped. * @return The original value of the file name before it was escaped, or null if the escaped * fileName seems invalid. */ @Nullable public static String unescapeFileName(String fileName) { int length = fileName.length(); int percentCharacterCount = 0; for (int i = 0; i < length; i++) { if (fileName.charAt(i) == '%') { percentCharacterCount++; } } if (percentCharacterCount == 0) { return fileName; } int expectedLength = length - percentCharacterCount * 2; StringBuilder builder = new StringBuilder(expectedLength); Matcher matcher = ESCAPED_CHARACTER_PATTERN.matcher(fileName); int startOfNotEscaped = 0; while (percentCharacterCount > 0 && matcher.find()) { char unescapedCharacter = (char) Integer.parseInt(checkNotNull(matcher.group(1)), 16); builder.append(fileName, startOfNotEscaped, matcher.start()).append(unescapedCharacter); startOfNotEscaped = matcher.end(); percentCharacterCount--; } if (startOfNotEscaped < length) { builder.append(fileName, startOfNotEscaped, length); } if (builder.length() != expectedLength) { return null; } return builder.toString(); } /** Returns a data URI with the specified MIME type and data. */ public static Uri getDataUriForString(String mimeType, String data) { return Uri.parse( "data:" + mimeType + ";base64," + Base64.encodeToString(data.getBytes(), Base64.NO_WRAP)); } /** * A hacky method that always throws {@code t} even if {@code t} is a checked exception, and is * not declared to be thrown. */ public static void sneakyThrow(Throwable t) { sneakyThrowInternal(t); } @SuppressWarnings("unchecked") private static <T extends Throwable> void sneakyThrowInternal(Throwable t) throws T { throw (T) t; } /** Recursively deletes a directory and its content. */ public static void recursiveDelete(File fileOrDirectory) { File[] directoryFiles = fileOrDirectory.listFiles(); if (directoryFiles != null) { for (File child : directoryFiles) { recursiveDelete(child); } } fileOrDirectory.delete(); } /** Creates an empty directory in the directory returned by {@link Context#getCacheDir()}. */ public static File createTempDirectory(Context context, String prefix) throws IOException { File tempFile = createTempFile(context, prefix); tempFile.delete(); // Delete the temp file. tempFile.mkdir(); // Create a directory with the same name. return tempFile; } /** Creates a new empty file in the directory returned by {@link Context#getCacheDir()}. */ public static File createTempFile(Context context, String prefix) throws IOException { return File.createTempFile(prefix, null, checkNotNull(context.getCacheDir())); } /** * Returns the result of updating a CRC-32 with the specified bytes in a "most significant bit * first" order. * * @param bytes Array containing the bytes to update the crc value with. * @param start The index to the first byte in the byte range to update the crc with. * @param end The index after the last byte in the byte range to update the crc with. * @param initialValue The initial value for the crc calculation. * @return The result of updating the initial value with the specified bytes. */ public static int crc32(byte[] bytes, int start, int end, int initialValue) { for (int i = start; i < end; i++) { initialValue = (initialValue << 8) ^ CRC32_BYTES_MSBF[((initialValue >>> 24) ^ (bytes[i] & 0xFF)) & 0xFF]; } return initialValue; } /** * Returns the result of updating a CRC-8 with the specified bytes in a "most significant bit * first" order. * * @param bytes Array containing the bytes to update the crc value with. * @param start The index to the first byte in the byte range to update the crc with. * @param end The index after the last byte in the byte range to update the crc with. * @param initialValue The initial value for the crc calculation. * @return The result of updating the initial value with the specified bytes. */ public static int crc8(byte[] bytes, int start, int end, int initialValue) { for (int i = start; i < end; i++) { initialValue = CRC8_BYTES_MSBF[initialValue ^ (bytes[i] & 0xFF)]; } return initialValue; } /** Compresses {@code input} using gzip and returns the result in a newly allocated byte array. */ public static byte[] gzip(byte[] input) { ByteArrayOutputStream output = new ByteArrayOutputStream(); try (GZIPOutputStream os = new GZIPOutputStream(output)) { os.write(input); } catch (IOException e) { // A ByteArrayOutputStream wrapped in a GZipOutputStream should never throw IOException since // no I/O is happening. throw new IllegalStateException(e); } return output.toByteArray(); } /** * Absolute <i>get</i> method for reading an int value in {@link ByteOrder#BIG_ENDIAN} in a {@link * ByteBuffer}. Same as {@link ByteBuffer#getInt(int)} except the buffer's order as returned by * {@link ByteBuffer#order()} is ignored and {@link ByteOrder#BIG_ENDIAN} is used instead. * * @param buffer The buffer from which to read an int in big endian. * @param index The index from which the bytes will be read. * @return The int value at the given index with the buffer bytes ordered most significant to * least significant. */ public static int getBigEndianInt(ByteBuffer buffer, int index) { int value = buffer.getInt(index); return buffer.order() == ByteOrder.BIG_ENDIAN ? value : Integer.reverseBytes(value); } /** * Returns the upper-case ISO 3166-1 alpha-2 country code of the current registered operator's MCC * (Mobile Country Code), or the country code of the default Locale if not available. * * @param context A context to access the telephony service. If null, only the Locale can be used. * @return The upper-case ISO 3166-1 alpha-2 country code, or an empty String if unavailable. */ public static String getCountryCode(@Nullable Context context) { if (context != null) { @Nullable TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { String countryCode = telephonyManager.getNetworkCountryIso(); if (!TextUtils.isEmpty(countryCode)) { return Ascii.toUpperCase(countryCode); } } } return Ascii.toUpperCase(Locale.getDefault().getCountry()); } /** * Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages * ordered by preference. */ public static String[] getSystemLanguageCodes() { String[] systemLocales = getSystemLocales(); for (int i = 0; i < systemLocales.length; i++) { systemLocales[i] = normalizeLanguageCode(systemLocales[i]); } return systemLocales; } /** Returns the default {@link Locale.Category#DISPLAY DISPLAY} {@link Locale}. */ public static Locale getDefaultDisplayLocale() { return SDK_INT >= 24 ? Locale.getDefault(Locale.Category.DISPLAY) : Locale.getDefault(); } /** * Uncompresses the data in {@code input}. * * @param input Wraps the compressed input data. * @param output Wraps an output buffer to be used to store the uncompressed data. If {@code * output.data} isn't big enough to hold the uncompressed data, a new array is created. If * {@code true} is returned then the output's position will be set to 0 and its limit will be * set to the length of the uncompressed data. * @param inflater If not null, used to uncompressed the input. Otherwise a new {@link Inflater} * is created. * @return Whether the input is uncompressed successfully. */ public static boolean inflate( ParsableByteArray input, ParsableByteArray output, @Nullable Inflater inflater) { if (input.bytesLeft() <= 0) { return false; } if (output.capacity() < input.bytesLeft()) { output.ensureCapacity(2 * input.bytesLeft()); } if (inflater == null) { inflater = new Inflater(); } inflater.setInput(input.getData(), input.getPosition(), input.bytesLeft()); try { int outputSize = 0; while (true) { outputSize += inflater.inflate(output.getData(), outputSize, output.capacity() - outputSize); if (inflater.finished()) { output.setLimit(outputSize); return true; } if (inflater.needsDictionary() || inflater.needsInput()) { return false; } if (outputSize == output.capacity()) { output.ensureCapacity(output.capacity() * 2); } } } catch (DataFormatException e) { return false; } finally { inflater.reset(); } } /** * Returns whether the app is running on a TV device. * * @param context Any context. * @return Whether the app is running on a TV device. */ public static boolean isTv(Context context) { // See https://developer.android.com/training/tv/start/hardware.html#runtime-check. @Nullable UiModeManager uiModeManager = (UiModeManager) context.getApplicationContext().getSystemService(UI_MODE_SERVICE); return uiModeManager != null && uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION; } /** * Returns whether the app is running on an automotive device. * * @param context Any context. * @return Whether the app is running on an automotive device. */ public static boolean isAutomotive(Context context) { return SDK_INT >= 23 && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); } /** * Gets the size of the current mode of the default display, in pixels. * * <p>Note that due to application UI scaling, the number of pixels made available to applications * (as reported by {@link Display#getSize(Point)} may differ from the mode's actual resolution (as * reported by this function). For example, applications running on a display configured with a 4K * mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take * advantage of the full mode resolution through a {@link SurfaceView} using full size buffers. * * @param context Any context. * @return The size of the current mode, in pixels. */ public static Point getCurrentDisplayModeSize(Context context) { @Nullable Display defaultDisplay = null; if (SDK_INT >= 17) { @Nullable DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); // We don't expect displayManager to ever be null, so this check is just precautionary. // Consider removing it when the library minSdkVersion is increased to 17 or higher. if (displayManager != null) { defaultDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY); } } if (defaultDisplay == null) { WindowManager windowManager = checkNotNull((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)); defaultDisplay = windowManager.getDefaultDisplay(); } return getCurrentDisplayModeSize(context, defaultDisplay); } /** * Gets the size of the current mode of the specified display, in pixels. * * <p>Note that due to application UI scaling, the number of pixels made available to applications * (as reported by {@link Display#getSize(Point)} may differ from the mode's actual resolution (as * reported by this function). For example, applications running on a display configured with a 4K * mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take * advantage of the full mode resolution through a {@link SurfaceView} using full size buffers. * * @param context Any context. * @param display The display whose size is to be returned. * @return The size of the current mode, in pixels. */ public static Point getCurrentDisplayModeSize(Context context, Display display) { if (display.getDisplayId() == Display.DEFAULT_DISPLAY && isTv(context)) { // On Android TVs it's common for the UI to be driven at a lower resolution than the physical // resolution of the display (e.g., driving the UI at 1080p when the display is 4K). // SurfaceView outputs are still able to use the full physical resolution on such devices. // // Prior to API level 26, the Display object did not provide a way to obtain the true physical // resolution of the display. From API level 26, Display.getMode().getPhysical[Width|Height] // is expected to return the display's true physical resolution, but we still see devices // setting their hardware compositor output size incorrectly, which makes this unreliable. // Hence for TV devices, we try and read the display's true physical resolution from system // properties. // // From API level 28, Treble may prevent the system from writing sys.display-size, so we check // vendor.display-size instead. @Nullable String displaySize = SDK_INT < 28 ? getSystemProperty("sys.display-size") : getSystemProperty("vendor.display-size"); // If we managed to read the display size, attempt to parse it. if (!TextUtils.isEmpty(displaySize)) { try { String[] displaySizeParts = split(displaySize.trim(), "x"); if (displaySizeParts.length == 2) { int width = Integer.parseInt(displaySizeParts[0]); int height = Integer.parseInt(displaySizeParts[1]); if (width > 0 && height > 0) { return new Point(width, height); } } } catch (NumberFormatException e) { // Do nothing. } Log.e(TAG, "Invalid display size: " + displaySize); } // Sony Android TVs advertise support for 4k output via a system feature. if ("Sony".equals(MANUFACTURER) && MODEL.startsWith("BRAVIA") && context.getPackageManager().hasSystemFeature("com.sony.dtv.hardware.panel.qfhd")) { return new Point(3840, 2160); } } Point displaySize = new Point(); if (SDK_INT >= 23) { getDisplaySizeV23(display, displaySize); } else if (SDK_INT >= 17) { getDisplaySizeV17(display, displaySize); } else { getDisplaySizeV16(display, displaySize); } return displaySize; } /** * Returns a string representation of a {@link C.TrackType}. * * @param trackType A {@link C.TrackType} constant, * @return A string representation of this constant. */ public static String getTrackTypeString(@C.TrackType int trackType) { switch (trackType) { case C.TRACK_TYPE_DEFAULT: return "default"; case C.TRACK_TYPE_AUDIO: return "audio"; case C.TRACK_TYPE_VIDEO: return "video"; case C.TRACK_TYPE_TEXT: return "text"; case C.TRACK_TYPE_IMAGE: return "image"; case C.TRACK_TYPE_METADATA: return "metadata"; case C.TRACK_TYPE_CAMERA_MOTION: return "camera motion"; case C.TRACK_TYPE_NONE: return "none"; case C.TRACK_TYPE_UNKNOWN: return "unknown"; default: return trackType >= C.TRACK_TYPE_CUSTOM_BASE ? "custom (" + trackType + ")" : "?"; } } /** * Returns the current time in milliseconds since the epoch. * * @param elapsedRealtimeEpochOffsetMs The offset between {@link SystemClock#elapsedRealtime()} * and the time since the Unix epoch, or {@link C#TIME_UNSET} if unknown. * @return The Unix time in milliseconds since the epoch. */ public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs) { return elapsedRealtimeEpochOffsetMs == C.TIME_UNSET ? System.currentTimeMillis() : SystemClock.elapsedRealtime() + elapsedRealtimeEpochOffsetMs; } /** * Moves the elements starting at {@code fromIndex} to {@code newFromIndex}. * * @param items The list of which to move elements. * @param fromIndex The index at which the items to move start. * @param toIndex The index up to which elements should be moved (exclusive). * @param newFromIndex The new from index. */ @SuppressWarnings("ExtendsObject") // See go/lsc-extends-object public static <T extends Object> void moveItems( List<T> items, int fromIndex, int toIndex, int newFromIndex) { ArrayDeque<T> removedItems = new ArrayDeque<>(); int removedItemsLength = toIndex - fromIndex; for (int i = removedItemsLength - 1; i >= 0; i--) { removedItems.addFirst(items.remove(fromIndex + i)); } items.addAll(min(newFromIndex, items.size()), removedItems); } /** Returns whether the table exists in the database. */ public static boolean tableExists(SQLiteDatabase database, String tableName) { long count = DatabaseUtils.queryNumEntries( database, "sqlite_master", "tbl_name = ?", new String[] {tableName}); return count > 0; } /** * Attempts to parse an error code from a diagnostic string found in framework media exceptions. * * <p>For example: android.media.MediaCodec.error_1 or android.media.MediaDrm.error_neg_2. * * @param diagnosticsInfo A string from which to parse the error code. * @return The parser error code, or 0 if an error code could not be parsed. */ public static int getErrorCodeFromPlatformDiagnosticsInfo(@Nullable String diagnosticsInfo) { // TODO (internal b/192337376): Change 0 for ERROR_UNKNOWN once available. if (diagnosticsInfo == null) { return 0; } String[] strings = split(diagnosticsInfo, "_"); int length = strings.length; if (length < 2) { return 0; } String digitsSection = strings[length - 1]; boolean isNegative = length >= 3 && "neg".equals(strings[length - 2]); try { int errorCode = Integer.parseInt(Assertions.checkNotNull(digitsSection)); return isNegative ? -errorCode : errorCode; } catch (NumberFormatException e) { return 0; } } /** * Returns the number of maximum pending output frames that are allowed on a {@link MediaCodec} * decoder. */ public static int getMaxPendingFramesCountForMediaCodecDecoders( Context context, String codecName, boolean requestedHdrToneMapping) { if (SDK_INT < 29 || context.getApplicationContext().getApplicationInfo().targetSdkVersion < 29) { // Prior to API 29, decoders may drop frames to keep their output surface from growing out of // bounds. From API 29, if the app targets API 29 or later, the {@link // MediaFormat#KEY_ALLOW_FRAME_DROP} key prevents frame dropping even when the surface is // full. // Frame dropping is never desired, so a workaround is needed for older API levels. // Allow a maximum of one frame to be pending at a time to prevent frame dropping. // TODO(b/226330223): Investigate increasing this limit. return 1; } // Limit the maximum amount of frames for all decoders. This is a tentative value that should be // large enough to avoid significant performance degradation, but small enough to bypass decoder // issues. // // TODO: b/278234847 - Evaluate whether this reduces decoder timeouts, and consider restoring // prior higher limits as appropriate. // // Some OMX decoders don't correctly track their number of output buffers available, and get // stuck if too many frames are rendered without being processed. This value is experimentally // determined. See also // b/213455700, b/230097284, b/229978305, and b/245491744. // // OMX video codecs should no longer exist from android.os.Build.DEVICE_INITIAL_SDK_INT 31+. return 5; } /** * Returns string representation of a {@link C.FormatSupport} flag. * * @param formatSupport A {@link C.FormatSupport} flag. * @return A string representation of the flag. */ public static String getFormatSupportString(@C.FormatSupport int formatSupport) { switch (formatSupport) { case C.FORMAT_HANDLED: return "YES"; case C.FORMAT_EXCEEDS_CAPABILITIES: return "NO_EXCEEDS_CAPABILITIES"; case C.FORMAT_UNSUPPORTED_DRM: return "NO_UNSUPPORTED_DRM"; case C.FORMAT_UNSUPPORTED_SUBTYPE: return "NO_UNSUPPORTED_TYPE"; case C.FORMAT_UNSUPPORTED_TYPE: return "NO"; default: throw new IllegalStateException(); } } /** * Returns the {@link Commands} available in the {@link Player}. * * @param player The {@link Player}. * @param permanentAvailableCommands The commands permanently available in the player. * @return The available {@link Commands}. */ public static Commands getAvailableCommands(Player player, Commands permanentAvailableCommands) { boolean isPlayingAd = player.isPlayingAd(); boolean isCurrentMediaItemSeekable = player.isCurrentMediaItemSeekable(); boolean hasPreviousMediaItem = player.hasPreviousMediaItem(); boolean hasNextMediaItem = player.hasNextMediaItem(); boolean isCurrentMediaItemLive = player.isCurrentMediaItemLive(); boolean isCurrentMediaItemDynamic = player.isCurrentMediaItemDynamic(); boolean isTimelineEmpty = player.getCurrentTimeline().isEmpty(); return new Commands.Builder() .addAll(permanentAvailableCommands) .addIf(COMMAND_SEEK_TO_DEFAULT_POSITION, !isPlayingAd) .addIf(COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM, isCurrentMediaItemSeekable && !isPlayingAd) .addIf(COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM, hasPreviousMediaItem && !isPlayingAd) .addIf( COMMAND_SEEK_TO_PREVIOUS, !isTimelineEmpty && (hasPreviousMediaItem || !isCurrentMediaItemLive || isCurrentMediaItemSeekable) && !isPlayingAd) .addIf(COMMAND_SEEK_TO_NEXT_MEDIA_ITEM, hasNextMediaItem && !isPlayingAd) .addIf( COMMAND_SEEK_TO_NEXT, !isTimelineEmpty && (hasNextMediaItem || (isCurrentMediaItemLive && isCurrentMediaItemDynamic)) && !isPlayingAd) .addIf(COMMAND_SEEK_TO_MEDIA_ITEM, !isPlayingAd) .addIf(COMMAND_SEEK_BACK, isCurrentMediaItemSeekable && !isPlayingAd) .addIf(COMMAND_SEEK_FORWARD, isCurrentMediaItemSeekable && !isPlayingAd) .build(); } /** * Returns the sum of all summands of the given array. * * @param summands The summands to calculate the sum from. * @return The sum of all summands. */ public static long sum(long... summands) { long sum = 0; for (long summand : summands) { sum += summand; } return sum; } /** * Returns a {@link Drawable} for the given resource or throws a {@link * Resources.NotFoundException} if not found. * * @param context The context to get the theme from starting with API 21. * @param resources The resources to load the drawable from. * @param drawableRes The drawable resource int. * @return The loaded {@link Drawable}. */ public static Drawable getDrawable( Context context, Resources resources, @DrawableRes int drawableRes) { return SDK_INT >= 21 ? Api21.getDrawable(context, resources, drawableRes) : resources.getDrawable(drawableRes); } /** * Returns a string representation of the integer using radix value {@link Character#MAX_RADIX}. * * @param i An integer to be converted to String. */ public static String intToStringMaxRadix(int i) { return Integer.toString(i, Character.MAX_RADIX); } /** * Returns whether a play button should be presented on a UI element for playback control. If * {@code false}, a pause button should be shown instead. * * <p>Use {@link #handlePlayPauseButtonAction}, {@link #handlePlayButtonAction} or {@link * #handlePauseButtonAction} to handle the interaction with the play or pause button UI element. * * @param player The {@link Player}. May be null. */ @EnsuresNonNullIf(result = false, expression = "#1") public static boolean shouldShowPlayButton(@Nullable Player player) { return player == null || !player.getPlayWhenReady() || player.getPlaybackState() == Player.STATE_IDLE || player.getPlaybackState() == Player.STATE_ENDED; } /** * Updates the player to handle an interaction with a play button. * * <p>This method assumes the play button is enabled if {@link #shouldShowPlayButton} returns * true. * * @param player The {@link Player}. May be null. * @return Whether a player method was triggered to handle this action. */ public static boolean handlePlayButtonAction(@Nullable Player player) { if (player == null) { return false; } @Player.State int state = player.getPlaybackState(); boolean methodTriggered = false; if (state == Player.STATE_IDLE && player.isCommandAvailable(COMMAND_PREPARE)) { player.prepare(); methodTriggered = true; } else if (state == Player.STATE_ENDED && player.isCommandAvailable(COMMAND_SEEK_TO_DEFAULT_POSITION)) { player.seekToDefaultPosition(); methodTriggered = true; } if (player.isCommandAvailable(COMMAND_PLAY_PAUSE)) { player.play(); methodTriggered = true; } return methodTriggered; } /** * Updates the player to handle an interaction with a pause button. * * <p>This method assumes the pause button is enabled if {@link #shouldShowPlayButton} returns * false. * * @param player The {@link Player}. May be null. * @return Whether a player method was triggered to handle this action. */ public static boolean handlePauseButtonAction(@Nullable Player player) { if (player != null && player.isCommandAvailable(COMMAND_PLAY_PAUSE)) { player.pause(); return true; } return false; } /** * Updates the player to handle an interaction with a play or pause button. * * <p>This method assumes that the UI element enables a play button if {@link * #shouldShowPlayButton} returns true and a pause button otherwise. * * @param player The {@link Player}. May be null. * @return Whether a player method was triggered to handle this action. */ public static boolean handlePlayPauseButtonAction(@Nullable Player player) { if (shouldShowPlayButton(player)) { return handlePlayButtonAction(player); } else { return handlePauseButtonAction(player); } } @Nullable private static String getSystemProperty(String name) { try { @SuppressLint("PrivateApi") Class<?> systemProperties = Class.forName("android.os.SystemProperties"); Method getMethod = systemProperties.getMethod("get", String.class); return (String) getMethod.invoke(systemProperties, name); } catch (Exception e) { Log.e(TAG, "Failed to read system property " + name, e); return null; } } @RequiresApi(23) private static void getDisplaySizeV23(Display display, Point outSize) { Display.Mode mode = display.getMode(); outSize.x = mode.getPhysicalWidth(); outSize.y = mode.getPhysicalHeight(); } @RequiresApi(17) private static void getDisplaySizeV17(Display display, Point outSize) { display.getRealSize(outSize); } private static void getDisplaySizeV16(Display display, Point outSize) { display.getSize(outSize); } private static String[] getSystemLocales() { Configuration config = Resources.getSystem().getConfiguration(); return SDK_INT >= 24 ? getSystemLocalesV24(config) : new String[] {getLocaleLanguageTag(config.locale)}; } @RequiresApi(24) private static String[] getSystemLocalesV24(Configuration config) { return split(config.getLocales().toLanguageTags(), ","); } @RequiresApi(21) private static String getLocaleLanguageTagV21(Locale locale) { return locale.toLanguageTag(); } private static HashMap<String, String> createIsoLanguageReplacementMap() { String[] iso2Languages = Locale.getISOLanguages(); HashMap<String, String> replacedLanguages = new HashMap<>( /* initialCapacity= */ iso2Languages.length + additionalIsoLanguageReplacements.length); for (String iso2 : iso2Languages) { try { // This returns the ISO 639-2/T code for the language. String iso3 = new Locale(iso2).getISO3Language(); if (!TextUtils.isEmpty(iso3)) { replacedLanguages.put(iso3, iso2); } } catch (MissingResourceException e) { // Shouldn't happen for list of known languages, but we don't want to throw either. } } // Add additional replacement mappings. for (int i = 0; i < additionalIsoLanguageReplacements.length; i += 2) { replacedLanguages.put( additionalIsoLanguageReplacements[i], additionalIsoLanguageReplacements[i + 1]); } return replacedLanguages; } @RequiresApi(api = Build.VERSION_CODES.M) private static boolean requestExternalStoragePermission(Activity activity) { if (activity.checkSelfPermission(permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions( new String[] {permission.READ_EXTERNAL_STORAGE}, /* requestCode= */ 0); return true; } return false; } @RequiresApi(api = Build.VERSION_CODES.N) private static boolean isTrafficRestricted(Uri uri) { return "http".equals(uri.getScheme()) && !NetworkSecurityPolicy.getInstance() .isCleartextTrafficPermitted(checkNotNull(uri.getHost())); } private static String maybeReplaceLegacyLanguageTags(String languageTag) { for (int i = 0; i < isoLegacyTagReplacements.length; i += 2) { if (languageTag.startsWith(isoLegacyTagReplacements[i])) { return isoLegacyTagReplacements[i + 1] + languageTag.substring(/* beginIndex= */ isoLegacyTagReplacements[i].length()); } } return languageTag; } // Additional mapping from ISO3 to ISO2 language codes. private static final String[] additionalIsoLanguageReplacements = new String[] { // Bibliographical codes defined in ISO 639-2/B, replaced by terminological code defined in // ISO 639-2/T. See https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes. "alb", "sq", "arm", "hy", "baq", "eu", "bur", "my", "tib", "bo", "chi", "zh", "cze", "cs", "dut", "nl", "ger", "de", "gre", "el", "fre", "fr", "geo", "ka", "ice", "is", "mac", "mk", "mao", "mi", "may", "ms", "per", "fa", "rum", "ro", "scc", "hbs-srp", "slo", "sk", "wel", "cy", // Deprecated 2-letter codes, replaced by modern equivalent (including macrolanguage) // See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes, "ISO 639:1988" "id", "ms-ind", "iw", "he", "heb", "he", "ji", "yi", // Individual macrolanguage codes mapped back to full macrolanguage code. // See https://en.wikipedia.org/wiki/ISO_639_macrolanguage "arb", "ar-arb", "in", "ms-ind", "ind", "ms-ind", "nb", "no-nob", "nob", "no-nob", "nn", "no-nno", "nno", "no-nno", "tw", "ak-twi", "twi", "ak-twi", "bs", "hbs-bos", "bos", "hbs-bos", "hr", "hbs-hrv", "hrv", "hbs-hrv", "sr", "hbs-srp", "srp", "hbs-srp", "cmn", "zh-cmn", "hak", "zh-hak", "nan", "zh-nan", "hsn", "zh-hsn" }; // Legacy tags that have been replaced by modern equivalents (including macrolanguage) // See https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry. private static final String[] isoLegacyTagReplacements = new String[] { "i-lux", "lb", "i-hak", "zh-hak", "i-navajo", "nv", "no-bok", "no-nob", "no-nyn", "no-nno", "zh-guoyu", "zh-cmn", "zh-hakka", "zh-hak", "zh-min-nan", "zh-nan", "zh-xiang", "zh-hsn" }; /** * Allows the CRC-32 calculation to be done byte by byte instead of bit per bit in the order "most * significant bit first". */ private static final int[] CRC32_BYTES_MSBF = { 0X00000000, 0X04C11DB7, 0X09823B6E, 0X0D4326D9, 0X130476DC, 0X17C56B6B, 0X1A864DB2, 0X1E475005, 0X2608EDB8, 0X22C9F00F, 0X2F8AD6D6, 0X2B4BCB61, 0X350C9B64, 0X31CD86D3, 0X3C8EA00A, 0X384FBDBD, 0X4C11DB70, 0X48D0C6C7, 0X4593E01E, 0X4152FDA9, 0X5F15ADAC, 0X5BD4B01B, 0X569796C2, 0X52568B75, 0X6A1936C8, 0X6ED82B7F, 0X639B0DA6, 0X675A1011, 0X791D4014, 0X7DDC5DA3, 0X709F7B7A, 0X745E66CD, 0X9823B6E0, 0X9CE2AB57, 0X91A18D8E, 0X95609039, 0X8B27C03C, 0X8FE6DD8B, 0X82A5FB52, 0X8664E6E5, 0XBE2B5B58, 0XBAEA46EF, 0XB7A96036, 0XB3687D81, 0XAD2F2D84, 0XA9EE3033, 0XA4AD16EA, 0XA06C0B5D, 0XD4326D90, 0XD0F37027, 0XDDB056FE, 0XD9714B49, 0XC7361B4C, 0XC3F706FB, 0XCEB42022, 0XCA753D95, 0XF23A8028, 0XF6FB9D9F, 0XFBB8BB46, 0XFF79A6F1, 0XE13EF6F4, 0XE5FFEB43, 0XE8BCCD9A, 0XEC7DD02D, 0X34867077, 0X30476DC0, 0X3D044B19, 0X39C556AE, 0X278206AB, 0X23431B1C, 0X2E003DC5, 0X2AC12072, 0X128E9DCF, 0X164F8078, 0X1B0CA6A1, 0X1FCDBB16, 0X018AEB13, 0X054BF6A4, 0X0808D07D, 0X0CC9CDCA, 0X7897AB07, 0X7C56B6B0, 0X71159069, 0X75D48DDE, 0X6B93DDDB, 0X6F52C06C, 0X6211E6B5, 0X66D0FB02, 0X5E9F46BF, 0X5A5E5B08, 0X571D7DD1, 0X53DC6066, 0X4D9B3063, 0X495A2DD4, 0X44190B0D, 0X40D816BA, 0XACA5C697, 0XA864DB20, 0XA527FDF9, 0XA1E6E04E, 0XBFA1B04B, 0XBB60ADFC, 0XB6238B25, 0XB2E29692, 0X8AAD2B2F, 0X8E6C3698, 0X832F1041, 0X87EE0DF6, 0X99A95DF3, 0X9D684044, 0X902B669D, 0X94EA7B2A, 0XE0B41DE7, 0XE4750050, 0XE9362689, 0XEDF73B3E, 0XF3B06B3B, 0XF771768C, 0XFA325055, 0XFEF34DE2, 0XC6BCF05F, 0XC27DEDE8, 0XCF3ECB31, 0XCBFFD686, 0XD5B88683, 0XD1799B34, 0XDC3ABDED, 0XD8FBA05A, 0X690CE0EE, 0X6DCDFD59, 0X608EDB80, 0X644FC637, 0X7A089632, 0X7EC98B85, 0X738AAD5C, 0X774BB0EB, 0X4F040D56, 0X4BC510E1, 0X46863638, 0X42472B8F, 0X5C007B8A, 0X58C1663D, 0X558240E4, 0X51435D53, 0X251D3B9E, 0X21DC2629, 0X2C9F00F0, 0X285E1D47, 0X36194D42, 0X32D850F5, 0X3F9B762C, 0X3B5A6B9B, 0X0315D626, 0X07D4CB91, 0X0A97ED48, 0X0E56F0FF, 0X1011A0FA, 0X14D0BD4D, 0X19939B94, 0X1D528623, 0XF12F560E, 0XF5EE4BB9, 0XF8AD6D60, 0XFC6C70D7, 0XE22B20D2, 0XE6EA3D65, 0XEBA91BBC, 0XEF68060B, 0XD727BBB6, 0XD3E6A601, 0XDEA580D8, 0XDA649D6F, 0XC423CD6A, 0XC0E2D0DD, 0XCDA1F604, 0XC960EBB3, 0XBD3E8D7E, 0XB9FF90C9, 0XB4BCB610, 0XB07DABA7, 0XAE3AFBA2, 0XAAFBE615, 0XA7B8C0CC, 0XA379DD7B, 0X9B3660C6, 0X9FF77D71, 0X92B45BA8, 0X9675461F, 0X8832161A, 0X8CF30BAD, 0X81B02D74, 0X857130C3, 0X5D8A9099, 0X594B8D2E, 0X5408ABF7, 0X50C9B640, 0X4E8EE645, 0X4A4FFBF2, 0X470CDD2B, 0X43CDC09C, 0X7B827D21, 0X7F436096, 0X7200464F, 0X76C15BF8, 0X68860BFD, 0X6C47164A, 0X61043093, 0X65C52D24, 0X119B4BE9, 0X155A565E, 0X18197087, 0X1CD86D30, 0X029F3D35, 0X065E2082, 0X0B1D065B, 0X0FDC1BEC, 0X3793A651, 0X3352BBE6, 0X3E119D3F, 0X3AD08088, 0X2497D08D, 0X2056CD3A, 0X2D15EBE3, 0X29D4F654, 0XC5A92679, 0XC1683BCE, 0XCC2B1D17, 0XC8EA00A0, 0XD6AD50A5, 0XD26C4D12, 0XDF2F6BCB, 0XDBEE767C, 0XE3A1CBC1, 0XE760D676, 0XEA23F0AF, 0XEEE2ED18, 0XF0A5BD1D, 0XF464A0AA, 0XF9278673, 0XFDE69BC4, 0X89B8FD09, 0X8D79E0BE, 0X803AC667, 0X84FBDBD0, 0X9ABC8BD5, 0X9E7D9662, 0X933EB0BB, 0X97FFAD0C, 0XAFB010B1, 0XAB710D06, 0XA6322BDF, 0XA2F33668, 0XBCB4666D, 0XB8757BDA, 0XB5365D03, 0XB1F740B4 }; /** * Allows the CRC-8 calculation to be done byte by byte instead of bit per bit in the order "most * significant bit first". */ private static final int[] CRC8_BYTES_MSBF = { 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D, 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D, 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD, 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD, 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA, 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A, 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A, 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A, 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4, 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4, 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44, 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34, 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63, 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13, 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83, 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3 }; @RequiresApi(21) private static final class Api21 { @DoNotInline public static Drawable getDrawable(Context context, Resources resources, @DrawableRes int res) { return resources.getDrawable(res, context.getTheme()); } } }
google/ExoPlayer
library/common/src/main/java/com/google/android/exoplayer2/util/Util.java
2,345
/* * 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.druid.curator.discovery; import com.google.common.collect.ImmutableList; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.name.Names; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ZKPaths; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceCacheBuilder; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; import org.apache.curator.x.discovery.ServiceProviderBuilder; import org.apache.curator.x.discovery.details.ServiceCacheListener; import org.apache.druid.client.coordinator.Coordinator; import org.apache.druid.client.indexing.IndexingService; import org.apache.druid.curator.ZkEnablementConfig; import org.apache.druid.discovery.DruidLeaderSelector; import org.apache.druid.discovery.DruidNodeAnnouncer; import org.apache.druid.discovery.DruidNodeDiscoveryProvider; import org.apache.druid.guice.DruidBinders; import org.apache.druid.guice.JsonConfigProvider; import org.apache.druid.guice.KeyHolder; import org.apache.druid.guice.LazySingleton; import org.apache.druid.guice.LifecycleModule; import org.apache.druid.guice.PolyBind; import org.apache.druid.guice.annotations.Self; import org.apache.druid.java.util.common.lifecycle.Lifecycle; import org.apache.druid.server.DruidNode; import org.apache.druid.server.initialization.CuratorDiscoveryConfig; import org.apache.druid.server.initialization.ZkPathsConfig; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.function.Function; /** * The DiscoveryModule allows for the registration of Keys of DruidNode objects, which it intends to be * automatically announced at the end of the lifecycle start. * * In order for this to work a ServiceAnnouncer instance *must* be injected and instantiated first. * This can often be achieved by registering ServiceAnnouncer.class with the LifecycleModule. */ public class DiscoveryModule implements Module { private static final String NAME = "DiscoveryModule:internal"; private static final String INTERNAL_DISCOVERY_PROP = "druid.discovery.type"; private static final String CURATOR_KEY = "curator"; private boolean isZkEnabled = true; @Inject public void configure(Properties properties) { isZkEnabled = ZkEnablementConfig.isEnabled(properties); } /** * Requests that the un-annotated DruidNode instance be injected and published as part of the lifecycle. * * That is, this module will announce the DruidNode instance returned by * injector.getInstance(Key.get(DruidNode.class)) automatically. * Announcement will happen in the ANNOUNCEMENTS stage of the Lifecycle * * @param binder the Binder to register with */ public static void registerDefault(Binder binder) { registerKey(binder, Key.get(new TypeLiteral<DruidNode>(){})); } /** * Requests that the annotated DruidNode instance be injected and published as part of the lifecycle. * * That is, this module will announce the DruidNode instance returned by * injector.getInstance(Key.get(DruidNode.class, annotation)) automatically. * Announcement will happen in the ANNOUNCEMENTS stage of the Lifecycle * * @param annotation The annotation instance to use in finding the DruidNode instance, usually a Named annotation */ public static void register(Binder binder, Annotation annotation) { registerKey(binder, Key.get(new TypeLiteral<DruidNode>(){}, annotation)); } /** * Requests that the annotated DruidNode instance be injected and published as part of the lifecycle. * * That is, this module will announce the DruidNode instance returned by * injector.getInstance(Key.get(DruidNode.class, annotation)) automatically. * Announcement will happen in the ANNOUNCEMENTS stage of the Lifecycle * * @param binder the Binder to register with * @param annotation The annotation class to use in finding the DruidNode instance */ public static void register(Binder binder, Class<? extends Annotation> annotation) { registerKey(binder, Key.get(new TypeLiteral<DruidNode>(){}, annotation)); } /** * Requests that the keyed DruidNode instance be injected and published as part of the lifecycle. * * That is, this module will announce the DruidNode instance returned by * injector.getInstance(Key.get(DruidNode.class, annotation)) automatically. * Announcement will happen in the ANNOUNCEMENTS stage of the Lifecycle * * @param binder the Binder to register with * @param key The key to use in finding the DruidNode instance */ public static void registerKey(Binder binder, Key<DruidNode> key) { DruidBinders.discoveryAnnouncementBinder(binder).addBinding().toInstance(new KeyHolder<>(key)); LifecycleModule.register(binder, ServiceAnnouncer.class); } @Override public void configure(Binder binder) { JsonConfigProvider.bind(binder, "druid.discovery.curator", CuratorDiscoveryConfig.class); binder.bind(CuratorServiceAnnouncer.class).in(LazySingleton.class); // Build the binder so that it will at a minimum inject an empty set. DruidBinders.discoveryAnnouncementBinder(binder); if (isZkEnabled) { binder.bind(ServiceAnnouncer.class) .to(Key.get(CuratorServiceAnnouncer.class, Names.named(NAME))) .in(LazySingleton.class); } else { binder.bind(Key.get(ServiceAnnouncer.Noop.class, Names.named(NAME))).toInstance(new ServiceAnnouncer.Noop()); binder.bind(ServiceAnnouncer.class) .to(Key.get(ServiceAnnouncer.Noop.class, Names.named(NAME))) .in(LazySingleton.class); } // internal discovery bindings. PolyBind.createChoiceWithDefault(binder, INTERNAL_DISCOVERY_PROP, Key.get(DruidNodeAnnouncer.class), CURATOR_KEY); PolyBind.createChoiceWithDefault( binder, INTERNAL_DISCOVERY_PROP, Key.get(DruidNodeDiscoveryProvider.class), CURATOR_KEY ); PolyBind.createChoiceWithDefault( binder, INTERNAL_DISCOVERY_PROP, Key.get(DruidLeaderSelector.class, Coordinator.class), CURATOR_KEY ); PolyBind.createChoiceWithDefault( binder, INTERNAL_DISCOVERY_PROP, Key.get(DruidLeaderSelector.class, IndexingService.class), CURATOR_KEY ); PolyBind.optionBinder(binder, Key.get(DruidNodeDiscoveryProvider.class)) .addBinding(CURATOR_KEY) .to(CuratorDruidNodeDiscoveryProvider.class) .in(LazySingleton.class); PolyBind.optionBinder(binder, Key.get(DruidNodeAnnouncer.class)) .addBinding(CURATOR_KEY) .to(CuratorDruidNodeAnnouncer.class) .in(LazySingleton.class); PolyBind.optionBinder(binder, Key.get(DruidLeaderSelector.class, Coordinator.class)) .addBinding(CURATOR_KEY) .toProvider( new DruidLeaderSelectorProvider( zkPathsConfig -> ZKPaths.makePath(zkPathsConfig.getCoordinatorPath(), "_COORDINATOR") ) ) .in(LazySingleton.class); PolyBind.optionBinder(binder, Key.get(DruidLeaderSelector.class, IndexingService.class)) .addBinding(CURATOR_KEY) .toProvider( new DruidLeaderSelectorProvider( zkPathsConfig -> ZKPaths.makePath(zkPathsConfig.getOverlordPath(), "_OVERLORD") ) ) .in(LazySingleton.class); } @Provides @LazySingleton @Named(NAME) public CuratorServiceAnnouncer getServiceAnnouncer( final CuratorServiceAnnouncer announcer, final Injector injector, final Set<KeyHolder<DruidNode>> nodesToAnnounce, final Lifecycle lifecycle ) throws Exception { lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { private volatile List<DruidNode> nodes = null; @Override public void start() { if (nodes == null) { nodes = new ArrayList<>(); for (KeyHolder<DruidNode> holder : nodesToAnnounce) { nodes.add(injector.getInstance(holder.getKey())); } } for (DruidNode node : nodes) { announcer.announce(node); } } @Override public void stop() { if (nodes != null) { for (DruidNode node : nodes) { announcer.unannounce(node); } } } }, Lifecycle.Stage.ANNOUNCEMENTS ); return announcer; } @Provides @LazySingleton public ServiceDiscovery<Void> getServiceDiscovery( CuratorFramework curator, CuratorDiscoveryConfig config, Lifecycle lifecycle ) throws Exception { if (!config.useDiscovery()) { return new NoopServiceDiscovery<>(); } final ServiceDiscovery<Void> serviceDiscovery = ServiceDiscoveryBuilder.builder(Void.class) .basePath(config.getPath()) .client(curator) .build(); lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { serviceDiscovery.start(); } @Override public void stop() { try { serviceDiscovery.close(); } catch (Exception e) { throw new RuntimeException(e); } } } ); return serviceDiscovery; } @Provides @LazySingleton public ServerDiscoveryFactory getServerDiscoveryFactory( ServiceDiscovery<Void> serviceDiscovery ) { return new ServerDiscoveryFactory(serviceDiscovery); } private static class NoopServiceDiscovery<T> implements ServiceDiscovery<T> { @Override public void start() { } @Override public void registerService(ServiceInstance<T> service) { } @Override public void updateService(ServiceInstance<T> service) { } @Override public void unregisterService(ServiceInstance<T> service) { } @Override public ServiceCacheBuilder<T> serviceCacheBuilder() { return new NoopServiceCacheBuilder<>(); } @Override public Collection<String> queryForNames() { return ImmutableList.of(); } @Override public Collection<ServiceInstance<T>> queryForInstances(String name) { return ImmutableList.of(); } @Override public ServiceInstance<T> queryForInstance(String name, String id) { return null; } @Override public ServiceProviderBuilder<T> serviceProviderBuilder() { return new NoopServiceProviderBuilder<>(); } @Override public void close() { } } private static class NoopServiceCacheBuilder<T> implements ServiceCacheBuilder<T> { @Override public ServiceCache<T> build() { return new NoopServiceCache<>(); } @Override public ServiceCacheBuilder<T> name(String name) { return this; } @Override public ServiceCacheBuilder<T> threadFactory(ThreadFactory threadFactory) { return this; } @Override public ServiceCacheBuilder<T> executorService(ExecutorService executorService) { return this; } private static class NoopServiceCache<T> implements ServiceCache<T> { @Override public List<ServiceInstance<T>> getInstances() { return ImmutableList.of(); } @Override public void start() { // nothing } @Override public CountDownLatch startImmediate() { return null; } @Override public void close() { // nothing } @Override public void addListener(ServiceCacheListener listener) { // nothing } @Override public void addListener(ServiceCacheListener listener, Executor executor) { // nothing } @Override public void removeListener(ServiceCacheListener listener) { // nothing } } } private static class NoopServiceProviderBuilder<T> implements ServiceProviderBuilder<T> { @Override public ServiceProvider<T> build() { return new NoopServiceProvider<>(); } @Override public ServiceProviderBuilder<T> serviceName(String serviceName) { return this; } @Override public ServiceProviderBuilder<T> providerStrategy(ProviderStrategy<T> providerStrategy) { return this; } @Override public ServiceProviderBuilder<T> threadFactory(ThreadFactory threadFactory) { return this; } @Override public ServiceProviderBuilder<T> downInstancePolicy(DownInstancePolicy downInstancePolicy) { return this; } @Override public ServiceProviderBuilder<T> additionalFilter(InstanceFilter<T> tInstanceFilter) { return this; } @Override public ServiceProviderBuilder<T> executorService(ExecutorService executorService) { return this; } } private static class NoopServiceProvider<T> implements ServiceProvider<T> { @Override public void start() { // nothing } @Override public ServiceInstance<T> getInstance() { return null; } @Override public Collection<ServiceInstance<T>> getAllInstances() { return Collections.emptyList(); } @Override public void noteError(ServiceInstance<T> tServiceInstance) { // nothing } @Override public void close() { // nothing } } private static class DruidLeaderSelectorProvider implements Provider<DruidLeaderSelector> { @Inject private Provider<CuratorFramework> curatorFramework; @Inject @Self private DruidNode druidNode; @Inject private ZkPathsConfig zkPathsConfig; private final Function<ZkPathsConfig, String> latchPathFn; DruidLeaderSelectorProvider(Function<ZkPathsConfig, String> latchPathFn) { this.latchPathFn = latchPathFn; } @Override public DruidLeaderSelector get() { return new CuratorDruidLeaderSelector( curatorFramework.get(), druidNode, latchPathFn.apply(zkPathsConfig) ); } } }
apache/druid
server/src/main/java/org/apache/druid/curator/discovery/DiscoveryModule.java
2,346
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.plugin.jdbc; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.util.concurrent.UncheckedExecutionException; import javax.inject.Inject; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; import java.util.concurrent.ExecutorService; import static com.facebook.airlift.concurrent.Threads.daemonThreadsNamed; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.cache.CacheLoader.asyncReloading; import static java.util.Objects.requireNonNull; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class JdbcMetadataCache { private final JdbcClient jdbcClient; private final LoadingCache<KeyAndSession<SchemaTableName>, Optional<JdbcTableHandle>> tableHandleCache; private final LoadingCache<KeyAndSession<JdbcTableHandle>, List<JdbcColumnHandle>> columnHandlesCache; @Inject public JdbcMetadataCache(JdbcClient jdbcClient, JdbcMetadataConfig config, JdbcMetadataCacheStats stats) { this( newCachedThreadPool(daemonThreadsNamed("jdbc-metadata-cache" + "-%s")), jdbcClient, stats, OptionalLong.of(config.getMetadataCacheTtl().toMillis()), config.getMetadataCacheRefreshInterval().toMillis() >= config.getMetadataCacheTtl().toMillis() ? OptionalLong.empty() : OptionalLong.of(config.getMetadataCacheRefreshInterval().toMillis()), config.getMetadataCacheMaximumSize()); } public JdbcMetadataCache( ExecutorService executor, JdbcClient jdbcClient, JdbcMetadataCacheStats stats, OptionalLong cacheTtl, OptionalLong refreshInterval, long cacheMaximumSize) { this.jdbcClient = requireNonNull(jdbcClient, "jdbcClient is null"); this.tableHandleCache = newCacheBuilder(cacheTtl, refreshInterval, cacheMaximumSize) .build(asyncReloading(CacheLoader.from(this::loadTableHandle), executor)); stats.setTableHandleCache(tableHandleCache); this.columnHandlesCache = newCacheBuilder(cacheTtl, refreshInterval, cacheMaximumSize) .build(asyncReloading(CacheLoader.from(this::loadColumnHandles), executor)); stats.setColumnHandlesCache(columnHandlesCache); } public JdbcTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) { return get(tableHandleCache, new KeyAndSession<>(session, tableName)).orElse(null); } public List<JdbcColumnHandle> getColumns(ConnectorSession session, JdbcTableHandle jdbcTableHandle) { return get(columnHandlesCache, new KeyAndSession<>(session, jdbcTableHandle)); } private Optional<JdbcTableHandle> loadTableHandle(KeyAndSession<SchemaTableName> tableName) { // The returned tableHandle can be null if it does not contain the table return Optional.ofNullable(jdbcClient.getTableHandle(tableName.getSession(), JdbcIdentity.from(tableName.getSession()), tableName.getKey())); } private List<JdbcColumnHandle> loadColumnHandles(KeyAndSession<JdbcTableHandle> tableHandle) { return jdbcClient.getColumns(tableHandle.getSession(), tableHandle.getKey()); } private static CacheBuilder<Object, Object> newCacheBuilder(OptionalLong expiresAfterWriteMillis, OptionalLong refreshMillis, long maximumSize) { CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (expiresAfterWriteMillis.isPresent()) { cacheBuilder = cacheBuilder.expireAfterWrite(expiresAfterWriteMillis.getAsLong(), MILLISECONDS); } if (refreshMillis.isPresent() && (!expiresAfterWriteMillis.isPresent() || expiresAfterWriteMillis.getAsLong() > refreshMillis.getAsLong())) { cacheBuilder = cacheBuilder.refreshAfterWrite(refreshMillis.getAsLong(), MILLISECONDS); } return cacheBuilder.maximumSize(maximumSize).recordStats(); } private static <K, V> V get(LoadingCache<K, V> cache, K key) { try { return cache.getUnchecked(key); } catch (UncheckedExecutionException e) { throwIfInstanceOf(e.getCause(), PrestoException.class); throw e; } } private static class KeyAndSession<T> { private final ConnectorSession session; private final T key; public KeyAndSession(ConnectorSession session, T key) { this.session = requireNonNull(session, "session is null"); this.key = requireNonNull(key, "key is null"); } public ConnectorSession getSession() { return session; } public T getKey() { return key; } // Session object changes for every query. For caching to be effective across multiple queries, // we should NOT include session in equals() and hashCode() methods below. @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KeyAndSession<?> other = (KeyAndSession<?>) o; return Objects.equals(key, other.key); } @Override public int hashCode() { return Objects.hash(key); } @Override public String toString() { return toStringHelper(this) .add("session", session) .add("key", key) .toString(); } } }
prestodb/presto
presto-base-jdbc/src/main/java/com/facebook/presto/plugin/jdbc/JdbcMetadataCache.java
2,347
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.google.sheets; import com.facebook.airlift.json.JsonCodec; import com.facebook.airlift.log.Logger; import com.facebook.presto.common.type.VarcharType; import com.facebook.presto.spi.PrestoException; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.UncheckedExecutionException; import javax.inject.Inject; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.facebook.presto.google.sheets.SheetsErrorCode.SHEETS_BAD_CREDENTIALS_ERROR; import static com.facebook.presto.google.sheets.SheetsErrorCode.SHEETS_METASTORE_ERROR; import static com.facebook.presto.google.sheets.SheetsErrorCode.SHEETS_TABLE_LOAD_ERROR; import static com.facebook.presto.google.sheets.SheetsErrorCode.SHEETS_UNKNOWN_TABLE_ERROR; import static com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.newTrustedTransport; import static com.google.common.cache.CacheLoader.from; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class SheetsClient { private static final Logger log = Logger.get(SheetsClient.class); private static final String APPLICATION_NAME = "Presto google sheets integration"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final List<String> SCOPES = ImmutableList.of(SheetsScopes.SPREADSHEETS_READONLY); private final LoadingCache<String, Optional<String>> tableSheetMappingCache; private final LoadingCache<String, List<List<Object>>> sheetDataCache; private final String metadataSheetId; private final String credentialsFilePath; private final Sheets sheetsService; @Inject public SheetsClient(SheetsConfig config, JsonCodec<Map<String, List<SheetsTable>>> catalogCodec) { requireNonNull(config, "config is null"); requireNonNull(catalogCodec, "catalogCodec is null"); this.metadataSheetId = config.getMetadataSheetId(); this.credentialsFilePath = config.getCredentialsFilePath(); try { this.sheetsService = new Sheets.Builder(newTrustedTransport(), JSON_FACTORY, getCredentials()).setApplicationName(APPLICATION_NAME).build(); } catch (GeneralSecurityException | IOException e) { throw new PrestoException(SHEETS_BAD_CREDENTIALS_ERROR, e); } long expiresAfterWriteMillis = config.getSheetsDataExpireAfterWrite().toMillis(); long maxCacheSize = config.getSheetsDataMaxCacheSize(); this.tableSheetMappingCache = newCacheBuilder(expiresAfterWriteMillis, maxCacheSize) .build(new CacheLoader<String, Optional<String>>() { @Override public Optional<String> load(String tableName) { return getSheetExpressionForTable(tableName); } }); this.sheetDataCache = newCacheBuilder(expiresAfterWriteMillis, maxCacheSize).build(from(this::readAllValuesFromSheetExpression)); } public Optional<SheetsTable> getTable(String tableName) { List<List<Object>> values = readAllValues(tableName); if (values.size() > 0) { ImmutableList.Builder<SheetsColumn> columns = ImmutableList.builder(); Set<String> columnNames = new HashSet<>(); // Assuming 1st line is always header List<Object> header = values.get(0); int count = 0; for (Object column : header) { String columnValue = column.toString().toLowerCase(ENGLISH); // when empty or repeated column header, adding a placeholder column name if (columnValue.isEmpty() || columnNames.contains(columnValue)) { columnValue = "column_" + ++count; } columnNames.add(columnValue); columns.add(new SheetsColumn(columnValue, VarcharType.VARCHAR)); } List<List<Object>> dataValues = values.subList(1, values.size()); // removing header info return Optional.of(new SheetsTable(tableName, columns.build(), dataValues)); } return Optional.empty(); } public Set<String> getTableNames() { ImmutableSet.Builder<String> tables = ImmutableSet.builder(); try { List<List<Object>> tableMetadata = sheetDataCache.getUnchecked(metadataSheetId); for (int i = 1; i < tableMetadata.size(); i++) { if (tableMetadata.get(i).size() > 0) { tables.add(String.valueOf(tableMetadata.get(i).get(0))); } } return tables.build(); } catch (UncheckedExecutionException e) { throwIfInstanceOf(e.getCause(), PrestoException.class); throw new PrestoException(SHEETS_METASTORE_ERROR, e); } } public List<List<Object>> readAllValues(String tableName) { try { Optional<String> sheetExpression = tableSheetMappingCache.getUnchecked(tableName); if (!sheetExpression.isPresent()) { throw new PrestoException(SHEETS_UNKNOWN_TABLE_ERROR, "Sheet expression not found for table " + tableName); } return sheetDataCache.getUnchecked(sheetExpression.get()); } catch (UncheckedExecutionException e) { throwIfInstanceOf(e.getCause(), PrestoException.class); throw new PrestoException(SHEETS_TABLE_LOAD_ERROR, "Error loading data for table: " + tableName, e); } } private Optional<String> getSheetExpressionForTable(String tableName) { Map<String, Optional<String>> tableSheetMap = getAllTableSheetExpressionMapping(); if (!tableSheetMap.containsKey(tableName)) { return Optional.empty(); } return tableSheetMap.get(tableName); } private Map<String, Optional<String>> getAllTableSheetExpressionMapping() { ImmutableMap.Builder<String, Optional<String>> tableSheetMap = ImmutableMap.builder(); List<List<Object>> data = readAllValuesFromSheetExpression(metadataSheetId); // first line is assumed to be sheet header for (int i = 1; i < data.size(); i++) { if (data.get(i).size() >= 2) { String tableId = String.valueOf(data.get(i).get(0)); String sheetId = String.valueOf(data.get(i).get(1)); tableSheetMap.put(tableId.toLowerCase(Locale.ENGLISH), Optional.of(sheetId)); } } return tableSheetMap.build(); } private Credential getCredentials() { try (InputStream in = new FileInputStream(credentialsFilePath)) { return GoogleCredential.fromStream(in).createScoped(SCOPES); } catch (IOException e) { throw new PrestoException(SHEETS_BAD_CREDENTIALS_ERROR, e); } } private List<List<Object>> readAllValuesFromSheetExpression(String sheetExpression) { try { // by default loading up to 10k rows from the first tab of the sheet String defaultRange = "$1:$10000"; String[] tableOptions = sheetExpression.split("#"); String sheetId = tableOptions[0]; if (tableOptions.length > 1) { defaultRange = tableOptions[1]; } log.debug("Accessing sheet id [%s] with range [%s]", sheetId, defaultRange); return sheetsService.spreadsheets().values().get(sheetId, defaultRange).execute().getValues(); } catch (IOException e) { throw new PrestoException(SHEETS_UNKNOWN_TABLE_ERROR, "Failed reading data from sheet: " + sheetExpression, e); } } private static CacheBuilder<Object, Object> newCacheBuilder(long expiresAfterWriteMillis, long maximumSize) { return CacheBuilder.newBuilder().expireAfterWrite(expiresAfterWriteMillis, MILLISECONDS).maximumSize(maximumSize); } private static <X extends Throwable> void throwIfInstanceOf( Throwable throwable, Class<X> declaredType) throws X { requireNonNull(throwable); if (declaredType.isInstance(throwable)) { throw declaredType.cast(throwable); } } }
prestodb/presto
presto-google-sheets/src/main/java/com/facebook/presto/google/sheets/SheetsClient.java
2,348
package com.termux.terminal; /** * Implementation of wcwidth(3) for Unicode 15. * * Implementation from https://github.com/jquast/wcwidth but we return 0 for unprintable characters. * * IMPORTANT: * Must be kept in sync with the following: * https://github.com/termux/wcwidth * https://github.com/termux/libandroid-support * https://github.com/termux/termux-packages/tree/master/packages/libandroid-support */ public final class WcWidth { // From https://github.com/jquast/wcwidth/blob/master/wcwidth/table_zero.py // from https://github.com/jquast/wcwidth/pull/64 // at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16): private static final int[][] ZERO_WIDTH = { {0x00300, 0x0036f}, // Combining Grave Accent ..Combining Latin Small Le {0x00483, 0x00489}, // Combining Cyrillic Titlo..Combining Cyrillic Milli {0x00591, 0x005bd}, // Hebrew Accent Etnahta ..Hebrew Point Meteg {0x005bf, 0x005bf}, // Hebrew Point Rafe ..Hebrew Point Rafe {0x005c1, 0x005c2}, // Hebrew Point Shin Dot ..Hebrew Point Sin Dot {0x005c4, 0x005c5}, // Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot {0x005c7, 0x005c7}, // Hebrew Point Qamats Qata..Hebrew Point Qamats Qata {0x00610, 0x0061a}, // Arabic Sign Sallallahou ..Arabic Small Kasra {0x0064b, 0x0065f}, // Arabic Fathatan ..Arabic Wavy Hamza Below {0x00670, 0x00670}, // Arabic Letter Superscrip..Arabic Letter Superscrip {0x006d6, 0x006dc}, // Arabic Small High Ligatu..Arabic Small High Seen {0x006df, 0x006e4}, // Arabic Small High Rounde..Arabic Small High Madda {0x006e7, 0x006e8}, // Arabic Small High Yeh ..Arabic Small High Noon {0x006ea, 0x006ed}, // Arabic Empty Centre Low ..Arabic Small Low Meem {0x00711, 0x00711}, // Syriac Letter Superscrip..Syriac Letter Superscrip {0x00730, 0x0074a}, // Syriac Pthaha Above ..Syriac Barrekh {0x007a6, 0x007b0}, // Thaana Abafili ..Thaana Sukun {0x007eb, 0x007f3}, // Nko Combining Short High..Nko Combining Double Dot {0x007fd, 0x007fd}, // Nko Dantayalan ..Nko Dantayalan {0x00816, 0x00819}, // Samaritan Mark In ..Samaritan Mark Dagesh {0x0081b, 0x00823}, // Samaritan Mark Epentheti..Samaritan Vowel Sign A {0x00825, 0x00827}, // Samaritan Vowel Sign Sho..Samaritan Vowel Sign U {0x00829, 0x0082d}, // Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa {0x00859, 0x0085b}, // Mandaic Affrication Mark..Mandaic Gemination Mark {0x00898, 0x0089f}, // Arabic Small High Word A..Arabic Half Madda Over M {0x008ca, 0x008e1}, // Arabic Small High Farsi ..Arabic Small High Sign S {0x008e3, 0x00902}, // Arabic Turned Damma Belo..Devanagari Sign Anusvara {0x0093a, 0x0093a}, // Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe {0x0093c, 0x0093c}, // Devanagari Sign Nukta ..Devanagari Sign Nukta {0x00941, 0x00948}, // Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai {0x0094d, 0x0094d}, // Devanagari Sign Virama ..Devanagari Sign Virama {0x00951, 0x00957}, // Devanagari Stress Sign U..Devanagari Vowel Sign Uu {0x00962, 0x00963}, // Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo {0x00981, 0x00981}, // Bengali Sign Candrabindu..Bengali Sign Candrabindu {0x009bc, 0x009bc}, // Bengali Sign Nukta ..Bengali Sign Nukta {0x009c1, 0x009c4}, // Bengali Vowel Sign U ..Bengali Vowel Sign Vocal {0x009cd, 0x009cd}, // Bengali Sign Virama ..Bengali Sign Virama {0x009e2, 0x009e3}, // Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal {0x009fe, 0x009fe}, // Bengali Sandhi Mark ..Bengali Sandhi Mark {0x00a01, 0x00a02}, // Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi {0x00a3c, 0x00a3c}, // Gurmukhi Sign Nukta ..Gurmukhi Sign Nukta {0x00a41, 0x00a42}, // Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu {0x00a47, 0x00a48}, // Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai {0x00a4b, 0x00a4d}, // Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama {0x00a51, 0x00a51}, // Gurmukhi Sign Udaat ..Gurmukhi Sign Udaat {0x00a70, 0x00a71}, // Gurmukhi Tippi ..Gurmukhi Addak {0x00a75, 0x00a75}, // Gurmukhi Sign Yakash ..Gurmukhi Sign Yakash {0x00a81, 0x00a82}, // Gujarati Sign Candrabind..Gujarati Sign Anusvara {0x00abc, 0x00abc}, // Gujarati Sign Nukta ..Gujarati Sign Nukta {0x00ac1, 0x00ac5}, // Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand {0x00ac7, 0x00ac8}, // Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai {0x00acd, 0x00acd}, // Gujarati Sign Virama ..Gujarati Sign Virama {0x00ae2, 0x00ae3}, // Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca {0x00afa, 0x00aff}, // Gujarati Sign Sukun ..Gujarati Sign Two-circle {0x00b01, 0x00b01}, // Oriya Sign Candrabindu ..Oriya Sign Candrabindu {0x00b3c, 0x00b3c}, // Oriya Sign Nukta ..Oriya Sign Nukta {0x00b3f, 0x00b3f}, // Oriya Vowel Sign I ..Oriya Vowel Sign I {0x00b41, 0x00b44}, // Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic {0x00b4d, 0x00b4d}, // Oriya Sign Virama ..Oriya Sign Virama {0x00b55, 0x00b56}, // Oriya Sign Overline ..Oriya Ai Length Mark {0x00b62, 0x00b63}, // Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic {0x00b82, 0x00b82}, // Tamil Sign Anusvara ..Tamil Sign Anusvara {0x00bc0, 0x00bc0}, // Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii {0x00bcd, 0x00bcd}, // Tamil Sign Virama ..Tamil Sign Virama {0x00c00, 0x00c00}, // Telugu Sign Combining Ca..Telugu Sign Combining Ca {0x00c04, 0x00c04}, // Telugu Sign Combining An..Telugu Sign Combining An {0x00c3c, 0x00c3c}, // Telugu Sign Nukta ..Telugu Sign Nukta {0x00c3e, 0x00c40}, // Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii {0x00c46, 0x00c48}, // Telugu Vowel Sign E ..Telugu Vowel Sign Ai {0x00c4a, 0x00c4d}, // Telugu Vowel Sign O ..Telugu Sign Virama {0x00c55, 0x00c56}, // Telugu Length Mark ..Telugu Ai Length Mark {0x00c62, 0x00c63}, // Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali {0x00c81, 0x00c81}, // Kannada Sign Candrabindu..Kannada Sign Candrabindu {0x00cbc, 0x00cbc}, // Kannada Sign Nukta ..Kannada Sign Nukta {0x00cbf, 0x00cbf}, // Kannada Vowel Sign I ..Kannada Vowel Sign I {0x00cc6, 0x00cc6}, // Kannada Vowel Sign E ..Kannada Vowel Sign E {0x00ccc, 0x00ccd}, // Kannada Vowel Sign Au ..Kannada Sign Virama {0x00ce2, 0x00ce3}, // Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal {0x00d00, 0x00d01}, // Malayalam Sign Combining..Malayalam Sign Candrabin {0x00d3b, 0x00d3c}, // Malayalam Sign Vertical ..Malayalam Sign Circular {0x00d41, 0x00d44}, // Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc {0x00d4d, 0x00d4d}, // Malayalam Sign Virama ..Malayalam Sign Virama {0x00d62, 0x00d63}, // Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc {0x00d81, 0x00d81}, // Sinhala Sign Candrabindu..Sinhala Sign Candrabindu {0x00dca, 0x00dca}, // Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna {0x00dd2, 0x00dd4}, // Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti {0x00dd6, 0x00dd6}, // Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga {0x00e31, 0x00e31}, // Thai Character Mai Han-a..Thai Character Mai Han-a {0x00e34, 0x00e3a}, // Thai Character Sara I ..Thai Character Phinthu {0x00e47, 0x00e4e}, // Thai Character Maitaikhu..Thai Character Yamakkan {0x00eb1, 0x00eb1}, // Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan {0x00eb4, 0x00ebc}, // Lao Vowel Sign I ..Lao Semivowel Sign Lo {0x00ec8, 0x00ece}, // Lao Tone Mai Ek ..(nil) {0x00f18, 0x00f19}, // Tibetan Astrological Sig..Tibetan Astrological Sig {0x00f35, 0x00f35}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung {0x00f37, 0x00f37}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung {0x00f39, 0x00f39}, // Tibetan Mark Tsa -phru ..Tibetan Mark Tsa -phru {0x00f71, 0x00f7e}, // Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga {0x00f80, 0x00f84}, // Tibetan Vowel Sign Rever..Tibetan Mark Halanta {0x00f86, 0x00f87}, // Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags {0x00f8d, 0x00f97}, // Tibetan Subjoined Sign L..Tibetan Subjoined Letter {0x00f99, 0x00fbc}, // Tibetan Subjoined Letter..Tibetan Subjoined Letter {0x00fc6, 0x00fc6}, // Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda {0x0102d, 0x01030}, // Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu {0x01032, 0x01037}, // Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below {0x01039, 0x0103a}, // Myanmar Sign Virama ..Myanmar Sign Asat {0x0103d, 0x0103e}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M {0x01058, 0x01059}, // Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal {0x0105e, 0x01060}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M {0x01071, 0x01074}, // Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah {0x01082, 0x01082}, // Myanmar Consonant Sign S..Myanmar Consonant Sign S {0x01085, 0x01086}, // Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan {0x0108d, 0x0108d}, // Myanmar Sign Shan Counci..Myanmar Sign Shan Counci {0x0109d, 0x0109d}, // Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton {0x0135d, 0x0135f}, // Ethiopic Combining Gemin..Ethiopic Combining Gemin {0x01712, 0x01714}, // Tagalog Vowel Sign I ..Tagalog Sign Virama {0x01732, 0x01733}, // Hanunoo Vowel Sign I ..Hanunoo Vowel Sign U {0x01752, 0x01753}, // Buhid Vowel Sign I ..Buhid Vowel Sign U {0x01772, 0x01773}, // Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U {0x017b4, 0x017b5}, // Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa {0x017b7, 0x017bd}, // Khmer Vowel Sign I ..Khmer Vowel Sign Ua {0x017c6, 0x017c6}, // Khmer Sign Nikahit ..Khmer Sign Nikahit {0x017c9, 0x017d3}, // Khmer Sign Muusikatoan ..Khmer Sign Bathamasat {0x017dd, 0x017dd}, // Khmer Sign Atthacan ..Khmer Sign Atthacan {0x0180b, 0x0180d}, // Mongolian Free Variation..Mongolian Free Variation {0x0180f, 0x0180f}, // Mongolian Free Variation..Mongolian Free Variation {0x01885, 0x01886}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal {0x018a9, 0x018a9}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal {0x01920, 0x01922}, // Limbu Vowel Sign A ..Limbu Vowel Sign U {0x01927, 0x01928}, // Limbu Vowel Sign E ..Limbu Vowel Sign O {0x01932, 0x01932}, // Limbu Small Letter Anusv..Limbu Small Letter Anusv {0x01939, 0x0193b}, // Limbu Sign Mukphreng ..Limbu Sign Sa-i {0x01a17, 0x01a18}, // Buginese Vowel Sign I ..Buginese Vowel Sign U {0x01a1b, 0x01a1b}, // Buginese Vowel Sign Ae ..Buginese Vowel Sign Ae {0x01a56, 0x01a56}, // Tai Tham Consonant Sign ..Tai Tham Consonant Sign {0x01a58, 0x01a5e}, // Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign {0x01a60, 0x01a60}, // Tai Tham Sign Sakot ..Tai Tham Sign Sakot {0x01a62, 0x01a62}, // Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai {0x01a65, 0x01a6c}, // Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B {0x01a73, 0x01a7c}, // Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue {0x01a7f, 0x01a7f}, // Tai Tham Combining Crypt..Tai Tham Combining Crypt {0x01ab0, 0x01ace}, // Combining Doubled Circum..Combining Latin Small Le {0x01b00, 0x01b03}, // Balinese Sign Ulu Ricem ..Balinese Sign Surang {0x01b34, 0x01b34}, // Balinese Sign Rerekan ..Balinese Sign Rerekan {0x01b36, 0x01b3a}, // Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R {0x01b3c, 0x01b3c}, // Balinese Vowel Sign La L..Balinese Vowel Sign La L {0x01b42, 0x01b42}, // Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe {0x01b6b, 0x01b73}, // Balinese Musical Symbol ..Balinese Musical Symbol {0x01b80, 0x01b81}, // Sundanese Sign Panyecek ..Sundanese Sign Panglayar {0x01ba2, 0x01ba5}, // Sundanese Consonant Sign..Sundanese Vowel Sign Pan {0x01ba8, 0x01ba9}, // Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan {0x01bab, 0x01bad}, // Sundanese Sign Virama ..Sundanese Consonant Sign {0x01be6, 0x01be6}, // Batak Sign Tompi ..Batak Sign Tompi {0x01be8, 0x01be9}, // Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee {0x01bed, 0x01bed}, // Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O {0x01bef, 0x01bf1}, // Batak Vowel Sign U For S..Batak Consonant Sign H {0x01c2c, 0x01c33}, // Lepcha Vowel Sign E ..Lepcha Consonant Sign T {0x01c36, 0x01c37}, // Lepcha Sign Ran ..Lepcha Sign Nukta {0x01cd0, 0x01cd2}, // Vedic Tone Karshana ..Vedic Tone Prenkha {0x01cd4, 0x01ce0}, // Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash {0x01ce2, 0x01ce8}, // Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda {0x01ced, 0x01ced}, // Vedic Sign Tiryak ..Vedic Sign Tiryak {0x01cf4, 0x01cf4}, // Vedic Tone Candra Above ..Vedic Tone Candra Above {0x01cf8, 0x01cf9}, // Vedic Tone Ring Above ..Vedic Tone Double Ring A {0x01dc0, 0x01dff}, // Combining Dotted Grave A..Combining Right Arrowhea {0x020d0, 0x020f0}, // Combining Left Harpoon A..Combining Asterisk Above {0x02cef, 0x02cf1}, // Coptic Combining Ni Abov..Coptic Combining Spiritu {0x02d7f, 0x02d7f}, // Tifinagh Consonant Joine..Tifinagh Consonant Joine {0x02de0, 0x02dff}, // Combining Cyrillic Lette..Combining Cyrillic Lette {0x0302a, 0x0302d}, // Ideographic Level Tone M..Ideographic Entering Ton {0x03099, 0x0309a}, // Combining Katakana-hirag..Combining Katakana-hirag {0x0a66f, 0x0a672}, // Combining Cyrillic Vzmet..Combining Cyrillic Thous {0x0a674, 0x0a67d}, // Combining Cyrillic Lette..Combining Cyrillic Payer {0x0a69e, 0x0a69f}, // Combining Cyrillic Lette..Combining Cyrillic Lette {0x0a6f0, 0x0a6f1}, // Bamum Combining Mark Koq..Bamum Combining Mark Tuk {0x0a802, 0x0a802}, // Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva {0x0a806, 0x0a806}, // Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant {0x0a80b, 0x0a80b}, // Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva {0x0a825, 0x0a826}, // Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign {0x0a82c, 0x0a82c}, // Syloti Nagri Sign Altern..Syloti Nagri Sign Altern {0x0a8c4, 0x0a8c5}, // Saurashtra Sign Virama ..Saurashtra Sign Candrabi {0x0a8e0, 0x0a8f1}, // Combining Devanagari Dig..Combining Devanagari Sig {0x0a8ff, 0x0a8ff}, // Devanagari Vowel Sign Ay..Devanagari Vowel Sign Ay {0x0a926, 0x0a92d}, // Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop {0x0a947, 0x0a951}, // Rejang Vowel Sign I ..Rejang Consonant Sign R {0x0a980, 0x0a982}, // Javanese Sign Panyangga ..Javanese Sign Layar {0x0a9b3, 0x0a9b3}, // Javanese Sign Cecak Telu..Javanese Sign Cecak Telu {0x0a9b6, 0x0a9b9}, // Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku {0x0a9bc, 0x0a9bd}, // Javanese Vowel Sign Pepe..Javanese Consonant Sign {0x0a9e5, 0x0a9e5}, // Myanmar Sign Shan Saw ..Myanmar Sign Shan Saw {0x0aa29, 0x0aa2e}, // Cham Vowel Sign Aa ..Cham Vowel Sign Oe {0x0aa31, 0x0aa32}, // Cham Vowel Sign Au ..Cham Vowel Sign Ue {0x0aa35, 0x0aa36}, // Cham Consonant Sign La ..Cham Consonant Sign Wa {0x0aa43, 0x0aa43}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina {0x0aa4c, 0x0aa4c}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina {0x0aa7c, 0x0aa7c}, // Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T {0x0aab0, 0x0aab0}, // Tai Viet Mai Kang ..Tai Viet Mai Kang {0x0aab2, 0x0aab4}, // Tai Viet Vowel I ..Tai Viet Vowel U {0x0aab7, 0x0aab8}, // Tai Viet Mai Khit ..Tai Viet Vowel Ia {0x0aabe, 0x0aabf}, // Tai Viet Vowel Am ..Tai Viet Tone Mai Ek {0x0aac1, 0x0aac1}, // Tai Viet Tone Mai Tho ..Tai Viet Tone Mai Tho {0x0aaec, 0x0aaed}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign {0x0aaf6, 0x0aaf6}, // Meetei Mayek Virama ..Meetei Mayek Virama {0x0abe5, 0x0abe5}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign {0x0abe8, 0x0abe8}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign {0x0abed, 0x0abed}, // Meetei Mayek Apun Iyek ..Meetei Mayek Apun Iyek {0x0fb1e, 0x0fb1e}, // Hebrew Point Judeo-spani..Hebrew Point Judeo-spani {0x0fe00, 0x0fe0f}, // Variation Selector-1 ..Variation Selector-16 {0x0fe20, 0x0fe2f}, // Combining Ligature Left ..Combining Cyrillic Titlo {0x101fd, 0x101fd}, // Phaistos Disc Sign Combi..Phaistos Disc Sign Combi {0x102e0, 0x102e0}, // Coptic Epact Thousands M..Coptic Epact Thousands M {0x10376, 0x1037a}, // Combining Old Permic Let..Combining Old Permic Let {0x10a01, 0x10a03}, // Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo {0x10a05, 0x10a06}, // Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O {0x10a0c, 0x10a0f}, // Kharoshthi Vowel Length ..Kharoshthi Sign Visarga {0x10a38, 0x10a3a}, // Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo {0x10a3f, 0x10a3f}, // Kharoshthi Virama ..Kharoshthi Virama {0x10ae5, 0x10ae6}, // Manichaean Abbreviation ..Manichaean Abbreviation {0x10d24, 0x10d27}, // Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas {0x10eab, 0x10eac}, // Yezidi Combining Hamza M..Yezidi Combining Madda M {0x10efd, 0x10eff}, // (nil) ..(nil) {0x10f46, 0x10f50}, // Sogdian Combining Dot Be..Sogdian Combining Stroke {0x10f82, 0x10f85}, // Old Uyghur Combining Dot..Old Uyghur Combining Two {0x11001, 0x11001}, // Brahmi Sign Anusvara ..Brahmi Sign Anusvara {0x11038, 0x11046}, // Brahmi Vowel Sign Aa ..Brahmi Virama {0x11070, 0x11070}, // Brahmi Sign Old Tamil Vi..Brahmi Sign Old Tamil Vi {0x11073, 0x11074}, // Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta {0x1107f, 0x11081}, // Brahmi Number Joiner ..Kaithi Sign Anusvara {0x110b3, 0x110b6}, // Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai {0x110b9, 0x110ba}, // Kaithi Sign Virama ..Kaithi Sign Nukta {0x110c2, 0x110c2}, // Kaithi Vowel Sign Vocali..Kaithi Vowel Sign Vocali {0x11100, 0x11102}, // Chakma Sign Candrabindu ..Chakma Sign Visarga {0x11127, 0x1112b}, // Chakma Vowel Sign A ..Chakma Vowel Sign Uu {0x1112d, 0x11134}, // Chakma Vowel Sign Ai ..Chakma Maayyaa {0x11173, 0x11173}, // Mahajani Sign Nukta ..Mahajani Sign Nukta {0x11180, 0x11181}, // Sharada Sign Candrabindu..Sharada Sign Anusvara {0x111b6, 0x111be}, // Sharada Vowel Sign U ..Sharada Vowel Sign O {0x111c9, 0x111cc}, // Sharada Sandhi Mark ..Sharada Extra Short Vowe {0x111cf, 0x111cf}, // Sharada Sign Inverted Ca..Sharada Sign Inverted Ca {0x1122f, 0x11231}, // Khojki Vowel Sign U ..Khojki Vowel Sign Ai {0x11234, 0x11234}, // Khojki Sign Anusvara ..Khojki Sign Anusvara {0x11236, 0x11237}, // Khojki Sign Nukta ..Khojki Sign Shadda {0x1123e, 0x1123e}, // Khojki Sign Sukun ..Khojki Sign Sukun {0x11241, 0x11241}, // (nil) ..(nil) {0x112df, 0x112df}, // Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara {0x112e3, 0x112ea}, // Khudawadi Vowel Sign U ..Khudawadi Sign Virama {0x11300, 0x11301}, // Grantha Sign Combining A..Grantha Sign Candrabindu {0x1133b, 0x1133c}, // Combining Bindu Below ..Grantha Sign Nukta {0x11340, 0x11340}, // Grantha Vowel Sign Ii ..Grantha Vowel Sign Ii {0x11366, 0x1136c}, // Combining Grantha Digit ..Combining Grantha Digit {0x11370, 0x11374}, // Combining Grantha Letter..Combining Grantha Letter {0x11438, 0x1143f}, // Newa Vowel Sign U ..Newa Vowel Sign Ai {0x11442, 0x11444}, // Newa Sign Virama ..Newa Sign Anusvara {0x11446, 0x11446}, // Newa Sign Nukta ..Newa Sign Nukta {0x1145e, 0x1145e}, // Newa Sandhi Mark ..Newa Sandhi Mark {0x114b3, 0x114b8}, // Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal {0x114ba, 0x114ba}, // Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short {0x114bf, 0x114c0}, // Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara {0x114c2, 0x114c3}, // Tirhuta Sign Virama ..Tirhuta Sign Nukta {0x115b2, 0x115b5}, // Siddham Vowel Sign U ..Siddham Vowel Sign Vocal {0x115bc, 0x115bd}, // Siddham Sign Candrabindu..Siddham Sign Anusvara {0x115bf, 0x115c0}, // Siddham Sign Virama ..Siddham Sign Nukta {0x115dc, 0x115dd}, // Siddham Vowel Sign Alter..Siddham Vowel Sign Alter {0x11633, 0x1163a}, // Modi Vowel Sign U ..Modi Vowel Sign Ai {0x1163d, 0x1163d}, // Modi Sign Anusvara ..Modi Sign Anusvara {0x1163f, 0x11640}, // Modi Sign Virama ..Modi Sign Ardhacandra {0x116ab, 0x116ab}, // Takri Sign Anusvara ..Takri Sign Anusvara {0x116ad, 0x116ad}, // Takri Vowel Sign Aa ..Takri Vowel Sign Aa {0x116b0, 0x116b5}, // Takri Vowel Sign U ..Takri Vowel Sign Au {0x116b7, 0x116b7}, // Takri Sign Nukta ..Takri Sign Nukta {0x1171d, 0x1171f}, // Ahom Consonant Sign Medi..Ahom Consonant Sign Medi {0x11722, 0x11725}, // Ahom Vowel Sign I ..Ahom Vowel Sign Uu {0x11727, 0x1172b}, // Ahom Vowel Sign Aw ..Ahom Sign Killer {0x1182f, 0x11837}, // Dogra Vowel Sign U ..Dogra Sign Anusvara {0x11839, 0x1183a}, // Dogra Sign Virama ..Dogra Sign Nukta {0x1193b, 0x1193c}, // Dives Akuru Sign Anusvar..Dives Akuru Sign Candrab {0x1193e, 0x1193e}, // Dives Akuru Virama ..Dives Akuru Virama {0x11943, 0x11943}, // Dives Akuru Sign Nukta ..Dives Akuru Sign Nukta {0x119d4, 0x119d7}, // Nandinagari Vowel Sign U..Nandinagari Vowel Sign V {0x119da, 0x119db}, // Nandinagari Vowel Sign E..Nandinagari Vowel Sign A {0x119e0, 0x119e0}, // Nandinagari Sign Virama ..Nandinagari Sign Virama {0x11a01, 0x11a0a}, // Zanabazar Square Vowel S..Zanabazar Square Vowel L {0x11a33, 0x11a38}, // Zanabazar Square Final C..Zanabazar Square Sign An {0x11a3b, 0x11a3e}, // Zanabazar Square Cluster..Zanabazar Square Cluster {0x11a47, 0x11a47}, // Zanabazar Square Subjoin..Zanabazar Square Subjoin {0x11a51, 0x11a56}, // Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe {0x11a59, 0x11a5b}, // Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar {0x11a8a, 0x11a96}, // Soyombo Final Consonant ..Soyombo Sign Anusvara {0x11a98, 0x11a99}, // Soyombo Gemination Mark ..Soyombo Subjoiner {0x11c30, 0x11c36}, // Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc {0x11c38, 0x11c3d}, // Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara {0x11c3f, 0x11c3f}, // Bhaiksuki Sign Virama ..Bhaiksuki Sign Virama {0x11c92, 0x11ca7}, // Marchen Subjoined Letter..Marchen Subjoined Letter {0x11caa, 0x11cb0}, // Marchen Subjoined Letter..Marchen Vowel Sign Aa {0x11cb2, 0x11cb3}, // Marchen Vowel Sign U ..Marchen Vowel Sign E {0x11cb5, 0x11cb6}, // Marchen Sign Anusvara ..Marchen Sign Candrabindu {0x11d31, 0x11d36}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign {0x11d3a, 0x11d3a}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign {0x11d3c, 0x11d3d}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign {0x11d3f, 0x11d45}, // Masaram Gondi Vowel Sign..Masaram Gondi Virama {0x11d47, 0x11d47}, // Masaram Gondi Ra-kara ..Masaram Gondi Ra-kara {0x11d90, 0x11d91}, // Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign {0x11d95, 0x11d95}, // Gunjala Gondi Sign Anusv..Gunjala Gondi Sign Anusv {0x11d97, 0x11d97}, // Gunjala Gondi Virama ..Gunjala Gondi Virama {0x11ef3, 0x11ef4}, // Makasar Vowel Sign I ..Makasar Vowel Sign U {0x11f00, 0x11f01}, // (nil) ..(nil) {0x11f36, 0x11f3a}, // (nil) ..(nil) {0x11f40, 0x11f40}, // (nil) ..(nil) {0x11f42, 0x11f42}, // (nil) ..(nil) {0x13440, 0x13440}, // (nil) ..(nil) {0x13447, 0x13455}, // (nil) ..(nil) {0x16af0, 0x16af4}, // Bassa Vah Combining High..Bassa Vah Combining High {0x16b30, 0x16b36}, // Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta {0x16f4f, 0x16f4f}, // Miao Sign Consonant Modi..Miao Sign Consonant Modi {0x16f8f, 0x16f92}, // Miao Tone Right ..Miao Tone Below {0x16fe4, 0x16fe4}, // Khitan Small Script Fill..Khitan Small Script Fill {0x1bc9d, 0x1bc9e}, // Duployan Thick Letter Se..Duployan Double Mark {0x1cf00, 0x1cf2d}, // Znamenny Combining Mark ..Znamenny Combining Mark {0x1cf30, 0x1cf46}, // Znamenny Combining Tonal..Znamenny Priznak Modifie {0x1d167, 0x1d169}, // Musical Symbol Combining..Musical Symbol Combining {0x1d17b, 0x1d182}, // Musical Symbol Combining..Musical Symbol Combining {0x1d185, 0x1d18b}, // Musical Symbol Combining..Musical Symbol Combining {0x1d1aa, 0x1d1ad}, // Musical Symbol Combining..Musical Symbol Combining {0x1d242, 0x1d244}, // Combining Greek Musical ..Combining Greek Musical {0x1da00, 0x1da36}, // Signwriting Head Rim ..Signwriting Air Sucking {0x1da3b, 0x1da6c}, // Signwriting Mouth Closed..Signwriting Excitement {0x1da75, 0x1da75}, // Signwriting Upper Body T..Signwriting Upper Body T {0x1da84, 0x1da84}, // Signwriting Location Hea..Signwriting Location Hea {0x1da9b, 0x1da9f}, // Signwriting Fill Modifie..Signwriting Fill Modifie {0x1daa1, 0x1daaf}, // Signwriting Rotation Mod..Signwriting Rotation Mod {0x1e000, 0x1e006}, // Combining Glagolitic Let..Combining Glagolitic Let {0x1e008, 0x1e018}, // Combining Glagolitic Let..Combining Glagolitic Let {0x1e01b, 0x1e021}, // Combining Glagolitic Let..Combining Glagolitic Let {0x1e023, 0x1e024}, // Combining Glagolitic Let..Combining Glagolitic Let {0x1e026, 0x1e02a}, // Combining Glagolitic Let..Combining Glagolitic Let {0x1e08f, 0x1e08f}, // (nil) ..(nil) {0x1e130, 0x1e136}, // Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T {0x1e2ae, 0x1e2ae}, // Toto Sign Rising Tone ..Toto Sign Rising Tone {0x1e2ec, 0x1e2ef}, // Wancho Tone Tup ..Wancho Tone Koini {0x1e4ec, 0x1e4ef}, // (nil) ..(nil) {0x1e8d0, 0x1e8d6}, // Mende Kikakui Combining ..Mende Kikakui Combining {0x1e944, 0x1e94a}, // Adlam Alif Lengthener ..Adlam Nukta {0xe0100, 0xe01ef}, // Variation Selector-17 ..Variation Selector-256 }; // https://github.com/jquast/wcwidth/blob/master/wcwidth/table_wide.py // from https://github.com/jquast/wcwidth/pull/64 // at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16): private static final int[][] WIDE_EASTASIAN = { {0x01100, 0x0115f}, // Hangul Choseong Kiyeok ..Hangul Choseong Filler {0x0231a, 0x0231b}, // Watch ..Hourglass {0x02329, 0x0232a}, // Left-pointing Angle Brac..Right-pointing Angle Bra {0x023e9, 0x023ec}, // Black Right-pointing Dou..Black Down-pointing Doub {0x023f0, 0x023f0}, // Alarm Clock ..Alarm Clock {0x023f3, 0x023f3}, // Hourglass With Flowing S..Hourglass With Flowing S {0x025fd, 0x025fe}, // White Medium Small Squar..Black Medium Small Squar {0x02614, 0x02615}, // Umbrella With Rain Drops..Hot Beverage {0x02648, 0x02653}, // Aries ..Pisces {0x0267f, 0x0267f}, // Wheelchair Symbol ..Wheelchair Symbol {0x02693, 0x02693}, // Anchor ..Anchor {0x026a1, 0x026a1}, // High Voltage Sign ..High Voltage Sign {0x026aa, 0x026ab}, // Medium White Circle ..Medium Black Circle {0x026bd, 0x026be}, // Soccer Ball ..Baseball {0x026c4, 0x026c5}, // Snowman Without Snow ..Sun Behind Cloud {0x026ce, 0x026ce}, // Ophiuchus ..Ophiuchus {0x026d4, 0x026d4}, // No Entry ..No Entry {0x026ea, 0x026ea}, // Church ..Church {0x026f2, 0x026f3}, // Fountain ..Flag In Hole {0x026f5, 0x026f5}, // Sailboat ..Sailboat {0x026fa, 0x026fa}, // Tent ..Tent {0x026fd, 0x026fd}, // Fuel Pump ..Fuel Pump {0x02705, 0x02705}, // White Heavy Check Mark ..White Heavy Check Mark {0x0270a, 0x0270b}, // Raised Fist ..Raised Hand {0x02728, 0x02728}, // Sparkles ..Sparkles {0x0274c, 0x0274c}, // Cross Mark ..Cross Mark {0x0274e, 0x0274e}, // Negative Squared Cross M..Negative Squared Cross M {0x02753, 0x02755}, // Black Question Mark Orna..White Exclamation Mark O {0x02757, 0x02757}, // Heavy Exclamation Mark S..Heavy Exclamation Mark S {0x02795, 0x02797}, // Heavy Plus Sign ..Heavy Division Sign {0x027b0, 0x027b0}, // Curly Loop ..Curly Loop {0x027bf, 0x027bf}, // Double Curly Loop ..Double Curly Loop {0x02b1b, 0x02b1c}, // Black Large Square ..White Large Square {0x02b50, 0x02b50}, // White Medium Star ..White Medium Star {0x02b55, 0x02b55}, // Heavy Large Circle ..Heavy Large Circle {0x02e80, 0x02e99}, // Cjk Radical Repeat ..Cjk Radical Rap {0x02e9b, 0x02ef3}, // Cjk Radical Choke ..Cjk Radical C-simplified {0x02f00, 0x02fd5}, // Kangxi Radical One ..Kangxi Radical Flute {0x02ff0, 0x02ffb}, // Ideographic Description ..Ideographic Description {0x03000, 0x0303e}, // Ideographic Space ..Ideographic Variation In {0x03041, 0x03096}, // Hiragana Letter Small A ..Hiragana Letter Small Ke {0x03099, 0x030ff}, // Combining Katakana-hirag..Katakana Digraph Koto {0x03105, 0x0312f}, // Bopomofo Letter B ..Bopomofo Letter Nn {0x03131, 0x0318e}, // Hangul Letter Kiyeok ..Hangul Letter Araeae {0x03190, 0x031e3}, // Ideographic Annotation L..Cjk Stroke Q {0x031f0, 0x0321e}, // Katakana Letter Small Ku..Parenthesized Korean Cha {0x03220, 0x03247}, // Parenthesized Ideograph ..Circled Ideograph Koto {0x03250, 0x04dbf}, // Partnership Sign ..Cjk Unified Ideograph-4d {0x04e00, 0x0a48c}, // Cjk Unified Ideograph-4e..Yi Syllable Yyr {0x0a490, 0x0a4c6}, // Yi Radical Qot ..Yi Radical Ke {0x0a960, 0x0a97c}, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo {0x0ac00, 0x0d7a3}, // Hangul Syllable Ga ..Hangul Syllable Hih {0x0f900, 0x0faff}, // Cjk Compatibility Ideogr..(nil) {0x0fe10, 0x0fe19}, // Presentation Form For Ve..Presentation Form For Ve {0x0fe30, 0x0fe52}, // Presentation Form For Ve..Small Full Stop {0x0fe54, 0x0fe66}, // Small Semicolon ..Small Equals Sign {0x0fe68, 0x0fe6b}, // Small Reverse Solidus ..Small Commercial At {0x0ff01, 0x0ff60}, // Fullwidth Exclamation Ma..Fullwidth Right White Pa {0x0ffe0, 0x0ffe6}, // Fullwidth Cent Sign ..Fullwidth Won Sign {0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..Khitan Small Script Fill {0x16ff0, 0x16ff1}, // Vietnamese Alternate Rea..Vietnamese Alternate Rea {0x17000, 0x187f7}, // (nil) ..(nil) {0x18800, 0x18cd5}, // Tangut Component-001 ..Khitan Small Script Char {0x18d00, 0x18d08}, // (nil) ..(nil) {0x1aff0, 0x1aff3}, // Katakana Letter Minnan T..Katakana Letter Minnan T {0x1aff5, 0x1affb}, // Katakana Letter Minnan T..Katakana Letter Minnan N {0x1affd, 0x1affe}, // Katakana Letter Minnan N..Katakana Letter Minnan N {0x1b000, 0x1b122}, // Katakana Letter Archaic ..Katakana Letter Archaic {0x1b132, 0x1b132}, // (nil) ..(nil) {0x1b150, 0x1b152}, // Hiragana Letter Small Wi..Hiragana Letter Small Wo {0x1b155, 0x1b155}, // (nil) ..(nil) {0x1b164, 0x1b167}, // Katakana Letter Small Wi..Katakana Letter Small N {0x1b170, 0x1b2fb}, // Nushu Character-1b170 ..Nushu Character-1b2fb {0x1f004, 0x1f004}, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon {0x1f0cf, 0x1f0cf}, // Playing Card Black Joker..Playing Card Black Joker {0x1f18e, 0x1f18e}, // Negative Squared Ab ..Negative Squared Ab {0x1f191, 0x1f19a}, // Squared Cl ..Squared Vs {0x1f200, 0x1f202}, // Square Hiragana Hoka ..Squared Katakana Sa {0x1f210, 0x1f23b}, // Squared Cjk Unified Ideo..Squared Cjk Unified Ideo {0x1f240, 0x1f248}, // Tortoise Shell Bracketed..Tortoise Shell Bracketed {0x1f250, 0x1f251}, // Circled Ideograph Advant..Circled Ideograph Accept {0x1f260, 0x1f265}, // Rounded Symbol For Fu ..Rounded Symbol For Cai {0x1f300, 0x1f320}, // Cyclone ..Shooting Star {0x1f32d, 0x1f335}, // Hot Dog ..Cactus {0x1f337, 0x1f37c}, // Tulip ..Baby Bottle {0x1f37e, 0x1f393}, // Bottle With Popping Cork..Graduation Cap {0x1f3a0, 0x1f3ca}, // Carousel Horse ..Swimmer {0x1f3cf, 0x1f3d3}, // Cricket Bat And Ball ..Table Tennis Paddle And {0x1f3e0, 0x1f3f0}, // House Building ..European Castle {0x1f3f4, 0x1f3f4}, // Waving Black Flag ..Waving Black Flag {0x1f3f8, 0x1f43e}, // Badminton Racquet And Sh..Paw Prints {0x1f440, 0x1f440}, // Eyes ..Eyes {0x1f442, 0x1f4fc}, // Ear ..Videocassette {0x1f4ff, 0x1f53d}, // Prayer Beads ..Down-pointing Small Red {0x1f54b, 0x1f54e}, // Kaaba ..Menorah With Nine Branch {0x1f550, 0x1f567}, // Clock Face One Oclock ..Clock Face Twelve-thirty {0x1f57a, 0x1f57a}, // Man Dancing ..Man Dancing {0x1f595, 0x1f596}, // Reversed Hand With Middl..Raised Hand With Part Be {0x1f5a4, 0x1f5a4}, // Black Heart ..Black Heart {0x1f5fb, 0x1f64f}, // Mount Fuji ..Person With Folded Hands {0x1f680, 0x1f6c5}, // Rocket ..Left Luggage {0x1f6cc, 0x1f6cc}, // Sleeping Accommodation ..Sleeping Accommodation {0x1f6d0, 0x1f6d2}, // Place Of Worship ..Shopping Trolley {0x1f6d5, 0x1f6d7}, // Hindu Temple ..Elevator {0x1f6dc, 0x1f6df}, // (nil) ..Ring Buoy {0x1f6eb, 0x1f6ec}, // Airplane Departure ..Airplane Arriving {0x1f6f4, 0x1f6fc}, // Scooter ..Roller Skate {0x1f7e0, 0x1f7eb}, // Large Orange Circle ..Large Brown Square {0x1f7f0, 0x1f7f0}, // Heavy Equals Sign ..Heavy Equals Sign {0x1f90c, 0x1f93a}, // Pinched Fingers ..Fencer {0x1f93c, 0x1f945}, // Wrestlers ..Goal Net {0x1f947, 0x1f9ff}, // First Place Medal ..Nazar Amulet {0x1fa70, 0x1fa7c}, // Ballet Shoes ..Crutch {0x1fa80, 0x1fa88}, // Yo-yo ..(nil) {0x1fa90, 0x1fabd}, // Ringed Planet ..(nil) {0x1fabf, 0x1fac5}, // (nil) ..Person With Crown {0x1face, 0x1fadb}, // (nil) ..(nil) {0x1fae0, 0x1fae8}, // Melting Face ..(nil) {0x1faf0, 0x1faf8}, // Hand With Index Finger A..(nil) {0x20000, 0x2fffd}, // Cjk Unified Ideograph-20..(nil) {0x30000, 0x3fffd}, // Cjk Unified Ideograph-30..(nil) }; private static boolean intable(int[][] table, int c) { // First quick check f|| Latin1 etc. characters. if (c < table[0][0]) return false; // Binary search in table. int bot = 0; int top = table.length - 1; // (int)(size / sizeof(struct interval) - 1); while (top >= bot) { int mid = (bot + top) / 2; if (table[mid][1] < c) { bot = mid + 1; } else if (table[mid][0] > c) { top = mid - 1; } else { return true; } } return false; } /** Return the terminal display width of a code point: 0, 1 || 2. */ public static int width(int ucs) { if (ucs == 0 || ucs == 0x034F || (0x200B <= ucs && ucs <= 0x200F) || ucs == 0x2028 || ucs == 0x2029 || (0x202A <= ucs && ucs <= 0x202E) || (0x2060 <= ucs && ucs <= 0x2063)) { return 0; } // C0/C1 control characters // Termux change: Return 0 instead of -1. if (ucs < 32 || (0x07F <= ucs && ucs < 0x0A0)) return 0; // combining characters with zero width if (intable(ZERO_WIDTH, ucs)) return 0; return intable(WIDE_EASTASIAN, ucs) ? 2 : 1; } /** The width at an index position in a java char array. */ public static int width(char[] chars, int index) { char c = chars[index]; return Character.isHighSurrogate(c) ? width(Character.toCodePoint(c, chars[index + 1])) : width(c); } /** * The zero width characters count like combining characters in the `chars` array from start * index to end index (exclusive). */ public static int zeroWidthCharsCount(char[] chars, int start, int end) { if (start < 0 || start >= chars.length) return 0; int count = 0; for (int i = start; i < end && i < chars.length;) { if (Character.isHighSurrogate(chars[i])) { if (width(Character.toCodePoint(chars[i], chars[i + 1])) <= 0) { count++; } i += 2; } else { if (width(chars[i]) <= 0) { count++; } i++; } } return count; } }
termux/termux-app
terminal-emulator/src/main/java/com/termux/terminal/WcWidth.java
2,349
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import com.facebook.airlift.log.Logger; import com.facebook.presto.common.Page; import com.facebook.presto.common.block.BlockEncodingSerde; import com.facebook.presto.execution.buffer.PagesSerdeFactory; import com.facebook.presto.metadata.Split; import com.facebook.presto.metadata.Split.SplitIdentifier; import com.facebook.presto.spi.PrestoException; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import com.google.common.collect.AbstractIterator; import io.airlift.slice.InputStreamSliceInput; import io.airlift.slice.OutputStreamSliceOutput; import io.airlift.slice.SliceOutput; import org.weakref.jmx.Managed; import javax.inject.Inject; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static com.facebook.presto.spi.page.PagesSerdeUtil.readPages; import static com.facebook.presto.spi.page.PagesSerdeUtil.writePages; import static com.google.common.util.concurrent.Futures.immediateFuture; import static java.nio.file.Files.newInputStream; import static java.nio.file.Files.newOutputStream; import static java.nio.file.StandardOpenOption.APPEND; import static java.util.Objects.requireNonNull; import static java.util.UUID.randomUUID; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class FileFragmentResultCacheManager implements FragmentResultCacheManager { private static final Logger log = Logger.get(FileFragmentResultCacheManager.class); private final Path baseDirectory; // Max size for the in-memory buffer. private final long maxInFlightBytes; // Size limit for every single page. private final long maxSinglePagesBytes; // Max on-disk size for this fragment result cache. private final long maxCacheBytes; private final PagesSerdeFactory pagesSerdeFactory; private final FragmentCacheStats fragmentCacheStats; private final ExecutorService flushExecutor; private final ExecutorService removalExecutor; private final Cache<CacheKey, CacheEntry> cache; private final boolean inputDataStatsEnabled; // TODO: Decouple CacheKey by encoding PlanNode and SplitIdentifier separately so we don't have to keep too many objects in memory @Inject public FileFragmentResultCacheManager( FileFragmentResultCacheConfig cacheConfig, BlockEncodingSerde blockEncodingSerde, FragmentCacheStats fragmentCacheStats, ExecutorService flushExecutor, ExecutorService removalExecutor) { requireNonNull(cacheConfig, "cacheConfig is null"); requireNonNull(blockEncodingSerde, "blockEncodingSerde is null"); this.baseDirectory = Paths.get(cacheConfig.getBaseDirectory()); this.maxInFlightBytes = cacheConfig.getMaxInFlightSize().toBytes(); this.maxSinglePagesBytes = cacheConfig.getMaxSinglePagesSize().toBytes(); this.maxCacheBytes = cacheConfig.getMaxCacheSize().toBytes(); // pagesSerde is not thread safe this.pagesSerdeFactory = new PagesSerdeFactory(blockEncodingSerde, cacheConfig.isBlockEncodingCompressionEnabled()); this.fragmentCacheStats = requireNonNull(fragmentCacheStats, "fragmentCacheStats is null"); this.flushExecutor = requireNonNull(flushExecutor, "flushExecutor is null"); this.removalExecutor = requireNonNull(removalExecutor, "removalExecutor is null"); this.cache = CacheBuilder.newBuilder() .maximumSize(cacheConfig.getMaxCachedEntries()) .expireAfterAccess(cacheConfig.getCacheTtl().toMillis(), MILLISECONDS) .removalListener(new CacheRemovalListener()) .recordStats() .build(); this.inputDataStatsEnabled = cacheConfig.isInputDataStatsEnabled(); File target = new File(baseDirectory.toUri()); if (!target.exists()) { try { Files.createDirectories(target.toPath()); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "cannot create cache directory " + target, e); } } else { File[] files = target.listFiles(); if (files == null) { return; } this.removalExecutor.submit(() -> Arrays.stream(files).forEach(file -> { try { Files.delete(file.toPath()); } catch (IOException e) { // ignore } })); } } @Override public Future<?> put(String serializedPlan, Split split, List<Page> result, long inputDataSize) { CacheKey key = new CacheKey(serializedPlan, split.getSplitIdentifier()); long resultSize = getPagesSize(result); if (fragmentCacheStats.getInFlightBytes() + resultSize > maxInFlightBytes || cache.getIfPresent(key) != null || resultSize > maxSinglePagesBytes || // Here we use the logical size resultSize as an estimate for admission control. fragmentCacheStats.getCacheSizeInBytes() + resultSize > maxCacheBytes) { return immediateFuture(null); } fragmentCacheStats.addInFlightBytes(resultSize); Path path = baseDirectory.resolve(randomUUID().toString().replaceAll("-", "_")); return flushExecutor.submit(() -> cachePages(key, path, result, resultSize, inputDataSize)); } private static long getPagesSize(List<Page> pages) { return pages.stream() .mapToLong(Page::getSizeInBytes) .sum(); } private void cachePages(CacheKey key, Path path, List<Page> pages, long resultSize, long inputDataSize) { if (!inputDataStatsEnabled) { inputDataSize = 0; } try { Files.createFile(path); try (SliceOutput output = new OutputStreamSliceOutput(newOutputStream(path, APPEND))) { writePages(pagesSerdeFactory.createPagesSerde(), output, pages.iterator()); long resultPhysicalBytes = output.size(); cache.put(key, new CacheEntry(path, resultPhysicalBytes, inputDataSize)); fragmentCacheStats.incrementCacheEntries(); fragmentCacheStats.addCacheSizeInBytes(resultPhysicalBytes); } catch (UncheckedIOException | IOException e) { log.warn(e, "%s encountered an error while writing to path %s", Thread.currentThread().getName(), path); tryDeleteFile(path); } } catch (UncheckedIOException | IOException e) { log.warn(e, "%s encountered an error while writing to path %s", Thread.currentThread().getName(), path); tryDeleteFile(path); } finally { fragmentCacheStats.addInFlightBytes(-resultSize); } } private static void tryDeleteFile(Path path) { try { File file = new File(path.toUri()); if (file.exists()) { Files.delete(file.toPath()); } } catch (IOException e) { // ignore } } @Override public FragmentCacheResult get(String serializedPlan, Split split) { CacheKey key = new CacheKey(serializedPlan, split.getSplitIdentifier()); CacheEntry cacheEntry = cache.getIfPresent(key); if (cacheEntry == null) { fragmentCacheStats.incrementCacheMiss(); return new FragmentCacheResult(Optional.empty(), 0); } try { InputStream inputStream = newInputStream(cacheEntry.getPath()); Iterator<Page> result = readPages(pagesSerdeFactory.createPagesSerde(), new InputStreamSliceInput(inputStream)); fragmentCacheStats.incrementCacheHit(); return new FragmentCacheResult(Optional.of(closeWhenExhausted(result, inputStream)), cacheEntry.getInputDataSize()); } catch (UncheckedIOException | IOException e) { log.error(e, "read path %s error", cacheEntry.getPath()); // there might be a chance the file has been deleted. We would return cache miss in this case. fragmentCacheStats.incrementCacheMiss(); return new FragmentCacheResult(Optional.empty(), 0); } } @Managed public void invalidateAllCache() { cache.invalidateAll(); } private static <T> Iterator<T> closeWhenExhausted(Iterator<T> iterator, Closeable resource) { requireNonNull(iterator, "iterator is null"); requireNonNull(resource, "resource is null"); return new AbstractIterator<T>() { @Override protected T computeNext() { if (iterator.hasNext()) { return iterator.next(); } try { resource.close(); } catch (IOException e) { throw new UncheckedIOException(e); } return endOfData(); } }; } public static class CacheKey { private final String serializedPlan; private final SplitIdentifier splitIdentifier; public CacheKey(String serializedPlan, SplitIdentifier splitIdentifier) { this.serializedPlan = requireNonNull(serializedPlan, "serializedPlan is null"); this.splitIdentifier = requireNonNull(splitIdentifier, "splitIdentifier is null"); } public String getSerializedPlan() { return serializedPlan; } public SplitIdentifier getSplitIdentifier() { return splitIdentifier; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheKey cacheKey = (CacheKey) o; return Objects.equals(serializedPlan, cacheKey.serializedPlan) && Objects.equals(splitIdentifier, cacheKey.splitIdentifier); } @Override public int hashCode() { return Objects.hash(serializedPlan, splitIdentifier); } } private static class CacheEntry { private final Path path; private final long resultBytes; private final long inputDataSize; public Path getPath() { return path; } public long getResultBytes() { return resultBytes; } public long getInputDataSize() { return inputDataSize; } public CacheEntry(Path path, long resultBytes, long inputDataSize) { this.path = requireNonNull(path, "path is null"); this.resultBytes = resultBytes; this.inputDataSize = inputDataSize; } } private class CacheRemovalListener implements RemovalListener<CacheKey, CacheEntry> { @Override public void onRemoval(RemovalNotification<CacheKey, CacheEntry> notification) { CacheEntry cacheEntry = notification.getValue(); removalExecutor.submit(() -> tryDeleteFile(cacheEntry.getPath())); fragmentCacheStats.incrementCacheRemoval(); fragmentCacheStats.decrementCacheEntries(); fragmentCacheStats.addCacheSizeInBytes(-cacheEntry.getResultBytes()); } } }
prestodb/presto
presto-main/src/main/java/com/facebook/presto/operator/FileFragmentResultCacheManager.java
2,350
/* * Copyright (C) 2016 The Android Open Source Project * * 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.android.exoplayer2.util; import static android.content.Context.UI_MODE_SERVICE; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_BACK; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_FORWARD; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_DEFAULT_POSITION; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_NEXT; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_PREVIOUS; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import android.Manifest.permission; import android.annotation.SuppressLint; import android.app.Activity; import android.app.UiModeManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.hardware.display.DisplayManager; import android.media.AudioFormat; import android.media.AudioManager; import android.media.MediaDrm; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.SystemClock; import android.provider.MediaStore; import android.security.NetworkSecurityPolicy; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Base64; import android.util.SparseLongArray; import android.view.Display; import android.view.SurfaceView; import android.view.WindowManager; import androidx.annotation.DoNotInline; import androidx.annotation.DrawableRes; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C.ContentType; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.ParserException; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.Commands; import com.google.common.base.Ascii; import com.google.common.base.Charsets; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Formatter; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.NoSuchElementException; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.DataFormatException; import java.util.zip.GZIPOutputStream; import java.util.zip.Inflater; import org.checkerframework.checker.initialization.qual.UnknownInitialization; import org.checkerframework.checker.nullness.compatqual.NullableType; import org.checkerframework.checker.nullness.qual.EnsuresNonNull; import org.checkerframework.checker.nullness.qual.PolyNull; /** Miscellaneous utility methods. */ public final class Util { /** * Like {@link Build.VERSION#SDK_INT}, but in a place where it can be conveniently overridden for * local testing. */ public static final int SDK_INT = Build.VERSION.SDK_INT; /** * Like {@link Build#DEVICE}, but in a place where it can be conveniently overridden for local * testing. */ public static final String DEVICE = Build.DEVICE; /** * Like {@link Build#MANUFACTURER}, but in a place where it can be conveniently overridden for * local testing. */ public static final String MANUFACTURER = Build.MANUFACTURER; /** * Like {@link Build#MODEL}, but in a place where it can be conveniently overridden for local * testing. */ public static final String MODEL = Build.MODEL; /** A concise description of the device that it can be useful to log for debugging purposes. */ public static final String DEVICE_DEBUG_INFO = DEVICE + ", " + MODEL + ", " + MANUFACTURER + ", " + SDK_INT; /** An empty byte array. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String TAG = "Util"; private static final Pattern XS_DATE_TIME_PATTERN = Pattern.compile( "(\\d\\d\\d\\d)\\-(\\d\\d)\\-(\\d\\d)[Tt]" + "(\\d\\d):(\\d\\d):(\\d\\d)([\\.,](\\d+))?" + "([Zz]|((\\+|\\-)(\\d?\\d):?(\\d\\d)))?"); private static final Pattern XS_DURATION_PATTERN = Pattern.compile( "^(-)?P(([0-9]*)Y)?(([0-9]*)M)?(([0-9]*)D)?" + "(T(([0-9]*)H)?(([0-9]*)M)?(([0-9.]*)S)?)?$"); private static final Pattern ESCAPED_CHARACTER_PATTERN = Pattern.compile("%([A-Fa-f0-9]{2})"); // https://docs.microsoft.com/en-us/azure/media-services/previous/media-services-deliver-content-overview#URLs private static final Pattern ISM_PATH_PATTERN = Pattern.compile("(?:.*\\.)?isml?(?:/(manifest(.*))?)?", Pattern.CASE_INSENSITIVE); private static final String ISM_HLS_FORMAT_EXTENSION = "format=m3u8-aapl"; private static final String ISM_DASH_FORMAT_EXTENSION = "format=mpd-time-csf"; // Replacement map of ISO language codes used for normalization. @Nullable private static HashMap<String, String> languageTagReplacementMap; private Util() {} /** * Converts the entirety of an {@link InputStream} to a byte array. * * @param inputStream the {@link InputStream} to be read. The input stream is not closed by this * method. * @return a byte array containing all of the inputStream's bytes. * @throws IOException if an error occurs reading from the stream. */ public static byte[] toByteArray(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024 * 4]; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } return outputStream.toByteArray(); } /** * Registers a {@link BroadcastReceiver} that's not intended to receive broadcasts from other * apps. This will be enforced by specifying {@link Context#RECEIVER_NOT_EXPORTED} if {@link * #SDK_INT} is 33 or above. * * @param context The context on which {@link Context#registerReceiver} will be called. * @param receiver The {@link BroadcastReceiver} to register. This value may be null. * @param filter Selects the Intent broadcasts to be received. * @return The first sticky intent found that matches {@code filter}, or null if there are none. */ @Nullable public static Intent registerReceiverNotExported( Context context, @Nullable BroadcastReceiver receiver, IntentFilter filter) { if (SDK_INT < 33) { return context.registerReceiver(receiver, filter); } else { return context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED); } } /** * Registers a {@link BroadcastReceiver} that's not intended to receive broadcasts from other * apps. This will be enforced by specifying {@link Context#RECEIVER_NOT_EXPORTED} if {@link * #SDK_INT} is 33 or above. * * @param context The context on which {@link Context#registerReceiver} will be called. * @param receiver The {@link BroadcastReceiver} to register. This value may be null. * @param filter Selects the Intent broadcasts to be received. * @param handler Handler identifying the thread that will receive the Intent. * @return The first sticky intent found that matches {@code filter}, or null if there are none. */ @Nullable public static Intent registerReceiverNotExported( Context context, BroadcastReceiver receiver, IntentFilter filter, Handler handler) { if (SDK_INT < 33) { return context.registerReceiver(receiver, filter, /* broadcastPermission= */ null, handler); } else { return context.registerReceiver( receiver, filter, /* broadcastPermission= */ null, handler, Context.RECEIVER_NOT_EXPORTED); } } /** * Calls {@link Context#startForegroundService(Intent)} if {@link #SDK_INT} is 26 or higher, or * {@link Context#startService(Intent)} otherwise. * * @param context The context to call. * @param intent The intent to pass to the called method. * @return The result of the called method. */ @Nullable public static ComponentName startForegroundService(Context context, Intent intent) { if (SDK_INT >= 26) { return context.startForegroundService(intent); } else { return context.startService(intent); } } /** * Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE} * permission read the specified {@link Uri}s, requesting the permission if necessary. * * @param activity The host activity for checking and requesting the permission. * @param uris {@link Uri}s that may require {@link permission#READ_EXTERNAL_STORAGE} to read. * @return Whether a permission request was made. */ public static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris) { if (SDK_INT < 23) { return false; } for (Uri uri : uris) { if (maybeRequestReadExternalStoragePermission(activity, uri)) { return true; } } return false; } /** * Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE} * permission for the specified {@link MediaItem media items}, requesting the permission if * necessary. * * @param activity The host activity for checking and requesting the permission. * @param mediaItems {@link MediaItem Media items}s that may require {@link * permission#READ_EXTERNAL_STORAGE} to read. * @return Whether a permission request was made. */ public static boolean maybeRequestReadExternalStoragePermission( Activity activity, MediaItem... mediaItems) { if (SDK_INT < 23) { return false; } for (MediaItem mediaItem : mediaItems) { if (mediaItem.localConfiguration == null) { continue; } if (maybeRequestReadExternalStoragePermission(activity, mediaItem.localConfiguration.uri)) { return true; } List<MediaItem.SubtitleConfiguration> subtitleConfigs = mediaItem.localConfiguration.subtitleConfigurations; for (int i = 0; i < subtitleConfigs.size(); i++) { if (maybeRequestReadExternalStoragePermission(activity, subtitleConfigs.get(i).uri)) { return true; } } } return false; } private static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri uri) { return SDK_INT >= 23 && (isLocalFileUri(uri) || isMediaStoreExternalContentUri(uri)) && requestExternalStoragePermission(activity); } private static boolean isMediaStoreExternalContentUri(Uri uri) { if (!"content".equals(uri.getScheme()) || !MediaStore.AUTHORITY.equals(uri.getAuthority())) { return false; } List<String> pathSegments = uri.getPathSegments(); if (pathSegments.isEmpty()) { return false; } String firstPathSegment = pathSegments.get(0); return MediaStore.VOLUME_EXTERNAL.equals(firstPathSegment) || MediaStore.VOLUME_EXTERNAL_PRIMARY.equals(firstPathSegment); } /** * Returns whether it may be possible to load the URIs of the given media items based on the * network security policy's cleartext traffic permissions. * * @param mediaItems A list of {@link MediaItem media items}. * @return Whether it may be possible to load the URIs of the given media items. */ public static boolean checkCleartextTrafficPermitted(MediaItem... mediaItems) { if (SDK_INT < 24) { // We assume cleartext traffic is permitted. return true; } for (MediaItem mediaItem : mediaItems) { if (mediaItem.localConfiguration == null) { continue; } if (isTrafficRestricted(mediaItem.localConfiguration.uri)) { return false; } for (int i = 0; i < mediaItem.localConfiguration.subtitleConfigurations.size(); i++) { if (isTrafficRestricted(mediaItem.localConfiguration.subtitleConfigurations.get(i).uri)) { return false; } } } return true; } /** * Returns true if the URI is a path to a local file or a reference to a local file. * * @param uri The uri to test. */ public static boolean isLocalFileUri(Uri uri) { String scheme = uri.getScheme(); return TextUtils.isEmpty(scheme) || "file".equals(scheme); } /** * Tests two objects for {@link Object#equals(Object)} equality, handling the case where one or * both may be null. * * @param o1 The first object. * @param o2 The second object. * @return {@code o1 == null ? o2 == null : o1.equals(o2)}. */ public static boolean areEqual(@Nullable Object o1, @Nullable Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } /** * Tests whether an {@code items} array contains an object equal to {@code item}, according to * {@link Object#equals(Object)}. * * <p>If {@code item} is null then true is returned if and only if {@code items} contains null. * * @param items The array of items to search. * @param item The item to search for. * @return True if the array contains an object equal to the item being searched for. */ public static boolean contains(@NullableType Object[] items, @Nullable Object item) { for (Object arrayItem : items) { if (areEqual(arrayItem, item)) { return true; } } return false; } /** * Removes an indexed range from a List. * * <p>Does nothing if the provided range is valid and {@code fromIndex == toIndex}. * * @param list The List to remove the range from. * @param fromIndex The first index to be removed (inclusive). * @param toIndex The last index to be removed (exclusive). * @throws IllegalArgumentException If {@code fromIndex} &lt; 0, {@code toIndex} &gt; {@code * list.size()}, or {@code fromIndex} &gt; {@code toIndex}. */ public static <T> void removeRange(List<T> list, int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > list.size() || fromIndex > toIndex) { throw new IllegalArgumentException(); } else if (fromIndex != toIndex) { // Checking index inequality prevents an unnecessary allocation. list.subList(fromIndex, toIndex).clear(); } } /** * Casts a nullable variable to a non-null variable without runtime null check. * * <p>Use {@link Assertions#checkNotNull(Object)} to throw if the value is null. */ @SuppressWarnings({"nullness:contracts.postcondition", "nullness:return"}) @EnsuresNonNull("#1") public static <T> T castNonNull(@Nullable T value) { return value; } /** Casts a nullable type array to a non-null type array without runtime null check. */ @SuppressWarnings({"nullness:contracts.postcondition", "nullness:return"}) @EnsuresNonNull("#1") public static <T> T[] castNonNullTypeArray(@NullableType T[] value) { return value; } /** * Copies and optionally truncates an array. Prevents null array elements created by {@link * Arrays#copyOf(Object[], int)} by ensuring the new length does not exceed the current length. * * @param input The input array. * @param length The output array length. Must be less or equal to the length of the input array. * @return The copied array. */ @SuppressWarnings({"nullness:argument", "nullness:return"}) public static <T> T[] nullSafeArrayCopy(T[] input, int length) { Assertions.checkArgument(length <= input.length); return Arrays.copyOf(input, length); } /** * Copies a subset of an array. * * @param input The input array. * @param from The start the range to be copied, inclusive * @param to The end of the range to be copied, exclusive. * @return The copied array. */ @SuppressWarnings({"nullness:argument", "nullness:return"}) public static <T> T[] nullSafeArrayCopyOfRange(T[] input, int from, int to) { Assertions.checkArgument(0 <= from); Assertions.checkArgument(to <= input.length); return Arrays.copyOfRange(input, from, to); } /** * Creates a new array containing {@code original} with {@code newElement} appended. * * @param original The input array. * @param newElement The element to append. * @return The new array. */ public static <T> T[] nullSafeArrayAppend(T[] original, T newElement) { @NullableType T[] result = Arrays.copyOf(original, original.length + 1); result[original.length] = newElement; return castNonNullTypeArray(result); } /** * Creates a new array containing the concatenation of two non-null type arrays. * * @param first The first array. * @param second The second array. * @return The concatenated result. */ @SuppressWarnings("nullness:assignment") public static <T> T[] nullSafeArrayConcatenation(T[] first, T[] second) { T[] concatenation = Arrays.copyOf(first, first.length + second.length); System.arraycopy( /* src= */ second, /* srcPos= */ 0, /* dest= */ concatenation, /* destPos= */ first.length, /* length= */ second.length); return concatenation; } /** * Copies the contents of {@code list} into {@code array}. * * <p>{@code list.size()} must be the same as {@code array.length} to ensure the contents can be * copied into {@code array} without leaving any nulls at the end. * * @param list The list to copy items from. * @param array The array to copy items to. */ @SuppressWarnings("nullness:toArray.nullable.elements.not.newarray") public static <T> void nullSafeListToArray(List<T> list, T[] array) { Assertions.checkState(list.size() == array.length); list.toArray(array); } /** * Creates a {@link Handler} on the current {@link Looper} thread. * * @throws IllegalStateException If the current thread doesn't have a {@link Looper}. */ public static Handler createHandlerForCurrentLooper() { return createHandlerForCurrentLooper(/* callback= */ null); } /** * Creates a {@link Handler} with the specified {@link Handler.Callback} on the current {@link * Looper} thread. * * <p>The method accepts partially initialized objects as callback under the assumption that the * Handler won't be used to send messages until the callback is fully initialized. * * @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no * callback is required. * @return A {@link Handler} with the specified callback on the current {@link Looper} thread. * @throws IllegalStateException If the current thread doesn't have a {@link Looper}. */ public static Handler createHandlerForCurrentLooper( @Nullable Handler.@UnknownInitialization Callback callback) { return createHandler(Assertions.checkStateNotNull(Looper.myLooper()), callback); } /** * Creates a {@link Handler} on the current {@link Looper} thread. * * <p>If the current thread doesn't have a {@link Looper}, the application's main thread {@link * Looper} is used. */ public static Handler createHandlerForCurrentOrMainLooper() { return createHandlerForCurrentOrMainLooper(/* callback= */ null); } /** * Creates a {@link Handler} with the specified {@link Handler.Callback} on the current {@link * Looper} thread. * * <p>The method accepts partially initialized objects as callback under the assumption that the * Handler won't be used to send messages until the callback is fully initialized. * * <p>If the current thread doesn't have a {@link Looper}, the application's main thread {@link * Looper} is used. * * @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no * callback is required. * @return A {@link Handler} with the specified callback on the current {@link Looper} thread. */ public static Handler createHandlerForCurrentOrMainLooper( @Nullable Handler.@UnknownInitialization Callback callback) { return createHandler(getCurrentOrMainLooper(), callback); } /** * Creates a {@link Handler} with the specified {@link Handler.Callback} on the specified {@link * Looper} thread. * * <p>The method accepts partially initialized objects as callback under the assumption that the * Handler won't be used to send messages until the callback is fully initialized. * * @param looper A {@link Looper} to run the callback on. * @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no * callback is required. * @return A {@link Handler} with the specified callback on the current {@link Looper} thread. */ @SuppressWarnings({"nullness:argument", "nullness:return"}) public static Handler createHandler( Looper looper, @Nullable Handler.@UnknownInitialization Callback callback) { return new Handler(looper, callback); } /** * Posts the {@link Runnable} if the calling thread differs with the {@link Looper} of the {@link * Handler}. Otherwise, runs the {@link Runnable} directly. * * @param handler The handler to which the {@link Runnable} will be posted. * @param runnable The runnable to either post or run. * @return {@code true} if the {@link Runnable} was successfully posted to the {@link Handler} or * run. {@code false} otherwise. */ public static boolean postOrRun(Handler handler, Runnable runnable) { Looper looper = handler.getLooper(); if (!looper.getThread().isAlive()) { return false; } if (handler.getLooper() == Looper.myLooper()) { runnable.run(); return true; } else { return handler.post(runnable); } } /** * Posts the {@link Runnable} if the calling thread differs with the {@link Looper} of the {@link * Handler}. Otherwise, runs the {@link Runnable} directly. Also returns a {@link * ListenableFuture} for when the {@link Runnable} has run. * * @param handler The handler to which the {@link Runnable} will be posted. * @param runnable The runnable to either post or run. * @param successValue The value to set in the {@link ListenableFuture} once the runnable * completes. * @param <T> The type of {@code successValue}. * @return A {@link ListenableFuture} for when the {@link Runnable} has run. */ public static <T> ListenableFuture<T> postOrRunWithCompletion( Handler handler, Runnable runnable, T successValue) { SettableFuture<T> outputFuture = SettableFuture.create(); postOrRun( handler, () -> { try { if (outputFuture.isCancelled()) { return; } runnable.run(); outputFuture.set(successValue); } catch (Throwable e) { outputFuture.setException(e); } }); return outputFuture; } /** * Asynchronously transforms the result of a {@link ListenableFuture}. * * <p>The transformation function is called using a {@linkplain MoreExecutors#directExecutor() * direct executor}. * * <p>The returned Future attempts to keep its cancellation state in sync with that of the input * future and that of the future returned by the transform function. That is, if the returned * Future is cancelled, it will attempt to cancel the other two, and if either of the other two is * cancelled, the returned Future will also be cancelled. All forwarded cancellations will not * attempt to interrupt. * * @param future The input {@link ListenableFuture}. * @param transformFunction The function transforming the result of the input future. * @param <T> The result type of the input future. * @param <U> The result type of the transformation function. * @return A {@link ListenableFuture} for the transformed result. */ public static <T, U> ListenableFuture<T> transformFutureAsync( ListenableFuture<U> future, AsyncFunction<U, T> transformFunction) { // This is a simplified copy of Guava's Futures.transformAsync. SettableFuture<T> outputFuture = SettableFuture.create(); outputFuture.addListener( () -> { if (outputFuture.isCancelled()) { future.cancel(/* mayInterruptIfRunning= */ false); } }, MoreExecutors.directExecutor()); future.addListener( () -> { U inputFutureResult; try { inputFutureResult = Futures.getDone(future); } catch (CancellationException cancellationException) { outputFuture.cancel(/* mayInterruptIfRunning= */ false); return; } catch (ExecutionException exception) { @Nullable Throwable cause = exception.getCause(); outputFuture.setException(cause == null ? exception : cause); return; } catch (RuntimeException | Error error) { outputFuture.setException(error); return; } try { outputFuture.setFuture(transformFunction.apply(inputFutureResult)); } catch (Throwable exception) { outputFuture.setException(exception); } }, MoreExecutors.directExecutor()); return outputFuture; } /** * Returns the {@link Looper} associated with the current thread, or the {@link Looper} of the * application's main thread if the current thread doesn't have a {@link Looper}. */ public static Looper getCurrentOrMainLooper() { @Nullable Looper myLooper = Looper.myLooper(); return myLooper != null ? myLooper : Looper.getMainLooper(); } /** * Instantiates a new single threaded executor whose thread has the specified name. * * @param threadName The name of the thread. * @return The executor. */ public static ExecutorService newSingleThreadExecutor(String threadName) { return Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, threadName)); } /** * Closes a {@link Closeable}, suppressing any {@link IOException} that may occur. Both {@link * java.io.OutputStream} and {@link InputStream} are {@code Closeable}. * * @param closeable The {@link Closeable} to close. */ public static void closeQuietly(@Nullable Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { // Ignore. } } /** * Reads an integer from a {@link Parcel} and interprets it as a boolean, with 0 mapping to false * and all other values mapping to true. * * @param parcel The {@link Parcel} to read from. * @return The read value. */ public static boolean readBoolean(Parcel parcel) { return parcel.readInt() != 0; } /** * Writes a boolean to a {@link Parcel}. The boolean is written as an integer with value 1 (true) * or 0 (false). * * @param parcel The {@link Parcel} to write to. * @param value The value to write. */ public static void writeBoolean(Parcel parcel, boolean value) { parcel.writeInt(value ? 1 : 0); } /** * Returns the language tag for a {@link Locale}. * * <p>For API levels &ge; 21, this tag is IETF BCP 47 compliant. Use {@link * #normalizeLanguageCode(String)} to retrieve a normalized IETF BCP 47 language tag for all API * levels if needed. * * @param locale A {@link Locale}. * @return The language tag. */ public static String getLocaleLanguageTag(Locale locale) { return SDK_INT >= 21 ? getLocaleLanguageTagV21(locale) : locale.toString(); } /** * Returns a normalized IETF BCP 47 language tag for {@code language}. * * @param language A case-insensitive language code supported by {@link * Locale#forLanguageTag(String)}. * @return The all-lowercase normalized code, or null if the input was null, or {@code * language.toLowerCase()} if the language could not be normalized. */ public static @PolyNull String normalizeLanguageCode(@PolyNull String language) { if (language == null) { return null; } // Locale data (especially for API < 21) may produce tags with '_' instead of the // standard-conformant '-'. String normalizedTag = language.replace('_', '-'); if (normalizedTag.isEmpty() || normalizedTag.equals(C.LANGUAGE_UNDETERMINED)) { // Tag isn't valid, keep using the original. normalizedTag = language; } normalizedTag = Ascii.toLowerCase(normalizedTag); String mainLanguage = splitAtFirst(normalizedTag, "-")[0]; if (languageTagReplacementMap == null) { languageTagReplacementMap = createIsoLanguageReplacementMap(); } @Nullable String replacedLanguage = languageTagReplacementMap.get(mainLanguage); if (replacedLanguage != null) { normalizedTag = replacedLanguage + normalizedTag.substring(/* beginIndex= */ mainLanguage.length()); mainLanguage = replacedLanguage; } if ("no".equals(mainLanguage) || "i".equals(mainLanguage) || "zh".equals(mainLanguage)) { normalizedTag = maybeReplaceLegacyLanguageTags(normalizedTag); } return normalizedTag; } /** * Returns a new {@link String} constructed by decoding UTF-8 encoded bytes. * * @param bytes The UTF-8 encoded bytes to decode. * @return The string. */ public static String fromUtf8Bytes(byte[] bytes) { return new String(bytes, Charsets.UTF_8); } /** * Returns a new {@link String} constructed by decoding UTF-8 encoded bytes in a subarray. * * @param bytes The UTF-8 encoded bytes to decode. * @param offset The index of the first byte to decode. * @param length The number of bytes to decode. * @return The string. */ public static String fromUtf8Bytes(byte[] bytes, int offset, int length) { return new String(bytes, offset, length, Charsets.UTF_8); } /** * Returns a new byte array containing the code points of a {@link String} encoded using UTF-8. * * @param value The {@link String} whose bytes should be obtained. * @return The code points encoding using UTF-8. */ public static byte[] getUtf8Bytes(String value) { return value.getBytes(Charsets.UTF_8); } /** * Splits a string using {@code value.split(regex, -1}). Note: this is is similar to {@link * String#split(String)} but empty matches at the end of the string will not be omitted from the * returned array. * * @param value The string to split. * @param regex A delimiting regular expression. * @return The array of strings resulting from splitting the string. */ public static String[] split(String value, String regex) { return value.split(regex, /* limit= */ -1); } /** * Splits the string at the first occurrence of the delimiter {@code regex}. If the delimiter does * not match, returns an array with one element which is the input string. If the delimiter does * match, returns an array with the portion of the string before the delimiter and the rest of the * string. * * @param value The string. * @param regex A delimiting regular expression. * @return The string split by the first occurrence of the delimiter. */ public static String[] splitAtFirst(String value, String regex) { return value.split(regex, /* limit= */ 2); } /** * Returns whether the given character is a carriage return ('\r') or a line feed ('\n'). * * @param c The character. * @return Whether the given character is a linebreak. */ public static boolean isLinebreak(int c) { return c == '\n' || c == '\r'; } /** * Formats a string using {@link Locale#US}. * * @see String#format(String, Object...) */ public static String formatInvariant(String format, Object... args) { return String.format(Locale.US, format, args); } /** * Divides a {@code numerator} by a {@code denominator}, returning the ceiled result. * * @param numerator The numerator to divide. * @param denominator The denominator to divide by. * @return The ceiled result of the division. */ public static int ceilDivide(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } /** * Divides a {@code numerator} by a {@code denominator}, returning the ceiled result. * * @param numerator The numerator to divide. * @param denominator The denominator to divide by. * @return The ceiled result of the division. */ public static long ceilDivide(long numerator, long denominator) { return (numerator + denominator - 1) / denominator; } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ public static int constrainValue(int value, int min, int max) { return max(min, min(value, max)); } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ public static long constrainValue(long value, long min, long max) { return max(min, min(value, max)); } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ public static float constrainValue(float value, float min, float max) { return max(min, min(value, max)); } /** * Returns the sum of two arguments, or a third argument if the result overflows. * * @param x The first value. * @param y The second value. * @param overflowResult The return value if {@code x + y} overflows. * @return {@code x + y}, or {@code overflowResult} if the result overflows. */ public static long addWithOverflowDefault(long x, long y, long overflowResult) { long result = x + y; // See Hacker's Delight 2-13 (H. Warren Jr). if (((x ^ result) & (y ^ result)) < 0) { return overflowResult; } return result; } /** * Returns the difference between two arguments, or a third argument if the result overflows. * * @param x The first value. * @param y The second value. * @param overflowResult The return value if {@code x - y} overflows. * @return {@code x - y}, or {@code overflowResult} if the result overflows. */ public static long subtractWithOverflowDefault(long x, long y, long overflowResult) { long result = x - y; // See Hacker's Delight 2-13 (H. Warren Jr). if (((x ^ y) & (x ^ result)) < 0) { return overflowResult; } return result; } /** * Returns the index of the first occurrence of {@code value} in {@code array}, or {@link * C#INDEX_UNSET} if {@code value} is not contained in {@code array}. * * @param array The array to search. * @param value The value to search for. * @return The index of the first occurrence of value in {@code array}, or {@link C#INDEX_UNSET} * if {@code value} is not contained in {@code array}. */ public static int linearSearch(int[] array, int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return C.INDEX_UNSET; } /** * Returns the index of the first occurrence of {@code value} in {@code array}, or {@link * C#INDEX_UNSET} if {@code value} is not contained in {@code array}. * * @param array The array to search. * @param value The value to search for. * @return The index of the first occurrence of value in {@code array}, or {@link C#INDEX_UNSET} * if {@code value} is not contained in {@code array}. */ public static int linearSearch(long[] array, long value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return C.INDEX_UNSET; } /** * Returns the index of the largest element in {@code array} that is less than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the first one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the array. If false then -1 will be returned. * @return The index of the largest element in {@code array} that is less than (or optionally * equal to) {@code value}. */ public static int binarySearchFloor( int[] array, int value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = -(index + 2); } else { while (--index >= 0 && array[index] == value) {} if (inclusive) { index++; } } return stayInBounds ? max(0, index) : index; } /** * Returns the index of the largest element in {@code array} that is less than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the first one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the array. If false then -1 will be returned. * @return The index of the largest element in {@code array} that is less than (or optionally * equal to) {@code value}. */ public static int binarySearchFloor( long[] array, long value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = -(index + 2); } else { while (--index >= 0 && array[index] == value) {} if (inclusive) { index++; } } return stayInBounds ? max(0, index) : index; } /** * Returns the index of the largest element in {@code list} that is less than (or optionally equal * to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the list must be sorted. If the * list contains multiple elements equal to {@code value} and {@code inclusive} is true, the index * of the first one will be returned. * * @param <T> The type of values being searched. * @param list The list to search. * @param value The value being searched for. * @param inclusive If the value is present in the list, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the list. If false then -1 will be returned. * @return The index of the largest element in {@code list} that is less than (or optionally equal * to) {@code value}. */ public static <T extends Comparable<? super T>> int binarySearchFloor( List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds) { int index = Collections.binarySearch(list, value); if (index < 0) { index = -(index + 2); } else { while (--index >= 0 && list.get(index).compareTo(value) == 0) {} if (inclusive) { index++; } } return stayInBounds ? max(0, index) : index; } /** * Returns the index of the largest element in {@code longArray} that is less than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the first one will be returned. * * @param longArray The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the largest element strictly less * than the value. * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than * the smallest element in the array. If false then -1 will be returned. * @return The index of the largest element in {@code array} that is less than (or optionally * equal to) {@code value}. */ public static int binarySearchFloor( LongArray longArray, long value, boolean inclusive, boolean stayInBounds) { int lowIndex = 0; int highIndex = longArray.size() - 1; while (lowIndex <= highIndex) { int midIndex = (lowIndex + highIndex) >>> 1; if (longArray.get(midIndex) < value) { lowIndex = midIndex + 1; } else { highIndex = midIndex - 1; } } if (inclusive && highIndex + 1 < longArray.size() && longArray.get(highIndex + 1) == value) { highIndex++; } else if (stayInBounds && highIndex == -1) { highIndex = 0; } return highIndex; } /** * Returns the index of the smallest element in {@code array} that is greater than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the last one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the smallest element strictly * greater than the value. * @param stayInBounds If true, then {@code (a.length - 1)} will be returned in the case that the * value is greater than the largest element in the array. If false then {@code a.length} will * be returned. * @return The index of the smallest element in {@code array} that is greater than (or optionally * equal to) {@code value}. */ public static int binarySearchCeil( int[] array, int value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = ~index; } else { while (++index < array.length && array[index] == value) {} if (inclusive) { index--; } } return stayInBounds ? min(array.length - 1, index) : index; } /** * Returns the index of the smallest element in {@code array} that is greater than (or optionally * equal to) a specified {@code value}. * * <p>The search is performed using a binary search algorithm, so the array must be sorted. If the * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the * index of the last one will be returned. * * @param array The array to search. * @param value The value being searched for. * @param inclusive If the value is present in the array, whether to return the corresponding * index. If false then the returned index corresponds to the smallest element strictly * greater than the value. * @param stayInBounds If true, then {@code (a.length - 1)} will be returned in the case that the * value is greater than the largest element in the array. If false then {@code a.length} will * be returned. * @return The index of the smallest element in {@code array} that is greater than (or optionally * equal to) {@code value}. */ public static int binarySearchCeil( long[] array, long value, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(array, value); if (index < 0) { index = ~index; } else { while (++index < array.length && array[index] == value) {} if (inclusive) { index--; } } return stayInBounds ? min(array.length - 1, index) : index; } /** * Returns the index of the smallest element in {@code list} that is greater than (or optionally * equal to) a specified value. * * <p>The search is performed using a binary search algorithm, so the list must be sorted. If the * list contains multiple elements equal to {@code value} and {@code inclusive} is true, the index * of the last one will be returned. * * @param <T> The type of values being searched. * @param list The list to search. * @param value The value being searched for. * @param inclusive If the value is present in the list, whether to return the corresponding * index. If false then the returned index corresponds to the smallest element strictly * greater than the value. * @param stayInBounds If true, then {@code (list.size() - 1)} will be returned in the case that * the value is greater than the largest element in the list. If false then {@code * list.size()} will be returned. * @return The index of the smallest element in {@code list} that is greater than (or optionally * equal to) {@code value}. */ public static <T extends Comparable<? super T>> int binarySearchCeil( List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds) { int index = Collections.binarySearch(list, value); if (index < 0) { index = ~index; } else { int listSize = list.size(); while (++index < listSize && list.get(index).compareTo(value) == 0) {} if (inclusive) { index--; } } return stayInBounds ? min(list.size() - 1, index) : index; } /** * Compares two long values and returns the same value as {@code Long.compare(long, long)}. * * @param left The left operand. * @param right The right operand. * @return 0, if left == right, a negative value if left &lt; right, or a positive value if left * &gt; right. */ public static int compareLong(long left, long right) { return left < right ? -1 : left == right ? 0 : 1; } /** * Returns the minimum value in the given {@link SparseLongArray}. * * @param sparseLongArray The {@link SparseLongArray}. * @return The minimum value. * @throws NoSuchElementException If the array is empty. */ @RequiresApi(18) public static long minValue(SparseLongArray sparseLongArray) { if (sparseLongArray.size() == 0) { throw new NoSuchElementException(); } long min = Long.MAX_VALUE; for (int i = 0; i < sparseLongArray.size(); i++) { min = min(min, sparseLongArray.valueAt(i)); } return min; } /** * Returns the maximum value in the given {@link SparseLongArray}. * * @param sparseLongArray The {@link SparseLongArray}. * @return The maximum value. * @throws NoSuchElementException If the array is empty. */ @RequiresApi(18) public static long maxValue(SparseLongArray sparseLongArray) { if (sparseLongArray.size() == 0) { throw new NoSuchElementException(); } long max = Long.MIN_VALUE; for (int i = 0; i < sparseLongArray.size(); i++) { max = max(max, sparseLongArray.valueAt(i)); } return max; } /** * Converts a time in microseconds to the corresponding time in milliseconds, preserving {@link * C#TIME_UNSET} and {@link C#TIME_END_OF_SOURCE} values. * * @param timeUs The time in microseconds. * @return The corresponding time in milliseconds. */ public static long usToMs(long timeUs) { return (timeUs == C.TIME_UNSET || timeUs == C.TIME_END_OF_SOURCE) ? timeUs : (timeUs / 1000); } /** * Converts a time in milliseconds to the corresponding time in microseconds, preserving {@link * C#TIME_UNSET} values and {@link C#TIME_END_OF_SOURCE} values. * * @param timeMs The time in milliseconds. * @return The corresponding time in microseconds. */ public static long msToUs(long timeMs) { return (timeMs == C.TIME_UNSET || timeMs == C.TIME_END_OF_SOURCE) ? timeMs : (timeMs * 1000); } /** * Parses an xs:duration attribute value, returning the parsed duration in milliseconds. * * @param value The attribute value to decode. * @return The parsed duration in milliseconds. */ public static long parseXsDuration(String value) { Matcher matcher = XS_DURATION_PATTERN.matcher(value); if (matcher.matches()) { boolean negated = !TextUtils.isEmpty(matcher.group(1)); // Durations containing years and months aren't completely defined. We assume there are // 30.4368 days in a month, and 365.242 days in a year. String years = matcher.group(3); double durationSeconds = (years != null) ? Double.parseDouble(years) * 31556908 : 0; String months = matcher.group(5); durationSeconds += (months != null) ? Double.parseDouble(months) * 2629739 : 0; String days = matcher.group(7); durationSeconds += (days != null) ? Double.parseDouble(days) * 86400 : 0; String hours = matcher.group(10); durationSeconds += (hours != null) ? Double.parseDouble(hours) * 3600 : 0; String minutes = matcher.group(12); durationSeconds += (minutes != null) ? Double.parseDouble(minutes) * 60 : 0; String seconds = matcher.group(14); durationSeconds += (seconds != null) ? Double.parseDouble(seconds) : 0; long durationMillis = (long) (durationSeconds * 1000); return negated ? -durationMillis : durationMillis; } else { return (long) (Double.parseDouble(value) * 3600 * 1000); } } /** * Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the * epoch. * * @param value The attribute value to decode. * @return The parsed timestamp in milliseconds since the epoch. * @throws ParserException if an error occurs parsing the dateTime attribute value. */ // incompatible types in argument. // dereference of possibly-null reference matcher.group(9) @SuppressWarnings({"nullness:argument", "nullness:dereference.of.nullable"}) public static long parseXsDateTime(String value) throws ParserException { Matcher matcher = XS_DATE_TIME_PATTERN.matcher(value); if (!matcher.matches()) { throw ParserException.createForMalformedContainer( "Invalid date/time format: " + value, /* cause= */ null); } int timezoneShift; if (matcher.group(9) == null) { // No time zone specified. timezoneShift = 0; } else if (matcher.group(9).equalsIgnoreCase("Z")) { timezoneShift = 0; } else { timezoneShift = ((Integer.parseInt(matcher.group(12)) * 60 + Integer.parseInt(matcher.group(13)))); if ("-".equals(matcher.group(11))) { timezoneShift *= -1; } } Calendar dateTime = new GregorianCalendar(TimeZone.getTimeZone("GMT")); dateTime.clear(); // Note: The month value is 0-based, hence the -1 on group(2) dateTime.set( Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)) - 1, Integer.parseInt(matcher.group(3)), Integer.parseInt(matcher.group(4)), Integer.parseInt(matcher.group(5)), Integer.parseInt(matcher.group(6))); if (!TextUtils.isEmpty(matcher.group(8))) { final BigDecimal bd = new BigDecimal("0." + matcher.group(8)); // we care only for milliseconds, so movePointRight(3) dateTime.set(Calendar.MILLISECOND, bd.movePointRight(3).intValue()); } long time = dateTime.getTimeInMillis(); if (timezoneShift != 0) { time -= timezoneShift * 60000L; } return time; } /** * Scales a large timestamp. * * <p>Logically, scaling consists of a multiplication followed by a division. The actual * operations performed are designed to minimize the probability of overflow. * * @param timestamp The timestamp to scale. * @param multiplier The multiplier. * @param divisor The divisor. * @return The scaled timestamp. */ public static long scaleLargeTimestamp(long timestamp, long multiplier, long divisor) { if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; return timestamp / divisionFactor; } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; return timestamp * multiplicationFactor; } else { double multiplicationFactor = (double) multiplier / divisor; return (long) (timestamp * multiplicationFactor); } } /** * Applies {@link #scaleLargeTimestamp(long, long, long)} to a list of unscaled timestamps. * * @param timestamps The timestamps to scale. * @param multiplier The multiplier. * @param divisor The divisor. * @return The scaled timestamps. */ public static long[] scaleLargeTimestamps(List<Long> timestamps, long multiplier, long divisor) { long[] scaledTimestamps = new long[timestamps.size()]; if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; for (int i = 0; i < scaledTimestamps.length; i++) { scaledTimestamps[i] = timestamps.get(i) / divisionFactor; } } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; for (int i = 0; i < scaledTimestamps.length; i++) { scaledTimestamps[i] = timestamps.get(i) * multiplicationFactor; } } else { double multiplicationFactor = (double) multiplier / divisor; for (int i = 0; i < scaledTimestamps.length; i++) { scaledTimestamps[i] = (long) (timestamps.get(i) * multiplicationFactor); } } return scaledTimestamps; } /** * Applies {@link #scaleLargeTimestamp(long, long, long)} to an array of unscaled timestamps. * * @param timestamps The timestamps to scale. * @param multiplier The multiplier. * @param divisor The divisor. */ public static void scaleLargeTimestampsInPlace(long[] timestamps, long multiplier, long divisor) { if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; for (int i = 0; i < timestamps.length; i++) { timestamps[i] /= divisionFactor; } } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; for (int i = 0; i < timestamps.length; i++) { timestamps[i] *= multiplicationFactor; } } else { double multiplicationFactor = (double) multiplier / divisor; for (int i = 0; i < timestamps.length; i++) { timestamps[i] = (long) (timestamps[i] * multiplicationFactor); } } } /** * Returns the duration of media that will elapse in {@code playoutDuration}. * * @param playoutDuration The duration to scale. * @param speed The factor by which playback is sped up. * @return The scaled duration, in the same units as {@code playoutDuration}. */ public static long getMediaDurationForPlayoutDuration(long playoutDuration, float speed) { if (speed == 1f) { return playoutDuration; } return Math.round((double) playoutDuration * speed); } /** * Returns the playout duration of {@code mediaDuration} of media. * * @param mediaDuration The duration to scale. * @return The scaled duration, in the same units as {@code mediaDuration}. */ public static long getPlayoutDurationForMediaDuration(long mediaDuration, float speed) { if (speed == 1f) { return mediaDuration; } return Math.round((double) mediaDuration / speed); } /** * Returns the integer equal to the big-endian concatenation of the characters in {@code string} * as bytes. The string must be no more than four characters long. * * @param string A string no more than four characters long. */ public static int getIntegerCodeForString(String string) { int length = string.length(); Assertions.checkArgument(length <= 4); int result = 0; for (int i = 0; i < length; i++) { result <<= 8; result |= string.charAt(i); } return result; } /** * Converts an integer to a long by unsigned conversion. * * <p>This method is equivalent to {@link Integer#toUnsignedLong(int)} for API 26+. */ public static long toUnsignedLong(int x) { // x is implicitly casted to a long before the bit operation is executed but this does not // impact the method correctness. return x & 0xFFFFFFFFL; } /** * Returns the long that is composed of the bits of the 2 specified integers. * * @param mostSignificantBits The 32 most significant bits of the long to return. * @param leastSignificantBits The 32 least significant bits of the long to return. * @return a long where its 32 most significant bits are {@code mostSignificantBits} bits and its * 32 least significant bits are {@code leastSignificantBits}. */ public static long toLong(int mostSignificantBits, int leastSignificantBits) { return (toUnsignedLong(mostSignificantBits) << 32) | toUnsignedLong(leastSignificantBits); } /** * Truncates a sequence of ASCII characters to a maximum length. * * <p>This preserves span styling in the {@link CharSequence}. If that's not important, use {@link * Ascii#truncate(CharSequence, int, String)}. * * <p><b>Note:</b> This is not safe to use in general on Unicode text because it may separate * characters from combining characters or split up surrogate pairs. * * @param sequence The character sequence to truncate. * @param maxLength The max length to truncate to. * @return {@code sequence} directly if {@code sequence.length() <= maxLength}, otherwise {@code * sequence.subsequence(0, maxLength}. */ public static CharSequence truncateAscii(CharSequence sequence, int maxLength) { return sequence.length() <= maxLength ? sequence : sequence.subSequence(0, maxLength); } /** * Returns a byte array containing values parsed from the hex string provided. * * @param hexString The hex string to convert to bytes. * @return A byte array containing values parsed from the hex string provided. */ public static byte[] getBytesFromHexString(String hexString) { byte[] data = new byte[hexString.length() / 2]; for (int i = 0; i < data.length; i++) { int stringOffset = i * 2; data[i] = (byte) ((Character.digit(hexString.charAt(stringOffset), 16) << 4) + Character.digit(hexString.charAt(stringOffset + 1), 16)); } return data; } /** * Returns a string containing a lower-case hex representation of the bytes provided. * * @param bytes The byte data to convert to hex. * @return A String containing the hex representation of {@code bytes}. */ public static String toHexString(byte[] bytes) { StringBuilder result = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { result .append(Character.forDigit((bytes[i] >> 4) & 0xF, 16)) .append(Character.forDigit(bytes[i] & 0xF, 16)); } return result.toString(); } /** * Returns a string with comma delimited simple names of each object's class. * * @param objects The objects whose simple class names should be comma delimited and returned. * @return A string with comma delimited simple names of each object's class. */ public static String getCommaDelimitedSimpleClassNames(Object[] objects) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < objects.length; i++) { stringBuilder.append(objects[i].getClass().getSimpleName()); if (i < objects.length - 1) { stringBuilder.append(", "); } } return stringBuilder.toString(); } /** * Returns a user agent string based on the given application name and the library version. * * @param context A valid context of the calling application. * @param applicationName String that will be prefix'ed to the generated user agent. * @return A user agent string generated using the applicationName and the library version. */ public static String getUserAgent(Context context, String applicationName) { String versionName; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); versionName = info.versionName; } catch (NameNotFoundException e) { versionName = "?"; } return applicationName + "/" + versionName + " (Linux;Android " + Build.VERSION.RELEASE + ") " + ExoPlayerLibraryInfo.VERSION_SLASHY; } /** Returns the number of codec strings in {@code codecs} whose type matches {@code trackType}. */ public static int getCodecCountOfType(@Nullable String codecs, @C.TrackType int trackType) { String[] codecArray = splitCodecs(codecs); int count = 0; for (String codec : codecArray) { if (trackType == MimeTypes.getTrackTypeOfCodec(codec)) { count++; } } return count; } /** * Returns a copy of {@code codecs} without the codecs whose track type doesn't match {@code * trackType}. * * @param codecs A codec sequence string, as defined in RFC 6381. * @param trackType The {@link C.TrackType track type}. * @return A copy of {@code codecs} without the codecs whose track type doesn't match {@code * trackType}. If this ends up empty, or {@code codecs} is null, returns null. */ @Nullable public static String getCodecsOfType(@Nullable String codecs, @C.TrackType int trackType) { String[] codecArray = splitCodecs(codecs); if (codecArray.length == 0) { return null; } StringBuilder builder = new StringBuilder(); for (String codec : codecArray) { if (trackType == MimeTypes.getTrackTypeOfCodec(codec)) { if (builder.length() > 0) { builder.append(","); } builder.append(codec); } } return builder.length() > 0 ? builder.toString() : null; } /** * Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings. * * @param codecs A codec sequence string, as defined in RFC 6381. * @return The split codecs, or an array of length zero if the input was empty or null. */ public static String[] splitCodecs(@Nullable String codecs) { if (TextUtils.isEmpty(codecs)) { return new String[0]; } return split(codecs.trim(), "(\\s*,\\s*)"); } /** * Gets a PCM {@link Format} with the specified parameters. * * @param pcmEncoding The {@link C.PcmEncoding}. * @param channels The number of channels, or {@link Format#NO_VALUE} if unknown. * @param sampleRate The sample rate in Hz, or {@link Format#NO_VALUE} if unknown. * @return The PCM format. */ public static Format getPcmFormat(@C.PcmEncoding int pcmEncoding, int channels, int sampleRate) { return new Format.Builder() .setSampleMimeType(MimeTypes.AUDIO_RAW) .setChannelCount(channels) .setSampleRate(sampleRate) .setPcmEncoding(pcmEncoding) .build(); } /** * Converts a sample bit depth to a corresponding PCM encoding constant. * * @param bitDepth The bit depth. Supported values are 8, 16, 24 and 32. * @return The corresponding encoding. One of {@link C#ENCODING_PCM_8BIT}, {@link * C#ENCODING_PCM_16BIT}, {@link C#ENCODING_PCM_24BIT} and {@link C#ENCODING_PCM_32BIT}. If * the bit depth is unsupported then {@link C#ENCODING_INVALID} is returned. */ public static @C.PcmEncoding int getPcmEncoding(int bitDepth) { switch (bitDepth) { case 8: return C.ENCODING_PCM_8BIT; case 16: return C.ENCODING_PCM_16BIT; case 24: return C.ENCODING_PCM_24BIT; case 32: return C.ENCODING_PCM_32BIT; default: return C.ENCODING_INVALID; } } /** * Returns whether {@code encoding} is one of the linear PCM encodings. * * @param encoding The encoding of the audio data. * @return Whether the encoding is one of the PCM encodings. */ public static boolean isEncodingLinearPcm(@C.Encoding int encoding) { return encoding == C.ENCODING_PCM_8BIT || encoding == C.ENCODING_PCM_16BIT || encoding == C.ENCODING_PCM_16BIT_BIG_ENDIAN || encoding == C.ENCODING_PCM_24BIT || encoding == C.ENCODING_PCM_32BIT || encoding == C.ENCODING_PCM_FLOAT; } /** * Returns whether {@code encoding} is high resolution (&gt; 16-bit) PCM. * * @param encoding The encoding of the audio data. * @return Whether the encoding is high resolution PCM. */ public static boolean isEncodingHighResolutionPcm(@C.PcmEncoding int encoding) { return encoding == C.ENCODING_PCM_24BIT || encoding == C.ENCODING_PCM_32BIT || encoding == C.ENCODING_PCM_FLOAT; } /** * Returns the audio track channel configuration for the given channel count, or {@link * AudioFormat#CHANNEL_INVALID} if output is not possible. * * @param channelCount The number of channels in the input audio. * @return The channel configuration or {@link AudioFormat#CHANNEL_INVALID} if output is not * possible. */ @SuppressLint("InlinedApi") // Inlined AudioFormat constants. public static int getAudioTrackChannelConfig(int channelCount) { switch (channelCount) { case 1: return AudioFormat.CHANNEL_OUT_MONO; case 2: return AudioFormat.CHANNEL_OUT_STEREO; case 3: return AudioFormat.CHANNEL_OUT_STEREO | AudioFormat.CHANNEL_OUT_FRONT_CENTER; case 4: return AudioFormat.CHANNEL_OUT_QUAD; case 5: return AudioFormat.CHANNEL_OUT_QUAD | AudioFormat.CHANNEL_OUT_FRONT_CENTER; case 6: return AudioFormat.CHANNEL_OUT_5POINT1; case 7: return AudioFormat.CHANNEL_OUT_5POINT1 | AudioFormat.CHANNEL_OUT_BACK_CENTER; case 8: return AudioFormat.CHANNEL_OUT_7POINT1_SURROUND; case 12: return AudioFormat.CHANNEL_OUT_7POINT1POINT4; default: return AudioFormat.CHANNEL_INVALID; } } /** * Returns the frame size for audio with {@code channelCount} channels in the specified encoding. * * @param pcmEncoding The encoding of the audio data. * @param channelCount The channel count. * @return The size of one audio frame in bytes. */ public static int getPcmFrameSize(@C.PcmEncoding int pcmEncoding, int channelCount) { switch (pcmEncoding) { case C.ENCODING_PCM_8BIT: return channelCount; case C.ENCODING_PCM_16BIT: case C.ENCODING_PCM_16BIT_BIG_ENDIAN: return channelCount * 2; case C.ENCODING_PCM_24BIT: return channelCount * 3; case C.ENCODING_PCM_32BIT: case C.ENCODING_PCM_FLOAT: return channelCount * 4; case C.ENCODING_INVALID: case Format.NO_VALUE: default: throw new IllegalArgumentException(); } } /** Returns the {@link C.AudioUsage} corresponding to the specified {@link C.StreamType}. */ public static @C.AudioUsage int getAudioUsageForStreamType(@C.StreamType int streamType) { switch (streamType) { case C.STREAM_TYPE_ALARM: return C.USAGE_ALARM; case C.STREAM_TYPE_DTMF: return C.USAGE_VOICE_COMMUNICATION_SIGNALLING; case C.STREAM_TYPE_NOTIFICATION: return C.USAGE_NOTIFICATION; case C.STREAM_TYPE_RING: return C.USAGE_NOTIFICATION_RINGTONE; case C.STREAM_TYPE_SYSTEM: return C.USAGE_ASSISTANCE_SONIFICATION; case C.STREAM_TYPE_VOICE_CALL: return C.USAGE_VOICE_COMMUNICATION; case C.STREAM_TYPE_MUSIC: default: return C.USAGE_MEDIA; } } /** Returns the {@link C.AudioContentType} corresponding to the specified {@link C.StreamType}. */ public static @C.AudioContentType int getAudioContentTypeForStreamType( @C.StreamType int streamType) { switch (streamType) { case C.STREAM_TYPE_ALARM: case C.STREAM_TYPE_DTMF: case C.STREAM_TYPE_NOTIFICATION: case C.STREAM_TYPE_RING: case C.STREAM_TYPE_SYSTEM: return C.AUDIO_CONTENT_TYPE_SONIFICATION; case C.STREAM_TYPE_VOICE_CALL: return C.AUDIO_CONTENT_TYPE_SPEECH; case C.STREAM_TYPE_MUSIC: default: return C.AUDIO_CONTENT_TYPE_MUSIC; } } /** Returns the {@link C.StreamType} corresponding to the specified {@link C.AudioUsage}. */ public static @C.StreamType int getStreamTypeForAudioUsage(@C.AudioUsage int usage) { switch (usage) { case C.USAGE_MEDIA: case C.USAGE_GAME: case C.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: return C.STREAM_TYPE_MUSIC; case C.USAGE_ASSISTANCE_SONIFICATION: return C.STREAM_TYPE_SYSTEM; case C.USAGE_VOICE_COMMUNICATION: return C.STREAM_TYPE_VOICE_CALL; case C.USAGE_VOICE_COMMUNICATION_SIGNALLING: return C.STREAM_TYPE_DTMF; case C.USAGE_ALARM: return C.STREAM_TYPE_ALARM; case C.USAGE_NOTIFICATION_RINGTONE: return C.STREAM_TYPE_RING; case C.USAGE_NOTIFICATION: case C.USAGE_NOTIFICATION_COMMUNICATION_REQUEST: case C.USAGE_NOTIFICATION_COMMUNICATION_INSTANT: case C.USAGE_NOTIFICATION_COMMUNICATION_DELAYED: case C.USAGE_NOTIFICATION_EVENT: return C.STREAM_TYPE_NOTIFICATION; case C.USAGE_ASSISTANCE_ACCESSIBILITY: case C.USAGE_ASSISTANT: case C.USAGE_UNKNOWN: default: return C.STREAM_TYPE_DEFAULT; } } /** * Returns a newly generated audio session identifier, or {@link AudioManager#ERROR} if an error * occurred in which case audio playback may fail. * * @see AudioManager#generateAudioSessionId() */ @RequiresApi(21) public static int generateAudioSessionIdV21(Context context) { @Nullable AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)); return audioManager == null ? AudioManager.ERROR : audioManager.generateAudioSessionId(); } /** * Derives a DRM {@link UUID} from {@code drmScheme}. * * @param drmScheme A UUID string, or {@code "widevine"}, {@code "playready"} or {@code * "clearkey"}. * @return The derived {@link UUID}, or {@code null} if one could not be derived. */ @Nullable public static UUID getDrmUuid(String drmScheme) { switch (Ascii.toLowerCase(drmScheme)) { case "widevine": return C.WIDEVINE_UUID; case "playready": return C.PLAYREADY_UUID; case "clearkey": return C.CLEARKEY_UUID; default: try { return UUID.fromString(drmScheme); } catch (RuntimeException e) { return null; } } } /** * Returns a {@link PlaybackException.ErrorCode} value that corresponds to the provided {@link * MediaDrm.ErrorCodes} value. Returns {@link PlaybackException#ERROR_CODE_DRM_SYSTEM_ERROR} if * the provided error code isn't recognised. */ public static @PlaybackException.ErrorCode int getErrorCodeForMediaDrmErrorCode( int mediaDrmErrorCode) { switch (mediaDrmErrorCode) { case MediaDrm.ErrorCodes.ERROR_PROVISIONING_CONFIG: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_PARSE: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_REQUEST_REJECTED: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_CERTIFICATE: case MediaDrm.ErrorCodes.ERROR_PROVISIONING_RETRY: return PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED; case MediaDrm.ErrorCodes.ERROR_LICENSE_PARSE: case MediaDrm.ErrorCodes.ERROR_LICENSE_RELEASE: case MediaDrm.ErrorCodes.ERROR_LICENSE_REQUEST_REJECTED: case MediaDrm.ErrorCodes.ERROR_LICENSE_RESTORE: case MediaDrm.ErrorCodes.ERROR_LICENSE_STATE: case MediaDrm.ErrorCodes.ERROR_CERTIFICATE_MALFORMED: return PlaybackException.ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED; case MediaDrm.ErrorCodes.ERROR_LICENSE_POLICY: case MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_OUTPUT_PROTECTION: case MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_SECURITY: case MediaDrm.ErrorCodes.ERROR_KEY_EXPIRED: case MediaDrm.ErrorCodes.ERROR_KEY_NOT_LOADED: return PlaybackException.ERROR_CODE_DRM_DISALLOWED_OPERATION; case MediaDrm.ErrorCodes.ERROR_INIT_DATA: case MediaDrm.ErrorCodes.ERROR_FRAME_TOO_LARGE: return PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR; default: return PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR; } } /** * @deprecated Use {@link #inferContentTypeForExtension(String)} when {@code overrideExtension} is * non-empty, and {@link #inferContentType(Uri)} otherwise. */ @Deprecated public static @ContentType int inferContentType(Uri uri, @Nullable String overrideExtension) { return TextUtils.isEmpty(overrideExtension) ? inferContentType(uri) : inferContentTypeForExtension(overrideExtension); } /** * Makes a best guess to infer the {@link ContentType} from a {@link Uri}. * * @param uri The {@link Uri}. * @return The content type. */ public static @ContentType int inferContentType(Uri uri) { @Nullable String scheme = uri.getScheme(); if (scheme != null && Ascii.equalsIgnoreCase("rtsp", scheme)) { return C.CONTENT_TYPE_RTSP; } @Nullable String lastPathSegment = uri.getLastPathSegment(); if (lastPathSegment == null) { return C.CONTENT_TYPE_OTHER; } int lastDotIndex = lastPathSegment.lastIndexOf('.'); if (lastDotIndex >= 0) { @C.ContentType int contentType = inferContentTypeForExtension(lastPathSegment.substring(lastDotIndex + 1)); if (contentType != C.CONTENT_TYPE_OTHER) { // If contentType is TYPE_SS that indicates the extension is .ism or .isml and shows the ISM // URI is missing the "/manifest" suffix, which contains the information used to // disambiguate between Smooth Streaming, HLS and DASH below - so we can just return TYPE_SS // here without further checks. return contentType; } } Matcher ismMatcher = ISM_PATH_PATTERN.matcher(checkNotNull(uri.getPath())); if (ismMatcher.matches()) { @Nullable String extensions = ismMatcher.group(2); if (extensions != null) { if (extensions.contains(ISM_DASH_FORMAT_EXTENSION)) { return C.CONTENT_TYPE_DASH; } else if (extensions.contains(ISM_HLS_FORMAT_EXTENSION)) { return C.CONTENT_TYPE_HLS; } } return C.CONTENT_TYPE_SS; } return C.CONTENT_TYPE_OTHER; } /** * @deprecated Use {@link Uri#parse(String)} and {@link #inferContentType(Uri)} for full file * paths or {@link #inferContentTypeForExtension(String)} for extensions. */ @Deprecated public static @ContentType int inferContentType(String fileName) { return inferContentType(Uri.parse("file:///" + fileName)); } /** * Makes a best guess to infer the {@link ContentType} from a file extension. * * @param fileExtension The extension of the file (excluding the '.'). * @return The content type. */ public static @ContentType int inferContentTypeForExtension(String fileExtension) { fileExtension = Ascii.toLowerCase(fileExtension); switch (fileExtension) { case "mpd": return C.CONTENT_TYPE_DASH; case "m3u8": return C.CONTENT_TYPE_HLS; case "ism": case "isml": return C.TYPE_SS; default: return C.CONTENT_TYPE_OTHER; } } /** * Makes a best guess to infer the {@link ContentType} from a {@link Uri} and optional MIME type. * * @param uri The {@link Uri}. * @param mimeType If MIME type, or {@code null}. * @return The content type. */ public static @ContentType int inferContentTypeForUriAndMimeType( Uri uri, @Nullable String mimeType) { if (mimeType == null) { return inferContentType(uri); } switch (mimeType) { case MimeTypes.APPLICATION_MPD: return C.CONTENT_TYPE_DASH; case MimeTypes.APPLICATION_M3U8: return C.CONTENT_TYPE_HLS; case MimeTypes.APPLICATION_SS: return C.CONTENT_TYPE_SS; case MimeTypes.APPLICATION_RTSP: return C.CONTENT_TYPE_RTSP; default: return C.CONTENT_TYPE_OTHER; } } /** * Returns the MIME type corresponding to the given adaptive {@link ContentType}, or {@code null} * if the content type is not adaptive. */ @Nullable public static String getAdaptiveMimeTypeForContentType(@ContentType int contentType) { switch (contentType) { case C.CONTENT_TYPE_DASH: return MimeTypes.APPLICATION_MPD; case C.CONTENT_TYPE_HLS: return MimeTypes.APPLICATION_M3U8; case C.CONTENT_TYPE_SS: return MimeTypes.APPLICATION_SS; case C.CONTENT_TYPE_RTSP: case C.CONTENT_TYPE_OTHER: default: return null; } } /** * If the provided URI is an ISM Presentation URI, returns the URI with "Manifest" appended to its * path (i.e., the corresponding default manifest URI). Else returns the provided URI without * modification. See [MS-SSTR] v20180912, section 2.2.1. * * @param uri The original URI. * @return The fixed URI. */ public static Uri fixSmoothStreamingIsmManifestUri(Uri uri) { @Nullable String path = uri.getPath(); if (path == null) { return uri; } Matcher ismMatcher = ISM_PATH_PATTERN.matcher(path); if (ismMatcher.matches() && ismMatcher.group(1) == null) { // Add missing "Manifest" suffix. return Uri.withAppendedPath(uri, "Manifest"); } return uri; } /** * Returns the specified millisecond time formatted as a string. * * @param builder The builder that {@code formatter} will write to. * @param formatter The formatter. * @param timeMs The time to format as a string, in milliseconds. * @return The time formatted as a string. */ public static String getStringForTime(StringBuilder builder, Formatter formatter, long timeMs) { if (timeMs == C.TIME_UNSET) { timeMs = 0; } String prefix = timeMs < 0 ? "-" : ""; timeMs = abs(timeMs); long totalSeconds = (timeMs + 500) / 1000; long seconds = totalSeconds % 60; long minutes = (totalSeconds / 60) % 60; long hours = totalSeconds / 3600; builder.setLength(0); return hours > 0 ? formatter.format("%s%d:%02d:%02d", prefix, hours, minutes, seconds).toString() : formatter.format("%s%02d:%02d", prefix, minutes, seconds).toString(); } /** * Escapes a string so that it's safe for use as a file or directory name on at least FAT32 * filesystems. FAT32 is the most restrictive of all filesystems still commonly used today. * * <p>For simplicity, this only handles common characters known to be illegal on FAT32: &lt;, * &gt;, :, ", /, \, |, ?, and *. % is also escaped since it is used as the escape character. * Escaping is performed in a consistent way so that no collisions occur and {@link * #unescapeFileName(String)} can be used to retrieve the original file name. * * @param fileName File name to be escaped. * @return An escaped file name which will be safe for use on at least FAT32 filesystems. */ public static String escapeFileName(String fileName) { int length = fileName.length(); int charactersToEscapeCount = 0; for (int i = 0; i < length; i++) { if (shouldEscapeCharacter(fileName.charAt(i))) { charactersToEscapeCount++; } } if (charactersToEscapeCount == 0) { return fileName; } int i = 0; StringBuilder builder = new StringBuilder(length + charactersToEscapeCount * 2); while (charactersToEscapeCount > 0) { char c = fileName.charAt(i++); if (shouldEscapeCharacter(c)) { builder.append('%').append(Integer.toHexString(c)); charactersToEscapeCount--; } else { builder.append(c); } } if (i < length) { builder.append(fileName, i, length); } return builder.toString(); } private static boolean shouldEscapeCharacter(char c) { switch (c) { case '<': case '>': case ':': case '"': case '/': case '\\': case '|': case '?': case '*': case '%': return true; default: return false; } } /** * Unescapes an escaped file or directory name back to its original value. * * <p>See {@link #escapeFileName(String)} for more information. * * @param fileName File name to be unescaped. * @return The original value of the file name before it was escaped, or null if the escaped * fileName seems invalid. */ @Nullable public static String unescapeFileName(String fileName) { int length = fileName.length(); int percentCharacterCount = 0; for (int i = 0; i < length; i++) { if (fileName.charAt(i) == '%') { percentCharacterCount++; } } if (percentCharacterCount == 0) { return fileName; } int expectedLength = length - percentCharacterCount * 2; StringBuilder builder = new StringBuilder(expectedLength); Matcher matcher = ESCAPED_CHARACTER_PATTERN.matcher(fileName); int startOfNotEscaped = 0; while (percentCharacterCount > 0 && matcher.find()) { char unescapedCharacter = (char) Integer.parseInt(checkNotNull(matcher.group(1)), 16); builder.append(fileName, startOfNotEscaped, matcher.start()).append(unescapedCharacter); startOfNotEscaped = matcher.end(); percentCharacterCount--; } if (startOfNotEscaped < length) { builder.append(fileName, startOfNotEscaped, length); } if (builder.length() != expectedLength) { return null; } return builder.toString(); } /** Returns a data URI with the specified MIME type and data. */ public static Uri getDataUriForString(String mimeType, String data) { return Uri.parse( "data:" + mimeType + ";base64," + Base64.encodeToString(data.getBytes(), Base64.NO_WRAP)); } /** * A hacky method that always throws {@code t} even if {@code t} is a checked exception, and is * not declared to be thrown. */ public static void sneakyThrow(Throwable t) { sneakyThrowInternal(t); } @SuppressWarnings("unchecked") private static <T extends Throwable> void sneakyThrowInternal(Throwable t) throws T { throw (T) t; } /** Recursively deletes a directory and its content. */ public static void recursiveDelete(File fileOrDirectory) { File[] directoryFiles = fileOrDirectory.listFiles(); if (directoryFiles != null) { for (File child : directoryFiles) { recursiveDelete(child); } } fileOrDirectory.delete(); } /** Creates an empty directory in the directory returned by {@link Context#getCacheDir()}. */ public static File createTempDirectory(Context context, String prefix) throws IOException { File tempFile = createTempFile(context, prefix); tempFile.delete(); // Delete the temp file. tempFile.mkdir(); // Create a directory with the same name. return tempFile; } /** Creates a new empty file in the directory returned by {@link Context#getCacheDir()}. */ public static File createTempFile(Context context, String prefix) throws IOException { return File.createTempFile(prefix, null, checkNotNull(context.getCacheDir())); } /** * Returns the result of updating a CRC-32 with the specified bytes in a "most significant bit * first" order. * * @param bytes Array containing the bytes to update the crc value with. * @param start The index to the first byte in the byte range to update the crc with. * @param end The index after the last byte in the byte range to update the crc with. * @param initialValue The initial value for the crc calculation. * @return The result of updating the initial value with the specified bytes. */ public static int crc32(byte[] bytes, int start, int end, int initialValue) { for (int i = start; i < end; i++) { initialValue = (initialValue << 8) ^ CRC32_BYTES_MSBF[((initialValue >>> 24) ^ (bytes[i] & 0xFF)) & 0xFF]; } return initialValue; } /** * Returns the result of updating a CRC-8 with the specified bytes in a "most significant bit * first" order. * * @param bytes Array containing the bytes to update the crc value with. * @param start The index to the first byte in the byte range to update the crc with. * @param end The index after the last byte in the byte range to update the crc with. * @param initialValue The initial value for the crc calculation. * @return The result of updating the initial value with the specified bytes. */ public static int crc8(byte[] bytes, int start, int end, int initialValue) { for (int i = start; i < end; i++) { initialValue = CRC8_BYTES_MSBF[initialValue ^ (bytes[i] & 0xFF)]; } return initialValue; } /** Compresses {@code input} using gzip and returns the result in a newly allocated byte array. */ public static byte[] gzip(byte[] input) { ByteArrayOutputStream output = new ByteArrayOutputStream(); try (GZIPOutputStream os = new GZIPOutputStream(output)) { os.write(input); } catch (IOException e) { // A ByteArrayOutputStream wrapped in a GZipOutputStream should never throw IOException since // no I/O is happening. throw new IllegalStateException(e); } return output.toByteArray(); } /** * Absolute <i>get</i> method for reading an int value in {@link ByteOrder#BIG_ENDIAN} in a {@link * ByteBuffer}. Same as {@link ByteBuffer#getInt(int)} except the buffer's order as returned by * {@link ByteBuffer#order()} is ignored and {@link ByteOrder#BIG_ENDIAN} is used instead. * * @param buffer The buffer from which to read an int in big endian. * @param index The index from which the bytes will be read. * @return The int value at the given index with the buffer bytes ordered most significant to * least significant. */ public static int getBigEndianInt(ByteBuffer buffer, int index) { int value = buffer.getInt(index); return buffer.order() == ByteOrder.BIG_ENDIAN ? value : Integer.reverseBytes(value); } /** * Returns the upper-case ISO 3166-1 alpha-2 country code of the current registered operator's MCC * (Mobile Country Code), or the country code of the default Locale if not available. * * @param context A context to access the telephony service. If null, only the Locale can be used. * @return The upper-case ISO 3166-1 alpha-2 country code, or an empty String if unavailable. */ public static String getCountryCode(@Nullable Context context) { if (context != null) { @Nullable TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { String countryCode = telephonyManager.getNetworkCountryIso(); if (!TextUtils.isEmpty(countryCode)) { return Ascii.toUpperCase(countryCode); } } } return Ascii.toUpperCase(Locale.getDefault().getCountry()); } /** * Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages * ordered by preference. */ public static String[] getSystemLanguageCodes() { String[] systemLocales = getSystemLocales(); for (int i = 0; i < systemLocales.length; i++) { systemLocales[i] = normalizeLanguageCode(systemLocales[i]); } return systemLocales; } /** Returns the default {@link Locale.Category#DISPLAY DISPLAY} {@link Locale}. */ public static Locale getDefaultDisplayLocale() { return SDK_INT >= 24 ? Locale.getDefault(Locale.Category.DISPLAY) : Locale.getDefault(); } /** * Uncompresses the data in {@code input}. * * @param input Wraps the compressed input data. * @param output Wraps an output buffer to be used to store the uncompressed data. If {@code * output.data} isn't big enough to hold the uncompressed data, a new array is created. If * {@code true} is returned then the output's position will be set to 0 and its limit will be * set to the length of the uncompressed data. * @param inflater If not null, used to uncompressed the input. Otherwise a new {@link Inflater} * is created. * @return Whether the input is uncompressed successfully. */ public static boolean inflate( ParsableByteArray input, ParsableByteArray output, @Nullable Inflater inflater) { if (input.bytesLeft() <= 0) { return false; } if (output.capacity() < input.bytesLeft()) { output.ensureCapacity(2 * input.bytesLeft()); } if (inflater == null) { inflater = new Inflater(); } inflater.setInput(input.getData(), input.getPosition(), input.bytesLeft()); try { int outputSize = 0; while (true) { outputSize += inflater.inflate(output.getData(), outputSize, output.capacity() - outputSize); if (inflater.finished()) { output.setLimit(outputSize); return true; } if (inflater.needsDictionary() || inflater.needsInput()) { return false; } if (outputSize == output.capacity()) { output.ensureCapacity(output.capacity() * 2); } } } catch (DataFormatException e) { return false; } finally { inflater.reset(); } } /** * Returns whether the app is running on a TV device. * * @param context Any context. * @return Whether the app is running on a TV device. */ public static boolean isTv(Context context) { // See https://developer.android.com/training/tv/start/hardware.html#runtime-check. @Nullable UiModeManager uiModeManager = (UiModeManager) context.getApplicationContext().getSystemService(UI_MODE_SERVICE); return uiModeManager != null && uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION; } /** * Returns whether the app is running on an automotive device. * * @param context Any context. * @return Whether the app is running on an automotive device. */ public static boolean isAutomotive(Context context) { return SDK_INT >= 23 && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); } /** * Gets the size of the current mode of the default display, in pixels. * * <p>Note that due to application UI scaling, the number of pixels made available to applications * (as reported by {@link Display#getSize(Point)} may differ from the mode's actual resolution (as * reported by this function). For example, applications running on a display configured with a 4K * mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take * advantage of the full mode resolution through a {@link SurfaceView} using full size buffers. * * @param context Any context. * @return The size of the current mode, in pixels. */ public static Point getCurrentDisplayModeSize(Context context) { @Nullable Display defaultDisplay = null; if (SDK_INT >= 17) { @Nullable DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); // We don't expect displayManager to ever be null, so this check is just precautionary. // Consider removing it when the library minSdkVersion is increased to 17 or higher. if (displayManager != null) { defaultDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY); } } if (defaultDisplay == null) { WindowManager windowManager = checkNotNull((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)); defaultDisplay = windowManager.getDefaultDisplay(); } return getCurrentDisplayModeSize(context, defaultDisplay); } /** * Gets the size of the current mode of the specified display, in pixels. * * <p>Note that due to application UI scaling, the number of pixels made available to applications * (as reported by {@link Display#getSize(Point)} may differ from the mode's actual resolution (as * reported by this function). For example, applications running on a display configured with a 4K * mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take * advantage of the full mode resolution through a {@link SurfaceView} using full size buffers. * * @param context Any context. * @param display The display whose size is to be returned. * @return The size of the current mode, in pixels. */ public static Point getCurrentDisplayModeSize(Context context, Display display) { if (display.getDisplayId() == Display.DEFAULT_DISPLAY && isTv(context)) { // On Android TVs it's common for the UI to be driven at a lower resolution than the physical // resolution of the display (e.g., driving the UI at 1080p when the display is 4K). // SurfaceView outputs are still able to use the full physical resolution on such devices. // // Prior to API level 26, the Display object did not provide a way to obtain the true physical // resolution of the display. From API level 26, Display.getMode().getPhysical[Width|Height] // is expected to return the display's true physical resolution, but we still see devices // setting their hardware compositor output size incorrectly, which makes this unreliable. // Hence for TV devices, we try and read the display's true physical resolution from system // properties. // // From API level 28, Treble may prevent the system from writing sys.display-size, so we check // vendor.display-size instead. @Nullable String displaySize = SDK_INT < 28 ? getSystemProperty("sys.display-size") : getSystemProperty("vendor.display-size"); // If we managed to read the display size, attempt to parse it. if (!TextUtils.isEmpty(displaySize)) { try { String[] displaySizeParts = split(displaySize.trim(), "x"); if (displaySizeParts.length == 2) { int width = Integer.parseInt(displaySizeParts[0]); int height = Integer.parseInt(displaySizeParts[1]); if (width > 0 && height > 0) { return new Point(width, height); } } } catch (NumberFormatException e) { // Do nothing. } Log.e(TAG, "Invalid display size: " + displaySize); } // Sony Android TVs advertise support for 4k output via a system feature. if ("Sony".equals(MANUFACTURER) && MODEL.startsWith("BRAVIA") && context.getPackageManager().hasSystemFeature("com.sony.dtv.hardware.panel.qfhd")) { return new Point(3840, 2160); } } Point displaySize = new Point(); if (SDK_INT >= 23) { getDisplaySizeV23(display, displaySize); } else if (SDK_INT >= 17) { getDisplaySizeV17(display, displaySize); } else { getDisplaySizeV16(display, displaySize); } return displaySize; } /** * Returns a string representation of a {@link C.TrackType}. * * @param trackType A {@link C.TrackType} constant, * @return A string representation of this constant. */ public static String getTrackTypeString(@C.TrackType int trackType) { switch (trackType) { case C.TRACK_TYPE_DEFAULT: return "default"; case C.TRACK_TYPE_AUDIO: return "audio"; case C.TRACK_TYPE_VIDEO: return "video"; case C.TRACK_TYPE_TEXT: return "text"; case C.TRACK_TYPE_IMAGE: return "image"; case C.TRACK_TYPE_METADATA: return "metadata"; case C.TRACK_TYPE_CAMERA_MOTION: return "camera motion"; case C.TRACK_TYPE_NONE: return "none"; case C.TRACK_TYPE_UNKNOWN: return "unknown"; default: return trackType >= C.TRACK_TYPE_CUSTOM_BASE ? "custom (" + trackType + ")" : "?"; } } /** * Returns the current time in milliseconds since the epoch. * * @param elapsedRealtimeEpochOffsetMs The offset between {@link SystemClock#elapsedRealtime()} * and the time since the Unix epoch, or {@link C#TIME_UNSET} if unknown. * @return The Unix time in milliseconds since the epoch. */ public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs) { return elapsedRealtimeEpochOffsetMs == C.TIME_UNSET ? System.currentTimeMillis() : SystemClock.elapsedRealtime() + elapsedRealtimeEpochOffsetMs; } /** * Moves the elements starting at {@code fromIndex} to {@code newFromIndex}. * * @param items The list of which to move elements. * @param fromIndex The index at which the items to move start. * @param toIndex The index up to which elements should be moved (exclusive). * @param newFromIndex The new from index. */ @SuppressWarnings("ExtendsObject") // See go/lsc-extends-object public static <T extends Object> void moveItems( List<T> items, int fromIndex, int toIndex, int newFromIndex) { ArrayDeque<T> removedItems = new ArrayDeque<>(); int removedItemsLength = toIndex - fromIndex; for (int i = removedItemsLength - 1; i >= 0; i--) { removedItems.addFirst(items.remove(fromIndex + i)); } items.addAll(min(newFromIndex, items.size()), removedItems); } /** Returns whether the table exists in the database. */ public static boolean tableExists(SQLiteDatabase database, String tableName) { long count = DatabaseUtils.queryNumEntries( database, "sqlite_master", "tbl_name = ?", new String[] {tableName}); return count > 0; } /** * Attempts to parse an error code from a diagnostic string found in framework media exceptions. * * <p>For example: android.media.MediaCodec.error_1 or android.media.MediaDrm.error_neg_2. * * @param diagnosticsInfo A string from which to parse the error code. * @return The parser error code, or 0 if an error code could not be parsed. */ public static int getErrorCodeFromPlatformDiagnosticsInfo(@Nullable String diagnosticsInfo) { // TODO (internal b/192337376): Change 0 for ERROR_UNKNOWN once available. if (diagnosticsInfo == null) { return 0; } String[] strings = split(diagnosticsInfo, "_"); int length = strings.length; if (length < 2) { return 0; } String digitsSection = strings[length - 1]; boolean isNegative = length >= 3 && "neg".equals(strings[length - 2]); try { int errorCode = Integer.parseInt(Assertions.checkNotNull(digitsSection)); return isNegative ? -errorCode : errorCode; } catch (NumberFormatException e) { return 0; } } /** * Returns string representation of a {@link C.FormatSupport} flag. * * @param formatSupport A {@link C.FormatSupport} flag. * @return A string representation of the flag. */ public static String getFormatSupportString(@C.FormatSupport int formatSupport) { switch (formatSupport) { case C.FORMAT_HANDLED: return "YES"; case C.FORMAT_EXCEEDS_CAPABILITIES: return "NO_EXCEEDS_CAPABILITIES"; case C.FORMAT_UNSUPPORTED_DRM: return "NO_UNSUPPORTED_DRM"; case C.FORMAT_UNSUPPORTED_SUBTYPE: return "NO_UNSUPPORTED_TYPE"; case C.FORMAT_UNSUPPORTED_TYPE: return "NO"; default: throw new IllegalStateException(); } } /** * Returns the {@link Commands} available in the {@link Player}. * * @param player The {@link Player}. * @param permanentAvailableCommands The commands permanently available in the player. * @return The available {@link Commands}. */ public static Commands getAvailableCommands(Player player, Commands permanentAvailableCommands) { boolean isPlayingAd = player.isPlayingAd(); boolean isCurrentMediaItemSeekable = player.isCurrentMediaItemSeekable(); boolean hasPreviousMediaItem = player.hasPreviousMediaItem(); boolean hasNextMediaItem = player.hasNextMediaItem(); boolean isCurrentMediaItemLive = player.isCurrentMediaItemLive(); boolean isCurrentMediaItemDynamic = player.isCurrentMediaItemDynamic(); boolean isTimelineEmpty = player.getCurrentTimeline().isEmpty(); return new Commands.Builder() .addAll(permanentAvailableCommands) .addIf(COMMAND_SEEK_TO_DEFAULT_POSITION, !isPlayingAd) .addIf(COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM, isCurrentMediaItemSeekable && !isPlayingAd) .addIf(COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM, hasPreviousMediaItem && !isPlayingAd) .addIf( COMMAND_SEEK_TO_PREVIOUS, !isTimelineEmpty && (hasPreviousMediaItem || !isCurrentMediaItemLive || isCurrentMediaItemSeekable) && !isPlayingAd) .addIf(COMMAND_SEEK_TO_NEXT_MEDIA_ITEM, hasNextMediaItem && !isPlayingAd) .addIf( COMMAND_SEEK_TO_NEXT, !isTimelineEmpty && (hasNextMediaItem || (isCurrentMediaItemLive && isCurrentMediaItemDynamic)) && !isPlayingAd) .addIf(COMMAND_SEEK_TO_MEDIA_ITEM, !isPlayingAd) .addIf(COMMAND_SEEK_BACK, isCurrentMediaItemSeekable && !isPlayingAd) .addIf(COMMAND_SEEK_FORWARD, isCurrentMediaItemSeekable && !isPlayingAd) .build(); } /** * Returns the sum of all summands of the given array. * * @param summands The summands to calculate the sum from. * @return The sum of all summands. */ public static long sum(long... summands) { long sum = 0; for (long summand : summands) { sum += summand; } return sum; } /** * Returns a {@link Drawable} for the given resource or throws a {@link * Resources.NotFoundException} if not found. * * @param context The context to get the theme from starting with API 21. * @param resources The resources to load the drawable from. * @param drawableRes The drawable resource int. * @return The loaded {@link Drawable}. */ public static Drawable getDrawable( Context context, Resources resources, @DrawableRes int drawableRes) { return SDK_INT >= 21 ? Api21.getDrawable(context, resources, drawableRes) : resources.getDrawable(drawableRes); } /** * Returns a string representation of the integer using radix value {@link Character#MAX_RADIX}. * * @param i An integer to be converted to String. */ public static String intToStringMaxRadix(int i) { return Integer.toString(i, Character.MAX_RADIX); } @Nullable private static String getSystemProperty(String name) { try { @SuppressLint("PrivateApi") Class<?> systemProperties = Class.forName("android.os.SystemProperties"); Method getMethod = systemProperties.getMethod("get", String.class); return (String) getMethod.invoke(systemProperties, name); } catch (Exception e) { Log.e(TAG, "Failed to read system property " + name, e); return null; } } @RequiresApi(23) private static void getDisplaySizeV23(Display display, Point outSize) { Display.Mode mode = display.getMode(); outSize.x = mode.getPhysicalWidth(); outSize.y = mode.getPhysicalHeight(); } @RequiresApi(17) private static void getDisplaySizeV17(Display display, Point outSize) { display.getRealSize(outSize); } private static void getDisplaySizeV16(Display display, Point outSize) { display.getSize(outSize); } private static String[] getSystemLocales() { Configuration config = Resources.getSystem().getConfiguration(); return SDK_INT >= 24 ? getSystemLocalesV24(config) : new String[] {getLocaleLanguageTag(config.locale)}; } @RequiresApi(24) private static String[] getSystemLocalesV24(Configuration config) { return split(config.getLocales().toLanguageTags(), ","); } @RequiresApi(21) private static String getLocaleLanguageTagV21(Locale locale) { return locale.toLanguageTag(); } private static HashMap<String, String> createIsoLanguageReplacementMap() { String[] iso2Languages = Locale.getISOLanguages(); HashMap<String, String> replacedLanguages = new HashMap<>( /* initialCapacity= */ iso2Languages.length + additionalIsoLanguageReplacements.length); for (String iso2 : iso2Languages) { try { // This returns the ISO 639-2/T code for the language. String iso3 = new Locale(iso2).getISO3Language(); if (!TextUtils.isEmpty(iso3)) { replacedLanguages.put(iso3, iso2); } } catch (MissingResourceException e) { // Shouldn't happen for list of known languages, but we don't want to throw either. } } // Add additional replacement mappings. for (int i = 0; i < additionalIsoLanguageReplacements.length; i += 2) { replacedLanguages.put( additionalIsoLanguageReplacements[i], additionalIsoLanguageReplacements[i + 1]); } return replacedLanguages; } @RequiresApi(api = Build.VERSION_CODES.M) private static boolean requestExternalStoragePermission(Activity activity) { if (Build.VERSION.SDK_INT >= 33) { ArrayList<String> permissions = new ArrayList<>(); if (activity.checkSelfPermission(permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) { permissions.add(permission.READ_MEDIA_VIDEO); } if (activity.checkSelfPermission(permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) { permissions.add(permission.READ_MEDIA_IMAGES); } if (activity.checkSelfPermission(permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) { permissions.add(permission.READ_MEDIA_AUDIO); } if (!permissions.isEmpty()) { activity.requestPermissions(permissions.toArray(new String[0]), /* requestCode= */ 0); return true; } return false; } else { if (activity.checkSelfPermission(permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions( new String[]{permission.READ_EXTERNAL_STORAGE}, /* requestCode= */ 0); return true; } return false; } } @RequiresApi(api = Build.VERSION_CODES.N) private static boolean isTrafficRestricted(Uri uri) { return "http".equals(uri.getScheme()) && !NetworkSecurityPolicy.getInstance() .isCleartextTrafficPermitted(checkNotNull(uri.getHost())); } private static String maybeReplaceLegacyLanguageTags(String languageTag) { for (int i = 0; i < isoLegacyTagReplacements.length; i += 2) { if (languageTag.startsWith(isoLegacyTagReplacements[i])) { return isoLegacyTagReplacements[i + 1] + languageTag.substring(/* beginIndex= */ isoLegacyTagReplacements[i].length()); } } return languageTag; } // Additional mapping from ISO3 to ISO2 language codes. private static final String[] additionalIsoLanguageReplacements = new String[] { // Bibliographical codes defined in ISO 639-2/B, replaced by terminological code defined in // ISO 639-2/T. See https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes. "alb", "sq", "arm", "hy", "baq", "eu", "bur", "my", "tib", "bo", "chi", "zh", "cze", "cs", "dut", "nl", "ger", "de", "gre", "el", "fre", "fr", "geo", "ka", "ice", "is", "mac", "mk", "mao", "mi", "may", "ms", "per", "fa", "rum", "ro", "scc", "hbs-srp", "slo", "sk", "wel", "cy", // Deprecated 2-letter codes, replaced by modern equivalent (including macrolanguage) // See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes, "ISO 639:1988" "id", "ms-ind", "iw", "he", "heb", "he", "ji", "yi", // Individual macrolanguage codes mapped back to full macrolanguage code. // See https://en.wikipedia.org/wiki/ISO_639_macrolanguage "arb", "ar-arb", "in", "ms-ind", "ind", "ms-ind", "nb", "no-nob", "nob", "no-nob", "nn", "no-nno", "nno", "no-nno", "tw", "ak-twi", "twi", "ak-twi", "bs", "hbs-bos", "bos", "hbs-bos", "hr", "hbs-hrv", "hrv", "hbs-hrv", "sr", "hbs-srp", "srp", "hbs-srp", "cmn", "zh-cmn", "hak", "zh-hak", "nan", "zh-nan", "hsn", "zh-hsn" }; // Legacy tags that have been replaced by modern equivalents (including macrolanguage) // See https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry. private static final String[] isoLegacyTagReplacements = new String[] { "i-lux", "lb", "i-hak", "zh-hak", "i-navajo", "nv", "no-bok", "no-nob", "no-nyn", "no-nno", "zh-guoyu", "zh-cmn", "zh-hakka", "zh-hak", "zh-min-nan", "zh-nan", "zh-xiang", "zh-hsn" }; /** * Allows the CRC-32 calculation to be done byte by byte instead of bit per bit in the order "most * significant bit first". */ private static final int[] CRC32_BYTES_MSBF = { 0X00000000, 0X04C11DB7, 0X09823B6E, 0X0D4326D9, 0X130476DC, 0X17C56B6B, 0X1A864DB2, 0X1E475005, 0X2608EDB8, 0X22C9F00F, 0X2F8AD6D6, 0X2B4BCB61, 0X350C9B64, 0X31CD86D3, 0X3C8EA00A, 0X384FBDBD, 0X4C11DB70, 0X48D0C6C7, 0X4593E01E, 0X4152FDA9, 0X5F15ADAC, 0X5BD4B01B, 0X569796C2, 0X52568B75, 0X6A1936C8, 0X6ED82B7F, 0X639B0DA6, 0X675A1011, 0X791D4014, 0X7DDC5DA3, 0X709F7B7A, 0X745E66CD, 0X9823B6E0, 0X9CE2AB57, 0X91A18D8E, 0X95609039, 0X8B27C03C, 0X8FE6DD8B, 0X82A5FB52, 0X8664E6E5, 0XBE2B5B58, 0XBAEA46EF, 0XB7A96036, 0XB3687D81, 0XAD2F2D84, 0XA9EE3033, 0XA4AD16EA, 0XA06C0B5D, 0XD4326D90, 0XD0F37027, 0XDDB056FE, 0XD9714B49, 0XC7361B4C, 0XC3F706FB, 0XCEB42022, 0XCA753D95, 0XF23A8028, 0XF6FB9D9F, 0XFBB8BB46, 0XFF79A6F1, 0XE13EF6F4, 0XE5FFEB43, 0XE8BCCD9A, 0XEC7DD02D, 0X34867077, 0X30476DC0, 0X3D044B19, 0X39C556AE, 0X278206AB, 0X23431B1C, 0X2E003DC5, 0X2AC12072, 0X128E9DCF, 0X164F8078, 0X1B0CA6A1, 0X1FCDBB16, 0X018AEB13, 0X054BF6A4, 0X0808D07D, 0X0CC9CDCA, 0X7897AB07, 0X7C56B6B0, 0X71159069, 0X75D48DDE, 0X6B93DDDB, 0X6F52C06C, 0X6211E6B5, 0X66D0FB02, 0X5E9F46BF, 0X5A5E5B08, 0X571D7DD1, 0X53DC6066, 0X4D9B3063, 0X495A2DD4, 0X44190B0D, 0X40D816BA, 0XACA5C697, 0XA864DB20, 0XA527FDF9, 0XA1E6E04E, 0XBFA1B04B, 0XBB60ADFC, 0XB6238B25, 0XB2E29692, 0X8AAD2B2F, 0X8E6C3698, 0X832F1041, 0X87EE0DF6, 0X99A95DF3, 0X9D684044, 0X902B669D, 0X94EA7B2A, 0XE0B41DE7, 0XE4750050, 0XE9362689, 0XEDF73B3E, 0XF3B06B3B, 0XF771768C, 0XFA325055, 0XFEF34DE2, 0XC6BCF05F, 0XC27DEDE8, 0XCF3ECB31, 0XCBFFD686, 0XD5B88683, 0XD1799B34, 0XDC3ABDED, 0XD8FBA05A, 0X690CE0EE, 0X6DCDFD59, 0X608EDB80, 0X644FC637, 0X7A089632, 0X7EC98B85, 0X738AAD5C, 0X774BB0EB, 0X4F040D56, 0X4BC510E1, 0X46863638, 0X42472B8F, 0X5C007B8A, 0X58C1663D, 0X558240E4, 0X51435D53, 0X251D3B9E, 0X21DC2629, 0X2C9F00F0, 0X285E1D47, 0X36194D42, 0X32D850F5, 0X3F9B762C, 0X3B5A6B9B, 0X0315D626, 0X07D4CB91, 0X0A97ED48, 0X0E56F0FF, 0X1011A0FA, 0X14D0BD4D, 0X19939B94, 0X1D528623, 0XF12F560E, 0XF5EE4BB9, 0XF8AD6D60, 0XFC6C70D7, 0XE22B20D2, 0XE6EA3D65, 0XEBA91BBC, 0XEF68060B, 0XD727BBB6, 0XD3E6A601, 0XDEA580D8, 0XDA649D6F, 0XC423CD6A, 0XC0E2D0DD, 0XCDA1F604, 0XC960EBB3, 0XBD3E8D7E, 0XB9FF90C9, 0XB4BCB610, 0XB07DABA7, 0XAE3AFBA2, 0XAAFBE615, 0XA7B8C0CC, 0XA379DD7B, 0X9B3660C6, 0X9FF77D71, 0X92B45BA8, 0X9675461F, 0X8832161A, 0X8CF30BAD, 0X81B02D74, 0X857130C3, 0X5D8A9099, 0X594B8D2E, 0X5408ABF7, 0X50C9B640, 0X4E8EE645, 0X4A4FFBF2, 0X470CDD2B, 0X43CDC09C, 0X7B827D21, 0X7F436096, 0X7200464F, 0X76C15BF8, 0X68860BFD, 0X6C47164A, 0X61043093, 0X65C52D24, 0X119B4BE9, 0X155A565E, 0X18197087, 0X1CD86D30, 0X029F3D35, 0X065E2082, 0X0B1D065B, 0X0FDC1BEC, 0X3793A651, 0X3352BBE6, 0X3E119D3F, 0X3AD08088, 0X2497D08D, 0X2056CD3A, 0X2D15EBE3, 0X29D4F654, 0XC5A92679, 0XC1683BCE, 0XCC2B1D17, 0XC8EA00A0, 0XD6AD50A5, 0XD26C4D12, 0XDF2F6BCB, 0XDBEE767C, 0XE3A1CBC1, 0XE760D676, 0XEA23F0AF, 0XEEE2ED18, 0XF0A5BD1D, 0XF464A0AA, 0XF9278673, 0XFDE69BC4, 0X89B8FD09, 0X8D79E0BE, 0X803AC667, 0X84FBDBD0, 0X9ABC8BD5, 0X9E7D9662, 0X933EB0BB, 0X97FFAD0C, 0XAFB010B1, 0XAB710D06, 0XA6322BDF, 0XA2F33668, 0XBCB4666D, 0XB8757BDA, 0XB5365D03, 0XB1F740B4 }; /** * Allows the CRC-8 calculation to be done byte by byte instead of bit per bit in the order "most * significant bit first". */ private static final int[] CRC8_BYTES_MSBF = { 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D, 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D, 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD, 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD, 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA, 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A, 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A, 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A, 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4, 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4, 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44, 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34, 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63, 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13, 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83, 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3 }; @RequiresApi(21) private static final class Api21 { @DoNotInline public static Drawable getDrawable(Context context, Resources resources, @DrawableRes int res) { return resources.getDrawable(res, context.getTheme()); } } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/com/google/android/exoplayer2/util/Util.java
2,351
/* * 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.hadoop.hbase.client; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.io.TimeRange; import org.apache.hadoop.hbase.security.access.Permission; import org.apache.hadoop.hbase.security.visibility.Authorizations; import org.apache.hadoop.hbase.util.Bytes; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used to perform Get operations on a single row. * <p> * To get everything for a row, instantiate a Get object with the row to get. To further narrow the * scope of what to Get, use the methods below. * <p> * To get all columns from specific families, execute {@link #addFamily(byte[]) addFamily} for each * family to retrieve. * <p> * To get specific columns, execute {@link #addColumn(byte[], byte[]) addColumn} for each column to * retrieve. * <p> * To only retrieve columns within a specific range of version timestamps, execute * {@link #setTimeRange(long, long) setTimeRange}. * <p> * To only retrieve columns with a specific timestamp, execute {@link #setTimestamp(long) * setTimestamp}. * <p> * To limit the number of versions of each column to be returned, execute {@link #readVersions(int) * readVersions}. * <p> * To add a filter, call {@link #setFilter(Filter) setFilter}. */ @InterfaceAudience.Public public class Get extends Query implements Row { private static final Logger LOG = LoggerFactory.getLogger(Get.class); private byte[] row = null; private int maxVersions = 1; private boolean cacheBlocks = true; private int storeLimit = -1; private int storeOffset = 0; private TimeRange tr = TimeRange.allTime(); private boolean checkExistenceOnly = false; private Map<byte[], NavigableSet<byte[]>> familyMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); /** * Create a Get operation for the specified row. * <p> * If no further operations are done, this will get the latest version of all columns in all * families of the specified row. * @param row row key */ public Get(byte[] row) { Mutation.checkRow(row); this.row = row; } /** * Copy-constructor */ public Get(Get get) { this(get.getRow()); // from Query this.setFilter(get.getFilter()); this.setReplicaId(get.getReplicaId()); this.setConsistency(get.getConsistency()); // from Get this.cacheBlocks = get.getCacheBlocks(); this.maxVersions = get.getMaxVersions(); this.storeLimit = get.getMaxResultsPerColumnFamily(); this.storeOffset = get.getRowOffsetPerColumnFamily(); this.tr = get.getTimeRange(); this.checkExistenceOnly = get.isCheckExistenceOnly(); this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue(); Map<byte[], NavigableSet<byte[]>> fams = get.getFamilyMap(); for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) { byte[] fam = entry.getKey(); NavigableSet<byte[]> cols = entry.getValue(); if (cols != null && cols.size() > 0) { for (byte[] col : cols) { addColumn(fam, col); } } else { addFamily(fam); } } for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) { setAttribute(attr.getKey(), attr.getValue()); } for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) { TimeRange tr = entry.getValue(); setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); } super.setPriority(get.getPriority()); } /** * Create a Get operation for the specified row. */ public Get(byte[] row, int rowOffset, int rowLength) { Mutation.checkRow(row, rowOffset, rowLength); this.row = Bytes.copy(row, rowOffset, rowLength); } /** * Create a Get operation for the specified row. */ public Get(ByteBuffer row) { Mutation.checkRow(row); this.row = new byte[row.remaining()]; row.get(this.row); } public boolean isCheckExistenceOnly() { return checkExistenceOnly; } public Get setCheckExistenceOnly(boolean checkExistenceOnly) { this.checkExistenceOnly = checkExistenceOnly; return this; } /** * Get all columns from the specified family. * <p> * Overrides previous calls to addColumn for this family. * @param family family name * @return the Get object */ public Get addFamily(byte[] family) { familyMap.remove(family); familyMap.put(family, null); return this; } /** * Get the column from the specific family with the specified qualifier. * <p> * Overrides previous calls to addFamily for this family. * @param family family name * @param qualifier column qualifier * @return the Get objec */ public Get addColumn(byte[] family, byte[] qualifier) { NavigableSet<byte[]> set = familyMap.get(family); if (set == null) { set = new TreeSet<>(Bytes.BYTES_COMPARATOR); familyMap.put(family, set); } if (qualifier == null) { qualifier = HConstants.EMPTY_BYTE_ARRAY; } set.add(qualifier); return this; } /** * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp). * @param minStamp minimum timestamp value, inclusive * @param maxStamp maximum timestamp value, exclusive * @return this for invocation chaining */ public Get setTimeRange(long minStamp, long maxStamp) throws IOException { tr = TimeRange.between(minStamp, maxStamp); return this; } /** * Get versions of columns with the specified timestamp. * @param timestamp version timestamp * @return this for invocation chaining */ public Get setTimestamp(long timestamp) { try { tr = TimeRange.at(timestamp); } catch (Exception e) { // This should never happen, unless integer overflow or something extremely wrong... LOG.error("TimeRange failed, likely caused by integer overflow. ", e); throw e; } return this; } @Override public Get setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) { return (Get) super.setColumnFamilyTimeRange(cf, minStamp, maxStamp); } /** * Get all available versions. * @return this for invocation chaining */ public Get readAllVersions() { this.maxVersions = Integer.MAX_VALUE; return this; } /** * Get up to the specified number of versions of each column. * @param versions specified number of versions for each column * @throws IOException if invalid number of versions * @return this for invocation chaining */ public Get readVersions(int versions) throws IOException { if (versions <= 0) { throw new IOException("versions must be positive"); } this.maxVersions = versions; return this; } @Override public Get setLoadColumnFamiliesOnDemand(boolean value) { return (Get) super.setLoadColumnFamiliesOnDemand(value); } /** * Set the maximum number of values to return per row per Column Family * @param limit the maximum number of values returned / row / CF * @return this for invocation chaining */ public Get setMaxResultsPerColumnFamily(int limit) { this.storeLimit = limit; return this; } /** * Set offset for the row per Column Family. This offset is only within a particular row/CF * combination. It gets reset back to zero when we move to the next row or CF. * @param offset is the number of kvs that will be skipped. * @return this for invocation chaining */ public Get setRowOffsetPerColumnFamily(int offset) { this.storeOffset = offset; return this; } @Override public Get setFilter(Filter filter) { super.setFilter(filter); return this; } /* Accessors */ /** * Set whether blocks should be cached for this Get. * <p> * This is true by default. When true, default settings of the table and family are used (this * will never override caching blocks if the block cache is disabled for that family or entirely). * @param cacheBlocks if false, default settings are overridden and blocks will not be cached */ public Get setCacheBlocks(boolean cacheBlocks) { this.cacheBlocks = cacheBlocks; return this; } /** * Get whether blocks should be cached for this Get. * @return true if default caching should be used, false if blocks should not be cached */ public boolean getCacheBlocks() { return cacheBlocks; } /** * Method for retrieving the get's row */ @Override public byte[] getRow() { return this.row; } /** * Method for retrieving the get's maximum number of version * @return the maximum number of version to fetch for this get */ public int getMaxVersions() { return this.maxVersions; } /** * Method for retrieving the get's maximum number of values to return per Column Family * @return the maximum number of values to fetch per CF */ public int getMaxResultsPerColumnFamily() { return this.storeLimit; } /** * Method for retrieving the get's offset per row per column family (#kvs to be skipped) * @return the row offset */ public int getRowOffsetPerColumnFamily() { return this.storeOffset; } /** * Method for retrieving the get's TimeRange */ public TimeRange getTimeRange() { return this.tr; } /** * Method for retrieving the keys in the familyMap * @return keys in the current familyMap */ public Set<byte[]> familySet() { return this.familyMap.keySet(); } /** * Method for retrieving the number of families to get from * @return number of families */ public int numFamilies() { return this.familyMap.size(); } /** * Method for checking if any families have been inserted into this Get * @return true if familyMap is non empty false otherwise */ public boolean hasFamilies() { return !this.familyMap.isEmpty(); } /** * Method for retrieving the get's familyMap */ public Map<byte[], NavigableSet<byte[]>> getFamilyMap() { return this.familyMap; } /** * Compile the table and column family (i.e. schema) information into a String. Useful for parsing * and aggregation by debugging, logging, and administration tools. */ @Override public Map<String, Object> getFingerprint() { Map<String, Object> map = new HashMap<>(); List<String> families = new ArrayList<>(this.familyMap.entrySet().size()); map.put("families", families); for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { families.add(Bytes.toStringBinary(entry.getKey())); } return map; } /** * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a * Map along with the fingerprinted information. Useful for debugging, logging, and administration * tools. * @param maxCols a limit on the number of columns output prior to truncation */ @Override public Map<String, Object> toMap(int maxCols) { // we start with the fingerprint map and build on top of it. Map<String, Object> map = getFingerprint(); // replace the fingerprint's simple list of families with a // map from column families to lists of qualifiers and kv details Map<String, List<String>> columns = new HashMap<>(); map.put("families", columns); // add scalar information first map.put("row", Bytes.toStringBinary(this.row)); map.put("maxVersions", this.maxVersions); map.put("cacheBlocks", this.cacheBlocks); List<Long> timeRange = new ArrayList<>(2); timeRange.add(this.tr.getMin()); timeRange.add(this.tr.getMax()); map.put("timeRange", timeRange); int colCount = 0; // iterate through affected families and add details for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { List<String> familyList = new ArrayList<>(); columns.put(Bytes.toStringBinary(entry.getKey()), familyList); if (entry.getValue() == null) { colCount++; --maxCols; familyList.add("ALL"); } else { colCount += entry.getValue().size(); if (maxCols <= 0) { continue; } for (byte[] column : entry.getValue()) { if (--maxCols <= 0) { continue; } familyList.add(Bytes.toStringBinary(column)); } } } map.put("totalColumns", colCount); if (this.filter != null) { map.put("filter", this.filter.toString()); } // add the id if set if (getId() != null) { map.put("id", getId()); } map.put("storeLimit", this.storeLimit); map.put("storeOffset", this.storeOffset); map.put("checkExistenceOnly", this.checkExistenceOnly); map.put("targetReplicaId", this.targetReplicaId); map.put("consistency", this.consistency); map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand); if (!colFamTimeRangeMap.isEmpty()) { Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream() .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> { TimeRange value = e.getValue(); List<Long> rangeList = new ArrayList<>(); rangeList.add(value.getMin()); rangeList.add(value.getMax()); return rangeList; })); map.put("colFamTimeRangeMap", colFamTimeRangeMapStr); } map.put("priority", getPriority()); return map; } @Override public int hashCode() { // TODO: This is wrong. Can't have two gets the same just because on same row. But it // matches how equals works currently and gets rid of the findbugs warning. return Bytes.hashCode(this.getRow()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Row)) { return false; } Row other = (Row) obj; // TODO: This is wrong. Can't have two gets the same just because on same row. return Row.COMPARATOR.compare(this, other) == 0; } @Override public Get setAttribute(String name, byte[] value) { return (Get) super.setAttribute(name, value); } @Override public Get setId(String id) { return (Get) super.setId(id); } @Override public Get setAuthorizations(Authorizations authorizations) { return (Get) super.setAuthorizations(authorizations); } @Override public Get setACL(Map<String, Permission> perms) { return (Get) super.setACL(perms); } @Override public Get setACL(String user, Permission perms) { return (Get) super.setACL(user, perms); } @Override public Get setConsistency(Consistency consistency) { return (Get) super.setConsistency(consistency); } @Override public Get setReplicaId(int Id) { return (Get) super.setReplicaId(Id); } @Override public Get setIsolationLevel(IsolationLevel level) { return (Get) super.setIsolationLevel(level); } @Override public Get setPriority(int priority) { return (Get) super.setPriority(priority); } }
apache/hbase
hbase-client/src/main/java/org/apache/hadoop/hbase/client/Get.java
2,352
package com.fishercoder.solutions; public class _1266 { public static class Solution1 { /** * Time: O(n) * Space: O(1) * <p> * credit: https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/436142/Sum-of-Chebyshev-distance-between-two-consecutive-points */ public int minTimeToVisitAllPoints(int[][] points) { int minTime = 0; for (int i = 0; i < points.length - 1; i++) { minTime += chebyshevDistance(points[i], points[i + 1]); } return minTime; } private int chebyshevDistance(int[] pointA, int[] pointB) { return Math.max(Math.abs(pointA[0] - pointB[0]), Math.abs(pointA[1] - pointB[1])); } } }
fishercoder1534/Leetcode
src/main/java/com/fishercoder/solutions/_1266.java
2,353
package io.quarkus.qute; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Provides quick and convenient access to the engine instance stored in a static variable. If a specific engine instance is not * set via the {@link #setEngine(Engine)} method a default engine is created lazily. * <p> * Moreover, the convenient {@code fmt()} methods that can be used to format messages easily. * * <pre> * Qute.fmt("Hello {}!", "Quarkus"); * // => Hello Quarkus! * * Qute.fmt("Hello {name} {surname ?: 'Default'}!", Map.of("name", "Martin")); * // => Hello Martin Default! * * Qute.fmt("&lt;html&gt;{header}&lt;/html&gt;").contentType("text/html").data("header", "&lt;h1&gt;Header&lt;/h1&gt;").render(); * // &lt;html&gt;{@literal &lt;}h1{@literal &gt;}Header{@literal &lt;}/h1{@literal &gt;}&lt;/html&gt; * // Note that for a "text/html" template the special chars are replaced with html entities by default. * </pre> * * @see #fmt(String) * @see #fmt(String, Map) * @see #fmt(String, Object...) */ public final class Qute { /** * If needed, a default engine is created lazily. * <p> * The default engine has in addition to {@link EngineBuilder#addDefaults()}: * <ul> * <li>{@link ReflectionValueResolver}</li> * <li>{@link IndexedArgumentsParserHook}</li> * <li>{@link HtmlEscaper} registered for {@code text/html} and {@code text/xml} content types</li> * </ul> * * @return the engine * @see #setEngine(Engine) */ public static Engine engine() { Engine engine = Qute.engine; if (engine == null) { synchronized (Qute.class) { if (engine == null) { engine = newDefaultEngine(); Qute.engine = engine; } } } return engine; } /** * Set a specific engine instance. * <p> * Note that the engine should have a {@link IndexedArgumentsParserHook} registered so that the * {@link #fmt(String, Object...)} method works correcly. * <p> * The cache is always cleared when a new engine is set. * * @param engine * @see #engine() */ public static void setEngine(Engine engine) { clearCache(); Qute.engine = engine; } /** * * @param template * @param data * @return the rendered template */ public static String fmt(String template, Map<String, Object> data) { return fmt(template).dataMap(data).render(); } /** * The data array is accessibe via the {@code data} key, e.g. {data[0]} is resolved to the first argument. * <p> * An empty expression <code>{}</code> is a placeholder that is replaced with an index-based array accessor * <code>{data[n]}</code> where {@code n} is the index of the placeholder. The first placeholder is replace with * <code>{data[0]}</code>, the second with <code>{data[1]}</code>, and so on. For example, <code>"Hello {}!"</code> becomes * <code>Hello {data[0]}!</code>. * * @param template * @param data * @return the rendered template */ public static String fmt(String template, Object... data) { return fmt(template).dataArray(data).render(); } /** * * @param template * @return a new format object */ public static Fmt fmt(String template) { return new Fmt(template); } /** * The template cache will be used by default. * * @see Fmt#cache() * @see #clearCache() */ public static void enableCache() { cacheByDefault = true; } /** * The template cache will not be used by default. * * @see Fmt#noCache() * @see #clearCache() */ public static void disableCache() { cacheByDefault = false; } /** * Clears the template cache. */ public static void clearCache() { CACHE.clear(); } /** * This construct is not thread-safe. */ public final static class Fmt { private final String template; private Map<String, Object> attributes; private Map<String, Object> dataMap; private boolean cache; private Variant variant; Fmt(String template) { this.template = template; this.cache = cacheByDefault; this.variant = PLAIN_TEXT; this.dataMap = new HashMap<>(); } /** * Use the template cache, i.e. first attempt to find the parsed template in the cache and if not found then parse the * template and store the instance in the cache. * <p> * Note that caching greatly improves the performance of formatting, albeit increases the memory usage. * * @return self * @see Qute#clearCache() */ public Fmt cache() { this.cache = true; return this; } /** * Do not use the cache, i.e. always parse the template. * * @return self */ public Fmt noCache() { this.cache = false; return this; } /** * Set the template content type. * * @return self * @see Variant */ public Fmt contentType(String contentType) { this.variant = Variant.forContentType(contentType); return this; } /** * Set the template variant. * * @return self * @see Variant */ public Fmt variant(Variant variant) { this.variant = variant; return this; } /** * Set the template instance attribute. * * @return self * @see TemplateInstance#setAttribute(String, Object) */ public Fmt attribute(String key, Object value) { if (attributes == null) { attributes = new HashMap<>(); } this.attributes.put(key, value); return this; } /** * The data array is accessibe via the {@code data} key, e.g. {data[0]} is resolved to the first argument. * <p> * An empty expression <code>{}</code> is a placeholder that is replaced with an index-based array accessor * <code>{data[n]}</code> where {@code n} is the index of the placeholder. The first placeholder is replace with * <code>{data[0]}</code>, the second with <code>{data[1]}</code>, and so on. For example, <code>"Hello {}!"</code> * becomes <code>Hello {data[0]}!</code>. * * @param data * @return self */ public Fmt dataArray(Object... data) { dataMap.put("data", data); return this; } public Fmt dataMap(Map<String, Object> data) { dataMap.putAll(data); return this; } public Fmt data(String key, Object data) { dataMap.put(key, data); return this; } /** * * @return the rendered template */ public String render() { return instance().render(); } /** * * @return a new template instance */ public TemplateInstance instance() { Engine engine = engine(); Template parsed; if (cache) { parsed = CACHE.computeIfAbsent(hashKey(template), key -> { String id = newId(); return engine.parse(template, variant, id); }); } else { parsed = engine.parse(template, variant, newId()); } TemplateInstance instance = parsed.instance(); if (attributes != null) { attributes.forEach(instance::setAttribute); } dataMap.forEach(instance::data); return instance; } @Override public String toString() { return render(); } } public static class IndexedArgumentsParserHook implements ParserHook { private final Pattern p = Pattern.compile("\\{\\}"); private final String prefix; public IndexedArgumentsParserHook() { this(TEMPLATE_PREFIX); } public IndexedArgumentsParserHook(String prefix) { this.prefix = prefix; } @Override public void beforeParsing(ParserHelper parserHelper) { if (prefix != null && !parserHelper.getTemplateId().startsWith(prefix)) { return; } parserHelper.addContentFilter(new Function<String, String>() { @Override public String apply(String input) { if (!input.contains("{}")) { return input; } // Find all empty expressions and turn them into index-based expressions // e.g. "Hello {} and {}!" turns into "Hello {data.0} and {data.1}!" StringBuilder builder = new StringBuilder(); Matcher m = p.matcher(input); int idx = 0; while (m.find()) { m.appendReplacement(builder, "{data." + idx + "}"); idx++; } m.appendTail(builder); return builder.toString(); } }); } } private static volatile Engine engine; private static volatile boolean cacheByDefault; private static final Map<Hash, Template> CACHE = new ConcurrentHashMap<>(); private static final Variant PLAIN_TEXT = Variant.forContentType(Variant.TEXT_PLAIN); private static final AtomicLong ID_GENERATOR = new AtomicLong(0); /* Internals */ private static final String TEMPLATE_PREFIX = "Qute$$"; private static String newId() { return TEMPLATE_PREFIX + ID_GENERATOR.incrementAndGet(); } private static Hash hashKey(String value) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); return new Hash(md.digest(value.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } private static final class Hash { private final byte[] hash; private final int hashCode; Hash(byte[] hash) { this.hash = hash; final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(hash); this.hashCode = result; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } Hash other = (Hash) obj; return Arrays.equals(hash, other.hash); } } private static Engine newDefaultEngine() { return Engine.builder() .addDefaults() .addValueResolver(new ReflectionValueResolver()) .addParserHook(new IndexedArgumentsParserHook()) .addResultMapper(new HtmlEscaper(ImmutableList.of("text/html", "text/xml"))) .build(); } }
quarkusio/quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/Qute.java
2,354
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.p3c.pmd.lang.java.rule.other; import com.alibaba.p3c.pmd.lang.AbstractXpathRule; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; /** * Avoid using *Apache Beanutils* to copy attributes. * Note: *Spring BeanUtils* and *Cglib BeanCopier* are recommended to be used, which have better performance. * * @author keriezhang * @date 2016/12/14 * */ public class AvoidApacheBeanUtilsCopyRule extends AbstractXpathRule { private static final String XPATH = "//PrimaryPrefix/Name[@Image='BeanUtils.copyProperties' and " + "//ImportDeclaration[@ImportedName='org.apache.commons.beanutils.BeanUtils']]"; public AvoidApacheBeanUtilsCopyRule() { setXPath(XPATH); } @Override public void addViolation(Object data, Node node, String arg) { ViolationUtils.addViolationWithPrecisePosition(this, node, data); } }
alibaba/p3c
p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidApacheBeanUtilsCopyRule.java
2,355
/* * Copyright 2019 Zhou Pengfei * SPDX-License-Identifier: Apache-2.0 */ package org.signal.glide.common.decode; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.Handler; import android.os.Looper; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; import org.signal.core.util.logging.Log; import org.signal.glide.common.executor.FrameDecoderExecutor; import org.signal.glide.common.io.Reader; import org.signal.glide.common.io.Writer; import org.signal.glide.common.loader.Loader; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; /** * @Description: Abstract Frame Animation Decoder * @Author: pengfei.zhou * @CreateDate: 2019/3/27 */ public abstract class FrameSeqDecoder<R extends Reader, W extends Writer> { private static final String TAG = Log.tag(FrameSeqDecoder.class); private final int taskId; private final Loader mLoader; private final Handler workerHandler; protected List<Frame> frames = new ArrayList<>(); protected int frameIndex = -1; private int playCount; private Integer loopLimit = null; private Set<RenderListener> renderListeners = new HashSet<>(); private AtomicBoolean paused = new AtomicBoolean(true); private static final Rect RECT_EMPTY = new Rect(); private Runnable renderTask = new Runnable() { @Override public void run() { if (paused.get()) { return; } if (canStep()) { long start = System.currentTimeMillis(); long delay = step(); long cost = System.currentTimeMillis() - start; workerHandler.postDelayed(this, Math.max(0, delay - cost)); for (RenderListener renderListener : renderListeners) { renderListener.onRender(frameBuffer); } } else { stop(); } } }; protected int sampleSize = 1; private Set<Bitmap> cacheBitmaps = new HashSet<>(); protected Map<Bitmap, Canvas> cachedCanvas = new WeakHashMap<>(); protected ByteBuffer frameBuffer; protected volatile Rect fullRect; private W mWriter = getWriter(); private R mReader = null; /** * If played all the needed */ private boolean finished = false; private enum State { IDLE, RUNNING, INITIALIZING, FINISHING, } private volatile State mState = State.IDLE; public Loader getLoader() { return mLoader; } protected abstract W getWriter(); protected abstract R getReader(Reader reader); protected Bitmap obtainBitmap(int width, int height) { Bitmap ret = null; Iterator<Bitmap> iterator = cacheBitmaps.iterator(); while (iterator.hasNext()) { int reuseSize = width * height * 4; ret = iterator.next(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (ret != null && ret.getAllocationByteCount() >= reuseSize) { iterator.remove(); if (ret.getWidth() != width || ret.getHeight() != height) { ret.reconfigure(width, height, Bitmap.Config.ARGB_8888); } ret.eraseColor(0); return ret; } } else { if (ret != null && ret.getByteCount() >= reuseSize) { if (ret.getWidth() == width && ret.getHeight() == height) { iterator.remove(); ret.eraseColor(0); } return ret; } } } try { Bitmap.Config config = Bitmap.Config.ARGB_8888; ret = Bitmap.createBitmap(width, height, config); } catch (OutOfMemoryError e) { e.printStackTrace(); } return ret; } protected void recycleBitmap(Bitmap bitmap) { if (bitmap != null && !cacheBitmaps.contains(bitmap)) { cacheBitmaps.add(bitmap); } } /** * 解码器的渲染回调 */ public interface RenderListener { /** * 播放开始 */ void onStart(); /** * 帧播放 */ void onRender(ByteBuffer byteBuffer); /** * 播放结束 */ void onEnd(); } /** * @param loader webp的reader * @param renderListener 渲染的回调 */ public FrameSeqDecoder(Loader loader, @Nullable RenderListener renderListener) { this.mLoader = loader; if (renderListener != null) { this.renderListeners.add(renderListener); } this.taskId = FrameDecoderExecutor.getInstance().generateTaskId(); this.workerHandler = new Handler(FrameDecoderExecutor.getInstance().getLooper(taskId)); } public void addRenderListener(final RenderListener renderListener) { this.workerHandler.post(new Runnable() { @Override public void run() { renderListeners.add(renderListener); } }); } public void removeRenderListener(final RenderListener renderListener) { this.workerHandler.post(new Runnable() { @Override public void run() { renderListeners.remove(renderListener); } }); } public void stopIfNeeded() { this.workerHandler.post(new Runnable() { @Override public void run() { if (renderListeners.size() == 0) { stop(); } } }); } public Rect getBounds() { if (fullRect == null) { if (mState == State.FINISHING) { Log.e(TAG, "In finishing,do not interrupt"); } final Thread thread = Thread.currentThread(); workerHandler.post(new Runnable() { @Override public void run() { try { if (fullRect == null) { if (mReader == null) { mReader = getReader(mLoader.obtain()); } else { mReader.reset(); } initCanvasBounds(read(mReader)); } } catch (Exception e) { e.printStackTrace(); fullRect = RECT_EMPTY; } finally { LockSupport.unpark(thread); } } }); LockSupport.park(thread); } return fullRect; } private void initCanvasBounds(Rect rect) { fullRect = rect; frameBuffer = ByteBuffer.allocate((rect.width() * rect.height() / (sampleSize * sampleSize) + 1) * 4); if (mWriter == null) { mWriter = getWriter(); } } private int getFrameCount() { return this.frames.size(); } /** * @return Loop Count defined in file */ protected abstract int getLoopCount(); public void start() { if (fullRect == RECT_EMPTY) { return; } if (mState == State.RUNNING || mState == State.INITIALIZING) { Log.i(TAG, debugInfo() + " Already started"); return; } if (mState == State.FINISHING) { Log.e(TAG, debugInfo() + " Processing,wait for finish at " + mState); } mState = State.INITIALIZING; if (Looper.myLooper() == workerHandler.getLooper()) { innerStart(); } else { workerHandler.post(new Runnable() { @Override public void run() { innerStart(); } }); } } @WorkerThread private void innerStart() { paused.compareAndSet(true, false); final long start = System.currentTimeMillis(); try { if (frames.size() == 0) { try { if (mReader == null) { mReader = getReader(mLoader.obtain()); } else { mReader.reset(); } initCanvasBounds(read(mReader)); } catch (Throwable e) { e.printStackTrace(); } } } finally { Log.i(TAG, debugInfo() + " Set state to RUNNING,cost " + (System.currentTimeMillis() - start)); mState = State.RUNNING; } if (getNumPlays() == 0 || !finished) { this.frameIndex = -1; renderTask.run(); for (RenderListener renderListener : renderListeners) { renderListener.onStart(); } } else { Log.i(TAG, debugInfo() + " No need to started"); } } @WorkerThread private void innerStop() { workerHandler.removeCallbacks(renderTask); frames.clear(); for (Bitmap bitmap : cacheBitmaps) { if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } } cacheBitmaps.clear(); if (frameBuffer != null) { frameBuffer = null; } cachedCanvas.clear(); try { if (mReader != null) { mReader.close(); mReader = null; } if (mWriter != null) { mWriter.close(); } } catch (IOException e) { e.printStackTrace(); } release(); mState = State.IDLE; for (RenderListener renderListener : renderListeners) { renderListener.onEnd(); } } public void stop() { if (fullRect == RECT_EMPTY) { return; } if (mState == State.FINISHING || mState == State.IDLE) { Log.i(TAG, debugInfo() + "No need to stop"); return; } if (mState == State.INITIALIZING) { Log.e(TAG, debugInfo() + "Processing,wait for finish at " + mState); } mState = State.FINISHING; if (Looper.myLooper() == workerHandler.getLooper()) { innerStop(); } else { workerHandler.post(new Runnable() { @Override public void run() { innerStop(); } }); } } private String debugInfo() { return ""; } protected abstract void release(); public boolean isRunning() { return mState == State.RUNNING || mState == State.INITIALIZING; } public boolean isPaused() { return paused.get(); } public void setLoopLimit(int limit) { this.loopLimit = limit; } public void reset() { this.playCount = 0; this.frameIndex = -1; this.finished = false; } public void pause() { workerHandler.removeCallbacks(renderTask); paused.compareAndSet(false, true); } public void resume() { paused.compareAndSet(true, false); workerHandler.removeCallbacks(renderTask); workerHandler.post(renderTask); } public int getSampleSize() { return sampleSize; } public boolean setDesiredSize(int width, int height) { boolean sampleSizeChanged = false; int sample = getDesiredSample(width, height); if (sample != this.sampleSize) { this.sampleSize = sample; sampleSizeChanged = true; final boolean tempRunning = isRunning(); workerHandler.removeCallbacks(renderTask); workerHandler.post(new Runnable() { @Override public void run() { innerStop(); try { initCanvasBounds(read(getReader(mLoader.obtain()))); if (tempRunning) { innerStart(); } } catch (IOException e) { e.printStackTrace(); } } }); } return sampleSizeChanged; } protected int getDesiredSample(int desiredWidth, int desiredHeight) { if (desiredWidth == 0 || desiredHeight == 0) { return 1; } int radio = Math.min(getBounds().width() / desiredWidth, getBounds().height() / desiredHeight); int sample = 1; while ((sample * 2) <= radio) { sample *= 2; } return sample; } protected abstract Rect read(R reader) throws IOException; private int getNumPlays() { return this.loopLimit != null ? this.loopLimit : this.getLoopCount(); } private boolean canStep() { if (!isRunning()) { return false; } if (frames.size() == 0) { return false; } if (getNumPlays() <= 0) { return true; } if (this.playCount < getNumPlays() - 1) { return true; } else if (this.playCount == getNumPlays() - 1 && this.frameIndex < this.getFrameCount() - 1) { return true; } finished = true; return false; } @WorkerThread private long step() { this.frameIndex++; if (this.frameIndex >= this.getFrameCount()) { this.frameIndex = 0; this.playCount++; } Frame frame = getFrame(this.frameIndex); if (frame == null) { return 0; } renderFrame(frame); return frame.frameDuration; } protected abstract void renderFrame(Frame frame); private Frame getFrame(int index) { if (index < 0 || index >= frames.size()) { return null; } return frames.get(index); } /** * Get Indexed frame * * @param index <0 means reverse from last index */ public Bitmap getFrameBitmap(int index) throws IOException { if (mState != State.IDLE) { Log.e(TAG, debugInfo() + ",stop first"); return null; } mState = State.RUNNING; paused.compareAndSet(true, false); if (frames.size() == 0) { if (mReader == null) { mReader = getReader(mLoader.obtain()); } else { mReader.reset(); } initCanvasBounds(read(mReader)); } if (index < 0) { index += this.frames.size(); } if (index < 0) { index = 0; } frameIndex = -1; while (frameIndex < index) { if (canStep()) { step(); } else { break; } } frameBuffer.rewind(); Bitmap bitmap = Bitmap.createBitmap(getBounds().width() / getSampleSize(), getBounds().height() / getSampleSize(), Bitmap.Config.ARGB_8888); bitmap.copyPixelsFromBuffer(frameBuffer); innerStop(); return bitmap; } }
signalapp/Signal-Android
app/src/main/java/org/signal/glide/common/decode/FrameSeqDecoder.java
2,356
package com.semmle.js.extractor; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase; import com.semmle.js.extractor.trapcache.CachingTrapWriter; import com.semmle.js.extractor.trapcache.ITrapCache; import com.semmle.util.data.StringUtil; import com.semmle.util.exception.Exceptions; import com.semmle.util.extraction.ExtractorOutputConfig; import com.semmle.util.files.FileUtil; import com.semmle.util.io.WholeIO; import com.semmle.util.trap.TrapWriter; import com.semmle.util.trap.TrapWriter.Label; /** * The file extractor extracts a single file and handles source archive population and TRAP caching; * it delegates to the appropriate {@link IExtractor} for extracting the contents of the file. */ public class FileExtractor { /** * Pattern to use on the shebang line of a script to identify whether it is a Node.js script. * * <p>There are many different ways of invoking the Node.js interpreter (directly, through {@code * env}, with or without flags, with or without modified environment, etc.), so we simply look for * the word {@code "node"} or {@code "nodejs"}. */ private static final Pattern NODE_INVOCATION = Pattern.compile("\\bnode(js)?\\b"); /** A pattern that matches strings starting with `{ "...":`, suggesting JSON data. */ public static final Pattern JSON_OBJECT_START = Pattern.compile("^(?s)\\s*\\{\\s*\"([^\"]|\\\\.)*\"\\s*:.*"); /** * Returns true if the byte sequence contains invalid UTF-8 or unprintable ASCII characters. */ private static boolean hasUnprintableUtf8(byte[] bytes, int length) { // Constants for bytes with N high-order 1-bits. // They are typed as `int` as the subsequent byte-to-int promotion would // otherwise fill the high-order `int` bits with 1s. final int high1 = 0b10000000; final int high2 = 0b11000000; final int high3 = 0b11100000; final int high4 = 0b11110000; final int high5 = 0b11111000; int startIndex = skipBOM(bytes, length); for (int i = startIndex; i < length; ++i) { int b = bytes[i]; if ((b & high1) == 0) { // 0xxxxxxx is an ASCII character // ASCII values 0-31 are unprintable, except 9-13 are whitespace. // 127 is the unprintable DEL character. if (b <= 8 || 14 <= b && b <= 31 || b == 127) { return true; } } else { // Check for malformed UTF-8 multibyte code point int trailingBytes = 0; if ((b & high3) == high2) { trailingBytes = 1; // 110xxxxx 10xxxxxx } else if ((b & high4) == high3) { trailingBytes = 2; // 1110xxxx 10xxxxxx 10xxxxxx } else if ((b & high5) == high4) { trailingBytes = 3; // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx } else { return true; // 10xxxxxx and 11111xxx are not valid here. } // Trailing bytes must be of form 10xxxxxx while (trailingBytes > 0) { ++i; --trailingBytes; if (i >= length) { return false; } if ((bytes[i] & high2) != high1) { return true; } } } } return false; } /** Returns the index after the initial BOM, if any, otherwise 0. */ private static int skipBOM(byte[] bytes, int length) { if (length >= 2 && (bytes[0] == (byte) 0xfe && bytes[1] == (byte) 0xff || bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xfe)) { return 2; } else { return 0; } } /** Information about supported file types. */ public static enum FileType { HTML(".htm", ".html", ".xhtm", ".xhtml", ".vue", ".hbs", ".ejs", ".njk", ".erb", ".jsp", ".dot") { @Override public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) { return new HTMLExtractor(config, state); } @Override public String toString() { return "html"; } @Override protected boolean contains(File f, String lcExt, ExtractorConfig config) { if (isBinaryFile(f, lcExt, config)) { return false; } // for ERB files we are only interrested in `.html.erb` files if (FileUtil.extension(f).equalsIgnoreCase(".erb")) { if (!f.getName().toLowerCase().endsWith(".html.erb")) { return false; } } // for DOT files we are only interrested in `.html.dot` files if (FileUtil.extension(f).equalsIgnoreCase(".dot")) { if (!f.getName().toLowerCase().endsWith(".html.dot")) { return false; } } return super.contains(f, lcExt, config); } }, JS(".js", ".jsx", ".mjs", ".cjs", ".es6", ".es") { @Override public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) { return new ScriptExtractor(config, state); } @Override protected boolean contains(File f, String lcExt, ExtractorConfig config) { if (isBinaryFile(f, lcExt, config)) { return false; } if (super.contains(f, lcExt, config)) return true; // detect Node.js scripts that are meant to be run from // the command line and do not have a `.js` extension if (f.isFile() && lcExt.isEmpty()) { try (BufferedReader br = new BufferedReader(new FileReader(f))) { String firstLine = br.readLine(); // do a cheap check first if (firstLine != null && firstLine.startsWith("#!")) { // now do the slightly more expensive one return NODE_INVOCATION.matcher(firstLine).find(); } } catch (IOException e) { Exceptions.ignore(e, "We simply skip this file."); } } return false; } @Override public String toString() { return "javascript"; } }, JSON(".json") { @Override public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) { return new JSONExtractor(config); } @Override protected boolean contains(File f, String lcExt, ExtractorConfig config) { if (super.contains(f, lcExt, config)) return true; // detect JSON-encoded configuration files whose name starts with `.` and ends with `rc` // (e.g., `.eslintrc` or `.babelrc`) if (f.isFile() && f.getName().matches("\\..*rc")) { try (BufferedReader br = new BufferedReader(new FileReader(f))) { // check whether the first two non-empty lines look like the start of a JSON object // (two lines because the opening brace is usually on a line by itself) StringBuilder firstTwoLines = new StringBuilder(); for (int i = 0; i < 2; ) { String nextLine = br.readLine(); if (nextLine == null) break; nextLine = nextLine.trim(); if (!nextLine.isEmpty()) { firstTwoLines.append(nextLine); ++i; } } return JSON_OBJECT_START.matcher(firstTwoLines).matches(); } catch (IOException e) { Exceptions.ignore(e, "We simply skip this file."); } } return false; } @Override public String toString() { return "json"; } }, TYPESCRIPT(".ts", ".tsx", ".mts", ".cts") { @Override protected boolean contains(File f, String lcExt, ExtractorConfig config) { if (config.getTypeScriptMode() == TypeScriptMode.NONE) return false; // Read the beginning of the file to guess the file type. if (hasBadFileHeader(f, lcExt, config)) { return false; } return super.contains(f, lcExt, config); } private boolean hasBadFileHeader(File f, String lcExt, ExtractorConfig config) { try (FileInputStream fis = new FileInputStream(f)) { byte[] bytes = new byte[fileHeaderSize]; int length = fis.read(bytes); if (length == -1) return false; // Avoid invalid or unprintable UTF-8 files. if (config.getDefaultEncoding().equals(StandardCharsets.UTF_8.name()) && hasUnprintableUtf8(bytes, length)) { return true; } // Avoid trying to extract XML files. if (isXml(bytes, length)) return true; // Avoid files with an unrecognized shebang header. if (hasUnrecognizedShebang(bytes, length)) { return true; } // Avoid Touchstone files if (isTouchstone(bytes, length)) return true; return false; } catch (IOException e) { Exceptions.ignore(e, "Let extractor handle this one."); } return false; } private boolean isXml(byte[] bytes, int length) { int startIndex = skipBOM(bytes, length); // Check for `<` encoded in Ascii/UTF-8 or litte-endian UTF-16. if (startIndex < length && bytes[startIndex] == '<') { return true; } // Check for `<` encoded in big-endian UTF-16 if (startIndex + 1 < length && bytes[startIndex] == 0 && bytes[startIndex + 1] == '<') { return true; } return false; } private boolean isTouchstone(byte[] bytes, int length) { String s = new String(bytes, 0, length, StandardCharsets.US_ASCII); return s.startsWith("! TOUCHSTONE file ") || s.startsWith("[Version] 2.0"); } /** * Returns true if the byte sequence starts with a shebang line that is not recognized as a * JavaScript interpreter. */ private boolean hasUnrecognizedShebang(byte[] bytes, int length) { // Shebangs preceded by a BOM aren't recognized in UNIX, but the BOM might only // be present in the source file, to be stripped out in the build process. int startIndex = skipBOM(bytes, length); if (startIndex + 2 >= length) return false; if (bytes[startIndex] != '#' || bytes[startIndex + 1] != '!') { return false; } int endOfLine = -1; for (int i = startIndex; i < length; ++i) { if (bytes[i] == '\r' || bytes[i] == '\n') { endOfLine = i; break; } } if (endOfLine == -1) { // The shebang is either very long or there are no other lines in the file. // Treat this as unrecognized. return true; } // Extract the shebang text int startOfText = startIndex + "#!".length(); int lengthOfText = endOfLine - startOfText; String text = new String(bytes, startOfText, lengthOfText, StandardCharsets.UTF_8); // Check if the shebang is a recognized JavaScript intepreter. return !NODE_INVOCATION.matcher(text).find(); } @Override public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) { return new TypeScriptExtractor(config, state); } @Override public String toString() { return "typescript"; } @Override public boolean isTrapCachingAllowed() { return false; // Type information cannot be cached per-file. } }, YAML(".raml", ".yaml", ".yml") { @Override public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) { return new YAMLExtractor(config); } @Override public String toString() { return "yaml"; } }; /** Number of bytes to read from the beginning of a file to sniff its file type. */ private static final int fileHeaderSize = 128; /** The file extensions (lower-case, including leading dot) corresponding to this file type. */ private final Set<String> extensions = new LinkedHashSet<String>(); private FileType(String... extensions) { for (String extension : extensions) this.extensions.add(extension); } public Set<String> getExtensions() { return extensions; } /** Construct an extractor for this file type with the appropriate configuration settings. */ public abstract IExtractor mkExtractor(ExtractorConfig config, ExtractorState state); /** Determine the {@link FileType} for a given file. */ public static FileType forFile(File f, ExtractorConfig config) { String lcExt = StringUtil.lc(FileUtil.extension(f)); for (FileType tp : values()) if (tp.contains(f, lcExt, config)) return tp; return null; } /** Determine the {@link FileType} for a given file based on its extension only. */ public static FileType forFileExtension(File f) { String lcExt = StringUtil.lc(FileUtil.extension(f)); for (FileType tp : values()) if (tp.getExtensions().contains(lcExt)) { return tp; } return null; } /** * Is the given file of this type? * * <p>For convenience, the lower-case file extension is also passed as an argument. */ protected boolean contains(File f, String lcExt, ExtractorConfig config) { return extensions.contains(lcExt); } /** * Can we cache the TRAP output of this file? * * <p>Caching is disabled for TypeScript files as they depend on type information from other * files. */ public boolean isTrapCachingAllowed() { return true; } /** Computes if `f` is a binary file based on whether the initial `fileHeaderSize` bytes are printable UTF-8 chars. */ public static boolean isBinaryFile(File f, String lcExt, ExtractorConfig config) { if (!config.getDefaultEncoding().equals(StandardCharsets.UTF_8.name())) { return false; } try (FileInputStream fis = new FileInputStream(f)) { byte[] bytes = new byte[fileHeaderSize]; int length = fis.read(bytes); if (length == -1) return false; // Avoid invalid or unprintable UTF-8 files. if (hasUnprintableUtf8(bytes, length)) { return true; } return false; } catch (IOException e) { Exceptions.ignore(e, "Let extractor handle this one."); } return false; } /** The names of all defined {@linkplain FileType}s. */ public static final Set<String> allNames = new LinkedHashSet<String>(); static { for (FileType ft : FileType.values()) allNames.add(ft.name()); } } private final ExtractorConfig config; private final ExtractorOutputConfig outputConfig; private final ITrapCache trapCache; public FileExtractor( ExtractorConfig config, ExtractorOutputConfig outputConfig, ITrapCache trapCache) { this.config = config; this.outputConfig = outputConfig; this.trapCache = trapCache; } public ExtractorConfig getConfig() { return config; } public boolean supports(File f) { return config.hasFileType() || FileType.forFile(f, config) != null; } /** @return the number of lines of code extracted, or {@code null} if the file was cached */ public ParseResultInfo extract(File f, ExtractorState state) throws IOException { FileSnippet snippet = state.getSnippets().get(f.toPath()); if (snippet != null) { return this.extractSnippet(f.toPath(), snippet, state); } // populate source archive String source = new WholeIO(config.getDefaultEncoding()).strictread(f); outputConfig.getSourceArchive().add(f, source); // extract language-independent bits TrapWriter trapwriter = outputConfig.getTrapWriterFactory().mkTrapWriter(f); Label fileLabel = trapwriter.populateFile(f); LocationManager locationManager = new LocationManager(f, trapwriter, fileLabel); locationManager.emitFileLocation(fileLabel, 0, 0, 0, 0); // now extract the contents return extractContents(f, fileLabel, source, locationManager, state); } /** * Extract the contents of a file that is a snippet from another file. * * <p>A trap file will be derived from the snippet file, but its file label, source locations, and * source archive entry are based on the original file. */ private ParseResultInfo extractSnippet(Path file, FileSnippet origin, ExtractorState state) throws IOException { TrapWriter trapwriter = outputConfig.getTrapWriterFactory().mkTrapWriter(file.toFile()); File originalFile = origin.getOriginalFile().toFile(); Label fileLabel = trapwriter.populateFile(originalFile); LocationManager locationManager = new LocationManager(originalFile, trapwriter, fileLabel); locationManager.setStart(origin.getLine(), origin.getColumn()); String source = new WholeIO(config.getDefaultEncoding()).strictread(file); return extractContents(file.toFile(), fileLabel, source, locationManager, state); } /** * Extract the contents of a file, potentially making use of cached information. * * <p>TRAP files can be logically split into two parts: a location-dependent prelude containing * all the `files`, `folders` and `containerparent` tuples, and a content-dependent main part * containing all the rest, which does not depend on the source file location at all. Locations in * the main part do, of course, refer to the source file's ID, but they do so via its symbolic * label, which is always #10000. * * <p>We only cache the content-dependent part, which makes up the bulk of the TRAP file anyway. * The location-dependent part is emitted from scratch every time by the {@link #extract(File, * ExtractorState)} method above. * * <p>In order to keep labels in the main part independent of the file's location, we bump the * TRAP label counter to a known value (currently 20000) after the location-dependent part has * been emitted. If the counter should already be larger than that (which is theoretically * possible with insanely deeply nested directories), we have to skip caching. * * <p>Also note that we support extraction with TRAP writer factories that are not file-backed; * obviously, no caching is done in that scenario. */ private ParseResultInfo extractContents( File extractedFile, Label fileLabel, String source, LocationManager locationManager, ExtractorState state) throws IOException { ExtractionMetrics metrics = new ExtractionMetrics(); metrics.startPhase(ExtractionPhase.FileExtractor_extractContents); metrics.setLength(source.length()); metrics.setFileLabel(fileLabel); TrapWriter trapwriter = locationManager.getTrapWriter(); FileType fileType = getFileType(extractedFile); File cacheFile = null, // the cache file for this extraction resultFile = null; // the final result TRAP file for this extraction if (bumpIdCounter(trapwriter)) { resultFile = outputConfig.getTrapWriterFactory().getTrapFileFor(extractedFile); } // check whether we can perform caching if (resultFile != null && fileType.isTrapCachingAllowed()) { cacheFile = trapCache.lookup(source, config, fileType); } boolean canUseCacheFile = cacheFile != null; boolean canReuseCacheFile = canUseCacheFile && cacheFile.exists(); metrics.setCacheFile(cacheFile); metrics.setCanReuseCacheFile(canReuseCacheFile); metrics.writeDataToTrap(trapwriter); if (canUseCacheFile) { FileUtil.close(trapwriter); if (canReuseCacheFile) { FileUtil.append(cacheFile, resultFile); return null; } // not in the cache yet, so use a caching TRAP writer to // put the data into the cache and append it to the result file trapwriter = new CachingTrapWriter(cacheFile, resultFile); bumpIdCounter(trapwriter); // re-initialise the location manager, since it keeps a reference to the TRAP writer locationManager = new LocationManager(extractedFile, trapwriter, locationManager.getFileLabel()); } // now do the extraction itself boolean successful = false; try { IExtractor extractor = fileType.mkExtractor(config, state); TextualExtractor textualExtractor = new TextualExtractor( trapwriter, locationManager, source, config.getExtractLines(), metrics, extractedFile); ParseResultInfo loc = extractor.extract(textualExtractor); int numLines = textualExtractor.isSnippet() ? 0 : textualExtractor.getNumLines(); int linesOfCode = loc.getLinesOfCode(), linesOfComments = loc.getLinesOfComments(); trapwriter.addTuple("numlines", fileLabel, numLines, linesOfCode, linesOfComments); trapwriter.addTuple("filetype", fileLabel, fileType.toString()); metrics.stopPhase(ExtractionPhase.FileExtractor_extractContents); metrics.writeTimingsToTrap(trapwriter); successful = true; return loc; } finally { if (!successful && trapwriter instanceof CachingTrapWriter) ((CachingTrapWriter) trapwriter).discard(); FileUtil.close(trapwriter); } } public FileType getFileType(File f) { return config.hasFileType() ? FileType.valueOf(config.getFileType()) : FileType.forFile(f, config); } /** * Bump trap ID counter to separate path-dependent and path-independent parts of the TRAP file. * * @return true if the counter was successfully bumped */ public boolean bumpIdCounter(TrapWriter trapwriter) { return trapwriter.bumpIdCount(20000); } }
github/codeql
javascript/extractor/src/com/semmle/js/extractor/FileExtractor.java
2,357
package google; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by sherxon on 7/10/17. */ public class FreeTheBunnyPrisoners { public static void main(String[] args) { int[][] a = answer(4, 4); for (int i = 0; i < a.length; i++) { System.out.println(Arrays.toString(a[i])); } } public static int[][] answer(int num_buns, int num_required) { int[] a = new int[num_buns]; boolean[] b = new boolean[num_buns]; List<List<Integer>> list = new ArrayList<>(); go(b, num_required, list, 0, 0); int total = list.size() * num_required; int rt = num_buns - num_required + 1; b = new boolean[num_buns]; List<List<Integer>> list2 = new ArrayList<>(); go(b, rt, list2, 0, 0); int[][] result = new int[num_buns][]; List<List<Integer>> r = new ArrayList<>(); for (int i = 0; i < num_buns; i++) { r.add(new ArrayList<>()); } for (int i = 0; i < total / rt; i++) { List<Integer> t = list2.get(i); for (int integer : t) { r.get(integer).add(i); } } for (int i = 0; i < r.size(); i++) { if (result[i] == null) { result[i] = new int[r.get(i).size()]; } for (int j = 0; j < r.get(i).size(); j++) { result[i][j] = r.get(i).get(j); } } return result; } private static void go(boolean[] b, int num_required, List<List<Integer>> list, int i, int k) { if (i > b.length) return; if (i == b.length && k >= num_required) { List<Integer> l = new ArrayList<>(num_required); for (int j = 0; j < b.length; j++) { if (b[j]) l.add(j); } list.add(l); } else { for (int j = i; j < b.length; j++) { if (!b[j] && k < num_required) { b[j] = true; go(b, num_required, list, j + 1, k + 1); b[j] = false; } else if (k == num_required) { go(b, num_required, list, j + 1, k + 1); } } } } }
sherxon/AlgoDS
src/google/FreeTheBunnyPrisoners.java
2,358
package imgproxytest; import org.junit.jupiter.api.Test; import java.util.Base64; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import static org.junit.jupiter.api.Assertions.*; public class ImgProxy{ @Test public void testWithJavaHmacApacheBase64ImgProxyTest() throws Exception { byte[] key = hexStringToByteArray("943b421c9eb07c830af81030552c86009268de4e532ba2ee2eab8247c6da0881"); byte[] salt = hexStringToByteArray("520f986b998545b4785e0defbc4f3c1203f22de2374a3d53cb7a7fe9fea309c5"); String path = "/rs:fit:300:300/plain/http://img.example.com/pretty/image.jpg"; String pathWithHash = signPath(key, salt, path); assertEquals("/m3k5QADfcKPDj-SDI2AIogZbC3FlAXszuwhtWXYqavc/rs:fit:300:300/plain/http://img.example.com/pretty/image.jpg", pathWithHash); } public static String signPath(byte[] key, byte[] salt, String path) throws Exception { final String HMACSHA256 = "HmacSHA256"; Mac sha256HMAC = Mac.getInstance(HMACSHA256); SecretKeySpec secretKey = new SecretKeySpec(key, HMACSHA256); sha256HMAC.init(secretKey); sha256HMAC.update(salt); String hash = Base64.getUrlEncoder().withoutPadding().encodeToString(sha256HMAC.doFinal(path.getBytes())); return "/" + hash + path; } private static byte[] hexStringToByteArray(String hex){ if (hex.length() % 2 != 0) throw new IllegalArgumentException("Even-length string required"); byte[] res = new byte[hex.length() / 2]; for (int i = 0; i < res.length; i++) { res[i]=(byte)((Character.digit(hex.charAt(i * 2), 16) << 4) | (Character.digit(hex.charAt(i * 2 + 1), 16))); } return res; } }
imgproxy/imgproxy
examples/signature.java
2,359
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.apache.rocketmq.common.BoundaryType; import org.apache.rocketmq.common.Pair; import org.apache.rocketmq.common.SystemClock; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.message.MessageExtBatch; import org.apache.rocketmq.common.message.MessageExtBrokerInner; import org.apache.rocketmq.remoting.protocol.body.HARuntimeInfo; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.ha.HAService; import org.apache.rocketmq.store.hook.PutMessageHook; import org.apache.rocketmq.store.hook.SendMessageBackHook; import org.apache.rocketmq.store.logfile.MappedFile; import org.apache.rocketmq.store.queue.ConsumeQueueInterface; import org.apache.rocketmq.store.queue.ConsumeQueueStoreInterface; import org.apache.rocketmq.store.stats.BrokerStatsManager; import org.apache.rocketmq.store.timer.TimerMessageStore; import org.apache.rocketmq.store.util.PerfCounter; import org.rocksdb.RocksDBException; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.ViewBuilder; /** * This class defines contracting interfaces to implement, allowing third-party vendor to use customized message store. */ public interface MessageStore { /** * Load previously stored messages. * * @return true if success; false otherwise. */ boolean load(); /** * Launch this message store. * * @throws Exception if there is any error. */ void start() throws Exception; /** * Shutdown this message store. */ void shutdown(); /** * Destroy this message store. Generally, all persistent files should be removed after invocation. */ void destroy(); /** * Store a message into store in async manner, the processor can process the next request rather than wait for * result when result is completed, notify the client in async manner * * @param msg MessageInstance to store * @return a CompletableFuture for the result of store operation */ default CompletableFuture<PutMessageResult> asyncPutMessage(final MessageExtBrokerInner msg) { return CompletableFuture.completedFuture(putMessage(msg)); } /** * Store a batch of messages in async manner * * @param messageExtBatch the message batch * @return a CompletableFuture for the result of store operation */ default CompletableFuture<PutMessageResult> asyncPutMessages(final MessageExtBatch messageExtBatch) { return CompletableFuture.completedFuture(putMessages(messageExtBatch)); } /** * Store a message into store. * * @param msg Message instance to store * @return result of store operation. */ PutMessageResult putMessage(final MessageExtBrokerInner msg); /** * Store a batch of messages. * * @param messageExtBatch Message batch. * @return result of storing batch messages. */ PutMessageResult putMessages(final MessageExtBatch messageExtBatch); /** * Query at most <code>maxMsgNums</code> messages belonging to <code>topic</code> at <code>queueId</code> starting * from given <code>offset</code>. Resulting messages will further be screened using provided message filter. * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final MessageFilter messageFilter); /** * Asynchronous get message * @see #getMessage(String, String, int, long, int, MessageFilter) getMessage * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ CompletableFuture<GetMessageResult> getMessageAsync(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final MessageFilter messageFilter); /** * Query at most <code>maxMsgNums</code> messages belonging to <code>topic</code> at <code>queueId</code> starting * from given <code>offset</code>. Resulting messages will further be screened using provided message filter. * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param maxTotalMsgSize Maximum total msg size of the messages * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final int maxTotalMsgSize, final MessageFilter messageFilter); /** * Asynchronous get message * @see #getMessage(String, String, int, long, int, int, MessageFilter) getMessage * * @param group Consumer group that launches this query. * @param topic Topic to query. * @param queueId Queue ID to query. * @param offset Logical offset to start from. * @param maxMsgNums Maximum count of messages to query. * @param maxTotalMsgSize Maximum total msg size of the messages * @param messageFilter Message filter used to screen desired messages. * @return Matched messages. */ CompletableFuture<GetMessageResult> getMessageAsync(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final int maxTotalMsgSize, final MessageFilter messageFilter); /** * Get maximum offset of the topic queue. * * @param topic Topic name. * @param queueId Queue ID. * @return Maximum offset at present. */ long getMaxOffsetInQueue(final String topic, final int queueId); /** * Get maximum offset of the topic queue. * * @param topic Topic name. * @param queueId Queue ID. * @param committed return the max offset in ConsumeQueue if true, or the max offset in CommitLog if false * @return Maximum offset at present. */ long getMaxOffsetInQueue(final String topic, final int queueId, final boolean committed); /** * Get the minimum offset of the topic queue. * * @param topic Topic name. * @param queueId Queue ID. * @return Minimum offset at present. */ long getMinOffsetInQueue(final String topic, final int queueId); TimerMessageStore getTimerMessageStore(); void setTimerMessageStore(TimerMessageStore timerMessageStore); /** * Get the offset of the message in the commit log, which is also known as physical offset. * * @param topic Topic of the message to lookup. * @param queueId Queue ID. * @param consumeQueueOffset offset of consume queue. * @return physical offset. */ long getCommitLogOffsetInQueue(final String topic, final int queueId, final long consumeQueueOffset); /** * Look up the physical offset of the message whose store timestamp is as specified. * * @param topic Topic of the message. * @param queueId Queue ID. * @param timestamp Timestamp to look up. * @return physical offset which matches. */ long getOffsetInQueueByTime(final String topic, final int queueId, final long timestamp); /** * Look up the physical offset of the message whose store timestamp is as specified with specific boundaryType. * * @param topic Topic of the message. * @param queueId Queue ID. * @param timestamp Timestamp to look up. * @param boundaryType Lower or Upper * @return physical offset which matches. */ long getOffsetInQueueByTime(final String topic, final int queueId, final long timestamp, final BoundaryType boundaryType); /** * Look up the message by given commit log offset. * * @param commitLogOffset physical offset. * @return Message whose physical offset is as specified. */ MessageExt lookMessageByOffset(final long commitLogOffset); /** * Look up the message by given commit log offset and size. * * @param commitLogOffset physical offset. * @param size message size * @return Message whose physical offset is as specified. */ MessageExt lookMessageByOffset(long commitLogOffset, int size); /** * Get one message from the specified commit log offset. * * @param commitLogOffset commit log offset. * @return wrapped result of the message. */ SelectMappedBufferResult selectOneMessageByOffset(final long commitLogOffset); /** * Get one message from the specified commit log offset. * * @param commitLogOffset commit log offset. * @param msgSize message size. * @return wrapped result of the message. */ SelectMappedBufferResult selectOneMessageByOffset(final long commitLogOffset, final int msgSize); /** * Get the running information of this store. * * @return message store running info. */ String getRunningDataInfo(); long getTimingMessageCount(String topic); /** * Message store runtime information, which should generally contains various statistical information. * * @return runtime information of the message store in format of key-value pairs. */ HashMap<String, String> getRuntimeInfo(); /** * HA runtime information * @return runtime information of ha */ HARuntimeInfo getHARuntimeInfo(); /** * Get the maximum commit log offset. * * @return maximum commit log offset. */ long getMaxPhyOffset(); /** * Get the minimum commit log offset. * * @return minimum commit log offset. */ long getMinPhyOffset(); /** * Get the store time of the earliest message in the given queue. * * @param topic Topic of the messages to query. * @param queueId Queue ID to find. * @return store time of the earliest message. */ long getEarliestMessageTime(final String topic, final int queueId); /** * Get the store time of the earliest message in this store. * * @return timestamp of the earliest message in this store. */ long getEarliestMessageTime(); /** * Asynchronous get the store time of the earliest message in this store. * @see #getEarliestMessageTime() getEarliestMessageTime * * @return timestamp of the earliest message in this store. */ CompletableFuture<Long> getEarliestMessageTimeAsync(final String topic, final int queueId); /** * Get the store time of the message specified. * * @param topic message topic. * @param queueId queue ID. * @param consumeQueueOffset consume queue offset. * @return store timestamp of the message. */ long getMessageStoreTimeStamp(final String topic, final int queueId, final long consumeQueueOffset); /** * Asynchronous get the store time of the message specified. * @see #getMessageStoreTimeStamp(String, int, long) getMessageStoreTimeStamp * * @param topic message topic. * @param queueId queue ID. * @param consumeQueueOffset consume queue offset. * @return store timestamp of the message. */ CompletableFuture<Long> getMessageStoreTimeStampAsync(final String topic, final int queueId, final long consumeQueueOffset); /** * Get the total number of the messages in the specified queue. * * @param topic Topic * @param queueId Queue ID. * @return total number. */ long getMessageTotalInQueue(final String topic, final int queueId); /** * Get the raw commit log data starting from the given offset, which should used for replication purpose. * * @param offset starting offset. * @return commit log data. */ SelectMappedBufferResult getCommitLogData(final long offset); /** * Get the raw commit log data starting from the given offset, across multiple mapped files. * * @param offset starting offset. * @param size size of data to get * @return commit log data. */ List<SelectMappedBufferResult> getBulkCommitLogData(final long offset, final int size); /** * Append data to commit log. * * @param startOffset starting offset. * @param data data to append. * @param dataStart the start index of data array * @param dataLength the length of data array * @return true if success; false otherwise. */ boolean appendToCommitLog(final long startOffset, final byte[] data, int dataStart, int dataLength); /** * Execute file deletion manually. */ void executeDeleteFilesManually(); /** * Query messages by given key. * * @param topic topic of the message. * @param key message key. * @param maxNum maximum number of the messages possible. * @param begin begin timestamp. * @param end end timestamp. */ QueryMessageResult queryMessage(final String topic, final String key, final int maxNum, final long begin, final long end); /** * Asynchronous query messages by given key. * @see #queryMessage(String, String, int, long, long) queryMessage * * @param topic topic of the message. * @param key message key. * @param maxNum maximum number of the messages possible. * @param begin begin timestamp. * @param end end timestamp. */ CompletableFuture<QueryMessageResult> queryMessageAsync(final String topic, final String key, final int maxNum, final long begin, final long end); /** * Update HA master address. * * @param newAddr new address. */ void updateHaMasterAddress(final String newAddr); /** * Update master address. * * @param newAddr new address. */ void updateMasterAddress(final String newAddr); /** * Return how much the slave falls behind. * * @return number of bytes that slave falls behind. */ long slaveFallBehindMuch(); /** * Return the current timestamp of the store. * * @return current time in milliseconds since 1970-01-01. */ long now(); /** * Delete topic's consume queue file and unused stats. * This interface allows user delete system topic. * * @param deleteTopics unused topic name set * @return the number of the topics which has been deleted. */ int deleteTopics(final Set<String> deleteTopics); /** * Clean unused topics which not in retain topic name set. * * @param retainTopics all valid topics. * @return number of the topics deleted. */ int cleanUnusedTopic(final Set<String> retainTopics); /** * Clean expired consume queues. */ void cleanExpiredConsumerQueue(); /** * Check if the given message has been swapped out of the memory. * * @param topic topic. * @param queueId queue ID. * @param consumeOffset consume queue offset. * @return true if the message is no longer in memory; false otherwise. * @deprecated As of RIP-57, replaced by {@link #checkInMemByConsumeOffset(String, int, long, int)}, see <a href="https://github.com/apache/rocketmq/issues/5837">this issue</a> for more details */ @Deprecated boolean checkInDiskByConsumeOffset(final String topic, final int queueId, long consumeOffset); /** * Check if the given message is in the page cache. * * @param topic topic. * @param queueId queue ID. * @param consumeOffset consume queue offset. * @return true if the message is in page cache; false otherwise. */ boolean checkInMemByConsumeOffset(final String topic, final int queueId, long consumeOffset, int batchSize); /** * Check if the given message is in store. * * @param topic topic. * @param queueId queue ID. * @param consumeOffset consume queue offset. * @return true if the message is in store; false otherwise. */ boolean checkInStoreByConsumeOffset(final String topic, final int queueId, long consumeOffset); /** * Get number of the bytes that have been stored in commit log and not yet dispatched to consume queue. * * @return number of the bytes to dispatch. */ long dispatchBehindBytes(); /** * Flush the message store to persist all data. * * @return maximum offset flushed to persistent storage device. */ long flush(); /** * Get the current flushed offset. * * @return flushed offset */ long getFlushedWhere(); /** * Reset written offset. * * @param phyOffset new offset. * @return true if success; false otherwise. */ boolean resetWriteOffset(long phyOffset); /** * Get confirm offset. * * @return confirm offset. */ long getConfirmOffset(); /** * Set confirm offset. * * @param phyOffset confirm offset to set. */ void setConfirmOffset(long phyOffset); /** * Check if the operating system page cache is busy or not. * * @return true if the OS page cache is busy; false otherwise. */ boolean isOSPageCacheBusy(); /** * Get lock time in milliseconds of the store by far. * * @return lock time in milliseconds. */ long lockTimeMills(); /** * Check if the transient store pool is deficient. * * @return true if the transient store pool is running out; false otherwise. */ boolean isTransientStorePoolDeficient(); /** * Get the dispatcher list. * * @return list of the dispatcher. */ LinkedList<CommitLogDispatcher> getDispatcherList(); /** * Add dispatcher. * * @param dispatcher commit log dispatcher to add */ void addDispatcher(CommitLogDispatcher dispatcher); /** * Get consume queue of the topic/queue. If consume queue not exist, will return null * * @param topic Topic. * @param queueId Queue ID. * @return Consume queue. */ ConsumeQueueInterface getConsumeQueue(String topic, int queueId); /** * Get consume queue of the topic/queue. If consume queue not exist, will create one then return it. * @param topic Topic. * @param queueId Queue ID. * @return Consume queue. */ ConsumeQueueInterface findConsumeQueue(String topic, int queueId); /** * Get BrokerStatsManager of the messageStore. * * @return BrokerStatsManager. */ BrokerStatsManager getBrokerStatsManager(); /** * Will be triggered when a new message is appended to commit log. * * @param msg the msg that is appended to commit log * @param result append message result * @param commitLogFile commit log file */ void onCommitLogAppend(MessageExtBrokerInner msg, AppendMessageResult result, MappedFile commitLogFile); /** * Will be triggered when a new dispatch request is sent to message store. * * @param dispatchRequest dispatch request * @param doDispatch do dispatch if true * @param commitLogFile commit log file * @param isRecover is from recover process * @param isFileEnd if the dispatch request represents 'file end' * @throws RocksDBException only in rocksdb mode */ void onCommitLogDispatch(DispatchRequest dispatchRequest, boolean doDispatch, MappedFile commitLogFile, boolean isRecover, boolean isFileEnd) throws RocksDBException; /** * Only used in rocksdb mode, because we build consumeQueue in batch(default 16 dispatchRequests) * It will be triggered in two cases: * @see org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService#doReput * @see CommitLog#recoverAbnormally */ void finishCommitLogDispatch(); /** * Get the message store config * * @return the message store config */ MessageStoreConfig getMessageStoreConfig(); /** * Get the statistics service * * @return the statistics service */ StoreStatsService getStoreStatsService(); /** * Get the store checkpoint component * * @return the checkpoint component */ StoreCheckpoint getStoreCheckpoint(); /** * Get the system clock * * @return the system clock */ SystemClock getSystemClock(); /** * Get the commit log * * @return the commit log */ CommitLog getCommitLog(); /** * Get running flags * * @return running flags */ RunningFlags getRunningFlags(); /** * Get the transient store pool * * @return the transient store pool */ TransientStorePool getTransientStorePool(); /** * Get the HA service * * @return the HA service */ HAService getHaService(); /** * Get the allocate-mappedFile service * * @return the allocate-mappedFile service */ AllocateMappedFileService getAllocateMappedFileService(); /** * Truncate dirty logic files * * @param phyOffset physical offset * @throws RocksDBException only in rocksdb mode */ void truncateDirtyLogicFiles(long phyOffset) throws RocksDBException; /** * Unlock mappedFile * * @param unlockMappedFile the file that needs to be unlocked */ void unlockMappedFile(MappedFile unlockMappedFile); /** * Get the perf counter component * * @return the perf counter component */ PerfCounter.Ticks getPerfCounter(); /** * Get the queue store * * @return the queue store */ ConsumeQueueStoreInterface getQueueStore(); /** * If 'sync disk flush' is configured in this message store * * @return yes if true, no if false */ boolean isSyncDiskFlush(); /** * If this message store is sync master role * * @return yes if true, no if false */ boolean isSyncMaster(); /** * Assign a message to queue offset. If there is a race condition, you need to lock/unlock this method * yourself. * * @param msg message * @throws RocksDBException */ void assignOffset(MessageExtBrokerInner msg) throws RocksDBException; /** * Increase queue offset in memory table. If there is a race condition, you need to lock/unlock this method * * @param msg message * @param messageNum message num */ void increaseOffset(MessageExtBrokerInner msg, short messageNum); /** * Get master broker message store in process in broker container * * @return */ MessageStore getMasterStoreInProcess(); /** * Set master broker message store in process * * @param masterStoreInProcess */ void setMasterStoreInProcess(MessageStore masterStoreInProcess); /** * Use FileChannel to get data * * @param offset * @param size * @param byteBuffer * @return */ boolean getData(long offset, int size, ByteBuffer byteBuffer); /** * Set the number of alive replicas in group. * * @param aliveReplicaNums number of alive replicas */ void setAliveReplicaNumInGroup(int aliveReplicaNums); /** * Get the number of alive replicas in group. * * @return number of alive replicas */ int getAliveReplicaNumInGroup(); /** * Wake up AutoRecoverHAClient to start HA connection. */ void wakeupHAClient(); /** * Get master flushed offset. * * @return master flushed offset */ long getMasterFlushedOffset(); /** * Get broker init max offset. * * @return broker max offset in startup */ long getBrokerInitMaxOffset(); /** * Set master flushed offset. * * @param masterFlushedOffset master flushed offset */ void setMasterFlushedOffset(long masterFlushedOffset); /** * Set broker init max offset. * * @param brokerInitMaxOffset broker init max offset */ void setBrokerInitMaxOffset(long brokerInitMaxOffset); /** * Calculate the checksum of a certain range of data. * * @param from begin offset * @param to end offset * @return checksum */ byte[] calcDeltaChecksum(long from, long to); /** * Truncate commitLog and consume queue to certain offset. * * @param offsetToTruncate offset to truncate * @return true if truncate succeed, false otherwise * @throws RocksDBException only in rocksdb mode */ boolean truncateFiles(long offsetToTruncate) throws RocksDBException; /** * Check if the offset is aligned with one message. * * @param offset offset to check * @return true if aligned, false otherwise */ boolean isOffsetAligned(long offset); /** * Get put message hook list * * @return List of PutMessageHook */ List<PutMessageHook> getPutMessageHookList(); /** * Set send message back hook * * @param sendMessageBackHook */ void setSendMessageBackHook(SendMessageBackHook sendMessageBackHook); /** * Get send message back hook * * @return SendMessageBackHook */ SendMessageBackHook getSendMessageBackHook(); //The following interfaces are used for duplication mode /** * Get last mapped file and return lase file first Offset * * @return lastMappedFile first Offset */ long getLastFileFromOffset(); /** * Get last mapped file * * @param startOffset * @return true when get the last mapped file, false when get null */ boolean getLastMappedFile(long startOffset); /** * Set physical offset * * @param phyOffset */ void setPhysicalOffset(long phyOffset); /** * Return whether mapped file is empty * * @return whether mapped file is empty */ boolean isMappedFilesEmpty(); /** * Get state machine version * * @return state machine version */ long getStateMachineVersion(); /** * Check message and return size * * @param byteBuffer * @param checkCRC * @param checkDupInfo * @param readBody * @return DispatchRequest */ DispatchRequest checkMessageAndReturnSize(final ByteBuffer byteBuffer, final boolean checkCRC, final boolean checkDupInfo, final boolean readBody); /** * Get remain transientStoreBuffer numbers * * @return remain transientStoreBuffer numbers */ int remainTransientStoreBufferNumbs(); /** * Get remain how many data to commit * * @return remain how many data to commit */ long remainHowManyDataToCommit(); /** * Get remain how many data to flush * * @return remain how many data to flush */ long remainHowManyDataToFlush(); /** * Get whether message store is shutdown * * @return whether shutdown */ boolean isShutdown(); /** * Estimate number of messages, within [from, to], which match given filter * * @param topic Topic name * @param queueId Queue ID * @param from Lower boundary of the range, inclusive. * @param to Upper boundary of the range, inclusive. * @param filter The message filter. * @return Estimate number of messages matching given filter. */ long estimateMessageCount(String topic, int queueId, long from, long to, MessageFilter filter); /** * Get metrics view of store * * @return List of metrics selector and view pair */ List<Pair<InstrumentSelector, ViewBuilder>> getMetricsView(); /** * Init store metrics * * @param meter opentelemetry meter * @param attributesBuilderSupplier metrics attributes builder */ void initMetrics(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier); /** * Recover topic queue table */ void recoverTopicQueueTable(); /** * notify message arrive if necessary */ void notifyMessageArriveIfNecessary(DispatchRequest dispatchRequest); }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/MessageStore.java
2,360
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store.config; import java.io.File; import org.apache.rocketmq.common.annotation.ImportantField; import org.apache.rocketmq.store.ConsumeQueue; import org.apache.rocketmq.store.StoreType; import org.apache.rocketmq.store.queue.BatchConsumeQueue; public class MessageStoreConfig { public static final String MULTI_PATH_SPLITTER = System.getProperty("rocketmq.broker.multiPathSplitter", ","); //The root directory in which the log data is kept @ImportantField private String storePathRootDir = System.getProperty("user.home") + File.separator + "store"; //The directory in which the commitlog is kept @ImportantField private String storePathCommitLog = null; @ImportantField private String storePathDLedgerCommitLog = null; //The directory in which the epochFile is kept @ImportantField private String storePathEpochFile = null; @ImportantField private String storePathBrokerIdentity = null; private String readOnlyCommitLogStorePaths = null; // CommitLog file size,default is 1G private int mappedFileSizeCommitLog = 1024 * 1024 * 1024; // CompactinLog file size, default is 100M private int compactionMappedFileSize = 100 * 1024 * 1024; // CompactionLog consumeQueue file size, default is 10M private int compactionCqMappedFileSize = 10 * 1024 * 1024; private int compactionScheduleInternal = 15 * 60 * 1000; private int maxOffsetMapSize = 100 * 1024 * 1024; private int compactionThreadNum = 6; private boolean enableCompaction = true; // TimerLog file size, default is 100M private int mappedFileSizeTimerLog = 100 * 1024 * 1024; private int timerPrecisionMs = 1000; private int timerRollWindowSlot = 3600 * 24 * 2; private int timerFlushIntervalMs = 1000; private int timerGetMessageThreadNum = 3; private int timerPutMessageThreadNum = 3; private boolean timerEnableDisruptor = false; private boolean timerEnableCheckMetrics = true; private boolean timerInterceptDelayLevel = false; private int timerMaxDelaySec = 3600 * 24 * 3; private boolean timerWheelEnable = true; /** * 1. Register to broker after (startTime + disappearTimeAfterStart) * 2. Internal msg exchange will start after (startTime + disappearTimeAfterStart) * A. PopReviveService * B. TimerDequeueGetService */ @ImportantField private int disappearTimeAfterStart = -1; private boolean timerStopEnqueue = false; private String timerCheckMetricsWhen = "05"; private boolean timerSkipUnknownError = false; private boolean timerWarmEnable = false; private boolean timerStopDequeue = false; private int timerCongestNumEachSlot = Integer.MAX_VALUE; private int timerMetricSmallThreshold = 1000000; private int timerProgressLogIntervalMs = 10 * 1000; // default, defaultRocksDB @ImportantField private String storeType = StoreType.DEFAULT.getStoreType(); // ConsumeQueue file size,default is 30W private int mappedFileSizeConsumeQueue = 300000 * ConsumeQueue.CQ_STORE_UNIT_SIZE; // enable consume queue ext private boolean enableConsumeQueueExt = false; // ConsumeQueue extend file size, 48M private int mappedFileSizeConsumeQueueExt = 48 * 1024 * 1024; private int mapperFileSizeBatchConsumeQueue = 300000 * BatchConsumeQueue.CQ_STORE_UNIT_SIZE; // Bit count of filter bit map. // this will be set by pipe of calculate filter bit map. private int bitMapLengthConsumeQueueExt = 64; // CommitLog flush interval // flush data to disk @ImportantField private int flushIntervalCommitLog = 500; // Only used if TransientStorePool enabled // flush data to FileChannel @ImportantField private int commitIntervalCommitLog = 200; private int maxRecoveryCommitlogFiles = 30; private int diskSpaceWarningLevelRatio = 90; private int diskSpaceCleanForciblyRatio = 85; /** * introduced since 4.0.x. Determine whether to use mutex reentrantLock when putting message.<br/> */ private boolean useReentrantLockWhenPutMessage = true; // Whether schedule flush @ImportantField private boolean flushCommitLogTimed = true; // ConsumeQueue flush interval private int flushIntervalConsumeQueue = 1000; // Resource reclaim interval private int cleanResourceInterval = 10000; // CommitLog removal interval private int deleteCommitLogFilesInterval = 100; // ConsumeQueue removal interval private int deleteConsumeQueueFilesInterval = 100; private int destroyMapedFileIntervalForcibly = 1000 * 120; private int redeleteHangedFileInterval = 1000 * 120; // When to delete,default is at 4 am @ImportantField private String deleteWhen = "04"; private int diskMaxUsedSpaceRatio = 75; // The number of hours to keep a log file before deleting it (in hours) @ImportantField private int fileReservedTime = 72; @ImportantField private int deleteFileBatchMax = 10; // Flow control for ConsumeQueue private int putMsgIndexHightWater = 600000; // The maximum size of message body,default is 4M,4M only for body length,not include others. private int maxMessageSize = 1024 * 1024 * 4; // The maximum size of message body can be set in config;count with maxMsgNums * CQ_STORE_UNIT_SIZE(20 || 46) private int maxFilterMessageSize = 16000; // Whether check the CRC32 of the records consumed. // This ensures no on-the-wire or on-disk corruption to the messages occurred. // This check adds some overhead,so it may be disabled in cases seeking extreme performance. private boolean checkCRCOnRecover = true; // How many pages are to be flushed when flush CommitLog private int flushCommitLogLeastPages = 4; // How many pages are to be committed when commit data to file private int commitCommitLogLeastPages = 4; // Flush page size when the disk in warming state private int flushLeastPagesWhenWarmMapedFile = 1024 / 4 * 16; // How many pages are to be flushed when flush ConsumeQueue private int flushConsumeQueueLeastPages = 2; private int flushCommitLogThoroughInterval = 1000 * 10; private int commitCommitLogThoroughInterval = 200; private int flushConsumeQueueThoroughInterval = 1000 * 60; @ImportantField private int maxTransferBytesOnMessageInMemory = 1024 * 256; @ImportantField private int maxTransferCountOnMessageInMemory = 32; @ImportantField private int maxTransferBytesOnMessageInDisk = 1024 * 64; @ImportantField private int maxTransferCountOnMessageInDisk = 8; @ImportantField private int accessMessageInMemoryMaxRatio = 40; @ImportantField private boolean messageIndexEnable = true; private int maxHashSlotNum = 5000000; private int maxIndexNum = 5000000 * 4; private int maxMsgsNumBatch = 64; @ImportantField private boolean messageIndexSafe = false; private int haListenPort = 10912; private int haSendHeartbeatInterval = 1000 * 5; private int haHousekeepingInterval = 1000 * 20; /** * Maximum size of data to transfer to slave. * NOTE: cannot be larger than HAClient.READ_MAX_BUFFER_SIZE */ private int haTransferBatchSize = 1024 * 32; @ImportantField private String haMasterAddress = null; private int haMaxGapNotInSync = 1024 * 1024 * 256; @ImportantField private volatile BrokerRole brokerRole = BrokerRole.ASYNC_MASTER; @ImportantField private FlushDiskType flushDiskType = FlushDiskType.ASYNC_FLUSH; // Used by GroupTransferService to sync messages from master to slave private int syncFlushTimeout = 1000 * 5; // Used by PutMessage to wait messages be flushed to disk and synchronized in current broker member group. private int putMessageTimeout = 1000 * 8; private int slaveTimeout = 3000; private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h"; private long flushDelayOffsetInterval = 1000 * 10; @ImportantField private boolean cleanFileForciblyEnable = true; private boolean warmMapedFileEnable = false; private boolean offsetCheckInSlave = false; private boolean debugLockEnable = false; private boolean duplicationEnable = false; private boolean diskFallRecorded = true; private long osPageCacheBusyTimeOutMills = 1000; private int defaultQueryMaxNum = 32; @ImportantField private boolean transientStorePoolEnable = false; private int transientStorePoolSize = 5; private boolean fastFailIfNoBufferInStorePool = false; // DLedger message store config private boolean enableDLegerCommitLog = false; private String dLegerGroup; private String dLegerPeers; private String dLegerSelfId; private String preferredLeaderId; private boolean enableBatchPush = false; private boolean enableScheduleMessageStats = true; private boolean enableLmq = false; private boolean enableMultiDispatch = false; private int maxLmqConsumeQueueNum = 20000; private boolean enableScheduleAsyncDeliver = false; private int scheduleAsyncDeliverMaxPendingLimit = 2000; private int scheduleAsyncDeliverMaxResendNum2Blocked = 3; private int maxBatchDeleteFilesNum = 50; //Polish dispatch private int dispatchCqThreads = 10; private int dispatchCqCacheNum = 1024 * 4; private boolean enableAsyncReput = true; //For recheck the reput private boolean recheckReputOffsetFromCq = false; // Maximum length of topic, it will be removed in the future release @Deprecated private int maxTopicLength = Byte.MAX_VALUE; /** * Use MessageVersion.MESSAGE_VERSION_V2 automatically if topic length larger than Bytes.MAX_VALUE. * Otherwise, store use MESSAGE_VERSION_V1. Note: Client couldn't decode MESSAGE_VERSION_V2 version message. * Enable this config to resolve this issue. https://github.com/apache/rocketmq/issues/5568 */ private boolean autoMessageVersionOnTopicLen = true; /** * It cannot be changed after the broker is started. * Modifications need to be restarted to take effect. */ private boolean enabledAppendPropCRC = false; private boolean forceVerifyPropCRC = false; private int travelCqFileNumWhenGetMessage = 1; // Sleep interval between to corrections private int correctLogicMinOffsetSleepInterval = 1; // Force correct min offset interval private int correctLogicMinOffsetForceInterval = 5 * 60 * 1000; // swap private boolean mappedFileSwapEnable = true; private long commitLogForceSwapMapInterval = 12L * 60 * 60 * 1000; private long commitLogSwapMapInterval = 1L * 60 * 60 * 1000; private int commitLogSwapMapReserveFileNum = 100; private long logicQueueForceSwapMapInterval = 12L * 60 * 60 * 1000; private long logicQueueSwapMapInterval = 1L * 60 * 60 * 1000; private long cleanSwapedMapInterval = 5L * 60 * 1000; private int logicQueueSwapMapReserveFileNum = 20; private boolean searchBcqByCacheEnable = true; @ImportantField private boolean dispatchFromSenderThread = false; @ImportantField private boolean wakeCommitWhenPutMessage = true; @ImportantField private boolean wakeFlushWhenPutMessage = false; @ImportantField private boolean enableCleanExpiredOffset = false; private int maxAsyncPutMessageRequests = 5000; private int pullBatchMaxMessageCount = 160; @ImportantField private int totalReplicas = 1; /** * Each message must be written successfully to at least in-sync replicas. * The master broker is considered one of the in-sync replicas, and it's included in the count of total. * If a master broker is ASYNC_MASTER, inSyncReplicas will be ignored. * If enableControllerMode is true and ackAckInSyncStateSet is true, inSyncReplicas will be ignored. */ @ImportantField private int inSyncReplicas = 1; /** * Will be worked in auto multiple replicas mode, to provide minimum in-sync replicas. * It is still valid in controller mode. */ @ImportantField private int minInSyncReplicas = 1; /** * Each message must be written successfully to all replicas in SyncStateSet. */ @ImportantField private boolean allAckInSyncStateSet = false; /** * Dynamically adjust in-sync replicas to provide higher availability, the real time in-sync replicas * will smaller than inSyncReplicas config. */ @ImportantField private boolean enableAutoInSyncReplicas = false; /** * Enable or not ha flow control */ @ImportantField private boolean haFlowControlEnable = false; /** * The max speed for one slave when transfer data in ha */ private long maxHaTransferByteInSecond = 100 * 1024 * 1024; /** * The max gap time that slave doesn't catch up to master. */ private long haMaxTimeSlaveNotCatchup = 1000 * 15; /** * Sync flush offset from master when broker startup, used in upgrading from old version broker. */ private boolean syncMasterFlushOffsetWhenStartup = false; /** * Max checksum range. */ private long maxChecksumRange = 1024 * 1024 * 1024; private int replicasPerDiskPartition = 1; private double logicalDiskSpaceCleanForciblyThreshold = 0.8; private long maxSlaveResendLength = 256 * 1024 * 1024; /** * Whether sync from lastFile when a new broker replicas(no data) join the master. */ private boolean syncFromLastFile = false; private boolean asyncLearner = false; /** * Number of records to scan before starting to estimate. */ private int maxConsumeQueueScan = 20_000; /** * Number of matched records before starting to estimate. */ private int sampleCountThreshold = 5000; private boolean coldDataFlowControlEnable = false; private boolean coldDataScanEnable = false; private boolean dataReadAheadEnable = true; private int timerColdDataCheckIntervalMs = 60 * 1000; private int sampleSteps = 32; private int accessMessageInMemoryHotRatio = 26; /** * Build ConsumeQueue concurrently with multi-thread */ private boolean enableBuildConsumeQueueConcurrently = false; private int batchDispatchRequestThreadPoolNums = 16; // rocksdb mode private long cleanRocksDBDirtyCQIntervalMin = 60; private long statRocksDBCQIntervalSec = 10; private long memTableFlushIntervalMs = 60 * 60 * 1000L; private boolean realTimePersistRocksDBConfig = true; private boolean enableRocksDBLog = false; private int topicQueueLockNum = 32; public boolean isEnabledAppendPropCRC() { return enabledAppendPropCRC; } public void setEnabledAppendPropCRC(boolean enabledAppendPropCRC) { this.enabledAppendPropCRC = enabledAppendPropCRC; } public boolean isDebugLockEnable() { return debugLockEnable; } public void setDebugLockEnable(final boolean debugLockEnable) { this.debugLockEnable = debugLockEnable; } public boolean isDuplicationEnable() { return duplicationEnable; } public void setDuplicationEnable(final boolean duplicationEnable) { this.duplicationEnable = duplicationEnable; } public long getOsPageCacheBusyTimeOutMills() { return osPageCacheBusyTimeOutMills; } public void setOsPageCacheBusyTimeOutMills(final long osPageCacheBusyTimeOutMills) { this.osPageCacheBusyTimeOutMills = osPageCacheBusyTimeOutMills; } public boolean isDiskFallRecorded() { return diskFallRecorded; } public void setDiskFallRecorded(final boolean diskFallRecorded) { this.diskFallRecorded = diskFallRecorded; } public boolean isWarmMapedFileEnable() { return warmMapedFileEnable; } public void setWarmMapedFileEnable(boolean warmMapedFileEnable) { this.warmMapedFileEnable = warmMapedFileEnable; } public int getCompactionMappedFileSize() { return compactionMappedFileSize; } public int getCompactionCqMappedFileSize() { return compactionCqMappedFileSize; } public void setCompactionMappedFileSize(int compactionMappedFileSize) { this.compactionMappedFileSize = compactionMappedFileSize; } public void setCompactionCqMappedFileSize(int compactionCqMappedFileSize) { this.compactionCqMappedFileSize = compactionCqMappedFileSize; } public int getCompactionScheduleInternal() { return compactionScheduleInternal; } public void setCompactionScheduleInternal(int compactionScheduleInternal) { this.compactionScheduleInternal = compactionScheduleInternal; } public int getMaxOffsetMapSize() { return maxOffsetMapSize; } public void setMaxOffsetMapSize(int maxOffsetMapSize) { this.maxOffsetMapSize = maxOffsetMapSize; } public int getCompactionThreadNum() { return compactionThreadNum; } public void setCompactionThreadNum(int compactionThreadNum) { this.compactionThreadNum = compactionThreadNum; } public boolean isEnableCompaction() { return enableCompaction; } public void setEnableCompaction(boolean enableCompaction) { this.enableCompaction = enableCompaction; } public int getMappedFileSizeCommitLog() { return mappedFileSizeCommitLog; } public void setMappedFileSizeCommitLog(int mappedFileSizeCommitLog) { this.mappedFileSizeCommitLog = mappedFileSizeCommitLog; } public boolean isEnableRocksDBStore() { return StoreType.DEFAULT_ROCKSDB.getStoreType().equalsIgnoreCase(this.storeType); } public String getStoreType() { return storeType; } public void setStoreType(String storeType) { this.storeType = storeType; } public int getMappedFileSizeConsumeQueue() { int factor = (int) Math.ceil(this.mappedFileSizeConsumeQueue / (ConsumeQueue.CQ_STORE_UNIT_SIZE * 1.0)); return (int) (factor * ConsumeQueue.CQ_STORE_UNIT_SIZE); } public void setMappedFileSizeConsumeQueue(int mappedFileSizeConsumeQueue) { this.mappedFileSizeConsumeQueue = mappedFileSizeConsumeQueue; } public boolean isEnableConsumeQueueExt() { return enableConsumeQueueExt; } public void setEnableConsumeQueueExt(boolean enableConsumeQueueExt) { this.enableConsumeQueueExt = enableConsumeQueueExt; } public int getMappedFileSizeConsumeQueueExt() { return mappedFileSizeConsumeQueueExt; } public void setMappedFileSizeConsumeQueueExt(int mappedFileSizeConsumeQueueExt) { this.mappedFileSizeConsumeQueueExt = mappedFileSizeConsumeQueueExt; } public int getBitMapLengthConsumeQueueExt() { return bitMapLengthConsumeQueueExt; } public void setBitMapLengthConsumeQueueExt(int bitMapLengthConsumeQueueExt) { this.bitMapLengthConsumeQueueExt = bitMapLengthConsumeQueueExt; } public int getFlushIntervalCommitLog() { return flushIntervalCommitLog; } public void setFlushIntervalCommitLog(int flushIntervalCommitLog) { this.flushIntervalCommitLog = flushIntervalCommitLog; } public int getFlushIntervalConsumeQueue() { return flushIntervalConsumeQueue; } public void setFlushIntervalConsumeQueue(int flushIntervalConsumeQueue) { this.flushIntervalConsumeQueue = flushIntervalConsumeQueue; } public int getPutMsgIndexHightWater() { return putMsgIndexHightWater; } public void setPutMsgIndexHightWater(int putMsgIndexHightWater) { this.putMsgIndexHightWater = putMsgIndexHightWater; } public int getCleanResourceInterval() { return cleanResourceInterval; } public void setCleanResourceInterval(int cleanResourceInterval) { this.cleanResourceInterval = cleanResourceInterval; } public int getMaxMessageSize() { return maxMessageSize; } public void setMaxMessageSize(int maxMessageSize) { this.maxMessageSize = maxMessageSize; } public int getMaxFilterMessageSize() { return maxFilterMessageSize; } public void setMaxFilterMessageSize(int maxFilterMessageSize) { this.maxFilterMessageSize = maxFilterMessageSize; } @Deprecated public int getMaxTopicLength() { return maxTopicLength; } @Deprecated public void setMaxTopicLength(int maxTopicLength) { this.maxTopicLength = maxTopicLength; } public boolean isAutoMessageVersionOnTopicLen() { return autoMessageVersionOnTopicLen; } public void setAutoMessageVersionOnTopicLen(boolean autoMessageVersionOnTopicLen) { this.autoMessageVersionOnTopicLen = autoMessageVersionOnTopicLen; } public int getTravelCqFileNumWhenGetMessage() { return travelCqFileNumWhenGetMessage; } public void setTravelCqFileNumWhenGetMessage(int travelCqFileNumWhenGetMessage) { this.travelCqFileNumWhenGetMessage = travelCqFileNumWhenGetMessage; } public int getCorrectLogicMinOffsetSleepInterval() { return correctLogicMinOffsetSleepInterval; } public void setCorrectLogicMinOffsetSleepInterval(int correctLogicMinOffsetSleepInterval) { this.correctLogicMinOffsetSleepInterval = correctLogicMinOffsetSleepInterval; } public int getCorrectLogicMinOffsetForceInterval() { return correctLogicMinOffsetForceInterval; } public void setCorrectLogicMinOffsetForceInterval(int correctLogicMinOffsetForceInterval) { this.correctLogicMinOffsetForceInterval = correctLogicMinOffsetForceInterval; } public boolean isCheckCRCOnRecover() { return checkCRCOnRecover; } public boolean getCheckCRCOnRecover() { return checkCRCOnRecover; } public void setCheckCRCOnRecover(boolean checkCRCOnRecover) { this.checkCRCOnRecover = checkCRCOnRecover; } public boolean isForceVerifyPropCRC() { return forceVerifyPropCRC; } public void setForceVerifyPropCRC(boolean forceVerifyPropCRC) { this.forceVerifyPropCRC = forceVerifyPropCRC; } public String getStorePathCommitLog() { if (storePathCommitLog == null) { return storePathRootDir + File.separator + "commitlog"; } return storePathCommitLog; } public void setStorePathCommitLog(String storePathCommitLog) { this.storePathCommitLog = storePathCommitLog; } public String getStorePathDLedgerCommitLog() { return storePathDLedgerCommitLog; } public void setStorePathDLedgerCommitLog(String storePathDLedgerCommitLog) { this.storePathDLedgerCommitLog = storePathDLedgerCommitLog; } public String getStorePathEpochFile() { if (storePathEpochFile == null) { return storePathRootDir + File.separator + "epochFileCheckpoint"; } return storePathEpochFile; } public void setStorePathEpochFile(String storePathEpochFile) { this.storePathEpochFile = storePathEpochFile; } public String getStorePathBrokerIdentity() { if (storePathBrokerIdentity == null) { return storePathRootDir + File.separator + "brokerIdentity"; } return storePathBrokerIdentity; } public void setStorePathBrokerIdentity(String storePathBrokerIdentity) { this.storePathBrokerIdentity = storePathBrokerIdentity; } public String getDeleteWhen() { return deleteWhen; } public void setDeleteWhen(String deleteWhen) { this.deleteWhen = deleteWhen; } public int getDiskMaxUsedSpaceRatio() { if (this.diskMaxUsedSpaceRatio < 10) return 10; if (this.diskMaxUsedSpaceRatio > 95) return 95; return diskMaxUsedSpaceRatio; } public void setDiskMaxUsedSpaceRatio(int diskMaxUsedSpaceRatio) { this.diskMaxUsedSpaceRatio = diskMaxUsedSpaceRatio; } public int getDeleteCommitLogFilesInterval() { return deleteCommitLogFilesInterval; } public void setDeleteCommitLogFilesInterval(int deleteCommitLogFilesInterval) { this.deleteCommitLogFilesInterval = deleteCommitLogFilesInterval; } public int getDeleteConsumeQueueFilesInterval() { return deleteConsumeQueueFilesInterval; } public void setDeleteConsumeQueueFilesInterval(int deleteConsumeQueueFilesInterval) { this.deleteConsumeQueueFilesInterval = deleteConsumeQueueFilesInterval; } public int getMaxTransferBytesOnMessageInMemory() { return maxTransferBytesOnMessageInMemory; } public void setMaxTransferBytesOnMessageInMemory(int maxTransferBytesOnMessageInMemory) { this.maxTransferBytesOnMessageInMemory = maxTransferBytesOnMessageInMemory; } public int getMaxTransferCountOnMessageInMemory() { return maxTransferCountOnMessageInMemory; } public void setMaxTransferCountOnMessageInMemory(int maxTransferCountOnMessageInMemory) { this.maxTransferCountOnMessageInMemory = maxTransferCountOnMessageInMemory; } public int getMaxTransferBytesOnMessageInDisk() { return maxTransferBytesOnMessageInDisk; } public void setMaxTransferBytesOnMessageInDisk(int maxTransferBytesOnMessageInDisk) { this.maxTransferBytesOnMessageInDisk = maxTransferBytesOnMessageInDisk; } public int getMaxTransferCountOnMessageInDisk() { return maxTransferCountOnMessageInDisk; } public void setMaxTransferCountOnMessageInDisk(int maxTransferCountOnMessageInDisk) { this.maxTransferCountOnMessageInDisk = maxTransferCountOnMessageInDisk; } public int getFlushCommitLogLeastPages() { return flushCommitLogLeastPages; } public void setFlushCommitLogLeastPages(int flushCommitLogLeastPages) { this.flushCommitLogLeastPages = flushCommitLogLeastPages; } public int getFlushConsumeQueueLeastPages() { return flushConsumeQueueLeastPages; } public void setFlushConsumeQueueLeastPages(int flushConsumeQueueLeastPages) { this.flushConsumeQueueLeastPages = flushConsumeQueueLeastPages; } public int getFlushCommitLogThoroughInterval() { return flushCommitLogThoroughInterval; } public void setFlushCommitLogThoroughInterval(int flushCommitLogThoroughInterval) { this.flushCommitLogThoroughInterval = flushCommitLogThoroughInterval; } public int getFlushConsumeQueueThoroughInterval() { return flushConsumeQueueThoroughInterval; } public void setFlushConsumeQueueThoroughInterval(int flushConsumeQueueThoroughInterval) { this.flushConsumeQueueThoroughInterval = flushConsumeQueueThoroughInterval; } public int getDestroyMapedFileIntervalForcibly() { return destroyMapedFileIntervalForcibly; } public void setDestroyMapedFileIntervalForcibly(int destroyMapedFileIntervalForcibly) { this.destroyMapedFileIntervalForcibly = destroyMapedFileIntervalForcibly; } public int getFileReservedTime() { return fileReservedTime; } public void setFileReservedTime(int fileReservedTime) { this.fileReservedTime = fileReservedTime; } public int getRedeleteHangedFileInterval() { return redeleteHangedFileInterval; } public void setRedeleteHangedFileInterval(int redeleteHangedFileInterval) { this.redeleteHangedFileInterval = redeleteHangedFileInterval; } public int getAccessMessageInMemoryMaxRatio() { return accessMessageInMemoryMaxRatio; } public void setAccessMessageInMemoryMaxRatio(int accessMessageInMemoryMaxRatio) { this.accessMessageInMemoryMaxRatio = accessMessageInMemoryMaxRatio; } public boolean isMessageIndexEnable() { return messageIndexEnable; } public void setMessageIndexEnable(boolean messageIndexEnable) { this.messageIndexEnable = messageIndexEnable; } public int getMaxHashSlotNum() { return maxHashSlotNum; } public void setMaxHashSlotNum(int maxHashSlotNum) { this.maxHashSlotNum = maxHashSlotNum; } public int getMaxIndexNum() { return maxIndexNum; } public void setMaxIndexNum(int maxIndexNum) { this.maxIndexNum = maxIndexNum; } public int getMaxMsgsNumBatch() { return maxMsgsNumBatch; } public void setMaxMsgsNumBatch(int maxMsgsNumBatch) { this.maxMsgsNumBatch = maxMsgsNumBatch; } public int getHaListenPort() { return haListenPort; } public void setHaListenPort(int haListenPort) { if (haListenPort < 0) { this.haListenPort = 0; return; } this.haListenPort = haListenPort; } public int getHaSendHeartbeatInterval() { return haSendHeartbeatInterval; } public void setHaSendHeartbeatInterval(int haSendHeartbeatInterval) { this.haSendHeartbeatInterval = haSendHeartbeatInterval; } public int getHaHousekeepingInterval() { return haHousekeepingInterval; } public void setHaHousekeepingInterval(int haHousekeepingInterval) { this.haHousekeepingInterval = haHousekeepingInterval; } public BrokerRole getBrokerRole() { return brokerRole; } public void setBrokerRole(BrokerRole brokerRole) { this.brokerRole = brokerRole; } public void setBrokerRole(String brokerRole) { this.brokerRole = BrokerRole.valueOf(brokerRole); } public int getHaTransferBatchSize() { return haTransferBatchSize; } public void setHaTransferBatchSize(int haTransferBatchSize) { this.haTransferBatchSize = haTransferBatchSize; } public int getHaMaxGapNotInSync() { return haMaxGapNotInSync; } public void setHaMaxGapNotInSync(int haMaxGapNotInSync) { this.haMaxGapNotInSync = haMaxGapNotInSync; } public FlushDiskType getFlushDiskType() { return flushDiskType; } public void setFlushDiskType(FlushDiskType flushDiskType) { this.flushDiskType = flushDiskType; } public void setFlushDiskType(String type) { this.flushDiskType = FlushDiskType.valueOf(type); } public int getSyncFlushTimeout() { return syncFlushTimeout; } public void setSyncFlushTimeout(int syncFlushTimeout) { this.syncFlushTimeout = syncFlushTimeout; } public int getPutMessageTimeout() { return putMessageTimeout; } public void setPutMessageTimeout(int putMessageTimeout) { this.putMessageTimeout = putMessageTimeout; } public int getSlaveTimeout() { return slaveTimeout; } public void setSlaveTimeout(int slaveTimeout) { this.slaveTimeout = slaveTimeout; } public String getHaMasterAddress() { return haMasterAddress; } public void setHaMasterAddress(String haMasterAddress) { this.haMasterAddress = haMasterAddress; } public String getMessageDelayLevel() { return messageDelayLevel; } public void setMessageDelayLevel(String messageDelayLevel) { this.messageDelayLevel = messageDelayLevel; } public long getFlushDelayOffsetInterval() { return flushDelayOffsetInterval; } public void setFlushDelayOffsetInterval(long flushDelayOffsetInterval) { this.flushDelayOffsetInterval = flushDelayOffsetInterval; } public boolean isCleanFileForciblyEnable() { return cleanFileForciblyEnable; } public void setCleanFileForciblyEnable(boolean cleanFileForciblyEnable) { this.cleanFileForciblyEnable = cleanFileForciblyEnable; } public boolean isMessageIndexSafe() { return messageIndexSafe; } public void setMessageIndexSafe(boolean messageIndexSafe) { this.messageIndexSafe = messageIndexSafe; } public boolean isFlushCommitLogTimed() { return flushCommitLogTimed; } public void setFlushCommitLogTimed(boolean flushCommitLogTimed) { this.flushCommitLogTimed = flushCommitLogTimed; } public String getStorePathRootDir() { return storePathRootDir; } public void setStorePathRootDir(String storePathRootDir) { this.storePathRootDir = storePathRootDir; } public int getFlushLeastPagesWhenWarmMapedFile() { return flushLeastPagesWhenWarmMapedFile; } public void setFlushLeastPagesWhenWarmMapedFile(int flushLeastPagesWhenWarmMapedFile) { this.flushLeastPagesWhenWarmMapedFile = flushLeastPagesWhenWarmMapedFile; } public boolean isOffsetCheckInSlave() { return offsetCheckInSlave; } public void setOffsetCheckInSlave(boolean offsetCheckInSlave) { this.offsetCheckInSlave = offsetCheckInSlave; } public int getDefaultQueryMaxNum() { return defaultQueryMaxNum; } public void setDefaultQueryMaxNum(int defaultQueryMaxNum) { this.defaultQueryMaxNum = defaultQueryMaxNum; } public boolean isTransientStorePoolEnable() { return transientStorePoolEnable; } public void setTransientStorePoolEnable(final boolean transientStorePoolEnable) { this.transientStorePoolEnable = transientStorePoolEnable; } public int getTransientStorePoolSize() { return transientStorePoolSize; } public void setTransientStorePoolSize(final int transientStorePoolSize) { this.transientStorePoolSize = transientStorePoolSize; } public int getCommitIntervalCommitLog() { return commitIntervalCommitLog; } public void setCommitIntervalCommitLog(final int commitIntervalCommitLog) { this.commitIntervalCommitLog = commitIntervalCommitLog; } public boolean isFastFailIfNoBufferInStorePool() { return fastFailIfNoBufferInStorePool; } public void setFastFailIfNoBufferInStorePool(final boolean fastFailIfNoBufferInStorePool) { this.fastFailIfNoBufferInStorePool = fastFailIfNoBufferInStorePool; } public boolean isUseReentrantLockWhenPutMessage() { return useReentrantLockWhenPutMessage; } public void setUseReentrantLockWhenPutMessage(final boolean useReentrantLockWhenPutMessage) { this.useReentrantLockWhenPutMessage = useReentrantLockWhenPutMessage; } public int getCommitCommitLogLeastPages() { return commitCommitLogLeastPages; } public void setCommitCommitLogLeastPages(final int commitCommitLogLeastPages) { this.commitCommitLogLeastPages = commitCommitLogLeastPages; } public int getCommitCommitLogThoroughInterval() { return commitCommitLogThoroughInterval; } public void setCommitCommitLogThoroughInterval(final int commitCommitLogThoroughInterval) { this.commitCommitLogThoroughInterval = commitCommitLogThoroughInterval; } public boolean isWakeCommitWhenPutMessage() { return wakeCommitWhenPutMessage; } public void setWakeCommitWhenPutMessage(boolean wakeCommitWhenPutMessage) { this.wakeCommitWhenPutMessage = wakeCommitWhenPutMessage; } public boolean isWakeFlushWhenPutMessage() { return wakeFlushWhenPutMessage; } public void setWakeFlushWhenPutMessage(boolean wakeFlushWhenPutMessage) { this.wakeFlushWhenPutMessage = wakeFlushWhenPutMessage; } public int getMapperFileSizeBatchConsumeQueue() { return mapperFileSizeBatchConsumeQueue; } public void setMapperFileSizeBatchConsumeQueue(int mapperFileSizeBatchConsumeQueue) { this.mapperFileSizeBatchConsumeQueue = mapperFileSizeBatchConsumeQueue; } public boolean isEnableCleanExpiredOffset() { return enableCleanExpiredOffset; } public void setEnableCleanExpiredOffset(boolean enableCleanExpiredOffset) { this.enableCleanExpiredOffset = enableCleanExpiredOffset; } public String getReadOnlyCommitLogStorePaths() { return readOnlyCommitLogStorePaths; } public void setReadOnlyCommitLogStorePaths(String readOnlyCommitLogStorePaths) { this.readOnlyCommitLogStorePaths = readOnlyCommitLogStorePaths; } public String getdLegerGroup() { return dLegerGroup; } public void setdLegerGroup(String dLegerGroup) { this.dLegerGroup = dLegerGroup; } public String getdLegerPeers() { return dLegerPeers; } public void setdLegerPeers(String dLegerPeers) { this.dLegerPeers = dLegerPeers; } public String getdLegerSelfId() { return dLegerSelfId; } public void setdLegerSelfId(String dLegerSelfId) { this.dLegerSelfId = dLegerSelfId; } public boolean isEnableDLegerCommitLog() { return enableDLegerCommitLog; } public void setEnableDLegerCommitLog(boolean enableDLegerCommitLog) { this.enableDLegerCommitLog = enableDLegerCommitLog; } public String getPreferredLeaderId() { return preferredLeaderId; } public void setPreferredLeaderId(String preferredLeaderId) { this.preferredLeaderId = preferredLeaderId; } public boolean isEnableBatchPush() { return enableBatchPush; } public void setEnableBatchPush(boolean enableBatchPush) { this.enableBatchPush = enableBatchPush; } public boolean isEnableScheduleMessageStats() { return enableScheduleMessageStats; } public void setEnableScheduleMessageStats(boolean enableScheduleMessageStats) { this.enableScheduleMessageStats = enableScheduleMessageStats; } public int getMaxAsyncPutMessageRequests() { return maxAsyncPutMessageRequests; } public void setMaxAsyncPutMessageRequests(int maxAsyncPutMessageRequests) { this.maxAsyncPutMessageRequests = maxAsyncPutMessageRequests; } public int getMaxRecoveryCommitlogFiles() { return maxRecoveryCommitlogFiles; } public void setMaxRecoveryCommitlogFiles(final int maxRecoveryCommitlogFiles) { this.maxRecoveryCommitlogFiles = maxRecoveryCommitlogFiles; } public boolean isDispatchFromSenderThread() { return dispatchFromSenderThread; } public void setDispatchFromSenderThread(boolean dispatchFromSenderThread) { this.dispatchFromSenderThread = dispatchFromSenderThread; } public int getDispatchCqThreads() { return dispatchCqThreads; } public void setDispatchCqThreads(final int dispatchCqThreads) { this.dispatchCqThreads = dispatchCqThreads; } public int getDispatchCqCacheNum() { return dispatchCqCacheNum; } public void setDispatchCqCacheNum(final int dispatchCqCacheNum) { this.dispatchCqCacheNum = dispatchCqCacheNum; } public boolean isEnableAsyncReput() { return enableAsyncReput; } public void setEnableAsyncReput(final boolean enableAsyncReput) { this.enableAsyncReput = enableAsyncReput; } public boolean isRecheckReputOffsetFromCq() { return recheckReputOffsetFromCq; } public void setRecheckReputOffsetFromCq(final boolean recheckReputOffsetFromCq) { this.recheckReputOffsetFromCq = recheckReputOffsetFromCq; } public long getCommitLogForceSwapMapInterval() { return commitLogForceSwapMapInterval; } public void setCommitLogForceSwapMapInterval(long commitLogForceSwapMapInterval) { this.commitLogForceSwapMapInterval = commitLogForceSwapMapInterval; } public int getCommitLogSwapMapReserveFileNum() { return commitLogSwapMapReserveFileNum; } public void setCommitLogSwapMapReserveFileNum(int commitLogSwapMapReserveFileNum) { this.commitLogSwapMapReserveFileNum = commitLogSwapMapReserveFileNum; } public long getLogicQueueForceSwapMapInterval() { return logicQueueForceSwapMapInterval; } public void setLogicQueueForceSwapMapInterval(long logicQueueForceSwapMapInterval) { this.logicQueueForceSwapMapInterval = logicQueueForceSwapMapInterval; } public int getLogicQueueSwapMapReserveFileNum() { return logicQueueSwapMapReserveFileNum; } public void setLogicQueueSwapMapReserveFileNum(int logicQueueSwapMapReserveFileNum) { this.logicQueueSwapMapReserveFileNum = logicQueueSwapMapReserveFileNum; } public long getCleanSwapedMapInterval() { return cleanSwapedMapInterval; } public void setCleanSwapedMapInterval(long cleanSwapedMapInterval) { this.cleanSwapedMapInterval = cleanSwapedMapInterval; } public long getCommitLogSwapMapInterval() { return commitLogSwapMapInterval; } public void setCommitLogSwapMapInterval(long commitLogSwapMapInterval) { this.commitLogSwapMapInterval = commitLogSwapMapInterval; } public long getLogicQueueSwapMapInterval() { return logicQueueSwapMapInterval; } public void setLogicQueueSwapMapInterval(long logicQueueSwapMapInterval) { this.logicQueueSwapMapInterval = logicQueueSwapMapInterval; } public int getMaxBatchDeleteFilesNum() { return maxBatchDeleteFilesNum; } public void setMaxBatchDeleteFilesNum(int maxBatchDeleteFilesNum) { this.maxBatchDeleteFilesNum = maxBatchDeleteFilesNum; } public boolean isSearchBcqByCacheEnable() { return searchBcqByCacheEnable; } public void setSearchBcqByCacheEnable(boolean searchBcqByCacheEnable) { this.searchBcqByCacheEnable = searchBcqByCacheEnable; } public int getDiskSpaceWarningLevelRatio() { return diskSpaceWarningLevelRatio; } public void setDiskSpaceWarningLevelRatio(int diskSpaceWarningLevelRatio) { this.diskSpaceWarningLevelRatio = diskSpaceWarningLevelRatio; } public int getDiskSpaceCleanForciblyRatio() { return diskSpaceCleanForciblyRatio; } public void setDiskSpaceCleanForciblyRatio(int diskSpaceCleanForciblyRatio) { this.diskSpaceCleanForciblyRatio = diskSpaceCleanForciblyRatio; } public boolean isMappedFileSwapEnable() { return mappedFileSwapEnable; } public void setMappedFileSwapEnable(boolean mappedFileSwapEnable) { this.mappedFileSwapEnable = mappedFileSwapEnable; } public int getPullBatchMaxMessageCount() { return pullBatchMaxMessageCount; } public void setPullBatchMaxMessageCount(int pullBatchMaxMessageCount) { this.pullBatchMaxMessageCount = pullBatchMaxMessageCount; } public int getDeleteFileBatchMax() { return deleteFileBatchMax; } public void setDeleteFileBatchMax(int deleteFileBatchMax) { this.deleteFileBatchMax = deleteFileBatchMax; } public int getTotalReplicas() { return totalReplicas; } public void setTotalReplicas(int totalReplicas) { this.totalReplicas = totalReplicas; } public int getInSyncReplicas() { return inSyncReplicas; } public void setInSyncReplicas(int inSyncReplicas) { this.inSyncReplicas = inSyncReplicas; } public int getMinInSyncReplicas() { return minInSyncReplicas; } public void setMinInSyncReplicas(int minInSyncReplicas) { this.minInSyncReplicas = minInSyncReplicas; } public boolean isAllAckInSyncStateSet() { return allAckInSyncStateSet; } public void setAllAckInSyncStateSet(boolean allAckInSyncStateSet) { this.allAckInSyncStateSet = allAckInSyncStateSet; } public boolean isEnableAutoInSyncReplicas() { return enableAutoInSyncReplicas; } public void setEnableAutoInSyncReplicas(boolean enableAutoInSyncReplicas) { this.enableAutoInSyncReplicas = enableAutoInSyncReplicas; } public boolean isHaFlowControlEnable() { return haFlowControlEnable; } public void setHaFlowControlEnable(boolean haFlowControlEnable) { this.haFlowControlEnable = haFlowControlEnable; } public long getMaxHaTransferByteInSecond() { return maxHaTransferByteInSecond; } public void setMaxHaTransferByteInSecond(long maxHaTransferByteInSecond) { this.maxHaTransferByteInSecond = maxHaTransferByteInSecond; } public long getHaMaxTimeSlaveNotCatchup() { return haMaxTimeSlaveNotCatchup; } public void setHaMaxTimeSlaveNotCatchup(long haMaxTimeSlaveNotCatchup) { this.haMaxTimeSlaveNotCatchup = haMaxTimeSlaveNotCatchup; } public boolean isSyncMasterFlushOffsetWhenStartup() { return syncMasterFlushOffsetWhenStartup; } public void setSyncMasterFlushOffsetWhenStartup(boolean syncMasterFlushOffsetWhenStartup) { this.syncMasterFlushOffsetWhenStartup = syncMasterFlushOffsetWhenStartup; } public long getMaxChecksumRange() { return maxChecksumRange; } public void setMaxChecksumRange(long maxChecksumRange) { this.maxChecksumRange = maxChecksumRange; } public int getReplicasPerDiskPartition() { return replicasPerDiskPartition; } public void setReplicasPerDiskPartition(int replicasPerDiskPartition) { this.replicasPerDiskPartition = replicasPerDiskPartition; } public double getLogicalDiskSpaceCleanForciblyThreshold() { return logicalDiskSpaceCleanForciblyThreshold; } public void setLogicalDiskSpaceCleanForciblyThreshold(double logicalDiskSpaceCleanForciblyThreshold) { this.logicalDiskSpaceCleanForciblyThreshold = logicalDiskSpaceCleanForciblyThreshold; } public int getDisappearTimeAfterStart() { return disappearTimeAfterStart; } public void setDisappearTimeAfterStart(int disappearTimeAfterStart) { this.disappearTimeAfterStart = disappearTimeAfterStart; } public long getMaxSlaveResendLength() { return maxSlaveResendLength; } public void setMaxSlaveResendLength(long maxSlaveResendLength) { this.maxSlaveResendLength = maxSlaveResendLength; } public boolean isSyncFromLastFile() { return syncFromLastFile; } public void setSyncFromLastFile(boolean syncFromLastFile) { this.syncFromLastFile = syncFromLastFile; } public boolean isEnableLmq() { return enableLmq; } public void setEnableLmq(boolean enableLmq) { this.enableLmq = enableLmq; } public boolean isEnableMultiDispatch() { return enableMultiDispatch; } public void setEnableMultiDispatch(boolean enableMultiDispatch) { this.enableMultiDispatch = enableMultiDispatch; } public int getMaxLmqConsumeQueueNum() { return maxLmqConsumeQueueNum; } public void setMaxLmqConsumeQueueNum(int maxLmqConsumeQueueNum) { this.maxLmqConsumeQueueNum = maxLmqConsumeQueueNum; } public boolean isEnableScheduleAsyncDeliver() { return enableScheduleAsyncDeliver; } public void setEnableScheduleAsyncDeliver(boolean enableScheduleAsyncDeliver) { this.enableScheduleAsyncDeliver = enableScheduleAsyncDeliver; } public int getScheduleAsyncDeliverMaxPendingLimit() { return scheduleAsyncDeliverMaxPendingLimit; } public void setScheduleAsyncDeliverMaxPendingLimit(int scheduleAsyncDeliverMaxPendingLimit) { this.scheduleAsyncDeliverMaxPendingLimit = scheduleAsyncDeliverMaxPendingLimit; } public int getScheduleAsyncDeliverMaxResendNum2Blocked() { return scheduleAsyncDeliverMaxResendNum2Blocked; } public void setScheduleAsyncDeliverMaxResendNum2Blocked(int scheduleAsyncDeliverMaxResendNum2Blocked) { this.scheduleAsyncDeliverMaxResendNum2Blocked = scheduleAsyncDeliverMaxResendNum2Blocked; } public boolean isAsyncLearner() { return asyncLearner; } public void setAsyncLearner(boolean asyncLearner) { this.asyncLearner = asyncLearner; } public int getMappedFileSizeTimerLog() { return mappedFileSizeTimerLog; } public void setMappedFileSizeTimerLog(final int mappedFileSizeTimerLog) { this.mappedFileSizeTimerLog = mappedFileSizeTimerLog; } public int getTimerPrecisionMs() { return timerPrecisionMs; } public void setTimerPrecisionMs(int timerPrecisionMs) { int[] candidates = {100, 200, 500, 1000}; for (int i = 1; i < candidates.length; i++) { if (timerPrecisionMs < candidates[i]) { this.timerPrecisionMs = candidates[i - 1]; return; } } this.timerPrecisionMs = candidates[candidates.length - 1]; } public int getTimerRollWindowSlot() { return timerRollWindowSlot; } public int getTimerGetMessageThreadNum() { return timerGetMessageThreadNum; } public void setTimerGetMessageThreadNum(int timerGetMessageThreadNum) { this.timerGetMessageThreadNum = timerGetMessageThreadNum; } public int getTimerPutMessageThreadNum() { return timerPutMessageThreadNum; } public void setTimerPutMessageThreadNum(int timerPutMessageThreadNum) { this.timerPutMessageThreadNum = timerPutMessageThreadNum; } public boolean isTimerEnableDisruptor() { return timerEnableDisruptor; } public boolean isTimerEnableCheckMetrics() { return timerEnableCheckMetrics; } public void setTimerEnableCheckMetrics(boolean timerEnableCheckMetrics) { this.timerEnableCheckMetrics = timerEnableCheckMetrics; } public boolean isTimerStopEnqueue() { return timerStopEnqueue; } public void setTimerStopEnqueue(boolean timerStopEnqueue) { this.timerStopEnqueue = timerStopEnqueue; } public String getTimerCheckMetricsWhen() { return timerCheckMetricsWhen; } public boolean isTimerSkipUnknownError() { return timerSkipUnknownError; } public void setTimerSkipUnknownError(boolean timerSkipUnknownError) { this.timerSkipUnknownError = timerSkipUnknownError; } public boolean isTimerWarmEnable() { return timerWarmEnable; } public boolean isTimerWheelEnable() { return timerWheelEnable; } public void setTimerWheelEnable(boolean timerWheelEnable) { this.timerWheelEnable = timerWheelEnable; } public boolean isTimerStopDequeue() { return timerStopDequeue; } public int getTimerMetricSmallThreshold() { return timerMetricSmallThreshold; } public void setTimerMetricSmallThreshold(int timerMetricSmallThreshold) { this.timerMetricSmallThreshold = timerMetricSmallThreshold; } public int getTimerCongestNumEachSlot() { return timerCongestNumEachSlot; } public void setTimerCongestNumEachSlot(int timerCongestNumEachSlot) { // In order to get this value from messageStoreConfig properties file created before v4.4.1. this.timerCongestNumEachSlot = timerCongestNumEachSlot; } public int getTimerFlushIntervalMs() { return timerFlushIntervalMs; } public void setTimerFlushIntervalMs(final int timerFlushIntervalMs) { this.timerFlushIntervalMs = timerFlushIntervalMs; } public void setTimerRollWindowSlot(final int timerRollWindowSlot) { this.timerRollWindowSlot = timerRollWindowSlot; } public int getTimerProgressLogIntervalMs() { return timerProgressLogIntervalMs; } public void setTimerProgressLogIntervalMs(final int timerProgressLogIntervalMs) { this.timerProgressLogIntervalMs = timerProgressLogIntervalMs; } public boolean isTimerInterceptDelayLevel() { return timerInterceptDelayLevel; } public void setTimerInterceptDelayLevel(boolean timerInterceptDelayLevel) { this.timerInterceptDelayLevel = timerInterceptDelayLevel; } public int getTimerMaxDelaySec() { return timerMaxDelaySec; } public void setTimerMaxDelaySec(final int timerMaxDelaySec) { this.timerMaxDelaySec = timerMaxDelaySec; } public int getMaxConsumeQueueScan() { return maxConsumeQueueScan; } public void setMaxConsumeQueueScan(int maxConsumeQueueScan) { this.maxConsumeQueueScan = maxConsumeQueueScan; } public int getSampleCountThreshold() { return sampleCountThreshold; } public void setSampleCountThreshold(int sampleCountThreshold) { this.sampleCountThreshold = sampleCountThreshold; } public boolean isColdDataFlowControlEnable() { return coldDataFlowControlEnable; } public void setColdDataFlowControlEnable(boolean coldDataFlowControlEnable) { this.coldDataFlowControlEnable = coldDataFlowControlEnable; } public boolean isColdDataScanEnable() { return coldDataScanEnable; } public void setColdDataScanEnable(boolean coldDataScanEnable) { this.coldDataScanEnable = coldDataScanEnable; } public int getTimerColdDataCheckIntervalMs() { return timerColdDataCheckIntervalMs; } public void setTimerColdDataCheckIntervalMs(int timerColdDataCheckIntervalMs) { this.timerColdDataCheckIntervalMs = timerColdDataCheckIntervalMs; } public int getSampleSteps() { return sampleSteps; } public void setSampleSteps(int sampleSteps) { this.sampleSteps = sampleSteps; } public int getAccessMessageInMemoryHotRatio() { return accessMessageInMemoryHotRatio; } public void setAccessMessageInMemoryHotRatio(int accessMessageInMemoryHotRatio) { this.accessMessageInMemoryHotRatio = accessMessageInMemoryHotRatio; } public boolean isDataReadAheadEnable() { return dataReadAheadEnable; } public void setDataReadAheadEnable(boolean dataReadAheadEnable) { this.dataReadAheadEnable = dataReadAheadEnable; } public boolean isEnableBuildConsumeQueueConcurrently() { return enableBuildConsumeQueueConcurrently; } public void setEnableBuildConsumeQueueConcurrently(boolean enableBuildConsumeQueueConcurrently) { this.enableBuildConsumeQueueConcurrently = enableBuildConsumeQueueConcurrently; } public int getBatchDispatchRequestThreadPoolNums() { return batchDispatchRequestThreadPoolNums; } public void setBatchDispatchRequestThreadPoolNums(int batchDispatchRequestThreadPoolNums) { this.batchDispatchRequestThreadPoolNums = batchDispatchRequestThreadPoolNums; } public boolean isRealTimePersistRocksDBConfig() { return realTimePersistRocksDBConfig; } public void setRealTimePersistRocksDBConfig(boolean realTimePersistRocksDBConfig) { this.realTimePersistRocksDBConfig = realTimePersistRocksDBConfig; } public long getStatRocksDBCQIntervalSec() { return statRocksDBCQIntervalSec; } public void setStatRocksDBCQIntervalSec(long statRocksDBCQIntervalSec) { this.statRocksDBCQIntervalSec = statRocksDBCQIntervalSec; } public long getCleanRocksDBDirtyCQIntervalMin() { return cleanRocksDBDirtyCQIntervalMin; } public void setCleanRocksDBDirtyCQIntervalMin(long cleanRocksDBDirtyCQIntervalMin) { this.cleanRocksDBDirtyCQIntervalMin = cleanRocksDBDirtyCQIntervalMin; } public long getMemTableFlushIntervalMs() { return memTableFlushIntervalMs; } public void setMemTableFlushIntervalMs(long memTableFlushIntervalMs) { this.memTableFlushIntervalMs = memTableFlushIntervalMs; } public boolean isEnableRocksDBLog() { return enableRocksDBLog; } public void setEnableRocksDBLog(boolean enableRocksDBLog) { this.enableRocksDBLog = enableRocksDBLog; } public int getTopicQueueLockNum() { return topicQueueLockNum; } public void setTopicQueueLockNum(int topicQueueLockNum) { this.topicQueueLockNum = topicQueueLockNum; } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/config/MessageStoreConfig.java
2,361
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store.kv; import com.google.common.collect.Lists; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.common.constant.LoggerName; import org.apache.rocketmq.common.message.MessageDecoder; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.logging.org.slf4j.Logger; import org.apache.rocketmq.logging.org.slf4j.LoggerFactory; import org.apache.rocketmq.store.AppendMessageResult; import org.apache.rocketmq.store.AppendMessageStatus; import org.apache.rocketmq.store.CompactionAppendMsgCallback; import org.apache.rocketmq.store.DispatchRequest; import org.apache.rocketmq.store.GetMessageResult; import org.apache.rocketmq.store.GetMessageStatus; import org.apache.rocketmq.store.MappedFileQueue; import org.apache.rocketmq.common.message.MessageExtBrokerInner; import org.apache.rocketmq.store.MessageStore; import org.apache.rocketmq.store.PutMessageLock; import org.apache.rocketmq.store.PutMessageReentrantLock; import org.apache.rocketmq.store.PutMessageResult; import org.apache.rocketmq.store.PutMessageSpinLock; import org.apache.rocketmq.store.PutMessageStatus; import org.apache.rocketmq.store.SelectMappedBufferResult; import org.apache.rocketmq.store.StoreUtil; import org.apache.rocketmq.store.config.BrokerRole; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.logfile.MappedFile; import org.apache.rocketmq.store.queue.BatchConsumeQueue; import org.apache.rocketmq.store.queue.CqUnit; import org.apache.rocketmq.store.queue.ReferredIterator; import org.apache.rocketmq.store.queue.SparseConsumeQueue; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.security.DigestException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import static org.apache.rocketmq.common.message.MessageDecoder.BLANK_MAGIC_CODE; public class CompactionLog { private static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME); private static final int END_FILE_MIN_BLANK_LENGTH = 4 + 4; private static final int MAX_PULL_MSG_SIZE = 128 * 1024 * 1024; public static final String COMPACTING_SUB_FOLDER = "compacting"; public static final String REPLICATING_SUB_FOLDER = "replicating"; private final int compactionLogMappedFileSize; private final int compactionCqMappedFileSize; private final String compactionLogFilePath; private final String compactionCqFilePath; private final MessageStore defaultMessageStore; private final CompactionStore compactionStore; private final MessageStoreConfig messageStoreConfig; private final CompactionAppendMsgCallback endMsgCallback; private final String topic; private final int queueId; private final int offsetMapMemorySize; private final PutMessageLock putMessageLock; private final PutMessageLock readMessageLock; private TopicPartitionLog current; private TopicPartitionLog compacting; private TopicPartitionLog replicating; private final CompactionPositionMgr positionMgr; private final AtomicReference<State> state; public CompactionLog(final MessageStore messageStore, final CompactionStore compactionStore, final String topic, final int queueId) throws IOException { this.topic = topic; this.queueId = queueId; this.defaultMessageStore = messageStore; this.compactionStore = compactionStore; this.messageStoreConfig = messageStore.getMessageStoreConfig(); this.offsetMapMemorySize = compactionStore.getOffsetMapSize(); this.compactionCqMappedFileSize = messageStoreConfig.getCompactionCqMappedFileSize() / BatchConsumeQueue.CQ_STORE_UNIT_SIZE * BatchConsumeQueue.CQ_STORE_UNIT_SIZE; this.compactionLogMappedFileSize = getCompactionLogSize(compactionCqMappedFileSize, messageStoreConfig.getCompactionMappedFileSize()); this.compactionLogFilePath = Paths.get(compactionStore.getCompactionLogPath(), topic, String.valueOf(queueId)).toString(); this.compactionCqFilePath = compactionStore.getCompactionCqPath(); // batch consume queue already separated this.positionMgr = compactionStore.getPositionMgr(); this.putMessageLock = messageStore.getMessageStoreConfig().isUseReentrantLockWhenPutMessage() ? new PutMessageReentrantLock() : new PutMessageSpinLock(); this.readMessageLock = messageStore.getMessageStoreConfig().isUseReentrantLockWhenPutMessage() ? new PutMessageReentrantLock() : new PutMessageSpinLock(); this.endMsgCallback = new CompactionAppendEndMsgCallback(); this.state = new AtomicReference<>(State.INITIALIZING); log.info("CompactionLog {}:{} init completed.", topic, queueId); } private int getCompactionLogSize(int cqSize, int origLogSize) { int n = origLogSize / cqSize; if (n < 5) { return cqSize * 5; } int m = origLogSize % cqSize; if (m > 0 && m < (cqSize >> 1)) { return n * cqSize; } else { return (n + 1) * cqSize; } } public void load(boolean exitOk) throws IOException, RuntimeException { initLogAndCq(exitOk); if (defaultMessageStore.getMessageStoreConfig().getBrokerRole() == BrokerRole.SLAVE && getLog().isMappedFilesEmpty()) { log.info("{}:{} load compactionLog from remote master", topic, queueId); loadFromRemoteAsync(); } else { state.compareAndSet(State.INITIALIZING, State.NORMAL); } } private void initLogAndCq(boolean exitOk) throws IOException, RuntimeException { current = new TopicPartitionLog(this); current.init(exitOk); } private boolean putMessageFromRemote(byte[] bytes) { ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); // split bytebuffer to avoid encode message again while (byteBuffer.hasRemaining()) { int mark = byteBuffer.position(); ByteBuffer bb = byteBuffer.slice(); int size = bb.getInt(); if (size < 0 || size > byteBuffer.capacity()) { break; } else { bb.limit(size); bb.rewind(); } MessageExt messageExt = MessageDecoder.decode(bb, false, false); long messageOffset = messageExt.getQueueOffset(); long minOffsetInQueue = getCQ().getMinOffsetInQueue(); if (getLog().isMappedFilesEmpty() || messageOffset < minOffsetInQueue) { asyncPutMessage(bb, messageExt, replicating); } else { log.info("{}:{} message offset {} >= minOffsetInQueue {}, stop pull...", topic, queueId, messageOffset, minOffsetInQueue); return false; } byteBuffer.position(mark + size); } return true; } private void pullMessageFromMaster() throws Exception { if (StringUtils.isBlank(compactionStore.getMasterAddr())) { compactionStore.getCompactionSchedule().schedule(() -> { try { pullMessageFromMaster(); } catch (Exception e) { log.error("pullMessageFromMaster exception: ", e); } }, 5, TimeUnit.SECONDS); return; } replicating = new TopicPartitionLog(this, REPLICATING_SUB_FOLDER); try (MessageFetcher messageFetcher = new MessageFetcher()) { messageFetcher.pullMessageFromMaster(topic, queueId, getCQ().getMinOffsetInQueue(), compactionStore.getMasterAddr(), (currOffset, response) -> { if (currOffset < 0) { log.info("{}:{} current offset {}, stop pull...", topic, queueId, currOffset); return false; } return putMessageFromRemote(response.getBody()); // positionMgr.setOffset(topic, queueId, currOffset); }); } // merge files if (getLog().isMappedFilesEmpty()) { replaceFiles(getLog().getMappedFiles(), current, replicating); } else if (replicating.getLog().isMappedFilesEmpty()) { log.info("replicating message is empty"); //break } else { List<MappedFile> newFiles = Lists.newArrayList(); List<MappedFile> toCompactFiles = Lists.newArrayList(replicating.getLog().getMappedFiles()); putMessageLock.lock(); try { // combine current and replicating to mappedFileList newFiles = Lists.newArrayList(getLog().getMappedFiles()); toCompactFiles.addAll(newFiles); //all from current current.roll(toCompactFiles.size() * compactionLogMappedFileSize); } catch (Throwable e) { log.error("roll log and cq exception: ", e); } finally { putMessageLock.unlock(); } try { // doCompaction with current and replicating compactAndReplace(new ProcessFileList(toCompactFiles, toCompactFiles)); } catch (Throwable e) { log.error("do merge replicating and current exception: ", e); } } // cleanReplicatingResource, force clean cq replicating.clean(false, true); // positionMgr.setOffset(topic, queueId, currentPullOffset); state.compareAndSet(State.INITIALIZING, State.NORMAL); } private void loadFromRemoteAsync() { compactionStore.getCompactionSchedule().submit(() -> { try { pullMessageFromMaster(); } catch (Exception e) { log.error("fetch message from master exception: ", e); } }); // update (currentStatus) = LOADING // request => get (start, end) // pull message => current message offset > end // done // positionMgr.persist(); // update (currentStatus) = RUNNING } private long nextOffsetCorrection(long oldOffset, long newOffset) { long nextOffset = oldOffset; if (messageStoreConfig.getBrokerRole() != BrokerRole.SLAVE || messageStoreConfig.isOffsetCheckInSlave()) { nextOffset = newOffset; } return nextOffset; } private boolean checkInDiskByCommitOffset(long offsetPy, long maxOffsetPy) { long memory = (long) (StoreUtil.TOTAL_PHYSICAL_MEMORY_SIZE * (this.messageStoreConfig.getAccessMessageInMemoryMaxRatio() / 100.0)); return (maxOffsetPy - offsetPy) > memory; } private boolean isTheBatchFull(int sizePy, int unitBatchNum, int maxMsgNums, long maxMsgSize, int bufferTotal, int messageTotal, boolean isInDisk) { if (0 == bufferTotal || 0 == messageTotal) { return false; } if (messageTotal + unitBatchNum > maxMsgNums) { return true; } if (bufferTotal + sizePy > maxMsgSize) { return true; } if (isInDisk) { if ((bufferTotal + sizePy) > this.messageStoreConfig.getMaxTransferBytesOnMessageInDisk()) { return true; } if (messageTotal > this.messageStoreConfig.getMaxTransferCountOnMessageInDisk() - 1) { return true; } } else { if ((bufferTotal + sizePy) > this.messageStoreConfig.getMaxTransferBytesOnMessageInMemory()) { return true; } if (messageTotal > this.messageStoreConfig.getMaxTransferCountOnMessageInMemory() - 1) { return true; } } return false; } public long rollNextFile(final long offset) { return offset + compactionLogMappedFileSize - offset % compactionLogMappedFileSize; } boolean shouldRetainMsg(final MessageExt msgExt, final OffsetMap map) throws DigestException { if (msgExt.getQueueOffset() > map.getLastOffset()) { return true; } String key = msgExt.getKeys(); if (StringUtils.isNotBlank(key)) { boolean keyNotExistOrOffsetBigger = msgExt.getQueueOffset() >= map.get(key); boolean hasBody = ArrayUtils.isNotEmpty(msgExt.getBody()); return keyNotExistOrOffsetBigger && hasBody; } else { log.error("message has no keys"); return false; } } public void checkAndPutMessage(final SelectMappedBufferResult selectMappedBufferResult, final MessageExt msgExt, final OffsetMap offsetMap, final TopicPartitionLog tpLog) throws DigestException { if (shouldRetainMsg(msgExt, offsetMap)) { asyncPutMessage(selectMappedBufferResult.getByteBuffer(), msgExt, tpLog); } } public CompletableFuture<PutMessageResult> asyncPutMessage(final SelectMappedBufferResult selectMappedBufferResult) { return asyncPutMessage(selectMappedBufferResult, current); } public CompletableFuture<PutMessageResult> asyncPutMessage(final SelectMappedBufferResult selectMappedBufferResult, final TopicPartitionLog tpLog) { MessageExt msgExt = MessageDecoder.decode(selectMappedBufferResult.getByteBuffer(), false, false); return asyncPutMessage(selectMappedBufferResult.getByteBuffer(), msgExt, tpLog); } public CompletableFuture<PutMessageResult> asyncPutMessage(final ByteBuffer msgBuffer, final MessageExt msgExt, final TopicPartitionLog tpLog) { return asyncPutMessage(msgBuffer, msgExt.getTopic(), msgExt.getQueueId(), msgExt.getQueueOffset(), msgExt.getMsgId(), msgExt.getKeys(), MessageExtBrokerInner.tagsString2tagsCode(msgExt.getTags()), msgExt.getStoreTimestamp(), tpLog); } public CompletableFuture<PutMessageResult> asyncPutMessage(final ByteBuffer msgBuffer, final DispatchRequest dispatchRequest) { return asyncPutMessage(msgBuffer, dispatchRequest.getTopic(), dispatchRequest.getQueueId(), dispatchRequest.getConsumeQueueOffset(), dispatchRequest.getUniqKey(), dispatchRequest.getKeys(), dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(), current); } public CompletableFuture<PutMessageResult> asyncPutMessage(final ByteBuffer msgBuffer, final DispatchRequest dispatchRequest, final TopicPartitionLog tpLog) { return asyncPutMessage(msgBuffer, dispatchRequest.getTopic(), dispatchRequest.getQueueId(), dispatchRequest.getConsumeQueueOffset(), dispatchRequest.getUniqKey(), dispatchRequest.getKeys(), dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(), tpLog); } public CompletableFuture<PutMessageResult> asyncPutMessage(final ByteBuffer msgBuffer, String topic, int queueId, long queueOffset, String msgId, String keys, long tagsCode, long storeTimestamp, final TopicPartitionLog tpLog) { // fix duplicate if (tpLog.getCQ().getMaxOffsetInQueue() - 1 >= queueOffset) { return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null)); } if (StringUtils.isBlank(keys)) { log.warn("message {}-{}:{} have no key, will not put in compaction log", topic, queueId, msgId); return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null)); } putMessageLock.lock(); try { long beginTime = System.nanoTime(); if (tpLog.isEmptyOrCurrentFileFull()) { try { tpLog.roll(); } catch (IOException e) { log.error("create mapped file or consumerQueue exception: ", e); return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.CREATE_MAPPED_FILE_FAILED, null)); } } MappedFile mappedFile = tpLog.getLog().getLastMappedFile(); CompactionAppendMsgCallback callback = new CompactionAppendMessageCallback(topic, queueId, tagsCode, storeTimestamp, tpLog.getCQ()); AppendMessageResult result = mappedFile.appendMessage(msgBuffer, callback); switch (result.getStatus()) { case PUT_OK: break; case END_OF_FILE: try { tpLog.roll(); } catch (IOException e) { log.error("create mapped file2 error, topic: {}, msgId: {}", topic, msgId); return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.CREATE_MAPPED_FILE_FAILED, result)); } mappedFile = tpLog.getLog().getLastMappedFile(); result = mappedFile.appendMessage(msgBuffer, callback); break; default: return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result)); } return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.PUT_OK, result)); } finally { putMessageLock.unlock(); } } private SelectMappedBufferResult getMessage(final long offset, final int size) { MappedFile mappedFile = this.getLog().findMappedFileByOffset(offset, offset == 0); if (mappedFile != null) { int pos = (int) (offset % compactionLogMappedFileSize); return mappedFile.selectMappedBuffer(pos, size); } return null; } private boolean validateCqUnit(CqUnit cqUnit) { return cqUnit.getPos() >= 0 && cqUnit.getSize() > 0 && cqUnit.getQueueOffset() >= 0 && cqUnit.getBatchNum() > 0; } public GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final int maxTotalMsgSize) { readMessageLock.lock(); try { long beginTime = System.nanoTime(); GetMessageStatus status; long nextBeginOffset = offset; long minOffset = 0; long maxOffset = 0; GetMessageResult getResult = new GetMessageResult(); final long maxOffsetPy = getLog().getMaxOffset(); SparseConsumeQueue consumeQueue = getCQ(); if (consumeQueue != null) { minOffset = consumeQueue.getMinOffsetInQueue(); maxOffset = consumeQueue.getMaxOffsetInQueue(); if (maxOffset == 0) { status = GetMessageStatus.NO_MESSAGE_IN_QUEUE; nextBeginOffset = nextOffsetCorrection(offset, 0); } else if (offset == maxOffset) { status = GetMessageStatus.OFFSET_OVERFLOW_ONE; nextBeginOffset = nextOffsetCorrection(offset, offset); } else if (offset > maxOffset) { status = GetMessageStatus.OFFSET_OVERFLOW_BADLY; if (0 == minOffset) { nextBeginOffset = nextOffsetCorrection(offset, minOffset); } else { nextBeginOffset = nextOffsetCorrection(offset, maxOffset); } } else { long maxPullSize = Math.max(maxTotalMsgSize, 100); if (maxPullSize > MAX_PULL_MSG_SIZE) { log.warn("The max pull size is too large maxPullSize={} topic={} queueId={}", maxPullSize, topic, queueId); maxPullSize = MAX_PULL_MSG_SIZE; } status = GetMessageStatus.NO_MATCHED_MESSAGE; long maxPhyOffsetPulling = 0; int cqFileNum = 0; while (getResult.getBufferTotalSize() <= 0 && nextBeginOffset < maxOffset && cqFileNum++ < this.messageStoreConfig.getTravelCqFileNumWhenGetMessage()) { ReferredIterator<CqUnit> bufferConsumeQueue = consumeQueue.iterateFromOrNext(nextBeginOffset); if (bufferConsumeQueue == null) { status = GetMessageStatus.OFFSET_FOUND_NULL; nextBeginOffset = nextOffsetCorrection(nextBeginOffset, consumeQueue.rollNextFile(nextBeginOffset)); log.warn("consumer request topic:{}, offset:{}, minOffset:{}, maxOffset:{}, " + "but access logic queue failed. correct nextBeginOffset to {}", topic, offset, minOffset, maxOffset, nextBeginOffset); break; } try { long nextPhyFileStartOffset = Long.MIN_VALUE; while (bufferConsumeQueue.hasNext() && nextBeginOffset < maxOffset) { CqUnit cqUnit = bufferConsumeQueue.next(); if (!validateCqUnit(cqUnit)) { break; } long offsetPy = cqUnit.getPos(); int sizePy = cqUnit.getSize(); boolean isInDisk = checkInDiskByCommitOffset(offsetPy, maxOffsetPy); if (isTheBatchFull(sizePy, cqUnit.getBatchNum(), maxMsgNums, maxPullSize, getResult.getBufferTotalSize(), getResult.getMessageCount(), isInDisk)) { break; } if (getResult.getBufferTotalSize() >= maxPullSize) { break; } maxPhyOffsetPulling = offsetPy; //Be careful, here should before the isTheBatchFull nextBeginOffset = cqUnit.getQueueOffset() + cqUnit.getBatchNum(); if (nextPhyFileStartOffset != Long.MIN_VALUE) { if (offsetPy < nextPhyFileStartOffset) { continue; } } SelectMappedBufferResult selectResult = getMessage(offsetPy, sizePy); if (null == selectResult) { if (getResult.getBufferTotalSize() == 0) { status = GetMessageStatus.MESSAGE_WAS_REMOVING; } // nextPhyFileStartOffset = this.commitLog.rollNextFile(offsetPy); nextPhyFileStartOffset = rollNextFile(offsetPy); continue; } this.defaultMessageStore.getStoreStatsService().getGetMessageTransferredMsgCount().add(cqUnit.getBatchNum()); getResult.addMessage(selectResult, cqUnit.getQueueOffset(), cqUnit.getBatchNum()); status = GetMessageStatus.FOUND; nextPhyFileStartOffset = Long.MIN_VALUE; } } finally { bufferConsumeQueue.release(); } } long diff = maxOffsetPy - maxPhyOffsetPulling; long memory = (long)(StoreUtil.TOTAL_PHYSICAL_MEMORY_SIZE * (this.messageStoreConfig.getAccessMessageInMemoryMaxRatio() / 100.0)); getResult.setSuggestPullingFromSlave(diff > memory); } } else { status = GetMessageStatus.NO_MATCHED_LOGIC_QUEUE; nextBeginOffset = nextOffsetCorrection(offset, 0); } if (GetMessageStatus.FOUND == status) { this.defaultMessageStore.getStoreStatsService().getGetMessageTimesTotalFound().add(getResult.getMessageCount()); } else { this.defaultMessageStore.getStoreStatsService().getGetMessageTimesTotalMiss().add(getResult.getMessageCount()); } long elapsedTime = this.defaultMessageStore.getSystemClock().now() - beginTime; this.defaultMessageStore.getStoreStatsService().setGetMessageEntireTimeMax(elapsedTime); getResult.setStatus(status); getResult.setNextBeginOffset(nextBeginOffset); getResult.setMaxOffset(maxOffset); getResult.setMinOffset(minOffset); return getResult; } finally { readMessageLock.unlock(); } } ProcessFileList getCompactionFile() { List<MappedFile> mappedFileList = Lists.newArrayList(getLog().getMappedFiles()); if (mappedFileList.size() < 2) { return null; } List<MappedFile> toCompactFiles = mappedFileList.subList(0, mappedFileList.size() - 1); //exclude the last writing file List<MappedFile> newFiles = Lists.newArrayList(); for (int i = 0; i < mappedFileList.size() - 1; i++) { MappedFile mf = mappedFileList.get(i); long maxQueueOffsetInFile = getCQ().getMaxMsgOffsetFromFile(mf.getFile().getName()); if (maxQueueOffsetInFile > positionMgr.getOffset(topic, queueId)) { newFiles.add(mf); } } if (newFiles.isEmpty()) { return null; } return new ProcessFileList(toCompactFiles, newFiles); } void compactAndReplace(ProcessFileList compactFiles) throws Throwable { if (compactFiles == null || compactFiles.isEmpty()) { return; } long startTime = System.nanoTime(); OffsetMap offsetMap = getOffsetMap(compactFiles.newFiles); compaction(compactFiles.toCompactFiles, offsetMap); replaceFiles(compactFiles.toCompactFiles, current, compacting); positionMgr.setOffset(topic, queueId, offsetMap.lastOffset); positionMgr.persist(); compacting.clean(false, false); log.info("this compaction elapsed {} milliseconds", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); } void doCompaction() { if (!state.compareAndSet(State.NORMAL, State.COMPACTING)) { log.warn("compactionLog state is {}, skip this time", state.get()); return; } try { compactAndReplace(getCompactionFile()); } catch (Throwable e) { log.error("do compaction exception: ", e); } state.compareAndSet(State.COMPACTING, State.NORMAL); } protected OffsetMap getOffsetMap(List<MappedFile> mappedFileList) throws NoSuchAlgorithmException, DigestException { OffsetMap offsetMap = new OffsetMap(offsetMapMemorySize); for (MappedFile mappedFile : mappedFileList) { Iterator<SelectMappedBufferResult> iterator = mappedFile.iterator(0); while (iterator.hasNext()) { SelectMappedBufferResult smb = null; try { smb = iterator.next(); //decode bytebuffer MessageExt msg = MessageDecoder.decode(smb.getByteBuffer(), true, false); if (msg != null) { ////get key & offset and put to offsetMap if (msg.getQueueOffset() > positionMgr.getOffset(topic, queueId)) { offsetMap.put(msg.getKeys(), msg.getQueueOffset()); } } else { // msg is null indicate that file is end break; } } catch (DigestException e) { log.error("offsetMap put exception: ", e); throw e; } finally { if (smb != null) { smb.release(); } } } } return offsetMap; } protected void putEndMessage(MappedFileQueue mappedFileQueue) { MappedFile lastFile = mappedFileQueue.getLastMappedFile(); if (!lastFile.isFull()) { lastFile.appendMessage(ByteBuffer.allocate(0), endMsgCallback); } } protected void compaction(List<MappedFile> mappedFileList, OffsetMap offsetMap) throws DigestException { compacting = new TopicPartitionLog(this, COMPACTING_SUB_FOLDER); for (MappedFile mappedFile : mappedFileList) { Iterator<SelectMappedBufferResult> iterator = mappedFile.iterator(0); while (iterator.hasNext()) { SelectMappedBufferResult smb = null; try { smb = iterator.next(); MessageExt msgExt = MessageDecoder.decode(smb.getByteBuffer(), true, true); if (msgExt == null) { // file end break; } else { checkAndPutMessage(smb, msgExt, offsetMap, compacting); } } finally { if (smb != null) { smb.release(); } } } } putEndMessage(compacting.getLog()); } protected void replaceFiles(List<MappedFile> mappedFileList, TopicPartitionLog current, TopicPartitionLog newLog) { MappedFileQueue dest = current.getLog(); MappedFileQueue src = newLog.getLog(); long beginTime = System.nanoTime(); // List<String> fileNameToReplace = mappedFileList.stream() // .map(m -> m.getFile().getName()) // .collect(Collectors.toList()); List<String> fileNameToReplace = dest.getMappedFiles().stream() .filter(mappedFileList::contains) .map(mf -> mf.getFile().getName()) .collect(Collectors.toList()); mappedFileList.forEach(MappedFile::renameToDelete); src.getMappedFiles().forEach(mappedFile -> { try { mappedFile.flush(0); mappedFile.moveToParent(); } catch (IOException e) { log.error("move file {} to parent directory exception: ", mappedFile.getFileName()); } }); dest.getMappedFiles().stream() .filter(m -> !mappedFileList.contains(m)) .forEach(m -> src.getMappedFiles().add(m)); readMessageLock.lock(); try { mappedFileList.forEach(mappedFile -> mappedFile.destroy(1000)); dest.getMappedFiles().clear(); dest.getMappedFiles().addAll(src.getMappedFiles()); src.getMappedFiles().clear(); replaceCqFiles(getCQ(), newLog.getCQ(), fileNameToReplace); log.info("replace file elapsed {} milliseconds", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime)); } finally { readMessageLock.unlock(); } } protected void replaceCqFiles(SparseConsumeQueue currentBcq, SparseConsumeQueue compactionBcq, List<String> fileNameToReplace) { long beginTime = System.nanoTime(); MappedFileQueue currentMq = currentBcq.getMappedFileQueue(); MappedFileQueue compactMq = compactionBcq.getMappedFileQueue(); List<MappedFile> fileListToDelete = currentMq.getMappedFiles().stream().filter(m -> fileNameToReplace.contains(m.getFile().getName())).collect(Collectors.toList()); fileListToDelete.forEach(MappedFile::renameToDelete); compactMq.getMappedFiles().forEach(mappedFile -> { try { mappedFile.flush(0); mappedFile.moveToParent(); } catch (IOException e) { log.error("move consume queue file {} to parent directory exception: ", mappedFile.getFileName(), e); } }); currentMq.getMappedFiles().stream() .filter(m -> !fileListToDelete.contains(m)) .forEach(m -> compactMq.getMappedFiles().add(m)); fileListToDelete.forEach(mappedFile -> mappedFile.destroy(1000)); currentMq.getMappedFiles().clear(); currentMq.getMappedFiles().addAll(compactMq.getMappedFiles()); compactMq.getMappedFiles().clear(); currentBcq.refresh(); log.info("replace consume queue file elapsed {} millsecs.", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime)); } public MappedFileQueue getLog() { return current.mappedFileQueue; } public SparseConsumeQueue getCQ() { return current.consumeQueue; } // public SparseConsumeQueue getCompactionScq() { // return compactionScq; // } public void flush(int flushLeastPages) { this.flushLog(flushLeastPages); this.flushCQ(flushLeastPages); } public void flushLog(int flushLeastPages) { getLog().flush(flushLeastPages); } public void flushCQ(int flushLeastPages) { getCQ().flush(flushLeastPages); } static class CompactionAppendEndMsgCallback implements CompactionAppendMsgCallback { @Override public AppendMessageResult doAppend(ByteBuffer bbDest, long fileFromOffset, int maxBlank, ByteBuffer bbSrc) { ByteBuffer endInfo = ByteBuffer.allocate(END_FILE_MIN_BLANK_LENGTH); endInfo.putInt(maxBlank); endInfo.putInt(BLANK_MAGIC_CODE); return new AppendMessageResult(AppendMessageStatus.END_OF_FILE, fileFromOffset + bbDest.position(), maxBlank, System.currentTimeMillis()); } } static class CompactionAppendMessageCallback implements CompactionAppendMsgCallback { private final String topic; private final int queueId; private final long tagsCode; private final long storeTimestamp; private final SparseConsumeQueue bcq; public CompactionAppendMessageCallback(MessageExt msgExt, SparseConsumeQueue bcq) { this.topic = msgExt.getTopic(); this.queueId = msgExt.getQueueId(); this.tagsCode = MessageExtBrokerInner.tagsString2tagsCode(msgExt.getTags()); this.storeTimestamp = msgExt.getStoreTimestamp(); this.bcq = bcq; } public CompactionAppendMessageCallback(String topic, int queueId, long tagsCode, long storeTimestamp, SparseConsumeQueue bcq) { this.topic = topic; this.queueId = queueId; this.tagsCode = tagsCode; this.storeTimestamp = storeTimestamp; this.bcq = bcq; } @Override public AppendMessageResult doAppend(ByteBuffer bbDest, long fileFromOffset, int maxBlank, ByteBuffer bbSrc) { final int msgLen = bbSrc.getInt(0); MappedFile bcqMappedFile = bcq.getMappedFileQueue().getLastMappedFile(); if (bcqMappedFile.getWrotePosition() + BatchConsumeQueue.CQ_STORE_UNIT_SIZE >= bcqMappedFile.getFileSize() || (msgLen + END_FILE_MIN_BLANK_LENGTH) > maxBlank) { //bcq will full or log will full bcq.putEndPositionInfo(bcqMappedFile); bbDest.putInt(maxBlank); bbDest.putInt(BLANK_MAGIC_CODE); return new AppendMessageResult(AppendMessageStatus.END_OF_FILE, fileFromOffset + bbDest.position(), maxBlank, storeTimestamp); } //get logic offset and physical offset int logicOffsetPos = 4 + 4 + 4 + 4 + 4; long logicOffset = bbSrc.getLong(logicOffsetPos); int destPos = bbDest.position(); long physicalOffset = fileFromOffset + bbDest.position(); bbSrc.rewind(); bbSrc.limit(msgLen); bbDest.put(bbSrc); bbDest.putLong(destPos + logicOffsetPos + 8, physicalOffset); //replace physical offset boolean result = bcq.putBatchMessagePositionInfo(physicalOffset, msgLen, tagsCode, storeTimestamp, logicOffset, (short)1); if (!result) { log.error("put message {}-{} position info failed", topic, queueId); } return new AppendMessageResult(AppendMessageStatus.PUT_OK, physicalOffset, msgLen, storeTimestamp); } } static class OffsetMap { private final ByteBuffer dataBytes; private final int capacity; private final int entrySize; private int entryNum; private final MessageDigest digest; private final int hashSize; private long lastOffset; private final byte[] hash1; private final byte[] hash2; public OffsetMap(int memorySize) throws NoSuchAlgorithmException { this(memorySize, MessageDigest.getInstance("MD5")); } public OffsetMap(int memorySize, MessageDigest digest) { this.hashSize = digest.getDigestLength(); this.entrySize = hashSize + (Long.SIZE / Byte.SIZE); this.capacity = Math.max(memorySize / entrySize, 100); this.dataBytes = ByteBuffer.allocate(capacity * entrySize); this.hash1 = new byte[hashSize]; this.hash2 = new byte[hashSize]; this.entryNum = 0; this.digest = digest; } public void put(String key, final long offset) throws DigestException { if (entryNum >= capacity) { throw new IllegalArgumentException("offset map is full"); } hashInto(key, hash1); int tryNum = 0; int index = indexOf(hash1, tryNum); while (!isEmpty(index)) { dataBytes.position(index); dataBytes.get(hash2); if (Arrays.equals(hash1, hash2)) { dataBytes.putLong(offset); lastOffset = offset; return; } tryNum++; index = indexOf(hash1, tryNum); } dataBytes.position(index); dataBytes.put(hash1); dataBytes.putLong(offset); lastOffset = offset; entryNum += 1; } public long get(String key) throws DigestException { hashInto(key, hash1); int tryNum = 0; int maxTryNum = entryNum + hashSize - 4; int index = 0; do { if (tryNum >= maxTryNum) { return -1L; } index = indexOf(hash1, tryNum); dataBytes.position(index); if (isEmpty(index)) { return -1L; } dataBytes.get(hash2); tryNum++; } while (!Arrays.equals(hash1, hash2)); return dataBytes.getLong(); } public long getLastOffset() { return lastOffset; } private boolean isEmpty(int pos) { return dataBytes.getLong(pos) == 0 && dataBytes.getLong(pos + 8) == 0 && dataBytes.getLong(pos + 16) == 0; } private int indexOf(byte[] hash, int tryNum) { int index = readInt(hash, Math.min(tryNum, hashSize - 4)) + Math.max(0, tryNum - hashSize + 4); int entry = Math.abs(index) % capacity; return entry * entrySize; } private void hashInto(String key, byte[] buf) throws DigestException { digest.update(key.getBytes(StandardCharsets.UTF_8)); digest.digest(buf, 0, hashSize); } private int readInt(byte[] buf, int offset) { return ((buf[offset] & 0xFF) << 24) | ((buf[offset + 1] & 0xFF) << 16) | ((buf[offset + 2] & 0xFF) << 8) | ((buf[offset + 3] & 0xFF)); } } static class TopicPartitionLog { MappedFileQueue mappedFileQueue; SparseConsumeQueue consumeQueue; public TopicPartitionLog(CompactionLog compactionLog) { this(compactionLog, null); } public TopicPartitionLog(CompactionLog compactionLog, String subFolder) { if (StringUtils.isBlank(subFolder)) { mappedFileQueue = new MappedFileQueue(compactionLog.compactionLogFilePath, compactionLog.compactionLogMappedFileSize, null); consumeQueue = new SparseConsumeQueue(compactionLog.topic, compactionLog.queueId, compactionLog.compactionCqFilePath, compactionLog.compactionCqMappedFileSize, compactionLog.defaultMessageStore); } else { mappedFileQueue = new MappedFileQueue(compactionLog.compactionLogFilePath + File.separator + subFolder, compactionLog.compactionLogMappedFileSize, null); consumeQueue = new SparseConsumeQueue(compactionLog.topic, compactionLog.queueId, compactionLog.compactionCqFilePath, compactionLog.compactionCqMappedFileSize, compactionLog.defaultMessageStore, subFolder); } } public void shutdown() { mappedFileQueue.shutdown(1000 * 30); consumeQueue.getMappedFileQueue().shutdown(1000 * 30); } public void init(boolean exitOk) throws IOException, RuntimeException { if (!mappedFileQueue.load()) { shutdown(); throw new IOException("load log exception"); } if (!consumeQueue.load()) { shutdown(); throw new IOException("load consume queue exception"); } try { consumeQueue.recover(); recover(); sanityCheck(); } catch (Exception e) { shutdown(); throw e; } } private void recover() { long maxCqPhysicOffset = consumeQueue.getMaxPhyOffsetInLog(); log.info("{}:{} max physical offset in compaction log is {}", consumeQueue.getTopic(), consumeQueue.getQueueId(), maxCqPhysicOffset); if (maxCqPhysicOffset > 0) { this.mappedFileQueue.setFlushedWhere(maxCqPhysicOffset); this.mappedFileQueue.setCommittedWhere(maxCqPhysicOffset); this.mappedFileQueue.truncateDirtyFiles(maxCqPhysicOffset); } } void sanityCheck() throws RuntimeException { List<MappedFile> mappedFileList = mappedFileQueue.getMappedFiles(); for (MappedFile file : mappedFileList) { if (!consumeQueue.containsOffsetFile(Long.parseLong(file.getFile().getName()))) { throw new RuntimeException("log file mismatch with consumeQueue file " + file.getFileName()); } } List<MappedFile> cqMappedFileList = consumeQueue.getMappedFileQueue().getMappedFiles(); for (MappedFile file: cqMappedFileList) { if (mappedFileList.stream().noneMatch(m -> Objects.equals(m.getFile().getName(), file.getFile().getName()))) { throw new RuntimeException("consumeQueue file mismatch with log file " + file.getFileName()); } } } public synchronized void roll() throws IOException { MappedFile mappedFile = mappedFileQueue.getLastMappedFile(0); if (mappedFile == null) { throw new IOException("create new file error"); } long baseOffset = mappedFile.getFileFromOffset(); MappedFile cqFile = consumeQueue.createFile(baseOffset); if (cqFile == null) { mappedFile.destroy(1000); mappedFileQueue.getMappedFiles().remove(mappedFile); throw new IOException("create new consumeQueue file error"); } } public synchronized void roll(int baseOffset) throws IOException { MappedFile mappedFile = mappedFileQueue.tryCreateMappedFile(baseOffset); if (mappedFile == null) { throw new IOException("create new file error"); } MappedFile cqFile = consumeQueue.createFile(baseOffset); if (cqFile == null) { mappedFile.destroy(1000); mappedFileQueue.getMappedFiles().remove(mappedFile); throw new IOException("create new consumeQueue file error"); } } public boolean isEmptyOrCurrentFileFull() { return mappedFileQueue.isEmptyOrCurrentFileFull() || consumeQueue.getMappedFileQueue().isEmptyOrCurrentFileFull(); } public void clean(MappedFileQueue mappedFileQueue) throws IOException { for (MappedFile mf : mappedFileQueue.getMappedFiles()) { if (mf.getFile().exists()) { log.error("directory {} with {} not empty.", mappedFileQueue.getStorePath(), mf.getFileName()); throw new IOException("directory " + mappedFileQueue.getStorePath() + " not empty."); } } mappedFileQueue.destroy(); } public void clean(boolean forceCleanLog, boolean forceCleanCq) throws IOException { //clean and delete sub_folder if (forceCleanLog) { mappedFileQueue.destroy(); } else { clean(mappedFileQueue); } if (forceCleanCq) { consumeQueue.getMappedFileQueue().destroy(); } else { clean(consumeQueue.getMappedFileQueue()); } } public MappedFileQueue getLog() { return mappedFileQueue; } public SparseConsumeQueue getCQ() { return consumeQueue; } } enum State { NORMAL, INITIALIZING, COMPACTING, } static class ProcessFileList { List<MappedFile> newFiles; List<MappedFile> toCompactFiles; public ProcessFileList(List<MappedFile> toCompactFiles, List<MappedFile> newFiles) { this.toCompactFiles = toCompactFiles; this.newFiles = newFiles; } boolean isEmpty() { return CollectionUtils.isEmpty(newFiles) || CollectionUtils.isEmpty(toCompactFiles); } } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/kv/CompactionLog.java
2,362
package timus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by sherxon on 12/4/16. */ public class Thebattleneartheswamp1990 { public static void main(String[] args) { FastReader reader= new FastReader(); int n=reader.nextInt(); int k=reader.nextInt(); int b=0; int ad=0; int ub=0; for (int i = 0; i < n; i++) { b=reader.nextInt(); if(b>k)ub+=b-k; else ad+=k-b; } System.out.println(ub+ " " + ad); } private static class FastReader { BufferedReader bf; StringTokenizer st; public static void main(String[] args) { FastReader fastReader= new FastReader(); String s=fastReader.nextLine(); String s1=fastReader.nextLine(); String s2=fastReader.next(); String s3=fastReader.next(); } public FastReader() { bf=new BufferedReader(new InputStreamReader(System.in)); } String nextLine(){ String st=""; try { st=bf.readLine(); } catch (IOException e) { e.printStackTrace(); } return st; } String next(){ while (st==null || !st.hasMoreTokens()){ try { st= new StringTokenizer(bf.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } } }
sherxon/AlgoDS
src/timus/Thebattleneartheswamp1990.java
2,363
package com.taobao.tddl.dbsync.binlog; import java.nio.charset.Charset; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * An utility class implements MySQL/Java charsets conversion. you can see * com.mysql.jdbc.CharsetMapping. * * @author <a href="mailto:[email protected]">Changyuan.lh</a> */ public final class CharsetConversion { static final Log logger = LogFactory.getLog(CharsetConversion.class); static final class Entry { protected final int charsetId; protected final String mysqlCharset; protected final String mysqlCollation; protected final String javaCharset; protected final Charset charset; Entry(final int id, String mysqlCharset, // NL String mysqlCollation, String javaCharset){ this.charsetId = id; this.mysqlCharset = mysqlCharset; this.mysqlCollation = mysqlCollation; this.javaCharset = javaCharset; this.charset = Charset.isSupported(javaCharset) ? Charset.forName(javaCharset) : null; } } // Character set data used in lookups. The array will be sparse. static final Entry[] entries = new Entry[2048]; static Entry getEntry(final int id) { if (id >= 0 && id < entries.length) { return entries[id]; } else { throw new IllegalArgumentException("Invalid charset id: " + id); } } // Loads character set information. static void putEntry(final int charsetId, String mysqlCharset, String mysqlCollation, String javaCharset) { entries[charsetId] = new Entry(charsetId, mysqlCharset, // NL mysqlCollation, javaCharset); } // Loads character set information. @Deprecated static void putEntry(final int charsetId, String mysqlCharset, String mysqlCollation) { entries[charsetId] = new Entry(charsetId, mysqlCharset, // NL mysqlCollation, /* Unknown java charset */ null); } // Load character set data statically. static { putEntry(1, "big5", "big5_chinese_ci", "Big5"); putEntry(2, "latin2", "latin2_czech_cs", "ISO8859_2"); putEntry(3, "dec8", "dec8_swedish_ci", "ISO8859_1"); putEntry(4, "cp850", "cp850_general_ci", "Cp850"); putEntry(5, "latin1", "latin1_german1_ci", "ISO8859_1"); putEntry(6, "hp8", "hp8_english_ci", "ISO8859_1"); putEntry(7, "koi8r", "koi8r_general_ci", "KOI8_R"); putEntry(8, "latin1", "latin1_swedish_ci", "ISO8859_1"); putEntry(9, "latin2", "latin2_general_ci", "ISO8859_2"); putEntry(10, "swe7", "swe7_swedish_ci", "ISO8859_1"); putEntry(11, "ascii", "ascii_general_ci", "US-ASCII"); putEntry(12, "ujis", "ujis_japanese_ci", "EUC_JP"); putEntry(13, "sjis", "sjis_japanese_ci", "SJIS"); putEntry(14, "cp1251", "cp1251_bulgarian_ci", "Cp1251"); putEntry(15, "latin1", "latin1_danish_ci", "ISO8859_1"); putEntry(16, "hebrew", "hebrew_general_ci", "ISO8859_8"); putEntry(17, "filename", "filename", "ISO8859_1"); putEntry(18, "tis620", "tis620_thai_ci", "TIS620"); putEntry(19, "euckr", "euckr_korean_ci", "EUC_KR"); putEntry(20, "latin7", "latin7_estonian_cs", "ISO8859_7"); putEntry(21, "latin2", "latin2_hungarian_ci", "ISO8859_2"); putEntry(22, "koi8u", "koi8u_general_ci", "KOI8_U"); putEntry(23, "cp1251", "cp1251_ukrainian_ci", "Cp1251"); putEntry(24, "gb2312", "gb2312_chinese_ci", "EUC_CN"); putEntry(25, "greek", "greek_general_ci", "ISO8859_7"); putEntry(26, "cp1250", "cp1250_general_ci", "Cp1250"); putEntry(27, "latin2", "latin2_croatian_ci", "ISO8859_2"); putEntry(28, "gbk", "gbk_chinese_ci", "GBK"); putEntry(29, "cp1257", "cp1257_lithuanian_ci", "Cp1257"); putEntry(30, "latin5", "latin5_turkish_ci", "ISO8859_5"); putEntry(31, "latin1", "latin1_german2_ci", "ISO8859_1"); putEntry(32, "armscii8", "armscii8_general_ci", "ISO8859_1"); putEntry(33, "utf8", "utf8_general_ci", "UTF-8"); putEntry(34, "cp1250", "cp1250_czech_cs", "Cp1250"); putEntry(35, "ucs2", "ucs2_general_ci", "UnicodeBig"); putEntry(36, "cp866", "cp866_general_ci", "Cp866"); putEntry(37, "keybcs2", "keybcs2_general_ci", "Cp852"); putEntry(38, "macce", "macce_general_ci", "MacCentralEurope"); putEntry(39, "macroman", "macroman_general_ci", "MacRoman"); putEntry(40, "cp852", "cp852_general_ci", "Cp852"); putEntry(41, "latin7", "latin7_general_ci", "ISO8859_7"); putEntry(42, "latin7", "latin7_general_cs", "ISO8859_7"); putEntry(43, "macce", "macce_bin", "MacCentralEurope"); putEntry(44, "cp1250", "cp1250_croatian_ci", "Cp1250"); putEntry(45, "utf8mb4", "utf8mb4_general_ci", "UTF-8"); putEntry(46, "utf8mb4", "utf8mb4_bin", "UTF-8"); putEntry(47, "latin1", "latin1_bin", "ISO8859_1"); putEntry(48, "latin1", "latin1_general_ci", "ISO8859_1"); putEntry(49, "latin1", "latin1_general_cs", "ISO8859_1"); putEntry(50, "cp1251", "cp1251_bin", "Cp1251"); putEntry(51, "cp1251", "cp1251_general_ci", "Cp1251"); putEntry(52, "cp1251", "cp1251_general_cs", "Cp1251"); putEntry(53, "macroman", "macroman_bin", "MacRoman"); putEntry(54, "utf16", "utf16_general_ci", "UTF-16"); putEntry(55, "utf16", "utf16_bin", "UTF-16"); putEntry(57, "cp1256", "cp1256_general_ci", "Cp1256"); putEntry(58, "cp1257", "cp1257_bin", "Cp1257"); putEntry(59, "cp1257", "cp1257_general_ci", "Cp1257"); putEntry(60, "utf32", "utf32_general_ci", "UTF-32"); putEntry(61, "utf32", "utf32_bin", "UTF-32"); putEntry(63, "binary", "binary", "US-ASCII"); putEntry(64, "armscii8", "armscii8_bin", "ISO8859_2"); putEntry(65, "ascii", "ascii_bin", "US-ASCII"); putEntry(66, "cp1250", "cp1250_bin", "Cp1250"); putEntry(67, "cp1256", "cp1256_bin", "Cp1256"); putEntry(68, "cp866", "cp866_bin", "Cp866"); putEntry(69, "dec8", "dec8_bin", "US-ASCII"); putEntry(70, "greek", "greek_bin", "ISO8859_7"); putEntry(71, "hebrew", "hebrew_bin", "ISO8859_8"); putEntry(72, "hp8", "hp8_bin", "US-ASCII"); putEntry(73, "keybcs2", "keybcs2_bin", "Cp852"); putEntry(74, "koi8r", "koi8r_bin", "KOI8_R"); putEntry(75, "koi8u", "koi8u_bin", "KOI8_U"); putEntry(77, "latin2", "latin2_bin", "ISO8859_2"); putEntry(78, "latin5", "latin5_bin", "ISO8859_5"); putEntry(79, "latin7", "latin7_bin", "ISO8859_7"); putEntry(80, "cp850", "cp850_bin", "Cp850"); putEntry(81, "cp852", "cp852_bin", "Cp852"); putEntry(82, "swe7", "swe7_bin", "ISO8859_1"); putEntry(83, "utf8", "utf8_bin", "UTF-8"); putEntry(84, "big5", "big5_bin", "Big5"); putEntry(85, "euckr", "euckr_bin", "EUC_KR"); putEntry(86, "gb2312", "gb2312_bin", "EUC_CN"); putEntry(87, "gbk", "gbk_bin", "GBK"); putEntry(88, "sjis", "sjis_bin", "SJIS"); putEntry(89, "tis620", "tis620_bin", "TIS620"); putEntry(90, "ucs2", "ucs2_bin", "UnicodeBig"); putEntry(91, "ujis", "ujis_bin", "EUC_JP"); putEntry(92, "geostd8", "geostd8_general_ci", "US-ASCII"); putEntry(93, "geostd8", "geostd8_bin", "US-ASCII"); putEntry(94, "latin1", "latin1_spanish_ci", "ISO8859_1"); putEntry(95, "cp932", "cp932_japanese_ci", "Shift_JIS"); putEntry(96, "cp932", "cp932_bin", "Shift_JIS"); putEntry(97, "eucjpms", "eucjpms_japanese_ci", "EUC_JP"); putEntry(98, "eucjpms", "eucjpms_bin", "EUC_JP"); putEntry(99, "cp1250", "cp1250_polish_ci", "Cp1250"); putEntry(101, "utf16", "utf16_unicode_ci", "UTF-16"); putEntry(102, "utf16", "utf16_icelandic_ci", "UTF-16"); putEntry(103, "utf16", "utf16_latvian_ci", "UTF-16"); putEntry(104, "utf16", "utf16_romanian_ci", "UTF-16"); putEntry(105, "utf16", "utf16_slovenian_ci", "UTF-16"); putEntry(106, "utf16", "utf16_polish_ci", "UTF-16"); putEntry(107, "utf16", "utf16_estonian_ci", "UTF-16"); putEntry(108, "utf16", "utf16_spanish_ci", "UTF-16"); putEntry(109, "utf16", "utf16_swedish_ci", "UTF-16"); putEntry(110, "utf16", "utf16_turkish_ci", "UTF-16"); putEntry(111, "utf16", "utf16_czech_ci", "UTF-16"); putEntry(112, "utf16", "utf16_danish_ci", "UTF-16"); putEntry(113, "utf16", "utf16_lithuanian_ci", "UTF-16"); putEntry(114, "utf16", "utf16_slovak_ci", "UTF-16"); putEntry(115, "utf16", "utf16_spanish2_ci", "UTF-16"); putEntry(116, "utf16", "utf16_roman_ci", "UTF-16"); putEntry(117, "utf16", "utf16_persian_ci", "UTF-16"); putEntry(118, "utf16", "utf16_esperanto_ci", "UTF-16"); putEntry(119, "utf16", "utf16_hungarian_ci", "UTF-16"); putEntry(120, "utf16", "utf16_sinhala_ci", "UTF-16"); putEntry(128, "ucs2", "ucs2_unicode_ci", "UnicodeBig"); putEntry(129, "ucs2", "ucs2_icelandic_ci", "UnicodeBig"); putEntry(130, "ucs2", "ucs2_latvian_ci", "UnicodeBig"); putEntry(131, "ucs2", "ucs2_romanian_ci", "UnicodeBig"); putEntry(132, "ucs2", "ucs2_slovenian_ci", "UnicodeBig"); putEntry(133, "ucs2", "ucs2_polish_ci", "UnicodeBig"); putEntry(134, "ucs2", "ucs2_estonian_ci", "UnicodeBig"); putEntry(135, "ucs2", "ucs2_spanish_ci", "UnicodeBig"); putEntry(136, "ucs2", "ucs2_swedish_ci", "UnicodeBig"); putEntry(137, "ucs2", "ucs2_turkish_ci", "UnicodeBig"); putEntry(138, "ucs2", "ucs2_czech_ci", "UnicodeBig"); putEntry(139, "ucs2", "ucs2_danish_ci", "UnicodeBig"); putEntry(140, "ucs2", "ucs2_lithuanian_ci", "UnicodeBig"); putEntry(141, "ucs2", "ucs2_slovak_ci", "UnicodeBig"); putEntry(142, "ucs2", "ucs2_spanish2_ci", "UnicodeBig"); putEntry(143, "ucs2", "ucs2_roman_ci", "UnicodeBig"); putEntry(144, "ucs2", "ucs2_persian_ci", "UnicodeBig"); putEntry(145, "ucs2", "ucs2_esperanto_ci", "UnicodeBig"); putEntry(146, "ucs2", "ucs2_hungarian_ci", "UnicodeBig"); putEntry(147, "ucs2", "ucs2_sinhala_ci", "UnicodeBig"); putEntry(160, "utf32", "utf32_unicode_ci", "UTF-32"); putEntry(161, "utf32", "utf32_icelandic_ci", "UTF-32"); putEntry(162, "utf32", "utf32_latvian_ci", "UTF-32"); putEntry(163, "utf32", "utf32_romanian_ci", "UTF-32"); putEntry(164, "utf32", "utf32_slovenian_ci", "UTF-32"); putEntry(165, "utf32", "utf32_polish_ci", "UTF-32"); putEntry(166, "utf32", "utf32_estonian_ci", "UTF-32"); putEntry(167, "utf32", "utf32_spanish_ci", "UTF-32"); putEntry(168, "utf32", "utf32_swedish_ci", "UTF-32"); putEntry(169, "utf32", "utf32_turkish_ci", "UTF-32"); putEntry(170, "utf32", "utf32_czech_ci", "UTF-32"); putEntry(171, "utf32", "utf32_danish_ci", "UTF-32"); putEntry(172, "utf32", "utf32_lithuanian_ci", "UTF-32"); putEntry(173, "utf32", "utf32_slovak_ci", "UTF-32"); putEntry(174, "utf32", "utf32_spanish2_ci", "UTF-32"); putEntry(175, "utf32", "utf32_roman_ci", "UTF-32"); putEntry(176, "utf32", "utf32_persian_ci", "UTF-32"); putEntry(177, "utf32", "utf32_esperanto_ci", "UTF-32"); putEntry(178, "utf32", "utf32_hungarian_ci", "UTF-32"); putEntry(179, "utf32", "utf32_sinhala_ci", "UTF-32"); putEntry(192, "utf8", "utf8_unicode_ci", "UTF-8"); putEntry(193, "utf8", "utf8_icelandic_ci", "UTF-8"); putEntry(194, "utf8", "utf8_latvian_ci", "UTF-8"); putEntry(195, "utf8", "utf8_romanian_ci", "UTF-8"); putEntry(196, "utf8", "utf8_slovenian_ci", "UTF-8"); putEntry(197, "utf8", "utf8_polish_ci", "UTF-8"); putEntry(198, "utf8", "utf8_estonian_ci", "UTF-8"); putEntry(199, "utf8", "utf8_spanish_ci", "UTF-8"); putEntry(200, "utf8", "utf8_swedish_ci", "UTF-8"); putEntry(201, "utf8", "utf8_turkish_ci", "UTF-8"); putEntry(202, "utf8", "utf8_czech_ci", "UTF-8"); putEntry(203, "utf8", "utf8_danish_ci", "UTF-8"); putEntry(204, "utf8", "utf8_lithuanian_ci", "UTF-8"); putEntry(205, "utf8", "utf8_slovak_ci", "UTF-8"); putEntry(206, "utf8", "utf8_spanish2_ci", "UTF-8"); putEntry(207, "utf8", "utf8_roman_ci", "UTF-8"); putEntry(208, "utf8", "utf8_persian_ci", "UTF-8"); putEntry(209, "utf8", "utf8_esperanto_ci", "UTF-8"); putEntry(210, "utf8", "utf8_hungarian_ci", "UTF-8"); putEntry(211, "utf8", "utf8_sinhala_ci", "UTF-8"); putEntry(224, "utf8mb4", "utf8mb4_unicode_ci", "UTF-8"); putEntry(225, "utf8mb4", "utf8mb4_icelandic_ci", "UTF-8"); putEntry(226, "utf8mb4", "utf8mb4_latvian_ci", "UTF-8"); putEntry(227, "utf8mb4", "utf8mb4_romanian_ci", "UTF-8"); putEntry(228, "utf8mb4", "utf8mb4_slovenian_ci", "UTF-8"); putEntry(229, "utf8mb4", "utf8mb4_polish_ci", "UTF-8"); putEntry(230, "utf8mb4", "utf8mb4_estonian_ci", "UTF-8"); putEntry(231, "utf8mb4", "utf8mb4_spanish_ci", "UTF-8"); putEntry(232, "utf8mb4", "utf8mb4_swedish_ci", "UTF-8"); putEntry(233, "utf8mb4", "utf8mb4_turkish_ci", "UTF-8"); putEntry(234, "utf8mb4", "utf8mb4_czech_ci", "UTF-8"); putEntry(235, "utf8mb4", "utf8mb4_danish_ci", "UTF-8"); putEntry(236, "utf8mb4", "utf8mb4_lithuanian_ci", "UTF-8"); putEntry(237, "utf8mb4", "utf8mb4_slovak_ci", "UTF-8"); putEntry(238, "utf8mb4", "utf8mb4_spanish2_ci", "UTF-8"); putEntry(239, "utf8mb4", "utf8mb4_roman_ci", "UTF-8"); putEntry(240, "utf8mb4", "utf8mb4_persian_ci", "UTF-8"); putEntry(241, "utf8mb4", "utf8mb4_esperanto_ci", "UTF-8"); putEntry(242, "utf8mb4", "utf8mb4_hungarian_ci", "UTF-8"); putEntry(243, "utf8mb4", "utf8mb4_sinhala_ci", "UTF-8"); putEntry(244, "utf8mb4", "utf8mb4_german2_ci", "UTF-8"); putEntry(245, "utf8mb4", "utf8mb4_croatian_ci", "UTF-8"); putEntry(246, "utf8mb4", "utf8mb4_unicode_520_ci", "UTF-8"); putEntry(247, "utf8mb4", "utf8mb4_vietnamese_ci", "UTF-8"); putEntry(248, "gb18030", "gb18030_chinese_ci", "GB18030"); putEntry(249, "gb18030", "gb18030_bin", "GB18030"); putEntry(250, "gb18030", "gb18030_unicode_520_ci", "GB18030"); putEntry(254, "utf8", "utf8_general_cs", "UTF-8"); putEntry(255, "utf8mb4", "utf8mb4_0900_ai_ci", "UTF-8"); putEntry(256, "utf8mb4", "utf8mb4_de_pb_0900_ai_ci", "UTF-8"); putEntry(257, "utf8mb4", "utf8mb4_is_0900_ai_ci", "UTF-8"); putEntry(258, "utf8mb4", "utf8mb4_lv_0900_ai_ci", "UTF-8"); putEntry(259, "utf8mb4", "utf8mb4_ro_0900_ai_ci", "UTF-8"); putEntry(260, "utf8mb4", "utf8mb4_sl_0900_ai_ci", "UTF-8"); putEntry(261, "utf8mb4", "utf8mb4_pl_0900_ai_ci", "UTF-8"); putEntry(262, "utf8mb4", "utf8mb4_et_0900_ai_ci", "UTF-8"); putEntry(263, "utf8mb4", "utf8mb4_es_0900_ai_ci", "UTF-8"); putEntry(264, "utf8mb4", "utf8mb4_sv_0900_ai_ci", "UTF-8"); putEntry(265, "utf8mb4", "utf8mb4_tr_0900_ai_ci", "UTF-8"); putEntry(266, "utf8mb4", "utf8mb4_cs_0900_ai_ci", "UTF-8"); putEntry(267, "utf8mb4", "utf8mb4_da_0900_ai_ci", "UTF-8"); putEntry(268, "utf8mb4", "utf8mb4_lt_0900_ai_ci", "UTF-8"); putEntry(269, "utf8mb4", "utf8mb4_sk_0900_ai_ci", "UTF-8"); putEntry(270, "utf8mb4", "utf8mb4_es_trad_0900_ai_ci", "UTF-8"); putEntry(271, "utf8mb4", "utf8mb4_la_0900_ai_ci", "UTF-8"); putEntry(273, "utf8mb4", "utf8mb4_eo_0900_ai_ci", "UTF-8"); putEntry(274, "utf8mb4", "utf8mb4_hu_0900_ai_ci", "UTF-8"); putEntry(275, "utf8mb4", "utf8mb4_hr_0900_ai_ci", "UTF-8"); putEntry(277, "utf8mb4", "utf8mb4_vi_0900_ai_ci", "UTF-8"); putEntry(278, "utf8mb4", "utf8mb4_0900_as_cs", "UTF-8"); putEntry(279, "utf8mb4", "utf8mb4_de_pb_0900_as_cs", "UTF-8"); putEntry(280, "utf8mb4", "utf8mb4_is_0900_as_cs", "UTF-8"); putEntry(281, "utf8mb4", "utf8mb4_lv_0900_as_cs", "UTF-8"); putEntry(282, "utf8mb4", "utf8mb4_ro_0900_as_cs", "UTF-8"); putEntry(283, "utf8mb4", "utf8mb4_sl_0900_as_cs", "UTF-8"); putEntry(284, "utf8mb4", "utf8mb4_pl_0900_as_cs", "UTF-8"); putEntry(285, "utf8mb4", "utf8mb4_et_0900_as_cs", "UTF-8"); putEntry(286, "utf8mb4", "utf8mb4_es_0900_as_cs", "UTF-8"); putEntry(287, "utf8mb4", "utf8mb4_sv_0900_as_cs", "UTF-8"); putEntry(288, "utf8mb4", "utf8mb4_tr_0900_as_cs", "UTF-8"); putEntry(289, "utf8mb4", "utf8mb4_cs_0900_as_cs", "UTF-8"); putEntry(290, "utf8mb4", "utf8mb4_da_0900_as_cs", "UTF-8"); putEntry(291, "utf8mb4", "utf8mb4_lt_0900_as_cs", "UTF-8"); putEntry(292, "utf8mb4", "utf8mb4_sk_0900_as_cs", "UTF-8"); putEntry(293, "utf8mb4", "utf8mb4_es_trad_0900_as_cs", "UTF-8"); putEntry(294, "utf8mb4", "utf8mb4_la_0900_as_cs", "UTF-8"); putEntry(296, "utf8mb4", "utf8mb4_eo_0900_as_cs", "UTF-8"); putEntry(297, "utf8mb4", "utf8mb4_hu_0900_as_cs", "UTF-8"); putEntry(298, "utf8mb4", "utf8mb4_hr_0900_as_cs", "UTF-8"); putEntry(300, "utf8mb4", "utf8mb4_vi_0900_as_cs", "UTF-8"); putEntry(303, "utf8mb4", "utf8mb4_ja_0900_as_cs", "UTF-8"); putEntry(304, "utf8mb4", "utf8mb4_ja_0900_as_cs_ks", "UTF-8"); putEntry(305, "utf8mb4", "utf8mb4_0900_as_ci", "UTF-8"); putEntry(306, "utf8mb4", "utf8mb4_ru_0900_ai_ci", "UTF-8"); putEntry(307, "utf8mb4", "utf8mb4_ru_0900_as_cs", "UTF-8"); putEntry(326, "utf8mb4", "utf8mb4_test_ci", "UTF-8"); putEntry(327, "utf16", "utf16_test_ci", "UTF-16"); putEntry(328, "utf8mb4", "utf8mb4_test_400_ci", "UTF-8"); putEntry(336, "utf8", "utf8_bengali_standard_ci", "UTF-8"); putEntry(337, "utf8", "utf8_bengali_standard_ci", "UTF-8"); putEntry(352, "utf8", "utf8_phone_ci", "UTF-8"); putEntry(353, "utf8", "utf8_test_ci", "UTF-8"); putEntry(354, "utf8", "utf8_5624_1", "UTF-8"); putEntry(355, "utf8", "utf8_5624_2", "UTF-8"); putEntry(356, "utf8", "utf8_5624_3", "UTF-8"); putEntry(357, "utf8", "utf8_5624_4", "UTF-8"); putEntry(358, "ucs2", "ucs2_test_ci", "UnicodeBig"); putEntry(359, "ucs2", "ucs2_vn_ci", "UnicodeBig"); putEntry(360, "ucs2", "ucs2_5624_1", "UnicodeBig"); putEntry(368, "utf8", "utf8_5624_5", "UTF-8"); putEntry(391, "utf32", "utf32_test_ci", "UTF-32"); putEntry(2047, "utf8", "utf8_maxuserid_ci", "UTF-8"); } /** * Return defined charset name for mysql. */ public static String getCharset(final int id) { Entry entry = getEntry(id); if (entry != null) { return entry.mysqlCharset; } else { logger.warn("Unexpect mysql charset: " + id); return null; } } /** * Return defined collaction name for mysql. */ public static String getCollation(final int id) { Entry entry = getEntry(id); if (entry != null) { return entry.mysqlCollation; } else { logger.warn("Unexpect mysql charset: " + id); return null; } } /** * Return converted charset name for java. */ public static String getJavaCharset(final int id) { Entry entry = getEntry(id); if (entry != null) { if (entry.javaCharset != null) { return entry.javaCharset; } else { logger.warn("Unknown java charset for: id = " + id + ", name = " + entry.mysqlCharset + ", coll = " + entry.mysqlCollation); return null; } } else { logger.warn("Unexpect mysql charset: " + id); return null; } } public static Charset getNioCharset(final int id) { Entry entry = getEntry(id); if (entry != null) { if (entry.charset != null) { return entry.charset; } else { logger.warn("Unknown java charset for: id = " + id + ", name = " + entry.mysqlCharset + ", coll = " + entry.mysqlCollation); return null; } } else { logger.warn("Unexpect mysql charset: " + id); return null; } } public static void main(String[] args) { for (int i = 0; i < entries.length; i++) { Entry entry = entries[i]; System.out.print(i); System.out.print(','); System.out.print(' '); if (entry != null) { System.out.print(entry.mysqlCharset); System.out.print(','); System.out.print(' '); System.out.print(entry.javaCharset); if (entry.javaCharset != null) { System.out.print(','); System.out.print(' '); System.out.print(Charset.forName(entry.javaCharset).name()); } } else { System.out.print("null"); } System.out.println(); } } }
alibaba/canal
dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/CharsetConversion.java
2,364
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.locale; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; @Slf4j public class LanguageUtil { private static final List<String> userLanguageCodes = Arrays.asList( "en", // English "de", // German "es", // Spanish "pt", // Portuguese "pt-BR", // Portuguese (Brazil) "zh-Hans", // Chinese [Han Simplified] "zh-Hant", // Chinese [Han Traditional] "ru", // Russian "fr", // French "vi", // Vietnamese "th", // Thai "ja", // Japanese "fa", // Persian "it", // Italian "cs", // Czech "pl" // Polish /* // not translated yet "el", // Greek "sr-Latn-RS", // Serbian [Latin] (Serbia) "hu", // Hungarian "ro", // Romanian "tr" // Turkish "iw", // Hebrew "hi", // Hindi "ko", // Korean "sv", // Swedish "no", // Norwegian "nl", // Dutch "be", // Belarusian "fi", // Finnish "bg", // Bulgarian "lt", // Lithuanian "lv", // Latvian "hr", // Croatian "uk", // Ukrainian "sk", // Slovak "sl", // Slovenian "ga", // Irish "sq", // Albanian "ca", // Catalan "mk", // Macedonian "kk", // Kazakh "km", // Khmer "sw", // Swahili "in", // Indonesian "ms", // Malay "is", // Icelandic "et", // Estonian "ar", // Arabic "vi", // Vietnamese "th", // Thai "da", // Danish "mt" // Maltese */ ); private static final List<String> rtlLanguagesCodes = Arrays.asList( "fa", // Persian "ar", // Arabic "iw" // Hebrew ); public static List<String> getAllLanguageCodes() { List<Locale> allLocales = LocaleUtil.getAllLocales(); // Filter duplicate locale entries Set<String> allLocalesAsSet = allLocales.stream().filter(locale -> !locale.getLanguage().isEmpty() && !locale.getDisplayLanguage().isEmpty()) .map(Locale::getLanguage) .collect(Collectors.toSet()); List<String> allLanguageCodes = new ArrayList<>(); allLanguageCodes.addAll(allLocalesAsSet); allLanguageCodes.sort((o1, o2) -> getDisplayName(o1).compareTo(getDisplayName(o2))); return allLanguageCodes; } public static String getDefaultLanguage() { // might be set later in pref or config, so not use defaultLocale anywhere in the code return getLocale().getLanguage(); } public static String getDefaultLanguageLocaleAsCode() { return new Locale(LanguageUtil.getDefaultLanguage()).getLanguage(); } public static String getEnglishLanguageLocaleCode() { return new Locale(Locale.ENGLISH.getLanguage()).getLanguage(); } public static String getDisplayName(String code) { Locale locale = Locale.forLanguageTag(code); return locale.getDisplayName(locale); } public static boolean isDefaultLanguageRTL() { return rtlLanguagesCodes.contains(LanguageUtil.getDefaultLanguageLocaleAsCode()); } public static List<String> getUserLanguageCodes() { return userLanguageCodes; } private static Locale getLocale() { return GlobalSettings.getLocale(); } }
bisq-network/bisq
core/src/main/java/bisq/core/locale/LanguageUtil.java
2,365
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store.queue; import org.apache.rocketmq.common.BoundaryType; import org.apache.rocketmq.common.UtilAll; import org.apache.rocketmq.store.MessageStore; import org.apache.rocketmq.store.SelectMappedBufferResult; import org.apache.rocketmq.store.logfile.MappedFile; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; public class SparseConsumeQueue extends BatchConsumeQueue { public SparseConsumeQueue( final String topic, final int queueId, final String storePath, final int mappedFileSize, final MessageStore defaultMessageStore) { super(topic, queueId, storePath, mappedFileSize, defaultMessageStore); } public SparseConsumeQueue( final String topic, final int queueId, final String storePath, final int mappedFileSize, final MessageStore defaultMessageStore, final String subfolder) { super(topic, queueId, storePath, mappedFileSize, defaultMessageStore, subfolder); } @Override public void recover() { final List<MappedFile> mappedFiles = this.mappedFileQueue.getMappedFiles(); if (!mappedFiles.isEmpty()) { int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } MappedFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); int mappedFileOffset = 0; long processOffset = mappedFile.getFileFromOffset(); while (true) { for (int i = 0; i < mappedFileSize; i += CQ_STORE_UNIT_SIZE) { byteBuffer.position(i); long offset = byteBuffer.getLong(); int size = byteBuffer.getInt(); byteBuffer.getLong(); //tagscode byteBuffer.getLong(); //timestamp long msgBaseOffset = byteBuffer.getLong(); short batchSize = byteBuffer.getShort(); if (offset >= 0 && size > 0 && msgBaseOffset >= 0 && batchSize > 0) { mappedFileOffset += CQ_STORE_UNIT_SIZE; this.maxMsgPhyOffsetInCommitLog = offset; } else { log.info("Recover current batch consume queue file over, " + "file:{} offset:{} size:{} msgBaseOffset:{} batchSize:{} mappedFileOffset:{}", mappedFile.getFileName(), offset, size, msgBaseOffset, batchSize, mappedFileOffset); if (mappedFileOffset != mappedFileSize) { mappedFile.setWrotePosition(mappedFileOffset); mappedFile.setFlushedPosition(mappedFileOffset); mappedFile.setCommittedPosition(mappedFileOffset); } break; } } index++; if (index >= mappedFiles.size()) { log.info("Recover last batch consume queue file over, last mapped file:{} ", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); mappedFileOffset = 0; log.info("Recover next batch consume queue file: " + mappedFile.getFileName()); } } processOffset += mappedFileOffset; mappedFileQueue.setFlushedWhere(processOffset); mappedFileQueue.setCommittedWhere(processOffset); mappedFileQueue.truncateDirtyFiles(processOffset); reviseMaxAndMinOffsetInQueue(); } } public ReferredIterator<CqUnit> iterateFromOrNext(long startOffset) { SelectMappedBufferResult sbr = getBatchMsgIndexOrNextBuffer(startOffset); if (sbr == null) { return null; } return new BatchConsumeQueueIterator(sbr); } /** * Gets SelectMappedBufferResult by batch-message offset, if not found will return the next valid offset buffer * Node: the caller is responsible for the release of SelectMappedBufferResult * @param msgOffset * @return SelectMappedBufferResult */ public SelectMappedBufferResult getBatchMsgIndexOrNextBuffer(final long msgOffset) { MappedFile targetBcq; if (msgOffset <= minOffsetInQueue) { targetBcq = mappedFileQueue.getFirstMappedFile(); } else { targetBcq = searchFileByOffsetOrRight(msgOffset); } if (targetBcq == null) { return null; } BatchOffsetIndex minOffset = getMinMsgOffset(targetBcq, false, false); BatchOffsetIndex maxOffset = getMaxMsgOffset(targetBcq, false, false); if (null == minOffset || null == maxOffset) { return null; } SelectMappedBufferResult sbr = minOffset.getMappedFile().selectMappedBuffer(0); try { ByteBuffer byteBuffer = sbr.getByteBuffer(); int left = minOffset.getIndexPos(); int right = maxOffset.getIndexPos(); int mid = binarySearchRight(byteBuffer, left, right, CQ_STORE_UNIT_SIZE, MSG_BASE_OFFSET_INDEX, msgOffset, BoundaryType.LOWER); if (mid != -1) { return minOffset.getMappedFile().selectMappedBuffer(mid); } } finally { sbr.release(); } return null; } protected MappedFile searchOffsetFromCacheOrRight(long msgOffset) { Map.Entry<Long, MappedFile> ceilingEntry = this.offsetCache.ceilingEntry(msgOffset); if (ceilingEntry == null) { return null; } else { return ceilingEntry.getValue(); } } protected MappedFile searchFileByOffsetOrRight(long msgOffset) { MappedFile targetBcq = null; boolean searchBcqByCacheEnable = this.messageStore.getMessageStoreConfig().isSearchBcqByCacheEnable(); if (searchBcqByCacheEnable) { // it's not the last BCQ file, so search it through cache. targetBcq = this.searchOffsetFromCacheOrRight(msgOffset); // not found in cache if (targetBcq == null) { MappedFile firstBcq = mappedFileQueue.getFirstMappedFile(); BatchOffsetIndex minForFirstBcq = getMinMsgOffset(firstBcq, false, false); if (minForFirstBcq != null && minForFirstBcq.getMsgOffset() <= msgOffset && msgOffset < maxOffsetInQueue) { // old search logic targetBcq = this.searchOffsetFromFilesOrRight(msgOffset); } log.warn("cache is not working on BCQ [Topic: {}, QueueId: {}] for msgOffset: {}, targetBcq: {}", this.topic, this.queueId, msgOffset, targetBcq); } } else { // old search logic targetBcq = this.searchOffsetFromFilesOrRight(msgOffset); } return targetBcq; } public MappedFile searchOffsetFromFilesOrRight(long msgOffset) { MappedFile targetBcq = null; // find the mapped file one by one reversely int mappedFileNum = this.mappedFileQueue.getMappedFiles().size(); for (int i = mappedFileNum - 1; i >= 0; i--) { MappedFile mappedFile = mappedFileQueue.getMappedFiles().get(i); BatchOffsetIndex tmpMinMsgOffset = getMinMsgOffset(mappedFile, false, false); BatchOffsetIndex tmpMaxMsgOffset = getMaxMsgOffset(mappedFile, false, false); if (null != tmpMaxMsgOffset && tmpMaxMsgOffset.getMsgOffset() < msgOffset) { if (i != mappedFileNum - 1) { //not the last mapped file max msg offset targetBcq = mappedFileQueue.getMappedFiles().get(i + 1); break; } } if (null != tmpMinMsgOffset && tmpMinMsgOffset.getMsgOffset() <= msgOffset && null != tmpMaxMsgOffset && msgOffset <= tmpMaxMsgOffset.getMsgOffset()) { targetBcq = mappedFile; break; } } return targetBcq; } private MappedFile getPreFile(MappedFile file) { int index = mappedFileQueue.getMappedFiles().indexOf(file); if (index < 1) { // indicate that this is the first file or not found return null; } else { return mappedFileQueue.getMappedFiles().get(index - 1); } } private void cacheOffset(MappedFile file, Function<MappedFile, BatchOffsetIndex> offsetGetFunc) { try { BatchOffsetIndex offset = offsetGetFunc.apply(file); if (offset != null) { this.offsetCache.put(offset.getMsgOffset(), offset.getMappedFile()); this.timeCache.put(offset.getStoreTimestamp(), offset.getMappedFile()); } } catch (Exception e) { log.error("Failed caching offset and time on BCQ [Topic: {}, QueueId: {}, File: {}]", this.topic, this.queueId, file); } } @Override protected void cacheBcq(MappedFile bcq) { MappedFile file = getPreFile(bcq); if (file != null) { cacheOffset(file, m -> getMaxMsgOffset(m, false, true)); } } public void putEndPositionInfo(MappedFile mappedFile) { // cache max offset if (!mappedFile.isFull()) { this.byteBufferItem.flip(); this.byteBufferItem.limit(CQ_STORE_UNIT_SIZE); this.byteBufferItem.putLong(-1); this.byteBufferItem.putInt(0); this.byteBufferItem.putLong(0); this.byteBufferItem.putLong(0); this.byteBufferItem.putLong(0); this.byteBufferItem.putShort((short)0); this.byteBufferItem.putInt(INVALID_POS); this.byteBufferItem.putInt(0); // 4 bytes reserved boolean appendRes = mappedFile.appendMessage(this.byteBufferItem.array()); if (!appendRes) { log.error("append end position info into {} failed", mappedFile.getFileName()); } } cacheOffset(mappedFile, m -> getMaxMsgOffset(m, false, true)); } public MappedFile createFile(final long physicalOffset) throws IOException { // cache max offset return mappedFileQueue.tryCreateMappedFile(physicalOffset); } public boolean isLastFileFull() { if (mappedFileQueue.getLastMappedFile() != null) { return mappedFileQueue.getLastMappedFile().isFull(); } else { return true; } } public boolean shouldRoll() { if (mappedFileQueue.getLastMappedFile() == null) { return true; } if (mappedFileQueue.getLastMappedFile().isFull()) { return true; } if (mappedFileQueue.getLastMappedFile().getWrotePosition() + BatchConsumeQueue.CQ_STORE_UNIT_SIZE > mappedFileQueue.getMappedFileSize()) { return true; } return false; } public boolean containsOffsetFile(final long physicalOffset) { String fileName = UtilAll.offset2FileName(physicalOffset); return mappedFileQueue.getMappedFiles().stream() .anyMatch(mf -> Objects.equals(mf.getFile().getName(), fileName)); } public long getMaxPhyOffsetInLog() { MappedFile lastMappedFile = mappedFileQueue.getLastMappedFile(); Long maxOffsetInLog = getMax(lastMappedFile, b -> b.getLong(0) + b.getInt(8)); if (maxOffsetInLog != null) { return maxOffsetInLog; } else { return -1; } } private <T> T getMax(MappedFile mappedFile, Function<ByteBuffer, T> function) { if (mappedFile == null || mappedFile.getReadPosition() < CQ_STORE_UNIT_SIZE) { return null; } ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); for (int i = mappedFile.getReadPosition() - CQ_STORE_UNIT_SIZE; i >= 0; i -= CQ_STORE_UNIT_SIZE) { byteBuffer.position(i); long offset = byteBuffer.getLong(); int size = byteBuffer.getInt(); long tagsCode = byteBuffer.getLong(); //tagscode long timestamp = byteBuffer.getLong(); //timestamp long msgBaseOffset = byteBuffer.getLong(); short batchSize = byteBuffer.getShort(); if (offset >= 0 && size > 0 && msgBaseOffset >= 0 && batchSize > 0) { byteBuffer.position(i); //reset position return function.apply(byteBuffer.slice()); } } return null; } @Override protected BatchOffsetIndex getMaxMsgOffset(MappedFile mappedFile, boolean getBatchSize, boolean getStoreTime) { if (mappedFile == null || mappedFile.getReadPosition() < CQ_STORE_UNIT_SIZE) { return null; } ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); for (int i = mappedFile.getReadPosition() - CQ_STORE_UNIT_SIZE; i >= 0; i -= CQ_STORE_UNIT_SIZE) { byteBuffer.position(i); long offset = byteBuffer.getLong(); int size = byteBuffer.getInt(); byteBuffer.getLong(); //tagscode long timestamp = byteBuffer.getLong();//timestamp long msgBaseOffset = byteBuffer.getLong(); short batchSize = byteBuffer.getShort(); if (offset >= 0 && size > 0 && msgBaseOffset >= 0 && batchSize > 0) { // mappedFile.setWrotePosition(i + CQ_STORE_UNIT_SIZE); // mappedFile.setFlushedPosition(i + CQ_STORE_UNIT_SIZE); // mappedFile.setCommittedPosition(i + CQ_STORE_UNIT_SIZE); return new BatchOffsetIndex(mappedFile, i, msgBaseOffset, batchSize, timestamp); } } return null; } public long getMaxMsgOffsetFromFile(String simpleFileName) { MappedFile mappedFile = mappedFileQueue.getMappedFiles().stream() .filter(m -> Objects.equals(m.getFile().getName(), simpleFileName)) .findFirst() .orElse(null); if (mappedFile == null) { return -1; } BatchOffsetIndex max = getMaxMsgOffset(mappedFile, false, false); if (max == null) { return -1; } return max.getMsgOffset(); } private void refreshMaxCache() { doRefreshCache(m -> getMaxMsgOffset(m, false, true)); } @Override protected void refreshCache() { refreshMaxCache(); } public void refresh() { reviseMaxAndMinOffsetInQueue(); refreshCache(); } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/queue/SparseConsumeQueue.java
2,366
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * 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.jkiss.dbeaver.ext.oracle.model.dict; /** * NLS language dictionary */ public enum OracleLanguage { AMERICAN("AMERICAN"), ARABIC("ARABIC"), BENGALI("BENGALI"), BRAZILIAN_PORTUGUESE("BRAZILIAN PORTUGUESE "), BULGARIAN("BULGARIAN"), CANADIAN_FRENCH("CANADIAN FRENCH"), CATALAN("CATALAN"), SIMPLIFIED_CHINESE ("SIMPLIFIED CHINESE "), CROATIAN("CROATIAN"), CZECH("CZECH"), DANISH("DANISH"), DUTCH("DUTCH"), EGYPTIAN("EGYPTIAN"), ENGLISH("ENGLISH"), ESTONIAN("ESTONIAN"), FINNISH("FINNISH"), FRENCH("FRENCH"), GERMAN_DIN("GERMAN DIN "), GERMAN("GERMAN"), GREEK("GREEK"), HEBREW("HEBREW "), HUNGARIAN("HUNGARIAN"), ICELANDIC("ICELANDIC"), INDONESIAN("INDONESIAN"), ITALIAN("ITALIAN"), JAPANESE("JAPANESE"), KOREAN("KOREAN"), LATIN_AMERICAN_SPANISH("LATIN AMERICAN SPANISH "), LATVIAN("LATVIAN"), LITHUANIAN("LITHUANIAN"), MALAY("MALAY "), MEXICAN_SPANISH("MEXICAN SPANISH"), NORWEGIAN("NORWEGIAN"), POLISH("POLISH"), PORTUGUESE("PORTUGUESE"), ROMANIAN ("ROMANIAN "), RUSSIAN("RUSSIAN"), SLOVAK("SLOVAK"), SLOVENIAN ("SLOVENIAN "), SPANISH("SPANISH"), SWEDISH("SWEDISH"), THAI("THAI "), TRADITIONAL_CHINESE("TRADITIONAL CHINESE"), TURKISH("TURKISH"), UKRAINIAN("UKRAINIAN"), VIETNAMESE("VIETNAMESE"); private final String language; OracleLanguage(String language) { this.language = language; } public String getLanguage() { return language; } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/model/dict/OracleLanguage.java
2,367
package org.thoughtcrime.securesms.fonts; import java.util.HashMap; import java.util.Locale; import java.util.Map; /* * Copyright 2013 Phil Brown * * 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. * * * Get Script name by Locale * <br> * @author Phil Brown * @since 9:47:09 AM Dec 20, 2013 * */ class ScriptUtil { static final String LATIN = "Latn"; static final String CYRILLIC = "Cyrl"; static final String DEVANAGARI = "Deva"; static final String CHINESE_TRADITIONAL = "Hant"; static final String CHINESE_SIMPLIFIED = "Hans"; static final String ARABIC = "Arab"; static final String JAPANESE = "Jpan"; public static Map<String, Map<String, String>> SCRIPTS_BY_LOCALE = new HashMap<>(); public static Map<String, String> getScriptsMap(String... keyValuePairs) { Map<String, String> languages = new HashMap<String, String>(); for (int i = 0; i < keyValuePairs.length; i += 2) { languages.put(keyValuePairs[i], keyValuePairs[i + 1]); } return languages; } static { SCRIPTS_BY_LOCALE.put("aa", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ab", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("abq", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("abr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ace", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ach", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ada", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ady", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ae", getScriptsMap("", "Avst")); SCRIPTS_BY_LOCALE.put("af", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("agq", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("aii", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ain", getScriptsMap("", "Kana")); SCRIPTS_BY_LOCALE.put("ak", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("akk", getScriptsMap("", "Xsux")); SCRIPTS_BY_LOCALE.put("ale", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("alt", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("am", getScriptsMap("", "Ethi")); SCRIPTS_BY_LOCALE.put("amo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("an", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("anp", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("aoz", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ar", getScriptsMap("", "Arab", "IR", "Syrc")); SCRIPTS_BY_LOCALE.put("arc", getScriptsMap("", "Armi")); SCRIPTS_BY_LOCALE.put("arn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("arp", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("arw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("as", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("asa", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ast", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("atj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("av", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("awa", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("ay", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("az", getScriptsMap("", "Latn", "AZ", "Cyrl", "IR", "Arab")); SCRIPTS_BY_LOCALE.put("ba", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("bal", getScriptsMap("", "Arab", "IR", "Latn", "PK", "Latn")); SCRIPTS_BY_LOCALE.put("ban", getScriptsMap("", "Latn", "ID", "Bali")); SCRIPTS_BY_LOCALE.put("bap", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bas", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bax", getScriptsMap("", "Bamu")); SCRIPTS_BY_LOCALE.put("bbc", getScriptsMap("", "Latn", "ID", "Batk")); SCRIPTS_BY_LOCALE.put("bbj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bci", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("be", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("bej", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("bem", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bew", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bez", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bfd", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bfq", getScriptsMap("", "Taml")); SCRIPTS_BY_LOCALE.put("bft", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("bfy", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bg", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("bgc", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bgx", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bh", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bhb", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bhi", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bhk", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bho", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bik", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bin", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bjj", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bjn", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bkm", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bku", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bla", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("blt", getScriptsMap("", "Tavt")); SCRIPTS_BY_LOCALE.put("bm", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bmq", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bn", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("bo", getScriptsMap("", "Tibt")); SCRIPTS_BY_LOCALE.put("bqi", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bqv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("br", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bra", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("brh", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("brx", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bs", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bss", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bto", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("btv", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("bua", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("buc", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("bug", getScriptsMap("", "Latn", "ID", "Bugi")); SCRIPTS_BY_LOCALE.put("bum", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bvb", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bya", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("byn", getScriptsMap("", "Ethi")); SCRIPTS_BY_LOCALE.put("byv", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bze", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("bzx", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ca", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cad", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("car", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cay", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cch", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ccp", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("ce", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ceb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cgg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ch", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("chk", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("chm", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("chn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cho", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("chp", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("chr", getScriptsMap("", "Cher")); SCRIPTS_BY_LOCALE.put("chy", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cja", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("cjm", getScriptsMap("", "Cham")); SCRIPTS_BY_LOCALE.put("cjs", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ckb", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("ckt", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("co", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cop", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("cpe", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("cr", getScriptsMap("", "Cans")); SCRIPTS_BY_LOCALE.put("crh", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("crj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("crk", getScriptsMap("", "Cans")); SCRIPTS_BY_LOCALE.put("crl", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("crm", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("crs", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("cs", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("csb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("csw", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("cu", getScriptsMap("", "Glag")); SCRIPTS_BY_LOCALE.put("cv", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("cy", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("da", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("daf", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("dak", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dar", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("dav", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dcc", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("de", getScriptsMap("", "Latn", "BR", "Runr", "KZ", "Runr", "US", "Runr")); SCRIPTS_BY_LOCALE.put("del", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("den", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dgr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("din", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dje", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dng", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("doi", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("dsb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dtm", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("dua", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dv", getScriptsMap("", "Thaa")); SCRIPTS_BY_LOCALE.put("dyo", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("dyu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("dz", getScriptsMap("", "Tibt")); SCRIPTS_BY_LOCALE.put("ebu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ee", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("efi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("egy", getScriptsMap("", "Egyp")); SCRIPTS_BY_LOCALE.put("eka", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("eky", getScriptsMap("", "Kali")); SCRIPTS_BY_LOCALE.put("el", getScriptsMap("", "Grek")); SCRIPTS_BY_LOCALE.put("en", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("eo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("es", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("et", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ett", getScriptsMap("", "Ital")); SCRIPTS_BY_LOCALE.put("eu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("evn", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ewo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fa", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("fan", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ff", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ffm", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("fi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fil", getScriptsMap("", "Latn", "US", "Tglg")); SCRIPTS_BY_LOCALE.put("fiu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fj", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fon", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("frr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("frs", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fud", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("fuq", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("fur", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("fuv", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("fy", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ga", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gaa", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gag", getScriptsMap("", "Latn", "MD", "Cyrl")); SCRIPTS_BY_LOCALE.put("gay", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gba", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("gbm", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("gcr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gd", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gez", getScriptsMap("", "Ethi")); SCRIPTS_BY_LOCALE.put("ggn", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("gil", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gjk", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("gju", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("gl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gld", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("glk", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("gn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gon", getScriptsMap("", "Telu")); SCRIPTS_BY_LOCALE.put("gor", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gos", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("got", getScriptsMap("", "Goth")); SCRIPTS_BY_LOCALE.put("grb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("grc", getScriptsMap("", "Cprt")); SCRIPTS_BY_LOCALE.put("grt", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("gsw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gu", getScriptsMap("", "Gujr")); SCRIPTS_BY_LOCALE.put("gub", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("guz", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("gvr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("gwi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ha", getScriptsMap("", "Arab", "NE", "Latn", "GH", "Latn")); SCRIPTS_BY_LOCALE.put("hai", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("haw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("haz", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("he", getScriptsMap("", "Hebr")); SCRIPTS_BY_LOCALE.put("hi", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("hil", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hit", getScriptsMap("", "Xsux")); SCRIPTS_BY_LOCALE.put("hmn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hnd", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("hne", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("hnn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hno", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ho", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hoc", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("hoj", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("hop", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hsb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ht", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hup", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("hy", getScriptsMap("", "Armn")); SCRIPTS_BY_LOCALE.put("hz", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ia", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("iba", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ibb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("id", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ig", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ii", getScriptsMap("", "Yiii", "CN", "Latn")); SCRIPTS_BY_LOCALE.put("ik", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ikt", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ilo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("inh", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("is", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("it", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("iu", getScriptsMap("", "Cans", "CA", "Latn")); SCRIPTS_BY_LOCALE.put("ja", getScriptsMap("", "Jpan")); SCRIPTS_BY_LOCALE.put("jmc", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("jml", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("jpr", getScriptsMap("", "Hebr")); SCRIPTS_BY_LOCALE.put("jrb", getScriptsMap("", "Hebr")); SCRIPTS_BY_LOCALE.put("jv", getScriptsMap("", "Latn", "ID", "Java")); SCRIPTS_BY_LOCALE.put("ka", getScriptsMap("", "Geor")); SCRIPTS_BY_LOCALE.put("kaa", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kab", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kac", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kaj", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kam", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kao", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kbd", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kca", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kcg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kck", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kde", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kdt", getScriptsMap("", "Thai")); SCRIPTS_BY_LOCALE.put("kea", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kfo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kfr", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("kfy", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kge", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kgp", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kha", getScriptsMap("", "Latn", "IN", "Beng")); SCRIPTS_BY_LOCALE.put("khb", getScriptsMap("", "Talu")); SCRIPTS_BY_LOCALE.put("khn", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("khq", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kht", getScriptsMap("", "Mymr")); SCRIPTS_BY_LOCALE.put("khw", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ki", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kj", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kjg", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kjh", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kk", getScriptsMap("", "Arab", "KZ", "Cyrl", "TR", "Cyrl")); SCRIPTS_BY_LOCALE.put("kkj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kln", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("km", getScriptsMap("", "Khmr")); SCRIPTS_BY_LOCALE.put("kmb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kn", getScriptsMap("", "Knda")); SCRIPTS_BY_LOCALE.put("ko", getScriptsMap("", "Kore")); SCRIPTS_BY_LOCALE.put("koi", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kok", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("kos", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kpe", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kpy", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("krc", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kri", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("krl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kru", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("ks", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("ksb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ksf", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ksh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ku", getScriptsMap("", "Latn", "LB", "Arab")); SCRIPTS_BY_LOCALE.put("kum", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kut", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kv", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("kvr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kvx", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("kxm", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("kxp", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ky", getScriptsMap("", "Cyrl", "CN", "Arab", "TR", "Latn")); SCRIPTS_BY_LOCALE.put("kyu", getScriptsMap("", "Kali")); SCRIPTS_BY_LOCALE.put("la", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lad", getScriptsMap("", "Hebr")); SCRIPTS_BY_LOCALE.put("lag", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lah", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("laj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("lam", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lbe", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("lbw", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("lcp", getScriptsMap("", "Thai")); SCRIPTS_BY_LOCALE.put("lep", getScriptsMap("", "Lepc")); SCRIPTS_BY_LOCALE.put("lez", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("lg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("li", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lif", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("lis", getScriptsMap("", "Lisu")); SCRIPTS_BY_LOCALE.put("ljp", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("lki", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("lkt", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("lmn", getScriptsMap("", "Telu")); SCRIPTS_BY_LOCALE.put("lmo", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ln", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lo", getScriptsMap("", "Laoo")); SCRIPTS_BY_LOCALE.put("lol", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("loz", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lrc", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("lt", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lua", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lui", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lun", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("luo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lus", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("lut", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("luy", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("luz", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("lv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("lwl", getScriptsMap("", "Thai")); SCRIPTS_BY_LOCALE.put("mad", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("maf", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mag", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("mai", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("mak", getScriptsMap("", "Latn", "ID", "Bugi")); SCRIPTS_BY_LOCALE.put("man", getScriptsMap("", "Latn", "GN", "Nkoo")); SCRIPTS_BY_LOCALE.put("mas", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("maz", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mdf", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("mdh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mdr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mdt", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("men", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mer", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mfa", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mfe", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mgh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mgp", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mgy", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mic", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("min", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mk", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ml", getScriptsMap("", "Mlym")); SCRIPTS_BY_LOCALE.put("mn", getScriptsMap("", "Cyrl", "CN", "Mong")); SCRIPTS_BY_LOCALE.put("mnc", getScriptsMap("", "Mong")); SCRIPTS_BY_LOCALE.put("mni", getScriptsMap("", "Beng", "IN", "Mtei")); SCRIPTS_BY_LOCALE.put("mns", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("mnw", getScriptsMap("", "Mymr")); SCRIPTS_BY_LOCALE.put("moe", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("moh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mos", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mr", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("mrd", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mrj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ms", getScriptsMap("", "Arab", "MY", "Latn", "SG", "Latn")); SCRIPTS_BY_LOCALE.put("mt", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mtr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mua", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mus", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mvy", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mwk", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("mwl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("mwr", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("mxc", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("my", getScriptsMap("", "Mymr")); SCRIPTS_BY_LOCALE.put("myv", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("myx", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("myz", getScriptsMap("", "Mand")); SCRIPTS_BY_LOCALE.put("na", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nap", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("naq", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nbf", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nch", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nd", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ndc", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nds", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ne", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("new", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("ng", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ngl", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nhe", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nhw", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nia", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nij", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("niu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nmg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nnh", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nod", getScriptsMap("", "Lana")); SCRIPTS_BY_LOCALE.put("noe", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nog", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("nqo", getScriptsMap("", "Nkoo")); SCRIPTS_BY_LOCALE.put("nr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nsk", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("nso", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nus", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ny", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nym", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nyn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nyo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("nzi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("oc", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("oj", getScriptsMap("", "Cans")); SCRIPTS_BY_LOCALE.put("om", getScriptsMap("", "Latn", "ET", "Ethi")); SCRIPTS_BY_LOCALE.put("or", getScriptsMap("", "Orya")); SCRIPTS_BY_LOCALE.put("os", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("osa", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("osc", getScriptsMap("", "Ital")); SCRIPTS_BY_LOCALE.put("otk", getScriptsMap("", "Orkh")); SCRIPTS_BY_LOCALE.put("pa", getScriptsMap("", "Guru", "PK", "Arab")); SCRIPTS_BY_LOCALE.put("pag", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("pal", getScriptsMap("", "Phli")); SCRIPTS_BY_LOCALE.put("pam", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("pap", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("pau", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("peo", getScriptsMap("", "Xpeo")); SCRIPTS_BY_LOCALE.put("phn", getScriptsMap("", "Phnx")); SCRIPTS_BY_LOCALE.put("pi", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("pko", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("pl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("pon", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("pra", getScriptsMap("", "Brah")); SCRIPTS_BY_LOCALE.put("prd", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("prg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("prs", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("ps", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("pt", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("puu", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("qu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("raj", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rap", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rar", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rcf", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rej", getScriptsMap("", "Latn", "ID", "Rjng")); SCRIPTS_BY_LOCALE.put("ria", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rif", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rjs", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("rkt", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("rm", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rmf", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rmo", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rmt", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rng", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ro", getScriptsMap("", "Latn", "RS", "Cyrl")); SCRIPTS_BY_LOCALE.put("rob", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rof", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rom", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ru", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("rue", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("rup", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("rwk", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ryu", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("sa", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("sad", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("saf", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sah", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("sam", getScriptsMap("", "Hebr")); SCRIPTS_BY_LOCALE.put("saq", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sas", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sat", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("saz", getScriptsMap("", "Saur")); SCRIPTS_BY_LOCALE.put("sbp", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sc", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sck", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("scn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sco", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("scs", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("sd", getScriptsMap("", "Arab", "IN", "Deva")); SCRIPTS_BY_LOCALE.put("sdh", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("se", getScriptsMap("", "Latn", "NO", "Cyrl")); SCRIPTS_BY_LOCALE.put("see", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sef", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("seh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sel", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ses", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sga", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("shi", getScriptsMap("", "Tfng")); SCRIPTS_BY_LOCALE.put("shn", getScriptsMap("", "Mymr")); SCRIPTS_BY_LOCALE.put("si", getScriptsMap("", "Sinh")); SCRIPTS_BY_LOCALE.put("sid", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sk", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("skr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("sl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sm", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sma", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("smi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("smj", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("smn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sms", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("snk", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("so", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("son", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sou", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("sq", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("srn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("srr", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("srx", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ss", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ssy", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("st", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("su", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("suk", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sus", getScriptsMap("", "Latn", "GN", "Arab")); SCRIPTS_BY_LOCALE.put("sv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("sw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("swb", getScriptsMap("", "Arab", "YT", "Latn")); SCRIPTS_BY_LOCALE.put("swc", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("swv", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("sxn", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("syi", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("syl", getScriptsMap("", "Beng", "BD", "Sylo")); SCRIPTS_BY_LOCALE.put("syr", getScriptsMap("", "Syrc")); SCRIPTS_BY_LOCALE.put("ta", getScriptsMap("", "Taml")); SCRIPTS_BY_LOCALE.put("tab", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("taj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("tbw", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tcy", getScriptsMap("", "Knda")); SCRIPTS_BY_LOCALE.put("tdd", getScriptsMap("", "Tale")); SCRIPTS_BY_LOCALE.put("tdg", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("tdh", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("te", getScriptsMap("", "Telu")); SCRIPTS_BY_LOCALE.put("tem", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("teo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ter", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tet", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tg", getScriptsMap("", "Cyrl", "PK", "Arab")); SCRIPTS_BY_LOCALE.put("th", getScriptsMap("", "Thai")); SCRIPTS_BY_LOCALE.put("thl", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("thq", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("thr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("ti", getScriptsMap("", "Ethi")); SCRIPTS_BY_LOCALE.put("tig", getScriptsMap("", "Ethi")); SCRIPTS_BY_LOCALE.put("tiv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tk", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tkl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tkt", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("tli", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tmh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tn", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("to", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tog", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tpi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tr", getScriptsMap("", "Latn", "DE", "Arab", "MK", "Arab")); SCRIPTS_BY_LOCALE.put("tru", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("trv", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ts", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tsf", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("tsg", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tsi", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tsj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("tt", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("ttj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("tts", getScriptsMap("", "Thai")); SCRIPTS_BY_LOCALE.put("tum", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tut", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("tvl", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("twq", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ty", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("tyv", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("tzm", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ude", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("udm", getScriptsMap("", "Cyrl", "RU", "Latn")); SCRIPTS_BY_LOCALE.put("ug", getScriptsMap("", "Arab", "KZ", "Cyrl", "MN", "Cyrl")); SCRIPTS_BY_LOCALE.put("uga", getScriptsMap("", "Ugar")); SCRIPTS_BY_LOCALE.put("uk", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("uli", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("umb", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("und", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("unr", getScriptsMap("", "Beng", "NP", "Deva")); SCRIPTS_BY_LOCALE.put("unx", getScriptsMap("", "Beng")); SCRIPTS_BY_LOCALE.put("ur", getScriptsMap("", "Arab")); SCRIPTS_BY_LOCALE.put("uz", getScriptsMap("", "Latn", "AF", "Arab", "CN", "Cyrl")); SCRIPTS_BY_LOCALE.put("vai", getScriptsMap("", "Vaii")); SCRIPTS_BY_LOCALE.put("ve", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("vi", getScriptsMap("", "Latn", "US", "Hani")); SCRIPTS_BY_LOCALE.put("vic", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("vmw", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("vo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("vot", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("vun", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("wa", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("wae", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("wak", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("wal", getScriptsMap("", "Ethi")); SCRIPTS_BY_LOCALE.put("war", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("was", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("wbq", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("wbr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("wls", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("wo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("wtm", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("xal", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("xav", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("xcr", getScriptsMap("", "Cari")); SCRIPTS_BY_LOCALE.put("xh", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("xnr", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("xog", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("xpr", getScriptsMap("", "Prti")); SCRIPTS_BY_LOCALE.put("xsa", getScriptsMap("", "Sarb")); SCRIPTS_BY_LOCALE.put("xsr", getScriptsMap("", "Deva")); SCRIPTS_BY_LOCALE.put("xum", getScriptsMap("", "Ital")); SCRIPTS_BY_LOCALE.put("yao", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("yap", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("yav", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("ybb", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("yi", getScriptsMap("", "Hebr")); SCRIPTS_BY_LOCALE.put("yo", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("yrk", getScriptsMap("", "Cyrl")); SCRIPTS_BY_LOCALE.put("yua", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("yue", getScriptsMap("", "Hans")); SCRIPTS_BY_LOCALE.put("za", getScriptsMap("", "Latn", "CN", "Hans")); SCRIPTS_BY_LOCALE.put("zap", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("zdj", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("zea", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("zen", getScriptsMap("", "Tfng")); SCRIPTS_BY_LOCALE.put("zh", getScriptsMap("", "Hant", "CN", "Hans", "HK", "Hans", "MO", "Hans", "SG", "Hans", "MN", "Hans")); SCRIPTS_BY_LOCALE.put("zmi", getScriptsMap("", "")); SCRIPTS_BY_LOCALE.put("zu", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("zun", getScriptsMap("", "Latn")); SCRIPTS_BY_LOCALE.put("zza", getScriptsMap("", "Arab")); } /** * Gets the script for the given locale. For example, if a US citizen uses German Locale, * and calls this method with Locale.getDefault(), the result would be "Runr" * * @param locale * @return */ public static String getScript(Locale locale) { String localeString = locale.toString(); String language = ""; String country = ""; if (localeString.contains("_")) { String[] split = localeString.split("_"); language = split[0]; country = split[1]; } else language = localeString; Map<String, String> scripts = SCRIPTS_BY_LOCALE.get(language); if (scripts == null) { return null; } else { if (scripts.containsKey(country)) { return scripts.get(country); } else { return scripts.get(""); } } } }
signalapp/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/fonts/ScriptUtil.java
2,368
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store; import com.google.common.collect.Sets; import com.google.common.hash.Hashing; import io.openmessaging.storage.dledger.entry.DLedgerEntry; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.ViewBuilder; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileLock; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.common.AbstractBrokerRunnable; import org.apache.rocketmq.common.BoundaryType; import org.apache.rocketmq.common.BrokerConfig; import org.apache.rocketmq.common.BrokerIdentity; import org.apache.rocketmq.common.MixAll; import org.apache.rocketmq.common.Pair; import org.apache.rocketmq.common.ServiceThread; import org.apache.rocketmq.common.SystemClock; import org.apache.rocketmq.common.ThreadFactoryImpl; import org.apache.rocketmq.common.TopicConfig; import org.apache.rocketmq.common.UtilAll; import org.apache.rocketmq.common.attribute.CQType; import org.apache.rocketmq.common.attribute.CleanupPolicy; import org.apache.rocketmq.common.constant.LoggerName; import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.common.message.MessageDecoder; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.message.MessageExtBatch; import org.apache.rocketmq.common.message.MessageExtBrokerInner; import org.apache.rocketmq.common.running.RunningStats; import org.apache.rocketmq.common.sysflag.MessageSysFlag; import org.apache.rocketmq.common.topic.TopicValidator; import org.apache.rocketmq.common.utils.CleanupPolicyUtils; import org.apache.rocketmq.common.utils.QueueTypeUtils; import org.apache.rocketmq.common.utils.ServiceProvider; import org.apache.rocketmq.common.utils.ThreadUtils; import org.apache.rocketmq.logging.org.slf4j.Logger; import org.apache.rocketmq.logging.org.slf4j.LoggerFactory; import org.apache.rocketmq.remoting.protocol.body.HARuntimeInfo; import org.apache.rocketmq.store.config.BrokerRole; import org.apache.rocketmq.store.config.FlushDiskType; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.config.StorePathConfigHelper; import org.apache.rocketmq.store.dledger.DLedgerCommitLog; import org.apache.rocketmq.store.ha.DefaultHAService; import org.apache.rocketmq.store.ha.HAService; import org.apache.rocketmq.store.ha.autoswitch.AutoSwitchHAService; import org.apache.rocketmq.store.hook.PutMessageHook; import org.apache.rocketmq.store.hook.SendMessageBackHook; import org.apache.rocketmq.store.index.IndexService; import org.apache.rocketmq.store.index.QueryOffsetResult; import org.apache.rocketmq.store.kv.CommitLogDispatcherCompaction; import org.apache.rocketmq.store.kv.CompactionService; import org.apache.rocketmq.store.kv.CompactionStore; import org.apache.rocketmq.store.logfile.MappedFile; import org.apache.rocketmq.store.metrics.DefaultStoreMetricsManager; import org.apache.rocketmq.store.queue.ConsumeQueueInterface; import org.apache.rocketmq.store.queue.ConsumeQueueStore; import org.apache.rocketmq.store.queue.ConsumeQueueStoreInterface; import org.apache.rocketmq.store.queue.CqUnit; import org.apache.rocketmq.store.queue.ReferredIterator; import org.apache.rocketmq.store.stats.BrokerStatsManager; import org.apache.rocketmq.store.timer.TimerMessageStore; import org.apache.rocketmq.store.util.PerfCounter; import org.rocksdb.RocksDBException; public class DefaultMessageStore implements MessageStore { protected static final Logger LOGGER = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME); protected static final Logger ERROR_LOG = LoggerFactory.getLogger(LoggerName.STORE_ERROR_LOGGER_NAME); public final PerfCounter.Ticks perfs = new PerfCounter.Ticks(LOGGER); private final MessageStoreConfig messageStoreConfig; // CommitLog protected final CommitLog commitLog; protected final ConsumeQueueStoreInterface consumeQueueStore; private final FlushConsumeQueueService flushConsumeQueueService; protected final CleanCommitLogService cleanCommitLogService; private final CleanConsumeQueueService cleanConsumeQueueService; private final CorrectLogicOffsetService correctLogicOffsetService; protected final IndexService indexService; private final AllocateMappedFileService allocateMappedFileService; private ReputMessageService reputMessageService; private HAService haService; // CompactionLog private CompactionStore compactionStore; private CompactionService compactionService; private final StoreStatsService storeStatsService; private final TransientStorePool transientStorePool; protected final RunningFlags runningFlags = new RunningFlags(); private final SystemClock systemClock = new SystemClock(); private final ScheduledExecutorService scheduledExecutorService; private final BrokerStatsManager brokerStatsManager; private final MessageArrivingListener messageArrivingListener; private final BrokerConfig brokerConfig; private volatile boolean shutdown = true; protected boolean notifyMessageArriveInBatch = false; private StoreCheckpoint storeCheckpoint; private TimerMessageStore timerMessageStore; private final LinkedList<CommitLogDispatcher> dispatcherList; private RandomAccessFile lockFile; private FileLock lock; boolean shutDownNormal = false; // Max pull msg size private final static int MAX_PULL_MSG_SIZE = 128 * 1024 * 1024; private volatile int aliveReplicasNum = 1; // Refer the MessageStore of MasterBroker in the same process. // If current broker is master, this reference point to null or itself. // If current broker is slave, this reference point to the store of master broker, and the two stores belong to // different broker groups. private MessageStore masterStoreInProcess = null; private volatile long masterFlushedOffset = -1L; private volatile long brokerInitMaxOffset = -1L; private List<PutMessageHook> putMessageHookList = new ArrayList<>(); private SendMessageBackHook sendMessageBackHook; private final ConcurrentSkipListMap<Integer /* level */, Long/* delay timeMillis */> delayLevelTable = new ConcurrentSkipListMap<>(); private int maxDelayLevel; private final AtomicInteger mappedPageHoldCount = new AtomicInteger(0); private final ConcurrentLinkedQueue<BatchDispatchRequest> batchDispatchRequestQueue = new ConcurrentLinkedQueue<>(); private int dispatchRequestOrderlyQueueSize = 16; private final DispatchRequestOrderlyQueue dispatchRequestOrderlyQueue = new DispatchRequestOrderlyQueue(dispatchRequestOrderlyQueueSize); private long stateMachineVersion = 0L; // this is a unmodifiableMap private ConcurrentMap<String, TopicConfig> topicConfigTable; private final ScheduledExecutorService scheduledCleanQueueExecutorService = ThreadUtils.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("StoreCleanQueueScheduledThread")); public DefaultMessageStore(final MessageStoreConfig messageStoreConfig, final BrokerStatsManager brokerStatsManager, final MessageArrivingListener messageArrivingListener, final BrokerConfig brokerConfig, final ConcurrentMap<String, TopicConfig> topicConfigTable) throws IOException { this.messageArrivingListener = messageArrivingListener; this.brokerConfig = brokerConfig; this.messageStoreConfig = messageStoreConfig; this.aliveReplicasNum = messageStoreConfig.getTotalReplicas(); this.brokerStatsManager = brokerStatsManager; this.topicConfigTable = topicConfigTable; this.allocateMappedFileService = new AllocateMappedFileService(this); if (messageStoreConfig.isEnableDLegerCommitLog()) { this.commitLog = new DLedgerCommitLog(this); } else { this.commitLog = new CommitLog(this); } this.consumeQueueStore = createConsumeQueueStore(); this.flushConsumeQueueService = createFlushConsumeQueueService(); this.cleanCommitLogService = new CleanCommitLogService(); this.cleanConsumeQueueService = createCleanConsumeQueueService(); this.correctLogicOffsetService = createCorrectLogicOffsetService(); this.storeStatsService = new StoreStatsService(getBrokerIdentity()); this.indexService = new IndexService(this); if (!messageStoreConfig.isEnableDLegerCommitLog() && !this.messageStoreConfig.isDuplicationEnable()) { if (brokerConfig.isEnableControllerMode()) { this.haService = new AutoSwitchHAService(); LOGGER.warn("Load AutoSwitch HA Service: {}", AutoSwitchHAService.class.getSimpleName()); } else { this.haService = ServiceProvider.loadClass(HAService.class); if (null == this.haService) { this.haService = new DefaultHAService(); LOGGER.warn("Load default HA Service: {}", DefaultHAService.class.getSimpleName()); } } } if (!messageStoreConfig.isEnableBuildConsumeQueueConcurrently()) { this.reputMessageService = new ReputMessageService(); } else { this.reputMessageService = new ConcurrentReputMessageService(); } this.transientStorePool = new TransientStorePool(messageStoreConfig.getTransientStorePoolSize(), messageStoreConfig.getMappedFileSizeCommitLog()); this.scheduledExecutorService = ThreadUtils.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("StoreScheduledThread", getBrokerIdentity())); this.dispatcherList = new LinkedList<>(); this.dispatcherList.addLast(new CommitLogDispatcherBuildConsumeQueue()); this.dispatcherList.addLast(new CommitLogDispatcherBuildIndex()); if (messageStoreConfig.isEnableCompaction()) { this.compactionStore = new CompactionStore(this); this.compactionService = new CompactionService(commitLog, this, compactionStore); this.dispatcherList.addLast(new CommitLogDispatcherCompaction(compactionService)); } File file = new File(StorePathConfigHelper.getLockFile(messageStoreConfig.getStorePathRootDir())); UtilAll.ensureDirOK(file.getParent()); UtilAll.ensureDirOK(getStorePathPhysic()); UtilAll.ensureDirOK(getStorePathLogic()); lockFile = new RandomAccessFile(file, "rw"); parseDelayLevel(); } public ConsumeQueueStoreInterface createConsumeQueueStore() { return new ConsumeQueueStore(this); } public CleanConsumeQueueService createCleanConsumeQueueService() { return new CleanConsumeQueueService(); } public FlushConsumeQueueService createFlushConsumeQueueService() { return new FlushConsumeQueueService(); } public CorrectLogicOffsetService createCorrectLogicOffsetService() { return new CorrectLogicOffsetService(); } public boolean parseDelayLevel() { HashMap<String, Long> timeUnitTable = new HashMap<>(); timeUnitTable.put("s", 1000L); timeUnitTable.put("m", 1000L * 60); timeUnitTable.put("h", 1000L * 60 * 60); timeUnitTable.put("d", 1000L * 60 * 60 * 24); String levelString = messageStoreConfig.getMessageDelayLevel(); try { String[] levelArray = levelString.split(" "); for (int i = 0; i < levelArray.length; i++) { String value = levelArray[i]; String ch = value.substring(value.length() - 1); Long tu = timeUnitTable.get(ch); int level = i + 1; if (level > this.maxDelayLevel) { this.maxDelayLevel = level; } long num = Long.parseLong(value.substring(0, value.length() - 1)); long delayTimeMillis = tu * num; this.delayLevelTable.put(level, delayTimeMillis); } } catch (Exception e) { LOGGER.error("parse message delay level failed. messageDelayLevel = {}", levelString, e); return false; } return true; } @Override public void truncateDirtyLogicFiles(long phyOffset) throws RocksDBException { this.consumeQueueStore.truncateDirty(phyOffset); } /** * @throws IOException */ @Override public boolean load() { boolean result = true; try { boolean lastExitOK = !this.isTempFileExist(); LOGGER.info("last shutdown {}, store path root dir: {}", lastExitOK ? "normally" : "abnormally", messageStoreConfig.getStorePathRootDir()); // load Commit Log result = this.commitLog.load(); // load Consume Queue result = result && this.consumeQueueStore.load(); if (messageStoreConfig.isEnableCompaction()) { result = result && this.compactionService.load(lastExitOK); } if (result) { this.storeCheckpoint = new StoreCheckpoint( StorePathConfigHelper.getStoreCheckpoint(this.messageStoreConfig.getStorePathRootDir())); this.masterFlushedOffset = this.storeCheckpoint.getMasterFlushedOffset(); setConfirmOffset(this.storeCheckpoint.getConfirmPhyOffset()); result = this.indexService.load(lastExitOK); this.recover(lastExitOK); LOGGER.info("message store recover end, and the max phy offset = {}", this.getMaxPhyOffset()); } long maxOffset = this.getMaxPhyOffset(); this.setBrokerInitMaxOffset(maxOffset); LOGGER.info("load over, and the max phy offset = {}", maxOffset); } catch (Exception e) { LOGGER.error("load exception", e); result = false; } if (!result) { this.allocateMappedFileService.shutdown(); } return result; } /** * @throws Exception */ @Override public void start() throws Exception { if (!messageStoreConfig.isEnableDLegerCommitLog() && !this.messageStoreConfig.isDuplicationEnable()) { this.haService.init(this); } if (this.isTransientStorePoolEnable()) { this.transientStorePool.init(); } this.allocateMappedFileService.start(); this.indexService.start(); lock = lockFile.getChannel().tryLock(0, 1, false); if (lock == null || lock.isShared() || !lock.isValid()) { throw new RuntimeException("Lock failed,MQ already started"); } lockFile.getChannel().write(ByteBuffer.wrap("lock".getBytes(StandardCharsets.UTF_8))); lockFile.getChannel().force(true); this.reputMessageService.setReputFromOffset(this.commitLog.getConfirmOffset()); this.reputMessageService.start(); // Checking is not necessary, as long as the dLedger's implementation exactly follows the definition of Recover, // which is eliminating the dispatch inconsistency between the commitLog and consumeQueue at the end of recovery. this.doRecheckReputOffsetFromCq(); this.flushConsumeQueueService.start(); this.commitLog.start(); this.consumeQueueStore.start(); this.storeStatsService.start(); if (this.haService != null) { this.haService.start(); } this.createTempFile(); this.addScheduleTask(); this.perfs.start(); this.shutdown = false; } private void doRecheckReputOffsetFromCq() throws InterruptedException { if (!messageStoreConfig.isRecheckReputOffsetFromCq()) { return; } /** * 1. Make sure the fast-forward messages to be truncated during the recovering according to the max physical offset of the commitlog; * 2. DLedger committedPos may be missing, so the maxPhysicalPosInLogicQueue maybe bigger that maxOffset returned by DLedgerCommitLog, just let it go; * 3. Calculate the reput offset according to the consume queue; * 4. Make sure the fall-behind messages to be dispatched before starting the commitlog, especially when the broker role are automatically changed. */ long maxPhysicalPosInLogicQueue = commitLog.getMinOffset(); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.getConsumeQueueTable().values()) { for (ConsumeQueueInterface logic : maps.values()) { if (logic.getMaxPhysicOffset() > maxPhysicalPosInLogicQueue) { maxPhysicalPosInLogicQueue = logic.getMaxPhysicOffset(); } } } // If maxPhyPos(CQs) < minPhyPos(CommitLog), some newly deleted topics may be re-dispatched into cqs mistakenly. if (maxPhysicalPosInLogicQueue < 0) { maxPhysicalPosInLogicQueue = 0; } if (maxPhysicalPosInLogicQueue < this.commitLog.getMinOffset()) { maxPhysicalPosInLogicQueue = this.commitLog.getMinOffset(); /** * This happens in following conditions: * 1. If someone removes all the consumequeue files or the disk get damaged. * 2. Launch a new broker, and copy the commitlog from other brokers. * * All the conditions has the same in common that the maxPhysicalPosInLogicQueue should be 0. * If the maxPhysicalPosInLogicQueue is gt 0, there maybe something wrong. */ LOGGER.warn("[TooSmallCqOffset] maxPhysicalPosInLogicQueue={} clMinOffset={}", maxPhysicalPosInLogicQueue, this.commitLog.getMinOffset()); } LOGGER.info("[SetReputOffset] maxPhysicalPosInLogicQueue={} clMinOffset={} clMaxOffset={} clConfirmedOffset={}", maxPhysicalPosInLogicQueue, this.commitLog.getMinOffset(), this.commitLog.getMaxOffset(), this.commitLog.getConfirmOffset()); this.reputMessageService.setReputFromOffset(maxPhysicalPosInLogicQueue); /** * 1. Finish dispatching the messages fall behind, then to start other services. * 2. DLedger committedPos may be missing, so here just require dispatchBehindBytes <= 0 */ while (true) { if (dispatchBehindBytes() <= 0) { break; } Thread.sleep(1000); LOGGER.info("Try to finish doing reput the messages fall behind during the starting, reputOffset={} maxOffset={} behind={}", this.reputMessageService.getReputFromOffset(), this.getMaxPhyOffset(), this.dispatchBehindBytes()); } this.recoverTopicQueueTable(); } @Override public void shutdown() { if (!this.shutdown) { this.shutdown = true; this.scheduledExecutorService.shutdown(); this.scheduledCleanQueueExecutorService.shutdown(); try { this.scheduledExecutorService.awaitTermination(3, TimeUnit.SECONDS); this.scheduledCleanQueueExecutorService.awaitTermination(3, TimeUnit.SECONDS); Thread.sleep(1000 * 3); } catch (InterruptedException e) { LOGGER.error("shutdown Exception, ", e); } if (this.haService != null) { this.haService.shutdown(); } this.storeStatsService.shutdown(); this.commitLog.shutdown(); this.reputMessageService.shutdown(); this.consumeQueueStore.shutdown(); // dispatch-related services must be shut down after reputMessageService this.indexService.shutdown(); if (this.compactionService != null) { this.compactionService.shutdown(); } this.flushConsumeQueueService.shutdown(); this.allocateMappedFileService.shutdown(); this.storeCheckpoint.flush(); this.storeCheckpoint.shutdown(); this.perfs.shutdown(); if (this.runningFlags.isWriteable() && dispatchBehindBytes() == 0) { this.deleteFile(StorePathConfigHelper.getAbortFile(this.messageStoreConfig.getStorePathRootDir())); shutDownNormal = true; } else { LOGGER.warn("the store may be wrong, so shutdown abnormally, and keep abort file."); } } this.transientStorePool.destroy(); if (lockFile != null && lock != null) { try { lock.release(); lockFile.close(); } catch (IOException e) { } } } @Override public void destroy() { this.consumeQueueStore.destroy(); this.commitLog.destroy(); this.indexService.destroy(); this.deleteFile(StorePathConfigHelper.getAbortFile(this.messageStoreConfig.getStorePathRootDir())); this.deleteFile(StorePathConfigHelper.getStoreCheckpoint(this.messageStoreConfig.getStorePathRootDir())); } public long getMajorFileSize() { long commitLogSize = 0; if (this.commitLog != null) { commitLogSize = this.commitLog.getTotalSize(); } long consumeQueueSize = 0; if (this.consumeQueueStore != null) { consumeQueueSize = this.consumeQueueStore.getTotalSize(); } long indexFileSize = 0; if (this.indexService != null) { indexFileSize = this.indexService.getTotalSize(); } return commitLogSize + consumeQueueSize + indexFileSize; } @Override public CompletableFuture<PutMessageResult> asyncPutMessage(MessageExtBrokerInner msg) { for (PutMessageHook putMessageHook : putMessageHookList) { PutMessageResult handleResult = putMessageHook.executeBeforePutMessage(msg); if (handleResult != null) { return CompletableFuture.completedFuture(handleResult); } } if (msg.getProperties().containsKey(MessageConst.PROPERTY_INNER_NUM) && !MessageSysFlag.check(msg.getSysFlag(), MessageSysFlag.INNER_BATCH_FLAG)) { LOGGER.warn("[BUG]The message had property {} but is not an inner batch", MessageConst.PROPERTY_INNER_NUM); return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null)); } if (MessageSysFlag.check(msg.getSysFlag(), MessageSysFlag.INNER_BATCH_FLAG)) { Optional<TopicConfig> topicConfig = this.getTopicConfig(msg.getTopic()); if (!QueueTypeUtils.isBatchCq(topicConfig)) { LOGGER.error("[BUG]The message is an inner batch but cq type is not batch cq"); return CompletableFuture.completedFuture(new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null)); } } long beginTime = this.getSystemClock().now(); CompletableFuture<PutMessageResult> putResultFuture = this.commitLog.asyncPutMessage(msg); putResultFuture.thenAccept(result -> { long elapsedTime = this.getSystemClock().now() - beginTime; if (elapsedTime > 500) { LOGGER.warn("DefaultMessageStore#putMessage: CommitLog#putMessage cost {}ms, topic={}, bodyLength={}", elapsedTime, msg.getTopic(), msg.getBody().length); } this.storeStatsService.setPutMessageEntireTimeMax(elapsedTime); if (null == result || !result.isOk()) { this.storeStatsService.getPutMessageFailedTimes().add(1); } }); return putResultFuture; } @Override public CompletableFuture<PutMessageResult> asyncPutMessages(MessageExtBatch messageExtBatch) { for (PutMessageHook putMessageHook : putMessageHookList) { PutMessageResult handleResult = putMessageHook.executeBeforePutMessage(messageExtBatch); if (handleResult != null) { return CompletableFuture.completedFuture(handleResult); } } long beginTime = this.getSystemClock().now(); CompletableFuture<PutMessageResult> putResultFuture = this.commitLog.asyncPutMessages(messageExtBatch); putResultFuture.thenAccept(result -> { long eclipseTime = this.getSystemClock().now() - beginTime; if (eclipseTime > 500) { LOGGER.warn("not in lock eclipse time(ms)={}, bodyLength={}", eclipseTime, messageExtBatch.getBody().length); } this.storeStatsService.setPutMessageEntireTimeMax(eclipseTime); if (null == result || !result.isOk()) { this.storeStatsService.getPutMessageFailedTimes().add(1); } }); return putResultFuture; } @Override public PutMessageResult putMessage(MessageExtBrokerInner msg) { return waitForPutResult(asyncPutMessage(msg)); } @Override public PutMessageResult putMessages(MessageExtBatch messageExtBatch) { return waitForPutResult(asyncPutMessages(messageExtBatch)); } private PutMessageResult waitForPutResult(CompletableFuture<PutMessageResult> putMessageResultFuture) { try { int putMessageTimeout = Math.max(this.messageStoreConfig.getSyncFlushTimeout(), this.messageStoreConfig.getSlaveTimeout()) + 5000; return putMessageResultFuture.get(putMessageTimeout, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException e) { return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, null); } catch (TimeoutException e) { LOGGER.error("usually it will never timeout, putMessageTimeout is much bigger than slaveTimeout and " + "flushTimeout so the result can be got anyway, but in some situations timeout will happen like full gc " + "process hangs or other unexpected situations."); return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, null); } } @Override public boolean isOSPageCacheBusy() { long begin = this.getCommitLog().getBeginTimeInLock(); long diff = this.systemClock.now() - begin; return diff < 10000000 && diff > this.messageStoreConfig.getOsPageCacheBusyTimeOutMills(); } @Override public long lockTimeMills() { return this.commitLog.lockTimeMills(); } @Override public long getMasterFlushedOffset() { return this.masterFlushedOffset; } @Override public void setMasterFlushedOffset(long masterFlushedOffset) { this.masterFlushedOffset = masterFlushedOffset; this.storeCheckpoint.setMasterFlushedOffset(masterFlushedOffset); } @Override public long getBrokerInitMaxOffset() { return this.brokerInitMaxOffset; } @Override public void setBrokerInitMaxOffset(long brokerInitMaxOffset) { this.brokerInitMaxOffset = brokerInitMaxOffset; } public SystemClock getSystemClock() { return systemClock; } @Override public CommitLog getCommitLog() { return commitLog; } public void truncateDirtyFiles(long offsetToTruncate) throws RocksDBException { LOGGER.info("truncate dirty files to {}", offsetToTruncate); if (offsetToTruncate >= this.getMaxPhyOffset()) { LOGGER.info("no need to truncate files, truncate offset is {}, max physical offset is {}", offsetToTruncate, this.getMaxPhyOffset()); return; } this.reputMessageService.shutdown(); long oldReputFromOffset = this.reputMessageService.getReputFromOffset(); // truncate consume queue this.truncateDirtyLogicFiles(offsetToTruncate); // truncate commitLog this.commitLog.truncateDirtyFiles(offsetToTruncate); this.recoverTopicQueueTable(); if (!messageStoreConfig.isEnableBuildConsumeQueueConcurrently()) { this.reputMessageService = new ReputMessageService(); } else { this.reputMessageService = new ConcurrentReputMessageService(); } long resetReputOffset = Math.min(oldReputFromOffset, offsetToTruncate); LOGGER.info("oldReputFromOffset is {}, reset reput from offset to {}", oldReputFromOffset, resetReputOffset); this.reputMessageService.setReputFromOffset(resetReputOffset); this.reputMessageService.start(); } @Override public boolean truncateFiles(long offsetToTruncate) throws RocksDBException { if (offsetToTruncate >= this.getMaxPhyOffset()) { LOGGER.info("no need to truncate files, truncate offset is {}, max physical offset is {}", offsetToTruncate, this.getMaxPhyOffset()); return true; } if (!isOffsetAligned(offsetToTruncate)) { LOGGER.error("offset {} is not align, truncate failed, need manual fix", offsetToTruncate); return false; } truncateDirtyFiles(offsetToTruncate); return true; } @Override public boolean isOffsetAligned(long offset) { SelectMappedBufferResult mappedBufferResult = this.getCommitLogData(offset); if (mappedBufferResult == null) { return true; } DispatchRequest dispatchRequest = this.commitLog.checkMessageAndReturnSize(mappedBufferResult.getByteBuffer(), true, false); return dispatchRequest.isSuccess(); } @Override public GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final MessageFilter messageFilter) { return getMessage(group, topic, queueId, offset, maxMsgNums, MAX_PULL_MSG_SIZE, messageFilter); } @Override public CompletableFuture<GetMessageResult> getMessageAsync(String group, String topic, int queueId, long offset, int maxMsgNums, MessageFilter messageFilter) { return CompletableFuture.completedFuture(getMessage(group, topic, queueId, offset, maxMsgNums, messageFilter)); } @Override public GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset, final int maxMsgNums, final int maxTotalMsgSize, final MessageFilter messageFilter) { if (this.shutdown) { LOGGER.warn("message store has shutdown, so getMessage is forbidden"); return null; } if (!this.runningFlags.isReadable()) { LOGGER.warn("message store is not readable, so getMessage is forbidden " + this.runningFlags.getFlagBits()); return null; } Optional<TopicConfig> topicConfig = getTopicConfig(topic); CleanupPolicy policy = CleanupPolicyUtils.getDeletePolicy(topicConfig); //check request topic flag if (Objects.equals(policy, CleanupPolicy.COMPACTION) && messageStoreConfig.isEnableCompaction()) { return compactionStore.getMessage(group, topic, queueId, offset, maxMsgNums, maxTotalMsgSize); } // else skip long beginTime = this.getSystemClock().now(); GetMessageStatus status = GetMessageStatus.NO_MESSAGE_IN_QUEUE; long nextBeginOffset = offset; long minOffset = 0; long maxOffset = 0; GetMessageResult getResult = new GetMessageResult(); final long maxOffsetPy = this.commitLog.getMaxOffset(); ConsumeQueueInterface consumeQueue = findConsumeQueue(topic, queueId); if (consumeQueue != null) { minOffset = consumeQueue.getMinOffsetInQueue(); maxOffset = consumeQueue.getMaxOffsetInQueue(); if (maxOffset == 0) { status = GetMessageStatus.NO_MESSAGE_IN_QUEUE; nextBeginOffset = nextOffsetCorrection(offset, 0); } else if (offset < minOffset) { status = GetMessageStatus.OFFSET_TOO_SMALL; nextBeginOffset = nextOffsetCorrection(offset, minOffset); } else if (offset == maxOffset) { status = GetMessageStatus.OFFSET_OVERFLOW_ONE; nextBeginOffset = nextOffsetCorrection(offset, offset); } else if (offset > maxOffset) { status = GetMessageStatus.OFFSET_OVERFLOW_BADLY; nextBeginOffset = nextOffsetCorrection(offset, maxOffset); } else { final int maxFilterMessageSize = Math.max(this.messageStoreConfig.getMaxFilterMessageSize(), maxMsgNums * consumeQueue.getUnitSize()); final boolean diskFallRecorded = this.messageStoreConfig.isDiskFallRecorded(); long maxPullSize = Math.max(maxTotalMsgSize, 100); if (maxPullSize > MAX_PULL_MSG_SIZE) { LOGGER.warn("The max pull size is too large maxPullSize={} topic={} queueId={}", maxPullSize, topic, queueId); maxPullSize = MAX_PULL_MSG_SIZE; } status = GetMessageStatus.NO_MATCHED_MESSAGE; long maxPhyOffsetPulling = 0; int cqFileNum = 0; while (getResult.getBufferTotalSize() <= 0 && nextBeginOffset < maxOffset && cqFileNum++ < this.messageStoreConfig.getTravelCqFileNumWhenGetMessage()) { ReferredIterator<CqUnit> bufferConsumeQueue = null; try { bufferConsumeQueue = consumeQueue.iterateFrom(nextBeginOffset, maxMsgNums); if (bufferConsumeQueue == null) { status = GetMessageStatus.OFFSET_FOUND_NULL; nextBeginOffset = nextOffsetCorrection(nextBeginOffset, this.consumeQueueStore.rollNextFile(consumeQueue, nextBeginOffset)); LOGGER.warn("consumer request topic: " + topic + ", offset: " + offset + ", minOffset: " + minOffset + ", maxOffset: " + maxOffset + ", but access logic queue failed. Correct nextBeginOffset to " + nextBeginOffset); break; } long nextPhyFileStartOffset = Long.MIN_VALUE; while (bufferConsumeQueue.hasNext() && nextBeginOffset < maxOffset) { CqUnit cqUnit = bufferConsumeQueue.next(); long offsetPy = cqUnit.getPos(); int sizePy = cqUnit.getSize(); boolean isInMem = estimateInMemByCommitOffset(offsetPy, maxOffsetPy); if ((cqUnit.getQueueOffset() - offset) * consumeQueue.getUnitSize() > maxFilterMessageSize) { break; } if (this.isTheBatchFull(sizePy, cqUnit.getBatchNum(), maxMsgNums, maxPullSize, getResult.getBufferTotalSize(), getResult.getMessageCount(), isInMem)) { break; } if (getResult.getBufferTotalSize() >= maxPullSize) { break; } maxPhyOffsetPulling = offsetPy; //Be careful, here should before the isTheBatchFull nextBeginOffset = cqUnit.getQueueOffset() + cqUnit.getBatchNum(); if (nextPhyFileStartOffset != Long.MIN_VALUE) { if (offsetPy < nextPhyFileStartOffset) { continue; } } if (messageFilter != null && !messageFilter.isMatchedByConsumeQueue(cqUnit.getValidTagsCodeAsLong(), cqUnit.getCqExtUnit())) { if (getResult.getBufferTotalSize() == 0) { status = GetMessageStatus.NO_MATCHED_MESSAGE; } continue; } SelectMappedBufferResult selectResult = this.commitLog.getMessage(offsetPy, sizePy); if (null == selectResult) { if (getResult.getBufferTotalSize() == 0) { status = GetMessageStatus.MESSAGE_WAS_REMOVING; } nextPhyFileStartOffset = this.commitLog.rollNextFile(offsetPy); continue; } if (messageStoreConfig.isColdDataFlowControlEnable() && !MixAll.isSysConsumerGroupForNoColdReadLimit(group) && !selectResult.isInCache()) { getResult.setColdDataSum(getResult.getColdDataSum() + sizePy); } if (messageFilter != null && !messageFilter.isMatchedByCommitLog(selectResult.getByteBuffer().slice(), null)) { if (getResult.getBufferTotalSize() == 0) { status = GetMessageStatus.NO_MATCHED_MESSAGE; } // release... selectResult.release(); continue; } this.storeStatsService.getGetMessageTransferredMsgCount().add(cqUnit.getBatchNum()); getResult.addMessage(selectResult, cqUnit.getQueueOffset(), cqUnit.getBatchNum()); status = GetMessageStatus.FOUND; nextPhyFileStartOffset = Long.MIN_VALUE; } } catch (RocksDBException e) { ERROR_LOG.error("getMessage Failed. cid: {}, topic: {}, queueId: {}, offset: {}, minOffset: {}, maxOffset: {}, {}", group, topic, queueId, offset, minOffset, maxOffset, e.getMessage()); } finally { if (bufferConsumeQueue != null) { bufferConsumeQueue.release(); } } } if (diskFallRecorded) { long fallBehind = maxOffsetPy - maxPhyOffsetPulling; brokerStatsManager.recordDiskFallBehindSize(group, topic, queueId, fallBehind); } long diff = maxOffsetPy - maxPhyOffsetPulling; long memory = (long) (StoreUtil.TOTAL_PHYSICAL_MEMORY_SIZE * (this.messageStoreConfig.getAccessMessageInMemoryMaxRatio() / 100.0)); getResult.setSuggestPullingFromSlave(diff > memory); } } else { status = GetMessageStatus.NO_MATCHED_LOGIC_QUEUE; nextBeginOffset = nextOffsetCorrection(offset, 0); } if (GetMessageStatus.FOUND == status) { this.storeStatsService.getGetMessageTimesTotalFound().add(1); } else { this.storeStatsService.getGetMessageTimesTotalMiss().add(1); } long elapsedTime = this.getSystemClock().now() - beginTime; this.storeStatsService.setGetMessageEntireTimeMax(elapsedTime); // lazy init no data found. if (getResult == null) { getResult = new GetMessageResult(0); } getResult.setStatus(status); getResult.setNextBeginOffset(nextBeginOffset); getResult.setMaxOffset(maxOffset); getResult.setMinOffset(minOffset); return getResult; } @Override public CompletableFuture<GetMessageResult> getMessageAsync(String group, String topic, int queueId, long offset, int maxMsgNums, int maxTotalMsgSize, MessageFilter messageFilter) { return CompletableFuture.completedFuture(getMessage(group, topic, queueId, offset, maxMsgNums, maxTotalMsgSize, messageFilter)); } @Override public long getMaxOffsetInQueue(String topic, int queueId) { return getMaxOffsetInQueue(topic, queueId, true); } @Override public long getMaxOffsetInQueue(String topic, int queueId, boolean committed) { if (committed) { ConsumeQueueInterface logic = this.findConsumeQueue(topic, queueId); if (logic != null) { return logic.getMaxOffsetInQueue(); } } else { Long offset = this.consumeQueueStore.getMaxOffset(topic, queueId); if (offset != null) { return offset; } } return 0; } @Override public long getMinOffsetInQueue(String topic, int queueId) { try { return this.consumeQueueStore.getMinOffsetInQueue(topic, queueId); } catch (RocksDBException e) { ERROR_LOG.error("getMinOffsetInQueue Failed. topic: {}, queueId: {}", topic, queueId, e); return -1; } } @Override public TimerMessageStore getTimerMessageStore() { return this.timerMessageStore; } @Override public void setTimerMessageStore(TimerMessageStore timerMessageStore) { this.timerMessageStore = timerMessageStore; } @Override public long getCommitLogOffsetInQueue(String topic, int queueId, long consumeQueueOffset) { ConsumeQueueInterface consumeQueue = findConsumeQueue(topic, queueId); if (consumeQueue != null) { CqUnit cqUnit = consumeQueue.get(consumeQueueOffset); if (cqUnit != null) { return cqUnit.getPos(); } } return 0; } @Override public long getOffsetInQueueByTime(String topic, int queueId, long timestamp) { return this.getOffsetInQueueByTime(topic, queueId, timestamp, BoundaryType.LOWER); } @Override public long getOffsetInQueueByTime(String topic, int queueId, long timestamp, BoundaryType boundaryType) { try { return this.consumeQueueStore.getOffsetInQueueByTime(topic, queueId, timestamp, boundaryType); } catch (RocksDBException e) { ERROR_LOG.error("getOffsetInQueueByTime Failed. topic: {}, queueId: {}, timestamp: {} boundaryType: {}, {}", topic, queueId, timestamp, boundaryType, e.getMessage()); } return 0; } @Override public MessageExt lookMessageByOffset(long commitLogOffset) { SelectMappedBufferResult sbr = this.commitLog.getMessage(commitLogOffset, 4); if (null != sbr) { try { // 1 TOTALSIZE int size = sbr.getByteBuffer().getInt(); return lookMessageByOffset(commitLogOffset, size); } finally { sbr.release(); } } return null; } @Override public SelectMappedBufferResult selectOneMessageByOffset(long commitLogOffset) { SelectMappedBufferResult sbr = this.commitLog.getMessage(commitLogOffset, 4); if (null != sbr) { try { // 1 TOTALSIZE int size = sbr.getByteBuffer().getInt(); return this.commitLog.getMessage(commitLogOffset, size); } finally { sbr.release(); } } return null; } @Override public SelectMappedBufferResult selectOneMessageByOffset(long commitLogOffset, int msgSize) { return this.commitLog.getMessage(commitLogOffset, msgSize); } @Override public String getRunningDataInfo() { return this.storeStatsService.toString(); } public String getStorePathPhysic() { String storePathPhysic; if (DefaultMessageStore.this.getMessageStoreConfig().isEnableDLegerCommitLog()) { storePathPhysic = ((DLedgerCommitLog) DefaultMessageStore.this.getCommitLog()).getdLedgerServer().getdLedgerConfig().getDataStorePath(); } else { storePathPhysic = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog(); } return storePathPhysic; } public String getStorePathLogic() { return StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()); } public MessageArrivingListener getMessageArrivingListener() { return messageArrivingListener; } @Override public HashMap<String, String> getRuntimeInfo() { HashMap<String, String> result = this.storeStatsService.getRuntimeInfo(); { double minPhysicsUsedRatio = Double.MAX_VALUE; String commitLogStorePath = getStorePathPhysic(); String[] paths = commitLogStorePath.trim().split(MixAll.MULTI_PATH_SPLITTER); for (String clPath : paths) { double physicRatio = UtilAll.isPathExists(clPath) ? UtilAll.getDiskPartitionSpaceUsedPercent(clPath) : -1; result.put(RunningStats.commitLogDiskRatio.name() + "_" + clPath, String.valueOf(physicRatio)); minPhysicsUsedRatio = Math.min(minPhysicsUsedRatio, physicRatio); } result.put(RunningStats.commitLogDiskRatio.name(), String.valueOf(minPhysicsUsedRatio)); } { double logicsRatio = UtilAll.getDiskPartitionSpaceUsedPercent(getStorePathLogic()); result.put(RunningStats.consumeQueueDiskRatio.name(), String.valueOf(logicsRatio)); } result.put(RunningStats.commitLogMinOffset.name(), String.valueOf(DefaultMessageStore.this.getMinPhyOffset())); result.put(RunningStats.commitLogMaxOffset.name(), String.valueOf(DefaultMessageStore.this.getMaxPhyOffset())); return result; } @Override public long getMaxPhyOffset() { return this.commitLog.getMaxOffset(); } @Override public long getMinPhyOffset() { return this.commitLog.getMinOffset(); } @Override public long getLastFileFromOffset() { return this.commitLog.getLastFileFromOffset(); } @Override public boolean getLastMappedFile(long startOffset) { return this.commitLog.getLastMappedFile(startOffset); } @Override public long getEarliestMessageTime(String topic, int queueId) { ConsumeQueueInterface logicQueue = this.findConsumeQueue(topic, queueId); if (logicQueue != null) { Pair<CqUnit, Long> pair = logicQueue.getEarliestUnitAndStoreTime(); if (pair != null && pair.getObject2() != null) { return pair.getObject2(); } } return -1; } @Override public CompletableFuture<Long> getEarliestMessageTimeAsync(String topic, int queueId) { return CompletableFuture.completedFuture(getEarliestMessageTime(topic, queueId)); } @Override public long getEarliestMessageTime() { long minPhyOffset = this.getMinPhyOffset(); if (this.getCommitLog() instanceof DLedgerCommitLog) { minPhyOffset += DLedgerEntry.BODY_OFFSET; } final int size = MessageDecoder.MESSAGE_STORE_TIMESTAMP_POSITION + 8; return this.getCommitLog().pickupStoreTimestamp(minPhyOffset, size); } @Override public long getMessageStoreTimeStamp(String topic, int queueId, long consumeQueueOffset) { ConsumeQueueInterface logicQueue = this.findConsumeQueue(topic, queueId); if (logicQueue != null) { Pair<CqUnit, Long> pair = logicQueue.getCqUnitAndStoreTime(consumeQueueOffset); if (pair != null && pair.getObject2() != null) { return pair.getObject2(); } } return -1; } @Override public CompletableFuture<Long> getMessageStoreTimeStampAsync(String topic, int queueId, long consumeQueueOffset) { return CompletableFuture.completedFuture(getMessageStoreTimeStamp(topic, queueId, consumeQueueOffset)); } @Override public long getMessageTotalInQueue(String topic, int queueId) { ConsumeQueueInterface logicQueue = this.findConsumeQueue(topic, queueId); if (logicQueue != null) { return logicQueue.getMessageTotalInQueue(); } return -1; } @Override public SelectMappedBufferResult getCommitLogData(final long offset) { if (this.shutdown) { LOGGER.warn("message store has shutdown, so getPhyQueueData is forbidden"); return null; } return this.commitLog.getData(offset); } @Override public List<SelectMappedBufferResult> getBulkCommitLogData(final long offset, final int size) { if (this.shutdown) { LOGGER.warn("message store has shutdown, so getBulkCommitLogData is forbidden"); return null; } return this.commitLog.getBulkData(offset, size); } @Override public boolean appendToCommitLog(long startOffset, byte[] data, int dataStart, int dataLength) { if (this.shutdown) { LOGGER.warn("message store has shutdown, so appendToCommitLog is forbidden"); return false; } boolean result = this.commitLog.appendData(startOffset, data, dataStart, dataLength); if (result) { this.reputMessageService.wakeup(); } else { LOGGER.error( "DefaultMessageStore#appendToCommitLog: failed to append data to commitLog, physical offset={}, data " + "length={}", startOffset, data.length); } return result; } @Override public void executeDeleteFilesManually() { this.cleanCommitLogService.executeDeleteFilesManually(); } @Override public QueryMessageResult queryMessage(String topic, String key, int maxNum, long begin, long end) { QueryMessageResult queryMessageResult = new QueryMessageResult(); long lastQueryMsgTime = end; for (int i = 0; i < 3; i++) { QueryOffsetResult queryOffsetResult = this.indexService.queryOffset(topic, key, maxNum, begin, lastQueryMsgTime); if (queryOffsetResult.getPhyOffsets().isEmpty()) { break; } Collections.sort(queryOffsetResult.getPhyOffsets()); queryMessageResult.setIndexLastUpdatePhyoffset(queryOffsetResult.getIndexLastUpdatePhyoffset()); queryMessageResult.setIndexLastUpdateTimestamp(queryOffsetResult.getIndexLastUpdateTimestamp()); for (int m = 0; m < queryOffsetResult.getPhyOffsets().size(); m++) { long offset = queryOffsetResult.getPhyOffsets().get(m); try { MessageExt msg = this.lookMessageByOffset(offset); if (0 == m) { lastQueryMsgTime = msg.getStoreTimestamp(); } SelectMappedBufferResult result = this.commitLog.getData(offset, false); if (result != null) { int size = result.getByteBuffer().getInt(0); result.getByteBuffer().limit(size); result.setSize(size); queryMessageResult.addMessage(result); } } catch (Exception e) { LOGGER.error("queryMessage exception", e); } } if (queryMessageResult.getBufferTotalSize() > 0) { break; } if (lastQueryMsgTime < begin) { break; } } return queryMessageResult; } @Override public CompletableFuture<QueryMessageResult> queryMessageAsync(String topic, String key, int maxNum, long begin, long end) { return CompletableFuture.completedFuture(queryMessage(topic, key, maxNum, begin, end)); } @Override public void updateHaMasterAddress(String newAddr) { if (this.haService != null) { this.haService.updateHaMasterAddress(newAddr); } } @Override public void updateMasterAddress(String newAddr) { if (this.haService != null) { this.haService.updateMasterAddress(newAddr); } if (this.compactionService != null) { this.compactionService.updateMasterAddress(newAddr); } } @Override public void setAliveReplicaNumInGroup(int aliveReplicaNums) { this.aliveReplicasNum = aliveReplicaNums; } @Override public void wakeupHAClient() { if (this.haService != null) { this.haService.getHAClient().wakeup(); } } @Override public int getAliveReplicaNumInGroup() { return this.aliveReplicasNum; } @Override public long slaveFallBehindMuch() { if (this.haService == null || this.messageStoreConfig.isDuplicationEnable() || this.messageStoreConfig.isEnableDLegerCommitLog()) { LOGGER.warn("haServer is null or duplication is enable or enableDLegerCommitLog is true"); return -1; } else { return this.commitLog.getMaxOffset() - this.haService.getPush2SlaveMaxOffset().get(); } } @Override public long now() { return this.systemClock.now(); } /** * Lazy clean queue offset table. * If offset table is cleaned, and old messages are dispatching after the old consume queue is cleaned, * consume queue will be created with old offset, then later message with new offset table can not be * dispatched to consume queue. * @throws RocksDBException only in rocksdb mode */ @Override public int deleteTopics(final Set<String> deleteTopics) { if (deleteTopics == null || deleteTopics.isEmpty()) { return 0; } int deleteCount = 0; for (String topic : deleteTopics) { ConcurrentMap<Integer, ConsumeQueueInterface> queueTable = this.consumeQueueStore.findConsumeQueueMap(topic); if (queueTable == null || queueTable.isEmpty()) { continue; } for (ConsumeQueueInterface cq : queueTable.values()) { try { this.consumeQueueStore.destroy(cq); } catch (RocksDBException e) { LOGGER.error("DeleteTopic: ConsumeQueue cleans error!, topic={}, queueId={}", cq.getTopic(), cq.getQueueId(), e); } LOGGER.info("DeleteTopic: ConsumeQueue has been cleaned, topic={}, queueId={}", cq.getTopic(), cq.getQueueId()); this.consumeQueueStore.removeTopicQueueTable(cq.getTopic(), cq.getQueueId()); } // remove topic from cq table this.consumeQueueStore.getConsumeQueueTable().remove(topic); if (this.brokerConfig.isAutoDeleteUnusedStats()) { this.brokerStatsManager.onTopicDeleted(topic); } // destroy consume queue dir String consumeQueueDir = StorePathConfigHelper.getStorePathConsumeQueue( this.messageStoreConfig.getStorePathRootDir()) + File.separator + topic; String consumeQueueExtDir = StorePathConfigHelper.getStorePathConsumeQueueExt( this.messageStoreConfig.getStorePathRootDir()) + File.separator + topic; String batchConsumeQueueDir = StorePathConfigHelper.getStorePathBatchConsumeQueue( this.messageStoreConfig.getStorePathRootDir()) + File.separator + topic; UtilAll.deleteEmptyDirectory(new File(consumeQueueDir)); UtilAll.deleteEmptyDirectory(new File(consumeQueueExtDir)); UtilAll.deleteEmptyDirectory(new File(batchConsumeQueueDir)); LOGGER.info("DeleteTopic: Topic has been destroyed, topic={}", topic); deleteCount++; } return deleteCount; } @Override public int cleanUnusedTopic(final Set<String> retainTopics) { Set<String> consumeQueueTopicSet = this.getConsumeQueueTable().keySet(); int deleteCount = 0; for (String topicName : Sets.difference(consumeQueueTopicSet, retainTopics)) { if (retainTopics.contains(topicName) || TopicValidator.isSystemTopic(topicName) || MixAll.isLmq(topicName)) { continue; } deleteCount += this.deleteTopics(Sets.newHashSet(topicName)); } return deleteCount; } @Override public void cleanExpiredConsumerQueue() { long minCommitLogOffset = this.commitLog.getMinOffset(); this.consumeQueueStore.cleanExpired(minCommitLogOffset); } public Map<String, Long> getMessageIds(final String topic, final int queueId, long minOffset, long maxOffset, SocketAddress storeHost) { Map<String, Long> messageIds = new HashMap<>(); if (this.shutdown) { return messageIds; } ConsumeQueueInterface consumeQueue = findConsumeQueue(topic, queueId); if (consumeQueue != null) { minOffset = Math.max(minOffset, consumeQueue.getMinOffsetInQueue()); maxOffset = Math.min(maxOffset, consumeQueue.getMaxOffsetInQueue()); if (maxOffset == 0) { return messageIds; } long nextOffset = minOffset; while (nextOffset < maxOffset) { ReferredIterator<CqUnit> bufferConsumeQueue = consumeQueue.iterateFrom(nextOffset); try { if (bufferConsumeQueue != null && bufferConsumeQueue.hasNext()) { while (bufferConsumeQueue.hasNext()) { CqUnit cqUnit = bufferConsumeQueue.next(); long offsetPy = cqUnit.getPos(); InetSocketAddress inetSocketAddress = (InetSocketAddress) storeHost; int msgIdLength = (inetSocketAddress.getAddress() instanceof Inet6Address) ? 16 + 4 + 8 : 4 + 4 + 8; final ByteBuffer msgIdMemory = ByteBuffer.allocate(msgIdLength); String msgId = MessageDecoder.createMessageId(msgIdMemory, MessageExt.socketAddress2ByteBuffer(storeHost), offsetPy); messageIds.put(msgId, cqUnit.getQueueOffset()); nextOffset = cqUnit.getQueueOffset() + cqUnit.getBatchNum(); if (nextOffset >= maxOffset) { return messageIds; } } } else { return messageIds; } } finally { if (bufferConsumeQueue != null) { bufferConsumeQueue.release(); } } } } return messageIds; } @Override @Deprecated public boolean checkInDiskByConsumeOffset(final String topic, final int queueId, long consumeOffset) { final long maxOffsetPy = this.commitLog.getMaxOffset(); ConsumeQueueInterface consumeQueue = findConsumeQueue(topic, queueId); if (consumeQueue != null) { CqUnit cqUnit = consumeQueue.get(consumeOffset); if (cqUnit != null) { long offsetPy = cqUnit.getPos(); return !estimateInMemByCommitOffset(offsetPy, maxOffsetPy); } else { return false; } } return false; } @Override public boolean checkInMemByConsumeOffset(final String topic, final int queueId, long consumeOffset, int batchSize) { ConsumeQueueInterface consumeQueue = findConsumeQueue(topic, queueId); if (consumeQueue != null) { CqUnit firstCQItem = consumeQueue.get(consumeOffset); if (firstCQItem == null) { return false; } long startOffsetPy = firstCQItem.getPos(); if (batchSize <= 1) { int size = firstCQItem.getSize(); return checkInMemByCommitOffset(startOffsetPy, size); } CqUnit lastCQItem = consumeQueue.get(consumeOffset + batchSize); if (lastCQItem == null) { int size = firstCQItem.getSize(); return checkInMemByCommitOffset(startOffsetPy, size); } long endOffsetPy = lastCQItem.getPos(); int size = (int) (endOffsetPy - startOffsetPy) + lastCQItem.getSize(); return checkInMemByCommitOffset(startOffsetPy, size); } return false; } @Override public boolean checkInStoreByConsumeOffset(String topic, int queueId, long consumeOffset) { long commitLogOffset = getCommitLogOffsetInQueue(topic, queueId, consumeOffset); return checkInDiskByCommitOffset(commitLogOffset); } @Override public long dispatchBehindBytes() { return this.reputMessageService.behind(); } public long flushBehindBytes() { return this.commitLog.remainHowManyDataToCommit() + this.commitLog.remainHowManyDataToFlush(); } @Override public long flush() { return this.commitLog.flush(); } @Override public long getFlushedWhere() { return this.commitLog.getFlushedWhere(); } @Override public boolean resetWriteOffset(long phyOffset) { //copy a new map ConcurrentHashMap<String, Long> newMap = new ConcurrentHashMap<>(consumeQueueStore.getTopicQueueTable()); SelectMappedBufferResult lastBuffer = null; long startReadOffset = phyOffset == -1 ? 0 : phyOffset; while ((lastBuffer = selectOneMessageByOffset(startReadOffset)) != null) { try { if (lastBuffer.getStartOffset() > startReadOffset) { startReadOffset = lastBuffer.getStartOffset(); continue; } ByteBuffer bb = lastBuffer.getByteBuffer(); int magicCode = bb.getInt(bb.position() + 4); if (magicCode == CommitLog.BLANK_MAGIC_CODE) { startReadOffset += bb.getInt(bb.position()); continue; } else if (magicCode != MessageDecoder.MESSAGE_MAGIC_CODE) { throw new RuntimeException("Unknown magicCode: " + magicCode); } lastBuffer.getByteBuffer().mark(); DispatchRequest dispatchRequest = checkMessageAndReturnSize(lastBuffer.getByteBuffer(), true, messageStoreConfig.isDuplicationEnable(), true); if (!dispatchRequest.isSuccess()) break; lastBuffer.getByteBuffer().reset(); MessageExt msg = MessageDecoder.decode(lastBuffer.getByteBuffer(), true, false, false, false, true); if (msg == null) { break; } String key = msg.getTopic() + "-" + msg.getQueueId(); Long cur = newMap.get(key); if (cur != null && cur > msg.getQueueOffset()) { newMap.put(key, msg.getQueueOffset()); } startReadOffset += msg.getStoreSize(); } catch (Throwable e) { LOGGER.error("resetWriteOffset error.", e); } finally { if (lastBuffer != null) lastBuffer.release(); } } if (this.commitLog.resetOffset(phyOffset)) { this.consumeQueueStore.setTopicQueueTable(newMap); return true; } else { return false; } } // Fetch and compute the newest confirmOffset. // Even if it is just inited. @Override public long getConfirmOffset() { return this.commitLog.getConfirmOffset(); } // Fetch the original confirmOffset's value. // Without checking and re-computing. public long getConfirmOffsetDirectly() { return this.commitLog.getConfirmOffsetDirectly(); } @Override public void setConfirmOffset(long phyOffset) { this.commitLog.setConfirmOffset(phyOffset); } @Override public byte[] calcDeltaChecksum(long from, long to) { if (from < 0 || to <= from) { return new byte[0]; } int size = (int) (to - from); if (size > this.messageStoreConfig.getMaxChecksumRange()) { LOGGER.error("Checksum range from {}, size {} exceeds threshold {}", from, size, this.messageStoreConfig.getMaxChecksumRange()); return null; } List<MessageExt> msgList = new ArrayList<>(); List<SelectMappedBufferResult> bufferResultList = this.getBulkCommitLogData(from, size); if (bufferResultList.isEmpty()) { return new byte[0]; } for (SelectMappedBufferResult bufferResult : bufferResultList) { msgList.addAll(MessageDecoder.decodesBatch(bufferResult.getByteBuffer(), true, false, false)); bufferResult.release(); } if (msgList.isEmpty()) { return new byte[0]; } ByteBuffer byteBuffer = ByteBuffer.allocate(size); for (MessageExt msg : msgList) { try { byteBuffer.put(MessageDecoder.encodeUniquely(msg, false)); } catch (IOException ignore) { } } return Hashing.murmur3_128().hashBytes(byteBuffer.array()).asBytes(); } @Override public void setPhysicalOffset(long phyOffset) { this.commitLog.setMappedFileQueueOffset(phyOffset); } @Override public boolean isMappedFilesEmpty() { return this.commitLog.isMappedFilesEmpty(); } @Override public MessageExt lookMessageByOffset(long commitLogOffset, int size) { SelectMappedBufferResult sbr = this.commitLog.getMessage(commitLogOffset, size); if (null != sbr) { try { return MessageDecoder.decode(sbr.getByteBuffer(), true, false); } finally { sbr.release(); } } return null; } @Override public ConsumeQueueInterface findConsumeQueue(String topic, int queueId) { return this.consumeQueueStore.findOrCreateConsumeQueue(topic, queueId); } private long nextOffsetCorrection(long oldOffset, long newOffset) { long nextOffset = oldOffset; if (this.getMessageStoreConfig().getBrokerRole() != BrokerRole.SLAVE || this.getMessageStoreConfig().isOffsetCheckInSlave()) { nextOffset = newOffset; } return nextOffset; } private boolean estimateInMemByCommitOffset(long offsetPy, long maxOffsetPy) { long memory = (long) (StoreUtil.TOTAL_PHYSICAL_MEMORY_SIZE * (this.messageStoreConfig.getAccessMessageInMemoryMaxRatio() / 100.0)); return (maxOffsetPy - offsetPy) <= memory; } private boolean checkInMemByCommitOffset(long offsetPy, int size) { SelectMappedBufferResult message = this.commitLog.getMessage(offsetPy, size); if (message != null) { try { return message.isInMem(); } finally { message.release(); } } return false; } public boolean checkInDiskByCommitOffset(long offsetPy) { return offsetPy >= commitLog.getMinOffset(); } /** * The ratio val is estimated by the experiment and experience * so that the result is not high accurate for different business * @return */ public boolean checkInColdAreaByCommitOffset(long offsetPy, long maxOffsetPy) { long memory = (long)(StoreUtil.TOTAL_PHYSICAL_MEMORY_SIZE * (this.messageStoreConfig.getAccessMessageInMemoryHotRatio() / 100.0)); return (maxOffsetPy - offsetPy) > memory; } private boolean isTheBatchFull(int sizePy, int unitBatchNum, int maxMsgNums, long maxMsgSize, int bufferTotal, int messageTotal, boolean isInMem) { if (0 == bufferTotal || 0 == messageTotal) { return false; } if (messageTotal + unitBatchNum > maxMsgNums) { return true; } if (bufferTotal + sizePy > maxMsgSize) { return true; } if (isInMem) { if ((bufferTotal + sizePy) > this.messageStoreConfig.getMaxTransferBytesOnMessageInMemory()) { return true; } return messageTotal > this.messageStoreConfig.getMaxTransferCountOnMessageInMemory() - 1; } else { if ((bufferTotal + sizePy) > this.messageStoreConfig.getMaxTransferBytesOnMessageInDisk()) { return true; } return messageTotal > this.messageStoreConfig.getMaxTransferCountOnMessageInDisk() - 1; } } private void deleteFile(final String fileName) { File file = new File(fileName); boolean result = file.delete(); LOGGER.info(fileName + (result ? " delete OK" : " delete Failed")); } /** * @throws IOException */ private void createTempFile() throws IOException { String fileName = StorePathConfigHelper.getAbortFile(this.messageStoreConfig.getStorePathRootDir()); File file = new File(fileName); UtilAll.ensureDirOK(file.getParent()); boolean result = file.createNewFile(); LOGGER.info(fileName + (result ? " create OK" : " already exists")); MixAll.string2File(Long.toString(MixAll.getPID()), file.getAbsolutePath()); } private void addScheduleTask() { this.scheduledExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { DefaultMessageStore.this.cleanFilesPeriodically(); } }, 1000 * 60, this.messageStoreConfig.getCleanResourceInterval(), TimeUnit.MILLISECONDS); this.scheduledExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { DefaultMessageStore.this.checkSelf(); } }, 1, 10, TimeUnit.MINUTES); this.scheduledExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { if (DefaultMessageStore.this.getMessageStoreConfig().isDebugLockEnable()) { try { if (DefaultMessageStore.this.commitLog.getBeginTimeInLock() != 0) { long lockTime = System.currentTimeMillis() - DefaultMessageStore.this.commitLog.getBeginTimeInLock(); if (lockTime > 1000 && lockTime < 10000000) { String stack = UtilAll.jstack(); final String fileName = System.getProperty("user.home") + File.separator + "debug/lock/stack-" + DefaultMessageStore.this.commitLog.getBeginTimeInLock() + "-" + lockTime; MixAll.string2FileNotSafe(stack, fileName); } } } catch (Exception e) { } } } }, 1, 1, TimeUnit.SECONDS); this.scheduledExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { DefaultMessageStore.this.storeCheckpoint.flush(); } }, 1, 1, TimeUnit.SECONDS); this.scheduledCleanQueueExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { DefaultMessageStore.this.cleanQueueFilesPeriodically(); } }, 1000 * 60, this.messageStoreConfig.getCleanResourceInterval(), TimeUnit.MILLISECONDS); // this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { // @Override // public void run() { // DefaultMessageStore.this.cleanExpiredConsumerQueue(); // } // }, 1, 1, TimeUnit.HOURS); } private void cleanFilesPeriodically() { this.cleanCommitLogService.run(); } private void cleanQueueFilesPeriodically() { this.correctLogicOffsetService.run(); this.cleanConsumeQueueService.run(); } private void checkSelf() { this.commitLog.checkSelf(); this.consumeQueueStore.checkSelf(); } private boolean isTempFileExist() { String fileName = StorePathConfigHelper.getAbortFile(this.messageStoreConfig.getStorePathRootDir()); File file = new File(fileName); return file.exists(); } private boolean isRecoverConcurrently() { return this.brokerConfig.isRecoverConcurrently() && !this.messageStoreConfig.isEnableRocksDBStore(); } private void recover(final boolean lastExitOK) throws RocksDBException { boolean recoverConcurrently = this.isRecoverConcurrently(); LOGGER.info("message store recover mode: {}", recoverConcurrently ? "concurrent" : "normal"); // recover consume queue long recoverConsumeQueueStart = System.currentTimeMillis(); this.recoverConsumeQueue(); long maxPhyOffsetOfConsumeQueue = this.consumeQueueStore.getMaxPhyOffsetInConsumeQueue(); long recoverConsumeQueueEnd = System.currentTimeMillis(); // recover commitlog if (lastExitOK) { this.commitLog.recoverNormally(maxPhyOffsetOfConsumeQueue); } else { this.commitLog.recoverAbnormally(maxPhyOffsetOfConsumeQueue); } // recover consume offset table long recoverCommitLogEnd = System.currentTimeMillis(); this.recoverTopicQueueTable(); long recoverConsumeOffsetEnd = System.currentTimeMillis(); LOGGER.info("message store recover total cost: {} ms, " + "recoverConsumeQueue: {} ms, recoverCommitLog: {} ms, recoverOffsetTable: {} ms", recoverConsumeOffsetEnd - recoverConsumeQueueStart, recoverConsumeQueueEnd - recoverConsumeQueueStart, recoverCommitLogEnd - recoverConsumeQueueEnd, recoverConsumeOffsetEnd - recoverCommitLogEnd); } @Override public long getTimingMessageCount(String topic) { if (null == timerMessageStore) { return 0L; } else { return timerMessageStore.getTimerMetrics().getTimingCount(topic); } } @Override public MessageStoreConfig getMessageStoreConfig() { return messageStoreConfig; } @Override public void finishCommitLogDispatch() { // ignore } @Override public TransientStorePool getTransientStorePool() { return transientStorePool; } private void recoverConsumeQueue() { if (!this.isRecoverConcurrently()) { this.consumeQueueStore.recover(); } else { this.consumeQueueStore.recoverConcurrently(); } } @Override public void recoverTopicQueueTable() { long minPhyOffset = this.commitLog.getMinOffset(); this.consumeQueueStore.recoverOffsetTable(minPhyOffset); } @Override public AllocateMappedFileService getAllocateMappedFileService() { return allocateMappedFileService; } @Override public StoreStatsService getStoreStatsService() { return storeStatsService; } public RunningFlags getAccessRights() { return runningFlags; } public ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueueInterface>> getConsumeQueueTable() { return consumeQueueStore.getConsumeQueueTable(); } @Override public StoreCheckpoint getStoreCheckpoint() { return storeCheckpoint; } @Override public HAService getHaService() { return haService; } @Override public RunningFlags getRunningFlags() { return runningFlags; } public void doDispatch(DispatchRequest req) throws RocksDBException { for (CommitLogDispatcher dispatcher : this.dispatcherList) { dispatcher.dispatch(req); } } /** * @param dispatchRequest * @throws RocksDBException only in rocksdb mode */ protected void putMessagePositionInfo(DispatchRequest dispatchRequest) throws RocksDBException { this.consumeQueueStore.putMessagePositionInfoWrapper(dispatchRequest); } @Override public DispatchRequest checkMessageAndReturnSize(final ByteBuffer byteBuffer, final boolean checkCRC, final boolean checkDupInfo, final boolean readBody) { return this.commitLog.checkMessageAndReturnSize(byteBuffer, checkCRC, checkDupInfo, readBody); } @Override public long getStateMachineVersion() { return stateMachineVersion; } public void setStateMachineVersion(long stateMachineVersion) { this.stateMachineVersion = stateMachineVersion; } public BrokerStatsManager getBrokerStatsManager() { return brokerStatsManager; } public BrokerConfig getBrokerConfig() { return brokerConfig; } public int remainTransientStoreBufferNumbs() { if (this.isTransientStorePoolEnable()) { return this.transientStorePool.availableBufferNums(); } return Integer.MAX_VALUE; } @Override public boolean isTransientStorePoolDeficient() { return remainTransientStoreBufferNumbs() == 0; } @Override public long remainHowManyDataToCommit() { return this.commitLog.remainHowManyDataToCommit(); } @Override public long remainHowManyDataToFlush() { return this.commitLog.remainHowManyDataToFlush(); } @Override public LinkedList<CommitLogDispatcher> getDispatcherList() { return this.dispatcherList; } @Override public void addDispatcher(CommitLogDispatcher dispatcher) { this.dispatcherList.add(dispatcher); } @Override public void setMasterStoreInProcess(MessageStore masterStoreInProcess) { this.masterStoreInProcess = masterStoreInProcess; } @Override public MessageStore getMasterStoreInProcess() { return this.masterStoreInProcess; } @Override public boolean getData(long offset, int size, ByteBuffer byteBuffer) { return this.commitLog.getData(offset, size, byteBuffer); } @Override public ConsumeQueueInterface getConsumeQueue(String topic, int queueId) { ConcurrentMap<Integer, ConsumeQueueInterface> map = this.getConsumeQueueTable().get(topic); if (map == null) { return null; } return map.get(queueId); } @Override public void unlockMappedFile(final MappedFile mappedFile) { this.scheduledExecutorService.schedule(new Runnable() { @Override public void run() { mappedFile.munlock(); } }, 6, TimeUnit.SECONDS); } @Override public PerfCounter.Ticks getPerfCounter() { return perfs; } @Override public ConsumeQueueStoreInterface getQueueStore() { return consumeQueueStore; } @Override public void onCommitLogAppend(MessageExtBrokerInner msg, AppendMessageResult result, MappedFile commitLogFile) { // empty } @Override public void onCommitLogDispatch(DispatchRequest dispatchRequest, boolean doDispatch, MappedFile commitLogFile, boolean isRecover, boolean isFileEnd) throws RocksDBException { if (doDispatch && !isFileEnd) { this.doDispatch(dispatchRequest); } } @Override public boolean isSyncDiskFlush() { return FlushDiskType.SYNC_FLUSH == this.getMessageStoreConfig().getFlushDiskType(); } @Override public boolean isSyncMaster() { return BrokerRole.SYNC_MASTER == this.getMessageStoreConfig().getBrokerRole(); } @Override public void assignOffset(MessageExtBrokerInner msg) throws RocksDBException { final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag()); if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) { this.consumeQueueStore.assignQueueOffset(msg); } } @Override public void increaseOffset(MessageExtBrokerInner msg, short messageNum) { final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag()); if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) { this.consumeQueueStore.increaseQueueOffset(msg, messageNum); } } public ConcurrentMap<String, TopicConfig> getTopicConfigs() { return this.topicConfigTable; } public Optional<TopicConfig> getTopicConfig(String topic) { if (this.topicConfigTable == null) { return Optional.empty(); } return Optional.ofNullable(this.topicConfigTable.get(topic)); } public BrokerIdentity getBrokerIdentity() { if (messageStoreConfig.isEnableDLegerCommitLog()) { return new BrokerIdentity( brokerConfig.getBrokerClusterName(), brokerConfig.getBrokerName(), Integer.parseInt(messageStoreConfig.getdLegerSelfId().substring(1)), brokerConfig.isInBrokerContainer()); } else { return new BrokerIdentity( brokerConfig.getBrokerClusterName(), brokerConfig.getBrokerName(), brokerConfig.getBrokerId(), brokerConfig.isInBrokerContainer()); } } class CommitLogDispatcherBuildConsumeQueue implements CommitLogDispatcher { @Override public void dispatch(DispatchRequest request) throws RocksDBException { final int tranType = MessageSysFlag.getTransactionValue(request.getSysFlag()); switch (tranType) { case MessageSysFlag.TRANSACTION_NOT_TYPE: case MessageSysFlag.TRANSACTION_COMMIT_TYPE: putMessagePositionInfo(request); break; case MessageSysFlag.TRANSACTION_PREPARED_TYPE: case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE: break; } } } class CommitLogDispatcherBuildIndex implements CommitLogDispatcher { @Override public void dispatch(DispatchRequest request) { if (DefaultMessageStore.this.messageStoreConfig.isMessageIndexEnable()) { DefaultMessageStore.this.indexService.buildIndex(request); } } } class CleanCommitLogService { private final static int MAX_MANUAL_DELETE_FILE_TIMES = 20; private final String diskSpaceWarningLevelRatio = System.getProperty("rocketmq.broker.diskSpaceWarningLevelRatio", ""); private final String diskSpaceCleanForciblyRatio = System.getProperty("rocketmq.broker.diskSpaceCleanForciblyRatio", ""); private long lastRedeleteTimestamp = 0; private volatile int manualDeleteFileSeveralTimes = 0; private volatile boolean cleanImmediately = false; private int forceCleanFailedTimes = 0; double getDiskSpaceWarningLevelRatio() { double finalDiskSpaceWarningLevelRatio; if ("".equals(diskSpaceWarningLevelRatio)) { finalDiskSpaceWarningLevelRatio = DefaultMessageStore.this.getMessageStoreConfig().getDiskSpaceWarningLevelRatio() / 100.0; } else { finalDiskSpaceWarningLevelRatio = Double.parseDouble(diskSpaceWarningLevelRatio); } if (finalDiskSpaceWarningLevelRatio > 0.90) { finalDiskSpaceWarningLevelRatio = 0.90; } if (finalDiskSpaceWarningLevelRatio < 0.35) { finalDiskSpaceWarningLevelRatio = 0.35; } return finalDiskSpaceWarningLevelRatio; } double getDiskSpaceCleanForciblyRatio() { double finalDiskSpaceCleanForciblyRatio; if ("".equals(diskSpaceCleanForciblyRatio)) { finalDiskSpaceCleanForciblyRatio = DefaultMessageStore.this.getMessageStoreConfig().getDiskSpaceCleanForciblyRatio() / 100.0; } else { finalDiskSpaceCleanForciblyRatio = Double.parseDouble(diskSpaceCleanForciblyRatio); } if (finalDiskSpaceCleanForciblyRatio > 0.85) { finalDiskSpaceCleanForciblyRatio = 0.85; } if (finalDiskSpaceCleanForciblyRatio < 0.30) { finalDiskSpaceCleanForciblyRatio = 0.30; } return finalDiskSpaceCleanForciblyRatio; } public void executeDeleteFilesManually() { this.manualDeleteFileSeveralTimes = MAX_MANUAL_DELETE_FILE_TIMES; DefaultMessageStore.LOGGER.info("executeDeleteFilesManually was invoked"); } public void run() { try { this.deleteExpiredFiles(); this.reDeleteHangedFile(); } catch (Throwable e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } private void deleteExpiredFiles() { int deleteCount = 0; long fileReservedTime = DefaultMessageStore.this.getMessageStoreConfig().getFileReservedTime(); int deletePhysicFilesInterval = DefaultMessageStore.this.getMessageStoreConfig().getDeleteCommitLogFilesInterval(); int destroyMappedFileIntervalForcibly = DefaultMessageStore.this.getMessageStoreConfig().getDestroyMapedFileIntervalForcibly(); int deleteFileBatchMax = DefaultMessageStore.this.getMessageStoreConfig().getDeleteFileBatchMax(); boolean isTimeUp = this.isTimeToDelete(); boolean isUsageExceedsThreshold = this.isSpaceToDelete(); boolean isManualDelete = this.manualDeleteFileSeveralTimes > 0; if (isTimeUp || isUsageExceedsThreshold || isManualDelete) { if (isManualDelete) { this.manualDeleteFileSeveralTimes--; } boolean cleanAtOnce = DefaultMessageStore.this.getMessageStoreConfig().isCleanFileForciblyEnable() && this.cleanImmediately; LOGGER.info("begin to delete before {} hours file. isTimeUp: {} isUsageExceedsThreshold: {} manualDeleteFileSeveralTimes: {} cleanAtOnce: {} deleteFileBatchMax: {}", fileReservedTime, isTimeUp, isUsageExceedsThreshold, manualDeleteFileSeveralTimes, cleanAtOnce, deleteFileBatchMax); fileReservedTime *= 60 * 60 * 1000; deleteCount = DefaultMessageStore.this.commitLog.deleteExpiredFile(fileReservedTime, deletePhysicFilesInterval, destroyMappedFileIntervalForcibly, cleanAtOnce, deleteFileBatchMax); if (deleteCount > 0) { // If in the controller mode, we should notify the AutoSwitchHaService to truncateEpochFile if (DefaultMessageStore.this.brokerConfig.isEnableControllerMode()) { if (DefaultMessageStore.this.haService instanceof AutoSwitchHAService) { final long minPhyOffset = getMinPhyOffset(); ((AutoSwitchHAService) DefaultMessageStore.this.haService).truncateEpochFilePrefix(minPhyOffset - 1); } } } else if (isUsageExceedsThreshold) { LOGGER.warn("disk space will be full soon, but delete file failed."); } } } private void reDeleteHangedFile() { int interval = DefaultMessageStore.this.getMessageStoreConfig().getRedeleteHangedFileInterval(); long currentTimestamp = System.currentTimeMillis(); if ((currentTimestamp - this.lastRedeleteTimestamp) > interval) { this.lastRedeleteTimestamp = currentTimestamp; int destroyMappedFileIntervalForcibly = DefaultMessageStore.this.getMessageStoreConfig().getDestroyMapedFileIntervalForcibly(); if (DefaultMessageStore.this.commitLog.retryDeleteFirstFile(destroyMappedFileIntervalForcibly)) { } } } public String getServiceName() { return DefaultMessageStore.this.brokerConfig.getIdentifier() + CleanCommitLogService.class.getSimpleName(); } protected boolean isTimeToDelete() { String when = DefaultMessageStore.this.getMessageStoreConfig().getDeleteWhen(); if (UtilAll.isItTimeToDo(when)) { DefaultMessageStore.LOGGER.info("it's time to reclaim disk space, " + when); return true; } return false; } private boolean isSpaceToDelete() { cleanImmediately = false; String commitLogStorePath = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog(); String[] storePaths = commitLogStorePath.trim().split(MixAll.MULTI_PATH_SPLITTER); Set<String> fullStorePath = new HashSet<>(); double minPhysicRatio = 100; String minStorePath = null; for (String storePathPhysic : storePaths) { double physicRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePathPhysic); if (minPhysicRatio > physicRatio) { minPhysicRatio = physicRatio; minStorePath = storePathPhysic; } if (physicRatio > getDiskSpaceCleanForciblyRatio()) { fullStorePath.add(storePathPhysic); } } DefaultMessageStore.this.commitLog.setFullStorePaths(fullStorePath); if (minPhysicRatio > getDiskSpaceWarningLevelRatio()) { boolean diskFull = DefaultMessageStore.this.runningFlags.getAndMakeDiskFull(); if (diskFull) { DefaultMessageStore.LOGGER.error("physic disk maybe full soon " + minPhysicRatio + ", so mark disk full, storePathPhysic=" + minStorePath); } cleanImmediately = true; return true; } else if (minPhysicRatio > getDiskSpaceCleanForciblyRatio()) { cleanImmediately = true; return true; } else { boolean diskOK = DefaultMessageStore.this.runningFlags.getAndMakeDiskOK(); if (!diskOK) { DefaultMessageStore.LOGGER.info("physic disk space OK " + minPhysicRatio + ", so mark disk ok, storePathPhysic=" + minStorePath); } } String storePathLogics = StorePathConfigHelper .getStorePathConsumeQueue(DefaultMessageStore.this.getMessageStoreConfig().getStorePathRootDir()); double logicsRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePathLogics); if (logicsRatio > getDiskSpaceWarningLevelRatio()) { boolean diskOK = DefaultMessageStore.this.runningFlags.getAndMakeDiskFull(); if (diskOK) { DefaultMessageStore.LOGGER.error("logics disk maybe full soon " + logicsRatio + ", so mark disk full"); } cleanImmediately = true; return true; } else if (logicsRatio > getDiskSpaceCleanForciblyRatio()) { cleanImmediately = true; return true; } else { boolean diskOK = DefaultMessageStore.this.runningFlags.getAndMakeDiskOK(); if (!diskOK) { DefaultMessageStore.LOGGER.info("logics disk space OK " + logicsRatio + ", so mark disk ok"); } } double ratio = DefaultMessageStore.this.getMessageStoreConfig().getDiskMaxUsedSpaceRatio() / 100.0; int replicasPerPartition = DefaultMessageStore.this.getMessageStoreConfig().getReplicasPerDiskPartition(); // Only one commitLog in node if (replicasPerPartition <= 1) { if (minPhysicRatio < 0 || minPhysicRatio > ratio) { DefaultMessageStore.LOGGER.info("commitLog disk maybe full soon, so reclaim space, " + minPhysicRatio); return true; } if (logicsRatio < 0 || logicsRatio > ratio) { DefaultMessageStore.LOGGER.info("consumeQueue disk maybe full soon, so reclaim space, " + logicsRatio); return true; } return false; } else { long majorFileSize = DefaultMessageStore.this.getMajorFileSize(); long partitionLogicalSize = UtilAll.getDiskPartitionTotalSpace(minStorePath) / replicasPerPartition; double logicalRatio = 1.0 * majorFileSize / partitionLogicalSize; if (logicalRatio > DefaultMessageStore.this.getMessageStoreConfig().getLogicalDiskSpaceCleanForciblyThreshold()) { // if logical ratio exceeds 0.80, then clean immediately DefaultMessageStore.LOGGER.info("Logical disk usage {} exceeds logical disk space clean forcibly threshold {}, forcibly: {}", logicalRatio, minPhysicRatio, cleanImmediately); cleanImmediately = true; return true; } boolean isUsageExceedsThreshold = logicalRatio > ratio; if (isUsageExceedsThreshold) { DefaultMessageStore.LOGGER.info("Logical disk usage {} exceeds clean threshold {}, forcibly: {}", logicalRatio, ratio, cleanImmediately); } return isUsageExceedsThreshold; } } public int getManualDeleteFileSeveralTimes() { return manualDeleteFileSeveralTimes; } public void setManualDeleteFileSeveralTimes(int manualDeleteFileSeveralTimes) { this.manualDeleteFileSeveralTimes = manualDeleteFileSeveralTimes; } public double calcStorePathPhysicRatio() { Set<String> fullStorePath = new HashSet<>(); String storePath = getStorePathPhysic(); String[] paths = storePath.trim().split(MixAll.MULTI_PATH_SPLITTER); double minPhysicRatio = 100; for (String path : paths) { double physicRatio = UtilAll.isPathExists(path) ? UtilAll.getDiskPartitionSpaceUsedPercent(path) : -1; minPhysicRatio = Math.min(minPhysicRatio, physicRatio); if (physicRatio > getDiskSpaceCleanForciblyRatio()) { fullStorePath.add(path); } } DefaultMessageStore.this.commitLog.setFullStorePaths(fullStorePath); return minPhysicRatio; } public boolean isSpaceFull() { double physicRatio = calcStorePathPhysicRatio(); double ratio = DefaultMessageStore.this.getMessageStoreConfig().getDiskMaxUsedSpaceRatio() / 100.0; if (physicRatio > ratio) { DefaultMessageStore.LOGGER.info("physic disk of commitLog used: " + physicRatio); } if (physicRatio > this.getDiskSpaceWarningLevelRatio()) { boolean diskok = DefaultMessageStore.this.runningFlags.getAndMakeDiskFull(); if (diskok) { DefaultMessageStore.LOGGER.error("physic disk of commitLog maybe full soon, used " + physicRatio + ", so mark disk full"); } return true; } else { boolean diskok = DefaultMessageStore.this.runningFlags.getAndMakeDiskOK(); if (!diskok) { DefaultMessageStore.LOGGER.info("physic disk space of commitLog OK " + physicRatio + ", so mark disk ok"); } return false; } } } class CleanConsumeQueueService { protected long lastPhysicalMinOffset = 0; public void run() { try { this.deleteExpiredFiles(); } catch (Throwable e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } protected void deleteExpiredFiles() { int deleteLogicsFilesInterval = DefaultMessageStore.this.getMessageStoreConfig().getDeleteConsumeQueueFilesInterval(); long minOffset = DefaultMessageStore.this.commitLog.getMinOffset(); if (minOffset > this.lastPhysicalMinOffset) { this.lastPhysicalMinOffset = minOffset; ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueueInterface>> tables = DefaultMessageStore.this.getConsumeQueueTable(); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : tables.values()) { for (ConsumeQueueInterface logic : maps.values()) { int deleteCount = DefaultMessageStore.this.consumeQueueStore.deleteExpiredFile(logic, minOffset); if (deleteCount > 0 && deleteLogicsFilesInterval > 0) { try { Thread.sleep(deleteLogicsFilesInterval); } catch (InterruptedException ignored) { } } } } DefaultMessageStore.this.indexService.deleteExpiredFile(minOffset); } } public String getServiceName() { return DefaultMessageStore.this.brokerConfig.getIdentifier() + CleanConsumeQueueService.class.getSimpleName(); } } class CorrectLogicOffsetService { private long lastForceCorrectTime = -1L; public void run() { try { this.correctLogicMinOffset(); } catch (Throwable e) { LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } private boolean needCorrect(ConsumeQueueInterface logic, long minPhyOffset, long lastForeCorrectTimeCurRun) { if (logic == null) { return false; } // If first exist and not available, it means first file may destroy failed, delete it. if (DefaultMessageStore.this.consumeQueueStore.isFirstFileExist(logic) && !DefaultMessageStore.this.consumeQueueStore.isFirstFileAvailable(logic)) { LOGGER.error("CorrectLogicOffsetService.needCorrect. first file not available, trigger correct." + " topic:{}, queue:{}, maxPhyOffset in queue:{}, minPhyOffset " + "in commit log:{}, minOffset in queue:{}, maxOffset in queue:{}, cqType:{}" , logic.getTopic(), logic.getQueueId(), logic.getMaxPhysicOffset() , minPhyOffset, logic.getMinOffsetInQueue(), logic.getMaxOffsetInQueue(), logic.getCQType()); return true; } // logic.getMaxPhysicOffset() or minPhyOffset = -1 // means there is no message in current queue, so no need to correct. if (logic.getMaxPhysicOffset() == -1 || minPhyOffset == -1) { return false; } if (logic.getMaxPhysicOffset() < minPhyOffset) { if (logic.getMinOffsetInQueue() < logic.getMaxOffsetInQueue()) { LOGGER.error("CorrectLogicOffsetService.needCorrect. logic max phy offset: {} is less than min phy offset: {}, " + "but min offset: {} is less than max offset: {}. topic:{}, queue:{}, cqType:{}." , logic.getMaxPhysicOffset(), minPhyOffset, logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return true; } else if (logic.getMinOffsetInQueue() == logic.getMaxOffsetInQueue()) { return false; } else { LOGGER.error("CorrectLogicOffsetService.needCorrect. It should not happen, logic max phy offset: {} is less than min phy offset: {}," + " but min offset: {} is larger than max offset: {}. topic:{}, queue:{}, cqType:{}" , logic.getMaxPhysicOffset(), minPhyOffset, logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return false; } } //the logic.getMaxPhysicOffset() >= minPhyOffset int forceCorrectInterval = DefaultMessageStore.this.getMessageStoreConfig().getCorrectLogicMinOffsetForceInterval(); if ((System.currentTimeMillis() - lastForeCorrectTimeCurRun) > forceCorrectInterval) { lastForceCorrectTime = System.currentTimeMillis(); CqUnit cqUnit = logic.getEarliestUnit(); if (cqUnit == null) { if (logic.getMinOffsetInQueue() == logic.getMaxOffsetInQueue()) { return false; } else { LOGGER.error("CorrectLogicOffsetService.needCorrect. cqUnit is null, logic max phy offset: {} is greater than min phy offset: {}, " + "but min offset: {} is not equal to max offset: {}. topic:{}, queue:{}, cqType:{}." , logic.getMaxPhysicOffset(), minPhyOffset, logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return true; } } if (cqUnit.getPos() < minPhyOffset) { LOGGER.error("CorrectLogicOffsetService.needCorrect. logic max phy offset: {} is greater than min phy offset: {}, " + "but minPhyPos in cq is: {}. min offset in queue: {}, max offset in queue: {}, topic:{}, queue:{}, cqType:{}." , logic.getMaxPhysicOffset(), minPhyOffset, cqUnit.getPos(), logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return true; } if (cqUnit.getPos() >= minPhyOffset) { // Normal case, do not need to correct. return false; } } return false; } private void correctLogicMinOffset() { long lastForeCorrectTimeCurRun = lastForceCorrectTime; long minPhyOffset = getMinPhyOffset(); ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueueInterface>> tables = DefaultMessageStore.this.getConsumeQueueTable(); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : tables.values()) { for (ConsumeQueueInterface logic : maps.values()) { if (Objects.equals(CQType.SimpleCQ, logic.getCQType())) { // cq is not supported for now. continue; } if (needCorrect(logic, minPhyOffset, lastForeCorrectTimeCurRun)) { doCorrect(logic, minPhyOffset); } } } } private void doCorrect(ConsumeQueueInterface logic, long minPhyOffset) { DefaultMessageStore.this.consumeQueueStore.deleteExpiredFile(logic, minPhyOffset); int sleepIntervalWhenCorrectMinOffset = DefaultMessageStore.this.getMessageStoreConfig().getCorrectLogicMinOffsetSleepInterval(); if (sleepIntervalWhenCorrectMinOffset > 0) { try { Thread.sleep(sleepIntervalWhenCorrectMinOffset); } catch (InterruptedException ignored) { } } } public String getServiceName() { if (brokerConfig.isInBrokerContainer()) { return brokerConfig.getIdentifier() + CorrectLogicOffsetService.class.getSimpleName(); } return CorrectLogicOffsetService.class.getSimpleName(); } } class FlushConsumeQueueService extends ServiceThread { private static final int RETRY_TIMES_OVER = 3; private long lastFlushTimestamp = 0; private void doFlush(int retryTimes) { int flushConsumeQueueLeastPages = DefaultMessageStore.this.getMessageStoreConfig().getFlushConsumeQueueLeastPages(); if (retryTimes == RETRY_TIMES_OVER) { flushConsumeQueueLeastPages = 0; } long logicsMsgTimestamp = 0; int flushConsumeQueueThoroughInterval = DefaultMessageStore.this.getMessageStoreConfig().getFlushConsumeQueueThoroughInterval(); long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis >= (this.lastFlushTimestamp + flushConsumeQueueThoroughInterval)) { this.lastFlushTimestamp = currentTimeMillis; flushConsumeQueueLeastPages = 0; logicsMsgTimestamp = DefaultMessageStore.this.getStoreCheckpoint().getLogicsMsgTimestamp(); } ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueueInterface>> tables = DefaultMessageStore.this.getConsumeQueueTable(); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : tables.values()) { for (ConsumeQueueInterface cq : maps.values()) { boolean result = false; for (int i = 0; i < retryTimes && !result; i++) { result = DefaultMessageStore.this.consumeQueueStore.flush(cq, flushConsumeQueueLeastPages); } } } if (messageStoreConfig.isEnableCompaction()) { compactionStore.flush(flushConsumeQueueLeastPages); } if (0 == flushConsumeQueueLeastPages) { if (logicsMsgTimestamp > 0) { DefaultMessageStore.this.getStoreCheckpoint().setLogicsMsgTimestamp(logicsMsgTimestamp); } DefaultMessageStore.this.getStoreCheckpoint().flush(); } } @Override public void run() { DefaultMessageStore.LOGGER.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { int interval = DefaultMessageStore.this.getMessageStoreConfig().getFlushIntervalConsumeQueue(); this.waitForRunning(interval); this.doFlush(1); } catch (Exception e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } this.doFlush(RETRY_TIMES_OVER); DefaultMessageStore.LOGGER.info(this.getServiceName() + " service end"); } @Override public String getServiceName() { if (DefaultMessageStore.this.brokerConfig.isInBrokerContainer()) { return DefaultMessageStore.this.getBrokerIdentity().getIdentifier() + FlushConsumeQueueService.class.getSimpleName(); } return FlushConsumeQueueService.class.getSimpleName(); } @Override public long getJoinTime() { return 1000 * 60; } } class BatchDispatchRequest { private ByteBuffer byteBuffer; private int position; private int size; private long id; public BatchDispatchRequest(ByteBuffer byteBuffer, int position, int size, long id) { this.byteBuffer = byteBuffer; this.position = position; this.size = size; this.id = id; } } class DispatchRequestOrderlyQueue { DispatchRequest[][] buffer; long ptr = 0; AtomicLong maxPtr = new AtomicLong(); public DispatchRequestOrderlyQueue(int bufferNum) { this.buffer = new DispatchRequest[bufferNum][]; } public void put(long index, DispatchRequest[] dispatchRequests) { while (ptr + this.buffer.length <= index) { synchronized (this) { try { this.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } int mod = (int) (index % this.buffer.length); this.buffer[mod] = dispatchRequests; maxPtr.incrementAndGet(); } public DispatchRequest[] get(List<DispatchRequest[]> dispatchRequestsList) { synchronized (this) { for (int i = 0; i < this.buffer.length; i++) { int mod = (int) (ptr % this.buffer.length); DispatchRequest[] ret = this.buffer[mod]; if (ret == null) { this.notifyAll(); return null; } dispatchRequestsList.add(ret); this.buffer[mod] = null; ptr++; } } return null; } public synchronized boolean isEmpty() { return maxPtr.get() == ptr; } } @Override public void notifyMessageArriveIfNecessary(DispatchRequest dispatchRequest) { if (DefaultMessageStore.this.brokerConfig.isLongPollingEnable() && DefaultMessageStore.this.messageArrivingListener != null) { DefaultMessageStore.this.messageArrivingListener.arriving(dispatchRequest.getTopic(), dispatchRequest.getQueueId(), dispatchRequest.getConsumeQueueOffset() + 1, dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(), dispatchRequest.getBitMap(), dispatchRequest.getPropertiesMap()); DefaultMessageStore.this.reputMessageService.notifyMessageArrive4MultiQueue(dispatchRequest); } } class ReputMessageService extends ServiceThread { protected volatile long reputFromOffset = 0; public long getReputFromOffset() { return reputFromOffset; } public void setReputFromOffset(long reputFromOffset) { this.reputFromOffset = reputFromOffset; } @Override public void shutdown() { for (int i = 0; i < 50 && this.isCommitLogAvailable(); i++) { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } if (this.isCommitLogAvailable()) { LOGGER.warn("shutdown ReputMessageService, but CommitLog have not finish to be dispatched, CommitLog max" + " offset={}, reputFromOffset={}", DefaultMessageStore.this.commitLog.getMaxOffset(), this.reputFromOffset); } super.shutdown(); } public long behind() { return DefaultMessageStore.this.getConfirmOffset() - this.reputFromOffset; } public boolean isCommitLogAvailable() { return this.reputFromOffset < DefaultMessageStore.this.getConfirmOffset(); } public void doReput() { if (this.reputFromOffset < DefaultMessageStore.this.commitLog.getMinOffset()) { LOGGER.warn("The reputFromOffset={} is smaller than minPyOffset={}, this usually indicate that the dispatch behind too much and the commitlog has expired.", this.reputFromOffset, DefaultMessageStore.this.commitLog.getMinOffset()); this.reputFromOffset = DefaultMessageStore.this.commitLog.getMinOffset(); } for (boolean doNext = true; this.isCommitLogAvailable() && doNext; ) { SelectMappedBufferResult result = DefaultMessageStore.this.commitLog.getData(reputFromOffset); if (result == null) { break; } try { this.reputFromOffset = result.getStartOffset(); for (int readSize = 0; readSize < result.getSize() && reputFromOffset < DefaultMessageStore.this.getConfirmOffset() && doNext; ) { DispatchRequest dispatchRequest = DefaultMessageStore.this.commitLog.checkMessageAndReturnSize(result.getByteBuffer(), false, false, false); int size = dispatchRequest.getBufferSize() == -1 ? dispatchRequest.getMsgSize() : dispatchRequest.getBufferSize(); if (reputFromOffset + size > DefaultMessageStore.this.getConfirmOffset()) { doNext = false; break; } if (dispatchRequest.isSuccess()) { if (size > 0) { DefaultMessageStore.this.doDispatch(dispatchRequest); if (!notifyMessageArriveInBatch) { notifyMessageArriveIfNecessary(dispatchRequest); } this.reputFromOffset += size; readSize += size; if (!DefaultMessageStore.this.getMessageStoreConfig().isDuplicationEnable() && DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole() == BrokerRole.SLAVE) { DefaultMessageStore.this.storeStatsService .getSinglePutMessageTopicTimesTotal(dispatchRequest.getTopic()).add(dispatchRequest.getBatchSize()); DefaultMessageStore.this.storeStatsService .getSinglePutMessageTopicSizeTotal(dispatchRequest.getTopic()) .add(dispatchRequest.getMsgSize()); } } else if (size == 0) { this.reputFromOffset = DefaultMessageStore.this.commitLog.rollNextFile(this.reputFromOffset); readSize = result.getSize(); } } else { if (size > 0) { LOGGER.error("[BUG]read total count not equals msg total size. reputFromOffset={}", reputFromOffset); this.reputFromOffset += size; } else { doNext = false; // If user open the dledger pattern or the broker is master node, // it will not ignore the exception and fix the reputFromOffset variable if (DefaultMessageStore.this.getMessageStoreConfig().isEnableDLegerCommitLog() || DefaultMessageStore.this.brokerConfig.getBrokerId() == MixAll.MASTER_ID) { LOGGER.error("[BUG]dispatch message to consume queue error, COMMITLOG OFFSET: {}", this.reputFromOffset); this.reputFromOffset += result.getSize() - readSize; } } } } } catch (RocksDBException e) { ERROR_LOG.info("dispatch message to cq exception. reputFromOffset: {}", this.reputFromOffset, e); return; } finally { result.release(); } finishCommitLogDispatch(); } } private void notifyMessageArrive4MultiQueue(DispatchRequest dispatchRequest) { Map<String, String> prop = dispatchRequest.getPropertiesMap(); if (prop == null || dispatchRequest.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) { return; } String multiDispatchQueue = prop.get(MessageConst.PROPERTY_INNER_MULTI_DISPATCH); String multiQueueOffset = prop.get(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET); if (StringUtils.isBlank(multiDispatchQueue) || StringUtils.isBlank(multiQueueOffset)) { return; } String[] queues = multiDispatchQueue.split(MixAll.MULTI_DISPATCH_QUEUE_SPLITTER); String[] queueOffsets = multiQueueOffset.split(MixAll.MULTI_DISPATCH_QUEUE_SPLITTER); if (queues.length != queueOffsets.length) { return; } for (int i = 0; i < queues.length; i++) { String queueName = queues[i]; long queueOffset = Long.parseLong(queueOffsets[i]); int queueId = dispatchRequest.getQueueId(); if (DefaultMessageStore.this.getMessageStoreConfig().isEnableLmq() && MixAll.isLmq(queueName)) { queueId = 0; } DefaultMessageStore.this.messageArrivingListener.arriving( queueName, queueId, queueOffset + 1, dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(), dispatchRequest.getBitMap(), dispatchRequest.getPropertiesMap()); } } @Override public void run() { DefaultMessageStore.LOGGER.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { TimeUnit.MILLISECONDS.sleep(1); this.doReput(); } catch (Exception e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } DefaultMessageStore.LOGGER.info(this.getServiceName() + " service end"); } @Override public String getServiceName() { if (DefaultMessageStore.this.getBrokerConfig().isInBrokerContainer()) { return DefaultMessageStore.this.getBrokerIdentity().getIdentifier() + ReputMessageService.class.getSimpleName(); } return ReputMessageService.class.getSimpleName(); } } class MainBatchDispatchRequestService extends ServiceThread { private final ExecutorService batchDispatchRequestExecutor; public MainBatchDispatchRequestService() { batchDispatchRequestExecutor = ThreadUtils.newThreadPoolExecutor( DefaultMessageStore.this.getMessageStoreConfig().getBatchDispatchRequestThreadPoolNums(), DefaultMessageStore.this.getMessageStoreConfig().getBatchDispatchRequestThreadPoolNums(), 1000 * 60, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<>(4096), new ThreadFactoryImpl("BatchDispatchRequestServiceThread_"), new ThreadPoolExecutor.AbortPolicy()); } private void pollBatchDispatchRequest() { try { if (!batchDispatchRequestQueue.isEmpty()) { BatchDispatchRequest task = batchDispatchRequestQueue.peek(); batchDispatchRequestExecutor.execute(() -> { try { ByteBuffer tmpByteBuffer = task.byteBuffer; tmpByteBuffer.position(task.position); tmpByteBuffer.limit(task.position + task.size); List<DispatchRequest> dispatchRequestList = new ArrayList<>(); while (tmpByteBuffer.hasRemaining()) { DispatchRequest dispatchRequest = DefaultMessageStore.this.commitLog.checkMessageAndReturnSize(tmpByteBuffer, false, false, false); if (dispatchRequest.isSuccess()) { dispatchRequestList.add(dispatchRequest); } else { LOGGER.error("[BUG]read total count not equals msg total size."); } } dispatchRequestOrderlyQueue.put(task.id, dispatchRequestList.toArray(new DispatchRequest[dispatchRequestList.size()])); mappedPageHoldCount.getAndDecrement(); } catch (Exception e) { LOGGER.error("There is an exception in task execution.", e); } }); batchDispatchRequestQueue.poll(); } } catch (Exception e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } @Override public void run() { DefaultMessageStore.LOGGER.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { TimeUnit.MILLISECONDS.sleep(1); pollBatchDispatchRequest(); } catch (Exception e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } DefaultMessageStore.LOGGER.info(this.getServiceName() + " service end"); } @Override public String getServiceName() { if (DefaultMessageStore.this.getBrokerConfig().isInBrokerContainer()) { return DefaultMessageStore.this.getBrokerIdentity().getIdentifier() + MainBatchDispatchRequestService.class.getSimpleName(); } return MainBatchDispatchRequestService.class.getSimpleName(); } } class DispatchService extends ServiceThread { private final List<DispatchRequest[]> dispatchRequestsList = new ArrayList<>(); // dispatchRequestsList:[ // {dispatchRequests:[{dispatchRequest}, {dispatchRequest}]}, // {dispatchRequests:[{dispatchRequest}, {dispatchRequest}]}] private void dispatch() throws Exception { dispatchRequestsList.clear(); dispatchRequestOrderlyQueue.get(dispatchRequestsList); if (!dispatchRequestsList.isEmpty()) { for (DispatchRequest[] dispatchRequests : dispatchRequestsList) { for (DispatchRequest dispatchRequest : dispatchRequests) { DefaultMessageStore.this.doDispatch(dispatchRequest); // wake up long-polling DefaultMessageStore.this.notifyMessageArriveIfNecessary(dispatchRequest); if (!DefaultMessageStore.this.getMessageStoreConfig().isDuplicationEnable() && DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole() == BrokerRole.SLAVE) { DefaultMessageStore.this.storeStatsService .getSinglePutMessageTopicTimesTotal(dispatchRequest.getTopic()).add(1); DefaultMessageStore.this.storeStatsService .getSinglePutMessageTopicSizeTotal(dispatchRequest.getTopic()) .add(dispatchRequest.getMsgSize()); } } } } } @Override public void run() { DefaultMessageStore.LOGGER.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { TimeUnit.MILLISECONDS.sleep(1); dispatch(); } catch (Exception e) { DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e); } } DefaultMessageStore.LOGGER.info(this.getServiceName() + " service end"); } @Override public String getServiceName() { if (DefaultMessageStore.this.getBrokerConfig().isInBrokerContainer()) { return DefaultMessageStore.this.getBrokerIdentity().getIdentifier() + DispatchService.class.getSimpleName(); } return DispatchService.class.getSimpleName(); } } class ConcurrentReputMessageService extends ReputMessageService { private static final int BATCH_SIZE = 1024 * 1024 * 4; private long batchId = 0; private MainBatchDispatchRequestService mainBatchDispatchRequestService; private DispatchService dispatchService; public ConcurrentReputMessageService() { super(); this.mainBatchDispatchRequestService = new MainBatchDispatchRequestService(); this.dispatchService = new DispatchService(); } public void createBatchDispatchRequest(ByteBuffer byteBuffer, int position, int size) { if (position < 0) { return; } mappedPageHoldCount.getAndIncrement(); BatchDispatchRequest task = new BatchDispatchRequest(byteBuffer.duplicate(), position, size, batchId++); batchDispatchRequestQueue.offer(task); } @Override public void start() { super.start(); this.mainBatchDispatchRequestService.start(); this.dispatchService.start(); } @Override public void doReput() { if (this.reputFromOffset < DefaultMessageStore.this.commitLog.getMinOffset()) { LOGGER.warn("The reputFromOffset={} is smaller than minPyOffset={}, this usually indicate that the dispatch behind too much and the commitlog has expired.", this.reputFromOffset, DefaultMessageStore.this.commitLog.getMinOffset()); this.reputFromOffset = DefaultMessageStore.this.commitLog.getMinOffset(); } for (boolean doNext = true; this.isCommitLogAvailable() && doNext; ) { SelectMappedBufferResult result = DefaultMessageStore.this.commitLog.getData(reputFromOffset); if (result == null) { break; } int batchDispatchRequestStart = -1; int batchDispatchRequestSize = -1; try { this.reputFromOffset = result.getStartOffset(); for (int readSize = 0; readSize < result.getSize() && reputFromOffset < DefaultMessageStore.this.getConfirmOffset() && doNext; ) { ByteBuffer byteBuffer = result.getByteBuffer(); int totalSize = preCheckMessageAndReturnSize(byteBuffer); if (totalSize > 0) { if (batchDispatchRequestStart == -1) { batchDispatchRequestStart = byteBuffer.position(); batchDispatchRequestSize = 0; } batchDispatchRequestSize += totalSize; if (batchDispatchRequestSize > BATCH_SIZE) { this.createBatchDispatchRequest(byteBuffer, batchDispatchRequestStart, batchDispatchRequestSize); batchDispatchRequestStart = -1; batchDispatchRequestSize = -1; } byteBuffer.position(byteBuffer.position() + totalSize); this.reputFromOffset += totalSize; readSize += totalSize; } else { doNext = false; if (totalSize == 0) { this.reputFromOffset = DefaultMessageStore.this.commitLog.rollNextFile(this.reputFromOffset); } this.createBatchDispatchRequest(byteBuffer, batchDispatchRequestStart, batchDispatchRequestSize); batchDispatchRequestStart = -1; batchDispatchRequestSize = -1; } } } finally { this.createBatchDispatchRequest(result.getByteBuffer(), batchDispatchRequestStart, batchDispatchRequestSize); boolean over = mappedPageHoldCount.get() == 0; while (!over) { try { TimeUnit.MILLISECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); } over = mappedPageHoldCount.get() == 0; } result.release(); } } // only for rocksdb mode finishCommitLogDispatch(); } /** * pre-check the message and returns the message size * * @return 0 Come to the end of file // >0 Normal messages // -1 Message checksum failure */ public int preCheckMessageAndReturnSize(ByteBuffer byteBuffer) { byteBuffer.mark(); int totalSize = byteBuffer.getInt(); if (reputFromOffset + totalSize > DefaultMessageStore.this.getConfirmOffset()) { return -1; } int magicCode = byteBuffer.getInt(); switch (magicCode) { case MessageDecoder.MESSAGE_MAGIC_CODE: case MessageDecoder.MESSAGE_MAGIC_CODE_V2: break; case MessageDecoder.BLANK_MAGIC_CODE: return 0; default: return -1; } byteBuffer.reset(); return totalSize; } @Override public void shutdown() { for (int i = 0; i < 50 && this.isCommitLogAvailable(); i++) { try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException ignored) { } } if (this.isCommitLogAvailable()) { LOGGER.warn("shutdown concurrentReputMessageService, but CommitLog have not finish to be dispatched, CommitLog max" + " offset={}, reputFromOffset={}", DefaultMessageStore.this.commitLog.getMaxOffset(), this.reputFromOffset); } this.mainBatchDispatchRequestService.shutdown(); this.dispatchService.shutdown(); super.shutdown(); } @Override public String getServiceName() { if (DefaultMessageStore.this.getBrokerConfig().isInBrokerContainer()) { return DefaultMessageStore.this.getBrokerIdentity().getIdentifier() + ConcurrentReputMessageService.class.getSimpleName(); } return ConcurrentReputMessageService.class.getSimpleName(); } } @Override public HARuntimeInfo getHARuntimeInfo() { if (haService != null) { return this.haService.getRuntimeInfo(this.commitLog.getMaxOffset()); } else { return null; } } public int getMaxDelayLevel() { return maxDelayLevel; } public long computeDeliverTimestamp(final int delayLevel, final long storeTimestamp) { Long time = this.delayLevelTable.get(delayLevel); if (time != null) { return time + storeTimestamp; } return storeTimestamp + 1000; } public List<PutMessageHook> getPutMessageHookList() { return putMessageHookList; } @Override public void setSendMessageBackHook(SendMessageBackHook sendMessageBackHook) { this.sendMessageBackHook = sendMessageBackHook; } @Override public SendMessageBackHook getSendMessageBackHook() { return sendMessageBackHook; } @Override public boolean isShutdown() { return shutdown; } @Override public long estimateMessageCount(String topic, int queueId, long from, long to, MessageFilter filter) { if (from < 0) { from = 0; } if (from >= to) { return 0; } if (null == filter) { return to - from; } ConsumeQueueInterface consumeQueue = findConsumeQueue(topic, queueId); if (null == consumeQueue) { return 0; } // correct the "from" argument to min offset in queue if it is too small long minOffset = consumeQueue.getMinOffsetInQueue(); if (from < minOffset) { long diff = to - from; from = minOffset; to = from + diff; } long msgCount = consumeQueue.estimateMessageCount(from, to, filter); return msgCount == -1 ? to - from : msgCount; } @Override public List<Pair<InstrumentSelector, ViewBuilder>> getMetricsView() { return DefaultStoreMetricsManager.getMetricsView(); } @Override public void initMetrics(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier) { DefaultStoreMetricsManager.init(meter, attributesBuilderSupplier, this); } /** * Enable transient commitLog store pool only if transientStorePoolEnable is true and broker role is not SLAVE or * enableControllerMode is true * * @return <tt>true</tt> or <tt>false</tt> */ public boolean isTransientStorePoolEnable() { return this.messageStoreConfig.isTransientStorePoolEnable() && (this.brokerConfig.isEnableControllerMode() || this.messageStoreConfig.getBrokerRole() != BrokerRole.SLAVE); } public long getReputFromOffset() { return this.reputMessageService.getReputFromOffset(); } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/DefaultMessageStore.java
2,369
package com.alibaba.otter.canal.parse.driver.mysql.utils; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * mysql collation转换mapping关系表 * * @author agapple 2018年11月5日 下午1:01:15 * @since 1.1.2 */ public class CharsetUtil { private static final String[] INDEX_TO_CHARSET = new String[2048]; private static final Map<String, Integer> CHARSET_TO_INDEX = new HashMap<>(); static { INDEX_TO_CHARSET[1] = "big5"; INDEX_TO_CHARSET[84] = "big5"; INDEX_TO_CHARSET[3] = "dec8"; INDEX_TO_CHARSET[69] = "dec8"; INDEX_TO_CHARSET[4] = "cp850"; INDEX_TO_CHARSET[80] = "cp850"; INDEX_TO_CHARSET[6] = "hp8"; INDEX_TO_CHARSET[72] = "hp8"; INDEX_TO_CHARSET[7] = "koi8r"; INDEX_TO_CHARSET[74] = "koi8r"; INDEX_TO_CHARSET[5] = "latin1"; INDEX_TO_CHARSET[8] = "latin1"; INDEX_TO_CHARSET[15] = "latin1"; INDEX_TO_CHARSET[31] = "latin1"; INDEX_TO_CHARSET[47] = "latin1"; INDEX_TO_CHARSET[48] = "latin1"; INDEX_TO_CHARSET[49] = "latin1"; INDEX_TO_CHARSET[94] = "latin1"; INDEX_TO_CHARSET[9] = "latin2"; INDEX_TO_CHARSET[21] = "latin2"; INDEX_TO_CHARSET[27] = "latin2"; INDEX_TO_CHARSET[77] = "latin2"; INDEX_TO_CHARSET[10] = "swe7"; INDEX_TO_CHARSET[82] = "swe7"; INDEX_TO_CHARSET[11] = "ascii"; INDEX_TO_CHARSET[65] = "ascii"; INDEX_TO_CHARSET[12] = "ujis"; INDEX_TO_CHARSET[91] = "ujis"; INDEX_TO_CHARSET[13] = "sjis"; INDEX_TO_CHARSET[88] = "sjis"; INDEX_TO_CHARSET[16] = "hebrew"; INDEX_TO_CHARSET[71] = "hebrew"; INDEX_TO_CHARSET[18] = "tis620"; INDEX_TO_CHARSET[69] = "tis620"; INDEX_TO_CHARSET[19] = "euckr"; INDEX_TO_CHARSET[85] = "euckr"; INDEX_TO_CHARSET[22] = "koi8u"; INDEX_TO_CHARSET[75] = "koi8u"; INDEX_TO_CHARSET[24] = "gb2312"; INDEX_TO_CHARSET[86] = "gb2312"; INDEX_TO_CHARSET[25] = "greek"; INDEX_TO_CHARSET[70] = "greek"; INDEX_TO_CHARSET[26] = "cp1250"; INDEX_TO_CHARSET[34] = "cp1250"; INDEX_TO_CHARSET[44] = "cp1250"; INDEX_TO_CHARSET[66] = "cp1250"; INDEX_TO_CHARSET[99] = "cp1250"; INDEX_TO_CHARSET[28] = "gbk"; INDEX_TO_CHARSET[87] = "gbk"; INDEX_TO_CHARSET[30] = "latin5"; INDEX_TO_CHARSET[78] = "latin5"; INDEX_TO_CHARSET[32] = "armscii8"; INDEX_TO_CHARSET[64] = "armscii8"; INDEX_TO_CHARSET[33] = "utf8"; INDEX_TO_CHARSET[83] = "utf8"; for (int i = 192; i <= 223; i++) { INDEX_TO_CHARSET[i] = "utf8"; } for (int i = 336; i <= 337; i++) { INDEX_TO_CHARSET[i] = "utf8"; } for (int i = 352; i <= 357; i++) { INDEX_TO_CHARSET[i] = "utf8"; } INDEX_TO_CHARSET[368] = "utf8"; INDEX_TO_CHARSET[2047] = "utf8"; INDEX_TO_CHARSET[35] = "ucs2"; INDEX_TO_CHARSET[90] = "ucs2"; for (int i = 128; i <= 151; i++) { INDEX_TO_CHARSET[i] = "ucs2"; } INDEX_TO_CHARSET[159] = "ucs2"; for (int i = 358; i <= 360; i++) { INDEX_TO_CHARSET[i] = "ucs2"; } INDEX_TO_CHARSET[36] = "cp866"; INDEX_TO_CHARSET[68] = "cp866"; INDEX_TO_CHARSET[37] = "keybcs2"; INDEX_TO_CHARSET[73] = "keybcs2"; INDEX_TO_CHARSET[38] = "macce"; INDEX_TO_CHARSET[43] = "macce"; INDEX_TO_CHARSET[39] = "macroman"; INDEX_TO_CHARSET[53] = "macroman"; INDEX_TO_CHARSET[40] = "cp852"; INDEX_TO_CHARSET[81] = "cp852"; INDEX_TO_CHARSET[20] = "latin7"; INDEX_TO_CHARSET[41] = "latin7"; INDEX_TO_CHARSET[42] = "latin7"; INDEX_TO_CHARSET[79] = "latin7"; INDEX_TO_CHARSET[45] = "utf8mb4"; INDEX_TO_CHARSET[46] = "utf8mb4"; for (int i = 224; i <= 247; i++) { INDEX_TO_CHARSET[i] = "utf8mb4"; } for (int i = 255; i <= 271; i++) { INDEX_TO_CHARSET[i] = "utf8mb4"; } for (int i = 273; i <= 275; i++) { INDEX_TO_CHARSET[i] = "utf8mb4"; } for (int i = 277; i <= 294; i++) { INDEX_TO_CHARSET[i] = "utf8mb4"; } for (int i = 296; i <= 298; i++) { INDEX_TO_CHARSET[i] = "utf8mb4"; } INDEX_TO_CHARSET[300] = "utf8mb4"; for (int i = 303; i <= 307; i++) { INDEX_TO_CHARSET[i] = "utf8mb4"; } INDEX_TO_CHARSET[326] = "utf8mb4"; INDEX_TO_CHARSET[328] = "utf8mb4"; INDEX_TO_CHARSET[14] = "cp1251"; INDEX_TO_CHARSET[23] = "cp1251"; INDEX_TO_CHARSET[50] = "cp1251"; INDEX_TO_CHARSET[51] = "cp1251"; INDEX_TO_CHARSET[52] = "cp1251"; INDEX_TO_CHARSET[54] = "utf16"; INDEX_TO_CHARSET[55] = "utf16"; for (int i = 101; i <= 124; i++) { INDEX_TO_CHARSET[i] = "utf16"; } INDEX_TO_CHARSET[327] = "utf16"; INDEX_TO_CHARSET[56] = "utf16le"; INDEX_TO_CHARSET[62] = "utf16le"; INDEX_TO_CHARSET[57] = "cp1256"; INDEX_TO_CHARSET[67] = "cp1256"; INDEX_TO_CHARSET[29] = "cp1257"; INDEX_TO_CHARSET[58] = "cp1257"; INDEX_TO_CHARSET[59] = "cp1257"; INDEX_TO_CHARSET[60] = "utf32"; INDEX_TO_CHARSET[61] = "utf32"; for (int i = 160; i <= 183; i++) { INDEX_TO_CHARSET[i] = "utf32"; } INDEX_TO_CHARSET[391] = "utf32"; INDEX_TO_CHARSET[63] = "binary"; INDEX_TO_CHARSET[92] = "geostd8"; INDEX_TO_CHARSET[93] = "geostd8"; INDEX_TO_CHARSET[95] = "cp932"; INDEX_TO_CHARSET[96] = "cp932"; INDEX_TO_CHARSET[97] = "eucjpms"; INDEX_TO_CHARSET[98] = "eucjpms"; for (int i = 248; i <= 250; i++) { INDEX_TO_CHARSET[i] = "gb18030"; } // charset --> index for (int i = 0; i < 2048; i++) { String charset = INDEX_TO_CHARSET[i]; if (charset != null && CHARSET_TO_INDEX.get(charset) == null) { CHARSET_TO_INDEX.put(charset, i); } } CHARSET_TO_INDEX.put("iso-8859-1", 14); CHARSET_TO_INDEX.put("iso_8859_1", 14); CHARSET_TO_INDEX.put("utf-8", 33); CHARSET_TO_INDEX.put("utf8mb4", 45); } public static final String getCharset(int index) { return INDEX_TO_CHARSET[index]; } public static final int getIndex(String charset) { if (charset == null || charset.length() == 0) { return 0; } else { Integer i = CHARSET_TO_INDEX.get(charset.toLowerCase()); return (i == null) ? 0 : i.intValue(); } } /** * 'utf8' COLLATE 'utf8_general_ci' * * @param charset * @return */ public static final String collateCharset(String charset) { String[] output = StringUtils.split(charset, "COLLATE"); return output[0].replace('\'', ' ').trim(); } public static String getJavaCharset(String charset) { if ("utf8".equals(charset)) { return charset; } if (StringUtils.endsWithIgnoreCase(charset, "utf8mb4")) { return "utf-8"; } if (StringUtils.endsWithIgnoreCase(charset, "binary")) { return "iso_8859_1"; } return charset; } }
alibaba/canal
driver/src/main/java/com/alibaba/otter/canal/parse/driver/mysql/utils/CharsetUtil.java
2,370
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.quarkus.deployment; import io.quarkus.deployment.builditem.ShutdownContextBuildItem; import io.quarkus.deployment.logging.LoggingSetupBuildItem; import jakarta.enterprise.context.ApplicationScoped; import org.keycloak.quarkus.runtime.KeycloakRecorder; import org.keycloak.quarkus.runtime.storage.legacy.infinispan.CacheManagerFactory; import io.quarkus.arc.deployment.SyntheticBeanBuildItem; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.Consume; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; public class CacheBuildSteps { @Consume(ConfigBuildItem.class) // Consume LoggingSetupBuildItem.class and record RUNTIME_INIT are necessary to ensure that logging is set up before the caches are initialized. // This is to prevent the class TP in JGroups to pick up the trace logging at start up. While the logs will not appear on the console, // they will still be created and use CPU cycles and create garbage collection. // See: https://issues.redhat.com/browse/JGRP-2130 for the JGroups discussion, and https://github.com/keycloak/keycloak/issues/29129 for the issue Keycloak had with this. @Consume(LoggingSetupBuildItem.class) @Record(ExecutionTime.RUNTIME_INIT) @BuildStep void configureInfinispan(KeycloakRecorder recorder, BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItems, ShutdownContextBuildItem shutdownContext) { syntheticBeanBuildItems.produce(SyntheticBeanBuildItem.configure(CacheManagerFactory.class) .scope(ApplicationScoped.class) .unremovable() .setRuntimeInit() .runtimeValue(recorder.createCacheInitializer(shutdownContext)).done()); } }
keycloak/keycloak
quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/CacheBuildSteps.java
2,371
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store.queue; import java.io.File; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Function; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.common.Pair; import org.apache.rocketmq.common.BoundaryType; import org.apache.rocketmq.common.attribute.CQType; import org.apache.rocketmq.common.constant.LoggerName; import org.apache.rocketmq.common.message.MessageAccessor; import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.common.message.MessageDecoder; import org.apache.rocketmq.common.message.MessageExtBrokerInner; import org.apache.rocketmq.common.sysflag.MessageSysFlag; import org.apache.rocketmq.logging.org.slf4j.Logger; import org.apache.rocketmq.logging.org.slf4j.LoggerFactory; import org.apache.rocketmq.store.DispatchRequest; import org.apache.rocketmq.store.MappedFileQueue; import org.apache.rocketmq.store.MessageFilter; import org.apache.rocketmq.store.MessageStore; import org.apache.rocketmq.store.SelectMappedBufferResult; import org.apache.rocketmq.store.config.BrokerRole; import org.apache.rocketmq.store.logfile.MappedFile; public class BatchConsumeQueue implements ConsumeQueueInterface { protected static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME); /** * BatchConsumeQueue's store unit. Format: * <pre> * ┌─────────────────────────┬───────────┬────────────┬──────────┬─────────────┬─────────┬───────────────┬─────────┐ * │CommitLog Physical Offset│ Body Size │Tag HashCode│Store time│msgBaseOffset│batchSize│compactedOffset│reserved │ * │ (8 Bytes) │ (4 Bytes) │ (8 Bytes) │(8 Bytes) │(8 Bytes) │(2 Bytes)│ (4 Bytes) │(4 Bytes)│ * ├─────────────────────────┴───────────┴────────────┴──────────┴─────────────┴─────────┴───────────────┴─────────┤ * │ Store Unit │ * │ │ * </pre> * BatchConsumeQueue's store unit. Size: * CommitLog Physical Offset(8) + Body Size(4) + Tag HashCode(8) + Store time(8) + * msgBaseOffset(8) + batchSize(2) + compactedOffset(4) + reserved(4)= 46 Bytes */ public static final int CQ_STORE_UNIT_SIZE = 46; public static final int MSG_TAG_OFFSET_INDEX = 12; public static final int MSG_STORE_TIME_OFFSET_INDEX = 20; public static final int MSG_BASE_OFFSET_INDEX = 28; public static final int MSG_BATCH_SIZE_INDEX = 36; public static final int MSG_COMPACT_OFFSET_INDEX = 38; private static final int MSG_COMPACT_OFFSET_LENGTH = 4; public static final int INVALID_POS = -1; protected final MappedFileQueue mappedFileQueue; protected MessageStore messageStore; protected final String topic; protected final int queueId; protected final ByteBuffer byteBufferItem; protected final String storePath; protected final int mappedFileSize; protected volatile long maxMsgPhyOffsetInCommitLog = -1; protected volatile long minLogicOffset = 0; protected volatile long maxOffsetInQueue = 0; protected volatile long minOffsetInQueue = -1; protected final int commitLogSize; protected ConcurrentSkipListMap<Long, MappedFile> offsetCache = new ConcurrentSkipListMap<>(); protected ConcurrentSkipListMap<Long, MappedFile> timeCache = new ConcurrentSkipListMap<>(); public BatchConsumeQueue( final String topic, final int queueId, final String storePath, final int mappedFileSize, final MessageStore messageStore, final String subfolder) { this.storePath = storePath; this.mappedFileSize = mappedFileSize; this.messageStore = messageStore; this.commitLogSize = messageStore.getCommitLog().getCommitLogSize(); this.topic = topic; this.queueId = queueId; if (StringUtils.isBlank(subfolder)) { String queueDir = this.storePath + File.separator + topic + File.separator + queueId; this.mappedFileQueue = new MappedFileQueue(queueDir, mappedFileSize, null); } else { String queueDir = this.storePath + File.separator + topic + File.separator + queueId + File.separator + subfolder; this.mappedFileQueue = new MappedFileQueue(queueDir, mappedFileSize, null); } this.byteBufferItem = ByteBuffer.allocate(CQ_STORE_UNIT_SIZE); } public BatchConsumeQueue( final String topic, final int queueId, final String storePath, final int mappedFileSize, final MessageStore defaultMessageStore) { this(topic, queueId, storePath, mappedFileSize, defaultMessageStore, StringUtils.EMPTY); } @Override public boolean load() { boolean result = this.mappedFileQueue.load(); log.info("Load batch consume queue {}-{} {} {}", topic, queueId, result ? "OK" : "Failed", mappedFileQueue.getMappedFiles().size()); return result; } protected void doRefreshCache(Function<MappedFile, BatchOffsetIndex> offsetFunction) { if (!this.messageStore.getMessageStoreConfig().isSearchBcqByCacheEnable()) { return; } ConcurrentSkipListMap<Long, MappedFile> newOffsetCache = new ConcurrentSkipListMap<>(); ConcurrentSkipListMap<Long, MappedFile> newTimeCache = new ConcurrentSkipListMap<>(); List<MappedFile> mappedFiles = mappedFileQueue.getMappedFiles(); // iterate all BCQ files for (int i = 0; i < mappedFiles.size(); i++) { MappedFile bcq = mappedFiles.get(i); if (isNewFile(bcq)) { continue; } BatchOffsetIndex offset = offsetFunction.apply(bcq); if (offset == null) { continue; } newOffsetCache.put(offset.getMsgOffset(), offset.getMappedFile()); newTimeCache.put(offset.getStoreTimestamp(), offset.getMappedFile()); } this.offsetCache = newOffsetCache; this.timeCache = newTimeCache; log.info("refreshCache for BCQ [Topic: {}, QueueId: {}]." + "offsetCacheSize: {}, minCachedMsgOffset: {}, maxCachedMsgOffset: {}, " + "timeCacheSize: {}, minCachedTime: {}, maxCachedTime: {}", this.topic, this.queueId, this.offsetCache.size(), this.offsetCache.firstEntry(), this.offsetCache.lastEntry(), this.timeCache.size(), this.timeCache.firstEntry(), this.timeCache.lastEntry()); } protected void refreshCache() { doRefreshCache(m -> getMinMsgOffset(m, false, true)); } private void destroyCache() { this.offsetCache.clear(); this.timeCache.clear(); log.info("BCQ [Topic: {}, QueueId: {}]. Cache destroyed", this.topic, this.queueId); } protected void cacheBcq(MappedFile bcq) { try { BatchOffsetIndex min = getMinMsgOffset(bcq, false, true); this.offsetCache.put(min.getMsgOffset(), min.getMappedFile()); this.timeCache.put(min.getStoreTimestamp(), min.getMappedFile()); } catch (Exception e) { log.error("Failed caching offset and time on BCQ [Topic: {}, QueueId: {}, File: {}]", this.topic, this.queueId, bcq); } } protected boolean isNewFile(MappedFile mappedFile) { return mappedFile.getReadPosition() < CQ_STORE_UNIT_SIZE; } protected MappedFile searchOffsetFromCache(long msgOffset) { Map.Entry<Long, MappedFile> floorEntry = this.offsetCache.floorEntry(msgOffset); if (floorEntry == null) { // the offset is too small. return null; } else { return floorEntry.getValue(); } } private MappedFile searchTimeFromCache(long time) { Map.Entry<Long, MappedFile> floorEntry = this.timeCache.floorEntry(time); if (floorEntry == null) { // the timestamp is too small. so we decide to result first BCQ file. return this.mappedFileQueue.getFirstMappedFile(); } else { return floorEntry.getValue(); } } @Override public void recover() { final List<MappedFile> mappedFiles = this.mappedFileQueue.getMappedFiles(); if (!mappedFiles.isEmpty()) { int index = mappedFiles.size() - 3; if (index < 0) index = 0; int mappedFileSizeLogics = this.mappedFileSize; MappedFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); long processOffset = mappedFile.getFileFromOffset(); long mappedFileOffset = 0; while (true) { for (int i = 0; i < mappedFileSizeLogics; i += CQ_STORE_UNIT_SIZE) { byteBuffer.position(i); long offset = byteBuffer.getLong(); int size = byteBuffer.getInt(); byteBuffer.getLong();//tagscode byteBuffer.getLong();//timestamp long msgBaseOffset = byteBuffer.getLong(); short batchSize = byteBuffer.getShort(); if (offset >= 0 && size > 0 && msgBaseOffset >= 0 && batchSize > 0) { mappedFileOffset = i + CQ_STORE_UNIT_SIZE; this.maxMsgPhyOffsetInCommitLog = offset; } else { log.info("Recover current batch consume queue file over, file:{} offset:{} size:{} msgBaseOffset:{} batchSize:{} mappedFileOffset:{}", mappedFile.getFileName(), offset, size, msgBaseOffset, batchSize, mappedFileOffset); break; } } if (mappedFileOffset == mappedFileSizeLogics) { index++; if (index >= mappedFiles.size()) { log.info("Recover last batch consume queue file over, last mapped file:{} ", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); mappedFileOffset = 0; log.info("Recover next batch consume queue file: " + mappedFile.getFileName()); } } else { log.info("Recover current batch consume queue file over:{} processOffset:{}", mappedFile.getFileName(), processOffset + mappedFileOffset); break; } } processOffset += mappedFileOffset; this.mappedFileQueue.setFlushedWhere(processOffset); this.mappedFileQueue.setCommittedWhere(processOffset); this.mappedFileQueue.truncateDirtyFiles(processOffset); reviseMaxAndMinOffsetInQueue(); } } void reviseMinOffsetInQueue() { MappedFile firstMappedFile = this.mappedFileQueue.getFirstMappedFile(); if (null == firstMappedFile) { maxOffsetInQueue = 0; minOffsetInQueue = -1; minLogicOffset = -1; log.info("reviseMinOffsetInQueue found firstMappedFile null, topic:{} queue:{}", topic, queueId); return; } minLogicOffset = firstMappedFile.getFileFromOffset(); BatchOffsetIndex min = getMinMsgOffset(firstMappedFile, false, false); minOffsetInQueue = null == min ? -1 : min.getMsgOffset(); } void reviseMaxOffsetInQueue() { MappedFile lastMappedFile = this.mappedFileQueue.getLastMappedFile(); BatchOffsetIndex max = getMaxMsgOffset(lastMappedFile, true, false); if (null == max && this.mappedFileQueue.getMappedFiles().size() >= 2) { MappedFile lastTwoMappedFile = this.mappedFileQueue.getMappedFiles().get(this.mappedFileQueue.getMappedFiles().size() - 2); max = getMaxMsgOffset(lastTwoMappedFile, true, false); } maxOffsetInQueue = (null == max) ? 0 : max.getMsgOffset() + max.getBatchSize(); } void reviseMaxAndMinOffsetInQueue() { reviseMinOffsetInQueue(); reviseMaxOffsetInQueue(); } @Override public long getMaxPhysicOffset() { return maxMsgPhyOffsetInCommitLog; } @Override public long getMinLogicOffset() { return minLogicOffset; } @Override public ReferredIterator<CqUnit> iterateFrom(long startOffset) { SelectMappedBufferResult sbr = getBatchMsgIndexBuffer(startOffset); if (sbr == null) { return null; } return new BatchConsumeQueueIterator(sbr); } @Override public ReferredIterator<CqUnit> iterateFrom(long startIndex, int count) { return iterateFrom(startIndex); } @Override public CqUnit get(long offset) { ReferredIterator<CqUnit> it = iterateFrom(offset); if (it == null) { return null; } return it.nextAndRelease(); } @Override public Pair<CqUnit, Long> getCqUnitAndStoreTime(long index) { CqUnit cqUnit = get(index); Long messageStoreTime = this.messageStore.getQueueStore().getStoreTime(cqUnit); return new Pair<>(cqUnit, messageStoreTime); } @Override public Pair<CqUnit, Long> getEarliestUnitAndStoreTime() { CqUnit cqUnit = getEarliestUnit(); Long messageStoreTime = this.messageStore.getQueueStore().getStoreTime(cqUnit); return new Pair<>(cqUnit, messageStoreTime); } @Override public CqUnit getEarliestUnit() { return get(minOffsetInQueue); } @Override public CqUnit getLatestUnit() { return get(maxOffsetInQueue - 1); } @Override public long getLastOffset() { CqUnit latestUnit = getLatestUnit(); return latestUnit.getPos() + latestUnit.getSize(); } @Override public boolean isFirstFileAvailable() { MappedFile mappedFile = this.mappedFileQueue.getFirstMappedFile(); if (mappedFile != null) { return mappedFile.isAvailable(); } return false; } @Override public boolean isFirstFileExist() { MappedFile mappedFile = this.mappedFileQueue.getFirstMappedFile(); return mappedFile != null; } @Override public void truncateDirtyLogicFiles(long phyOffset) { long oldMinOffset = minOffsetInQueue; long oldMaxOffset = maxOffsetInQueue; int logicFileSize = this.mappedFileSize; this.maxMsgPhyOffsetInCommitLog = phyOffset - 1; boolean stop = false; while (!stop) { MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile(); if (mappedFile != null) { ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); mappedFile.setWrotePosition(0); mappedFile.setCommittedPosition(0); mappedFile.setFlushedPosition(0); for (int i = 0; i < logicFileSize; i += CQ_STORE_UNIT_SIZE) { byteBuffer.position(i); long offset = byteBuffer.getLong(); int size = byteBuffer.getInt(); byteBuffer.getLong();//tagscode byteBuffer.getLong();//timestamp long msgBaseOffset = byteBuffer.getLong(); short batchSize = byteBuffer.getShort(); if (0 == i) { if (offset >= phyOffset) { this.mappedFileQueue.deleteLastMappedFile(); break; } else { int pos = i + CQ_STORE_UNIT_SIZE; mappedFile.setWrotePosition(pos); mappedFile.setCommittedPosition(pos); mappedFile.setFlushedPosition(pos); this.maxMsgPhyOffsetInCommitLog = offset; } } else { if (offset >= 0 && size > 0 && msgBaseOffset >= 0 && batchSize > 0) { if (offset >= phyOffset) { stop = true; break; } int pos = i + CQ_STORE_UNIT_SIZE; mappedFile.setWrotePosition(pos); mappedFile.setCommittedPosition(pos); mappedFile.setFlushedPosition(pos); this.maxMsgPhyOffsetInCommitLog = offset; if (pos == logicFileSize) { stop = true; break; } } else { stop = true; break; } } } } else { break; } } reviseMaxAndMinOffsetInQueue(); log.info("Truncate batch logic file topic={} queue={} oldMinOffset={} oldMaxOffset={} minOffset={} maxOffset={} maxPhyOffsetHere={} maxPhyOffsetThere={}", topic, queueId, oldMinOffset, oldMaxOffset, minOffsetInQueue, maxOffsetInQueue, maxMsgPhyOffsetInCommitLog, phyOffset); } @Override public boolean flush(final int flushLeastPages) { boolean result = this.mappedFileQueue.flush(flushLeastPages); return result; } @Override public int deleteExpiredFile(long minCommitLogPos) { int cnt = this.mappedFileQueue.deleteExpiredFileByOffset(minCommitLogPos, CQ_STORE_UNIT_SIZE); this.correctMinOffset(minCommitLogPos); return cnt; } @Override public void correctMinOffset(long phyMinOffset) { reviseMinOffsetInQueue(); refreshCache(); long oldMinOffset = minOffsetInQueue; MappedFile mappedFile = this.mappedFileQueue.getFirstMappedFile(); if (mappedFile != null) { SelectMappedBufferResult result = mappedFile.selectMappedBuffer(0); if (result != null) { try { int startPos = result.getByteBuffer().position(); for (int i = 0; i < result.getSize(); i += BatchConsumeQueue.CQ_STORE_UNIT_SIZE) { result.getByteBuffer().position(startPos + i); long offsetPy = result.getByteBuffer().getLong(); result.getByteBuffer().getInt(); //size result.getByteBuffer().getLong();//tagscode result.getByteBuffer().getLong();//timestamp long msgBaseOffset = result.getByteBuffer().getLong(); short batchSize = result.getByteBuffer().getShort(); if (offsetPy < phyMinOffset) { this.minOffsetInQueue = msgBaseOffset + batchSize; } else { break; } } } catch (Exception e) { log.error("Exception thrown when correctMinOffset", e); } finally { result.release(); } } else { /** * It will go to here under two conditions: 1. the files number is 1, and it has no data 2. the pull process hold the cq reference, and release it just the moment */ log.warn("Correct min offset found null cq file topic:{} queue:{} files:{} minOffset:{} maxOffset:{}", topic, queueId, this.mappedFileQueue.getMappedFiles().size(), minOffsetInQueue, maxOffsetInQueue); } } if (oldMinOffset != this.minOffsetInQueue) { log.info("BatchCQ Compute new minOffset:{} oldMinOffset{} topic:{} queue:{}", minOffsetInQueue, oldMinOffset, topic, queueId); } } @Override public void putMessagePositionInfoWrapper(DispatchRequest request) { final int maxRetries = 30; boolean canWrite = this.messageStore.getRunningFlags().isCQWriteable(); if (request.getMsgBaseOffset() < 0 || request.getBatchSize() < 0) { log.warn("[NOTIFYME]unexpected dispatch request in batch consume queue topic:{} queue:{} offset:{}", topic, queueId, request.getCommitLogOffset()); return; } for (int i = 0; i < maxRetries && canWrite; i++) { boolean result = this.putBatchMessagePositionInfo(request.getCommitLogOffset(), request.getMsgSize(), request.getTagsCode(), request.getStoreTimestamp(), request.getMsgBaseOffset(), request.getBatchSize()); if (result) { if (BrokerRole.SLAVE == this.messageStore.getMessageStoreConfig().getBrokerRole()) { this.messageStore.getStoreCheckpoint().setPhysicMsgTimestamp(request.getStoreTimestamp()); } this.messageStore.getStoreCheckpoint().setLogicsMsgTimestamp(request.getStoreTimestamp()); return; } else { // XXX: warn and notify me log.warn("[NOTIFYME]put commit log position info to batch consume queue " + topic + ":" + queueId + " " + request.getCommitLogOffset() + " failed, retry " + i + " times"); try { Thread.sleep(1000); } catch (InterruptedException e) { log.warn("", e); } } } // XXX: warn and notify me log.error("[NOTIFYME]batch consume queue can not write, {} {}", this.topic, this.queueId); this.messageStore.getRunningFlags().makeLogicsQueueError(); } @Override public void assignQueueOffset(QueueOffsetOperator queueOffsetOperator, MessageExtBrokerInner msg) { String topicQueueKey = getTopic() + "-" + getQueueId(); long queueOffset = queueOffsetOperator.getBatchQueueOffset(topicQueueKey); if (MessageSysFlag.check(msg.getSysFlag(), MessageSysFlag.INNER_BATCH_FLAG)) { MessageAccessor.putProperty(msg, MessageConst.PROPERTY_INNER_BASE, String.valueOf(queueOffset)); msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties())); } msg.setQueueOffset(queueOffset); } @Override public void increaseQueueOffset(QueueOffsetOperator queueOffsetOperator, MessageExtBrokerInner msg, short messageNum) { String topicQueueKey = getTopic() + "-" + getQueueId(); queueOffsetOperator.increaseBatchQueueOffset(topicQueueKey, messageNum); } public boolean putBatchMessagePositionInfo(final long offset, final int size, final long tagsCode, final long storeTime, final long msgBaseOffset, final short batchSize) { if (offset <= this.maxMsgPhyOffsetInCommitLog) { if (System.currentTimeMillis() % 1000 == 0) { log.warn("Build batch consume queue repeatedly, maxMsgPhyOffsetInCommitLog:{} offset:{} Topic: {} QID: {}", maxMsgPhyOffsetInCommitLog, offset, this.topic, this.queueId); } return true; } long behind = System.currentTimeMillis() - storeTime; if (behind > 10000 && System.currentTimeMillis() % 10000 == 0) { String flag = "LEVEL" + (behind / 10000); log.warn("Reput behind {} topic:{} queue:{} offset:{} behind:{}", flag, topic, queueId, offset, behind); } this.byteBufferItem.flip(); this.byteBufferItem.limit(CQ_STORE_UNIT_SIZE); this.byteBufferItem.putLong(offset); this.byteBufferItem.putInt(size); this.byteBufferItem.putLong(tagsCode); this.byteBufferItem.putLong(storeTime); this.byteBufferItem.putLong(msgBaseOffset); this.byteBufferItem.putShort(batchSize); this.byteBufferItem.putInt(INVALID_POS); this.byteBufferItem.putInt(0); // 4 bytes reserved MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile(this.mappedFileQueue.getMaxOffset()); if (mappedFile != null) { boolean isNewFile = isNewFile(mappedFile); boolean appendRes = mappedFile.appendMessage(this.byteBufferItem.array()); if (appendRes) { maxMsgPhyOffsetInCommitLog = offset; maxOffsetInQueue = msgBaseOffset + batchSize; //only the first time need to correct the minOffsetInQueue //the other correctness is done in correctLogicMinoffsetService if (mappedFile.isFirstCreateInQueue() && minOffsetInQueue == -1) { reviseMinOffsetInQueue(); } if (isNewFile) { // cache new file this.cacheBcq(mappedFile); } } return appendRes; } return false; } protected BatchOffsetIndex getMinMsgOffset(MappedFile mappedFile, boolean getBatchSize, boolean getStoreTime) { if (mappedFile.getReadPosition() < CQ_STORE_UNIT_SIZE) { return null; } return getBatchOffsetIndexByPos(mappedFile, 0, getBatchSize, getStoreTime); } protected BatchOffsetIndex getBatchOffsetIndexByPos(MappedFile mappedFile, int pos, boolean getBatchSize, boolean getStoreTime) { SelectMappedBufferResult sbr = mappedFile.selectMappedBuffer(pos); try { return new BatchOffsetIndex(mappedFile, pos, sbr.getByteBuffer().getLong(MSG_BASE_OFFSET_INDEX), getBatchSize ? sbr.getByteBuffer().getShort(MSG_BATCH_SIZE_INDEX) : 0, getStoreTime ? sbr.getByteBuffer().getLong(MSG_STORE_TIME_OFFSET_INDEX) : 0); } finally { if (sbr != null) { sbr.release(); } } } protected BatchOffsetIndex getMaxMsgOffset(MappedFile mappedFile, boolean getBatchSize, boolean getStoreTime) { if (mappedFile == null || mappedFile.getReadPosition() < CQ_STORE_UNIT_SIZE) { return null; } int pos = mappedFile.getReadPosition() - CQ_STORE_UNIT_SIZE; return getBatchOffsetIndexByPos(mappedFile, pos, getBatchSize, getStoreTime); } private static int ceil(int pos) { return (pos / CQ_STORE_UNIT_SIZE) * CQ_STORE_UNIT_SIZE; } /** * Gets SelectMappedBufferResult by batch-message offset * Node: the caller is responsible for the release of SelectMappedBufferResult * @param msgOffset * @return SelectMappedBufferResult */ public SelectMappedBufferResult getBatchMsgIndexBuffer(final long msgOffset) { if (msgOffset >= maxOffsetInQueue) { return null; } MappedFile targetBcq; BatchOffsetIndex targetMinOffset; // first check the last bcq file MappedFile lastBcq = mappedFileQueue.getLastMappedFile(); BatchOffsetIndex minForLastBcq = getMinMsgOffset(lastBcq, false, false); if (null != minForLastBcq && minForLastBcq.getMsgOffset() <= msgOffset) { // found, it's the last bcq. targetBcq = lastBcq; targetMinOffset = minForLastBcq; } else { boolean searchBcqByCacheEnable = this.messageStore.getMessageStoreConfig().isSearchBcqByCacheEnable(); if (searchBcqByCacheEnable) { // it's not the last BCQ file, so search it through cache. targetBcq = this.searchOffsetFromCache(msgOffset); // not found in cache if (targetBcq == null) { MappedFile firstBcq = mappedFileQueue.getFirstMappedFile(); BatchOffsetIndex minForFirstBcq = getMinMsgOffset(firstBcq, false, false); if (minForFirstBcq != null && minForFirstBcq.getMsgOffset() <= msgOffset && msgOffset < minForLastBcq.getMsgOffset()) { // old search logic targetBcq = this.searchOffsetFromFiles(msgOffset); } log.warn("cache is not working on BCQ [Topic: {}, QueueId: {}] for msgOffset: {}, targetBcq: {}", this.topic, this.queueId, msgOffset, targetBcq); } } else { // old search logic targetBcq = this.searchOffsetFromFiles(msgOffset); } if (targetBcq == null) { return null; } targetMinOffset = getMinMsgOffset(targetBcq, false, false); } BatchOffsetIndex targetMaxOffset = getMaxMsgOffset(targetBcq, false, false); if (null == targetMinOffset || null == targetMaxOffset) { return null; } // then use binary search to find the indexed position SelectMappedBufferResult sbr = targetMinOffset.getMappedFile().selectMappedBuffer(0); try { ByteBuffer byteBuffer = sbr.getByteBuffer(); int left = targetMinOffset.getIndexPos(), right = targetMaxOffset.getIndexPos(); int mid = binarySearch(byteBuffer, left, right, CQ_STORE_UNIT_SIZE, MSG_BASE_OFFSET_INDEX, msgOffset); if (mid != -1) { // return a buffer that needs to be released manually. return targetMinOffset.getMappedFile().selectMappedBuffer(mid); } } finally { sbr.release(); } return null; } public MappedFile searchOffsetFromFiles(long msgOffset) { MappedFile targetBcq = null; // find the mapped file one by one reversely int mappedFileNum = this.mappedFileQueue.getMappedFiles().size(); for (int i = mappedFileNum - 1; i >= 0; i--) { MappedFile mappedFile = mappedFileQueue.getMappedFiles().get(i); BatchOffsetIndex tmpMinMsgOffset = getMinMsgOffset(mappedFile, false, false); if (null != tmpMinMsgOffset && tmpMinMsgOffset.getMsgOffset() <= msgOffset) { targetBcq = mappedFile; break; } } return targetBcq; } /** * Find the message whose timestamp is the smallest, greater than or equal to the given time. * * @param timestamp * @return */ @Deprecated @Override public long getOffsetInQueueByTime(final long timestamp) { return getOffsetInQueueByTime(timestamp, BoundaryType.LOWER); } @Override public long getOffsetInQueueByTime(long timestamp, BoundaryType boundaryType) { MappedFile targetBcq; BatchOffsetIndex targetMinOffset; // first check the last bcq MappedFile lastBcq = mappedFileQueue.getLastMappedFile(); BatchOffsetIndex minForLastBcq = getMinMsgOffset(lastBcq, false, true); if (null != minForLastBcq && minForLastBcq.getStoreTimestamp() <= timestamp) { // found, it's the last bcq. targetBcq = lastBcq; targetMinOffset = minForLastBcq; } else { boolean searchBcqByCacheEnable = this.messageStore.getMessageStoreConfig().isSearchBcqByCacheEnable(); if (searchBcqByCacheEnable) { // it's not the last BCQ file, so search it through cache. targetBcq = this.searchTimeFromCache(timestamp); if (targetBcq == null) { // not found in cache MappedFile firstBcq = mappedFileQueue.getFirstMappedFile(); BatchOffsetIndex minForFirstBcq = getMinMsgOffset(firstBcq, false, true); if (minForFirstBcq != null && minForFirstBcq.getStoreTimestamp() <= timestamp && timestamp < minForLastBcq.getStoreTimestamp()) { // old search logic targetBcq = this.searchTimeFromFiles(timestamp); } log.warn("cache is not working on BCQ [Topic: {}, QueueId: {}] for timestamp: {}, targetBcq: {}", this.topic, this.queueId, timestamp, targetBcq); } } else { // old search logic targetBcq = this.searchTimeFromFiles(timestamp); } if (targetBcq == null) { return -1; } targetMinOffset = getMinMsgOffset(targetBcq, false, true); } BatchOffsetIndex targetMaxOffset = getMaxMsgOffset(targetBcq, false, true); if (null == targetMinOffset || null == targetMaxOffset) { return -1; } //then use binary search to find the indexed position SelectMappedBufferResult sbr = targetMinOffset.getMappedFile().selectMappedBuffer(0); try { ByteBuffer byteBuffer = sbr.getByteBuffer(); int left = targetMinOffset.getIndexPos(), right = targetMaxOffset.getIndexPos(); long maxQueueTimestamp = byteBuffer.getLong(right + MSG_STORE_TIME_OFFSET_INDEX); if (timestamp >= maxQueueTimestamp) { return byteBuffer.getLong(right + MSG_BASE_OFFSET_INDEX); } int mid = binarySearchRight(byteBuffer, left, right, CQ_STORE_UNIT_SIZE, MSG_STORE_TIME_OFFSET_INDEX, timestamp, boundaryType); if (mid != -1) { return byteBuffer.getLong(mid + MSG_BASE_OFFSET_INDEX); } } finally { sbr.release(); } return -1; } private MappedFile searchTimeFromFiles(long timestamp) { MappedFile targetBcq = null; int mappedFileNum = this.mappedFileQueue.getMappedFiles().size(); for (int i = mappedFileNum - 1; i >= 0; i--) { MappedFile mappedFile = mappedFileQueue.getMappedFiles().get(i); BatchOffsetIndex tmpMinMsgOffset = getMinMsgOffset(mappedFile, false, true); if (tmpMinMsgOffset == null) { //Maybe the new file continue; } BatchOffsetIndex tmpMaxMsgOffset = getMaxMsgOffset(mappedFile, false, true); //Here should not be null if (tmpMaxMsgOffset == null) { break; } if (tmpMaxMsgOffset.getStoreTimestamp() >= timestamp) { if (tmpMinMsgOffset.getStoreTimestamp() <= timestamp) { targetBcq = mappedFile; break; } else { if (i - 1 < 0) { //This is the first file targetBcq = mappedFile; break; } else { //The min timestamp of this file is larger than the given timestamp, so check the next file continue; } } } else { //The max timestamp of this file is smaller than the given timestamp, so double check the previous file if (i + 1 <= mappedFileNum - 1) { mappedFile = mappedFileQueue.getMappedFiles().get(i + 1); targetBcq = mappedFile; break; } else { //There is no timestamp larger than the given timestamp break; } } } return targetBcq; } /** * Find the offset of which the value is equal or larger than the given targetValue. * If there are many values equal to the target, then return the lowest offset if boundaryType is LOWER while * return the highest offset if boundaryType is UPPER. */ public static int binarySearchRight(ByteBuffer byteBuffer, int left, int right, final int unitSize, final int unitShift, long targetValue, BoundaryType boundaryType) { int mid = -1; while (left <= right) { mid = ceil((left + right) / 2); long tmpValue = byteBuffer.getLong(mid + unitShift); if (mid == right) { //Means left and the right are the same if (tmpValue >= targetValue) { return mid; } else { return -1; } } else if (mid == left) { //Means the left + unitSize = right if (tmpValue >= targetValue) { return mid; } else { left = mid + unitSize; } } else { //mid is actually in the mid switch (boundaryType) { case LOWER: if (tmpValue < targetValue) { left = mid + unitSize; } else { right = mid; } break; case UPPER: if (tmpValue <= targetValue) { left = mid; } else { right = mid - unitSize; } break; default: log.warn("Unknown boundary type"); return -1; } } } return -1; } /** * Here is vulnerable, the min value of the bytebuffer must be smaller or equal then the given value. * Otherwise, it may get -1 */ protected int binarySearch(ByteBuffer byteBuffer, int left, int right, final int unitSize, final int unitShift, long targetValue) { int maxRight = right; int mid = -1; while (left <= right) { mid = ceil((left + right) / 2); long tmpValue = byteBuffer.getLong(mid + unitShift); if (tmpValue == targetValue) { return mid; } if (tmpValue > targetValue) { right = mid - unitSize; } else { if (mid == left) { //the binary search is converging to the left, so maybe the one on the right of mid is the exactly correct one if (mid + unitSize <= maxRight && byteBuffer.getLong(mid + unitSize + unitShift) <= targetValue) { return mid + unitSize; } else { return mid; } } else { left = mid; } } } return -1; } static class BatchConsumeQueueIterator implements ReferredIterator<CqUnit> { private SelectMappedBufferResult sbr; private int relativePos = 0; public BatchConsumeQueueIterator(SelectMappedBufferResult sbr) { this.sbr = sbr; if (sbr != null && sbr.getByteBuffer() != null) { relativePos = sbr.getByteBuffer().position(); } } @Override public boolean hasNext() { if (sbr == null || sbr.getByteBuffer() == null) { return false; } return sbr.getByteBuffer().hasRemaining(); } @Override public CqUnit next() { if (!hasNext()) { return null; } ByteBuffer tmpBuffer = sbr.getByteBuffer().slice(); tmpBuffer.position(MSG_COMPACT_OFFSET_INDEX); ByteBuffer compactOffsetStoreBuffer = tmpBuffer.slice(); compactOffsetStoreBuffer.limit(MSG_COMPACT_OFFSET_LENGTH); int relativePos = sbr.getByteBuffer().position(); long offsetPy = sbr.getByteBuffer().getLong(); int sizePy = sbr.getByteBuffer().getInt(); long tagsCode = sbr.getByteBuffer().getLong(); //tagscode sbr.getByteBuffer().getLong();//timestamp long msgBaseOffset = sbr.getByteBuffer().getLong(); short batchSize = sbr.getByteBuffer().getShort(); int compactedOffset = sbr.getByteBuffer().getInt(); sbr.getByteBuffer().position(relativePos + CQ_STORE_UNIT_SIZE); return new CqUnit(msgBaseOffset, offsetPy, sizePy, tagsCode, batchSize, compactedOffset, compactOffsetStoreBuffer); } @Override public void remove() { throw new UnsupportedOperationException("remove"); } @Override public void release() { if (sbr != null) { sbr.release(); sbr = null; } } @Override public CqUnit nextAndRelease() { try { return next(); } finally { release(); } } } @Override public String getTopic() { return topic; } @Override public int getQueueId() { return queueId; } @Override public CQType getCQType() { return CQType.BatchCQ; } @Override public long getTotalSize() { return this.mappedFileQueue.getTotalFileSize(); } @Override public int getUnitSize() { return CQ_STORE_UNIT_SIZE; } @Override public void destroy() { this.maxMsgPhyOffsetInCommitLog = -1; this.minOffsetInQueue = -1; this.maxOffsetInQueue = 0; this.mappedFileQueue.destroy(); this.destroyCache(); } @Override public long getMessageTotalInQueue() { return this.getMaxOffsetInQueue() - this.getMinOffsetInQueue(); } @Override public long rollNextFile(long nextBeginOffset) { return 0; } /** * Batch msg offset (deep logic offset) * * @return max deep offset */ @Override public long getMaxOffsetInQueue() { return maxOffsetInQueue; } @Override public long getMinOffsetInQueue() { return minOffsetInQueue; } @Override public void checkSelf() { mappedFileQueue.checkSelf(); } @Override public void swapMap(int reserveNum, long forceSwapIntervalMs, long normalSwapIntervalMs) { mappedFileQueue.swapMap(reserveNum, forceSwapIntervalMs, normalSwapIntervalMs); } @Override public void cleanSwappedMap(long forceCleanSwapIntervalMs) { mappedFileQueue.cleanSwappedMap(forceCleanSwapIntervalMs); } public MappedFileQueue getMappedFileQueue() { return mappedFileQueue; } @Override public long estimateMessageCount(long from, long to, MessageFilter filter) { // transfer message offset to physical offset SelectMappedBufferResult firstMappedFileBuffer = getBatchMsgIndexBuffer(from); if (firstMappedFileBuffer == null) { return -1; } long physicalOffsetFrom = firstMappedFileBuffer.getStartOffset(); SelectMappedBufferResult lastMappedFileBuffer = getBatchMsgIndexBuffer(to); if (lastMappedFileBuffer == null) { return -1; } long physicalOffsetTo = lastMappedFileBuffer.getStartOffset(); List<MappedFile> mappedFiles = mappedFileQueue.range(physicalOffsetFrom, physicalOffsetTo); if (mappedFiles.isEmpty()) { return -1; } boolean sample = false; long match = 0; long matchCqUnitCount = 0; long raw = 0; long scanCqUnitCount = 0; for (MappedFile mappedFile : mappedFiles) { int start = 0; int len = mappedFile.getFileSize(); // calculate start and len for first segment and last segment to reduce scanning // first file segment if (mappedFile.getFileFromOffset() <= physicalOffsetFrom) { start = (int) (physicalOffsetFrom - mappedFile.getFileFromOffset()); if (mappedFile.getFileFromOffset() + mappedFile.getFileSize() >= physicalOffsetTo) { // current mapped file covers search range completely. len = (int) (physicalOffsetTo - physicalOffsetFrom); } else { len = mappedFile.getFileSize() - start; } } // last file segment if (0 == start && mappedFile.getFileFromOffset() + mappedFile.getFileSize() > physicalOffsetTo) { len = (int) (physicalOffsetTo - mappedFile.getFileFromOffset()); } // select partial data to scan SelectMappedBufferResult slice = mappedFile.selectMappedBuffer(start, len); if (null != slice) { try { ByteBuffer buffer = slice.getByteBuffer(); int current = 0; while (current < len) { // skip physicalOffset and message length fields. buffer.position(current + MSG_TAG_OFFSET_INDEX); long tagCode = buffer.getLong(); buffer.position(current + MSG_BATCH_SIZE_INDEX); long batchSize = buffer.getShort(); if (filter.isMatchedByConsumeQueue(tagCode, null)) { match += batchSize; matchCqUnitCount++; } raw += batchSize; scanCqUnitCount++; current += CQ_STORE_UNIT_SIZE; if (scanCqUnitCount >= messageStore.getMessageStoreConfig().getMaxConsumeQueueScan()) { sample = true; break; } if (matchCqUnitCount > messageStore.getMessageStoreConfig().getSampleCountThreshold()) { sample = true; break; } } } finally { slice.release(); } } // we have scanned enough entries, now is the time to return an educated guess. if (sample) { break; } } long result = match; if (sample) { if (0 == raw) { log.error("[BUG]. Raw should NOT be 0"); return 0; } result = (long) (match * (to - from) * 1.0 / raw); } log.debug("Result={}, raw={}, match={}, sample={}", result, raw, match, sample); return result; } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/queue/BatchConsumeQueue.java
2,372
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store.plugin; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.apache.rocketmq.common.Pair; import org.apache.rocketmq.common.SystemClock; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.message.MessageExtBatch; import org.apache.rocketmq.common.message.MessageExtBrokerInner; import org.apache.rocketmq.remoting.protocol.body.HARuntimeInfo; import org.apache.rocketmq.store.AllocateMappedFileService; import org.apache.rocketmq.store.AppendMessageResult; import org.apache.rocketmq.store.CommitLog; import org.apache.rocketmq.store.CommitLogDispatcher; import org.apache.rocketmq.store.DispatchRequest; import org.apache.rocketmq.store.GetMessageResult; import org.apache.rocketmq.store.MessageFilter; import org.apache.rocketmq.store.MessageStore; import org.apache.rocketmq.store.PutMessageResult; import org.apache.rocketmq.store.QueryMessageResult; import org.apache.rocketmq.store.RunningFlags; import org.apache.rocketmq.store.SelectMappedBufferResult; import org.apache.rocketmq.store.StoreCheckpoint; import org.apache.rocketmq.store.StoreStatsService; import org.apache.rocketmq.store.TransientStorePool; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.ha.HAService; import org.apache.rocketmq.store.hook.PutMessageHook; import org.apache.rocketmq.store.hook.SendMessageBackHook; import org.apache.rocketmq.store.logfile.MappedFile; import org.apache.rocketmq.store.queue.ConsumeQueueInterface; import org.apache.rocketmq.store.queue.ConsumeQueueStoreInterface; import org.apache.rocketmq.store.stats.BrokerStatsManager; import org.apache.rocketmq.store.timer.TimerMessageStore; import org.apache.rocketmq.store.util.PerfCounter; import org.rocksdb.RocksDBException; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.ViewBuilder; public abstract class AbstractPluginMessageStore implements MessageStore { protected MessageStore next = null; protected MessageStorePluginContext context; public AbstractPluginMessageStore(MessageStorePluginContext context, MessageStore next) { this.next = next; this.context = context; } @Override public long getEarliestMessageTime() { return next.getEarliestMessageTime(); } @Override public long lockTimeMills() { return next.lockTimeMills(); } @Override public boolean isOSPageCacheBusy() { return next.isOSPageCacheBusy(); } @Override public boolean isTransientStorePoolDeficient() { return next.isTransientStorePoolDeficient(); } @Override public boolean load() { return next.load(); } @Override public void start() throws Exception { next.start(); } @Override public void shutdown() { next.shutdown(); } @Override public void destroy() { next.destroy(); } @Override public PutMessageResult putMessage(MessageExtBrokerInner msg) { return next.putMessage(msg); } @Override public CompletableFuture<PutMessageResult> asyncPutMessage(MessageExtBrokerInner msg) { return next.asyncPutMessage(msg); } @Override public CompletableFuture<PutMessageResult> asyncPutMessages(MessageExtBatch messageExtBatch) { return next.asyncPutMessages(messageExtBatch); } @Override public GetMessageResult getMessage(String group, String topic, int queueId, long offset, int maxMsgNums, final MessageFilter messageFilter) { return next.getMessage(group, topic, queueId, offset, maxMsgNums, messageFilter); } @Override public CompletableFuture<GetMessageResult> getMessageAsync(String group, String topic, int queueId, long offset, int maxMsgNums, MessageFilter messageFilter) { return next.getMessageAsync(group, topic, queueId, offset, maxMsgNums, messageFilter); } @Override public long getMaxOffsetInQueue(String topic, int queueId) { return next.getMaxOffsetInQueue(topic, queueId); } @Override public long getMaxOffsetInQueue(String topic, int queueId, boolean committed) { return next.getMaxOffsetInQueue(topic, queueId, committed); } @Override public long getMinOffsetInQueue(String topic, int queueId) { return next.getMinOffsetInQueue(topic, queueId); } @Override public long getCommitLogOffsetInQueue(String topic, int queueId, long consumeQueueOffset) { return next.getCommitLogOffsetInQueue(topic, queueId, consumeQueueOffset); } @Override public long getOffsetInQueueByTime(String topic, int queueId, long timestamp) { return next.getOffsetInQueueByTime(topic, queueId, timestamp); } @Override public MessageExt lookMessageByOffset(long commitLogOffset) { return next.lookMessageByOffset(commitLogOffset); } @Override public SelectMappedBufferResult selectOneMessageByOffset(long commitLogOffset) { return next.selectOneMessageByOffset(commitLogOffset); } @Override public SelectMappedBufferResult selectOneMessageByOffset(long commitLogOffset, int msgSize) { return next.selectOneMessageByOffset(commitLogOffset, msgSize); } @Override public String getRunningDataInfo() { return next.getRunningDataInfo(); } @Override public HashMap<String, String> getRuntimeInfo() { return next.getRuntimeInfo(); } @Override public long getMaxPhyOffset() { return next.getMaxPhyOffset(); } @Override public long getMinPhyOffset() { return next.getMinPhyOffset(); } @Override public long getEarliestMessageTime(String topic, int queueId) { return next.getEarliestMessageTime(topic, queueId); } @Override public CompletableFuture<Long> getEarliestMessageTimeAsync(String topic, int queueId) { return next.getEarliestMessageTimeAsync(topic, queueId); } @Override public long getMessageStoreTimeStamp(String topic, int queueId, long consumeQueueOffset) { return next.getMessageStoreTimeStamp(topic, queueId, consumeQueueOffset); } @Override public CompletableFuture<Long> getMessageStoreTimeStampAsync(String topic, int queueId, long consumeQueueOffset) { return next.getMessageStoreTimeStampAsync(topic, queueId, consumeQueueOffset); } @Override public long getMessageTotalInQueue(String topic, int queueId) { return next.getMessageTotalInQueue(topic, queueId); } @Override public SelectMappedBufferResult getCommitLogData(long offset) { return next.getCommitLogData(offset); } @Override public boolean appendToCommitLog(long startOffset, byte[] data, int dataStart, int dataLength) { return next.appendToCommitLog(startOffset, data, dataStart, dataLength); } @Override public void executeDeleteFilesManually() { next.executeDeleteFilesManually(); } @Override public QueryMessageResult queryMessage(String topic, String key, int maxNum, long begin, long end) { return next.queryMessage(topic, key, maxNum, begin, end); } @Override public CompletableFuture<QueryMessageResult> queryMessageAsync(String topic, String key, int maxNum, long begin, long end) { return next.queryMessageAsync(topic, key, maxNum, begin, end); } @Override public long now() { return next.now(); } @Override public int deleteTopics(final Set<String> deleteTopics) { return next.deleteTopics(deleteTopics); } @Override public int cleanUnusedTopic(final Set<String> retainTopics) { return next.cleanUnusedTopic(retainTopics); } @Override public void cleanExpiredConsumerQueue() { next.cleanExpiredConsumerQueue(); } @Override @Deprecated public boolean checkInDiskByConsumeOffset(String topic, int queueId, long consumeOffset) { return next.checkInDiskByConsumeOffset(topic, queueId, consumeOffset); } @Override public boolean checkInMemByConsumeOffset(String topic, int queueId, long consumeOffset, int batchSize) { return next.checkInMemByConsumeOffset(topic, queueId, consumeOffset, batchSize); } @Override public boolean checkInStoreByConsumeOffset(String topic, int queueId, long consumeOffset) { return next.checkInStoreByConsumeOffset(topic, queueId, consumeOffset); } @Override public long dispatchBehindBytes() { return next.dispatchBehindBytes(); } @Override public long flush() { return next.flush(); } @Override public boolean resetWriteOffset(long phyOffset) { return next.resetWriteOffset(phyOffset); } @Override public long getConfirmOffset() { return next.getConfirmOffset(); } @Override public void setConfirmOffset(long phyOffset) { next.setConfirmOffset(phyOffset); } @Override public LinkedList<CommitLogDispatcher> getDispatcherList() { return next.getDispatcherList(); } @Override public void addDispatcher(CommitLogDispatcher dispatcher) { next.addDispatcher(dispatcher); } @Override public ConsumeQueueInterface getConsumeQueue(String topic, int queueId) { return next.getConsumeQueue(topic, queueId); } @Override public ConsumeQueueInterface findConsumeQueue(String topic, int queueId) { return next.findConsumeQueue(topic, queueId); } @Override public BrokerStatsManager getBrokerStatsManager() { return next.getBrokerStatsManager(); } @Override public int remainTransientStoreBufferNumbs() { return next.remainTransientStoreBufferNumbs(); } @Override public long remainHowManyDataToCommit() { return next.remainHowManyDataToCommit(); } @Override public long remainHowManyDataToFlush() { return next.remainHowManyDataToFlush(); } @Override public DispatchRequest checkMessageAndReturnSize(final ByteBuffer byteBuffer, final boolean checkCRC, final boolean checkDupInfo, final boolean readBody) { return next.checkMessageAndReturnSize(byteBuffer, checkCRC, checkDupInfo, readBody); } @Override public long getStateMachineVersion() { return next.getStateMachineVersion(); } @Override public PutMessageResult putMessages(MessageExtBatch messageExtBatch) { return next.putMessages(messageExtBatch); } @Override public HARuntimeInfo getHARuntimeInfo() { return next.getHARuntimeInfo(); } @Override public boolean getLastMappedFile(long startOffset) { return next.getLastMappedFile(startOffset); } @Override public void updateHaMasterAddress(String newAddr) { next.updateHaMasterAddress(newAddr); } @Override public void updateMasterAddress(String newAddr) { next.updateMasterAddress(newAddr); } @Override public long slaveFallBehindMuch() { return next.slaveFallBehindMuch(); } @Override public long getFlushedWhere() { return next.getFlushedWhere(); } @Override public MessageStore getMasterStoreInProcess() { return next.getMasterStoreInProcess(); } @Override public void setMasterStoreInProcess(MessageStore masterStoreInProcess) { next.setMasterStoreInProcess(masterStoreInProcess); } @Override public boolean getData(long offset, int size, ByteBuffer byteBuffer) { return next.getData(offset, size, byteBuffer); } @Override public void setAliveReplicaNumInGroup(int aliveReplicaNums) { next.setAliveReplicaNumInGroup(aliveReplicaNums); } @Override public int getAliveReplicaNumInGroup() { return next.getAliveReplicaNumInGroup(); } @Override public void wakeupHAClient() { next.wakeupHAClient(); } @Override public long getMasterFlushedOffset() { return next.getMasterFlushedOffset(); } @Override public long getBrokerInitMaxOffset() { return next.getBrokerInitMaxOffset(); } @Override public void setMasterFlushedOffset(long masterFlushedOffset) { next.setMasterFlushedOffset(masterFlushedOffset); } @Override public void setBrokerInitMaxOffset(long brokerInitMaxOffset) { next.setBrokerInitMaxOffset(brokerInitMaxOffset); } @Override public byte[] calcDeltaChecksum(long from, long to) { return next.calcDeltaChecksum(from, to); } @Override public HAService getHaService() { return next.getHaService(); } @Override public boolean truncateFiles(long offsetToTruncate) throws RocksDBException { return next.truncateFiles(offsetToTruncate); } @Override public boolean isOffsetAligned(long offset) { return next.isOffsetAligned(offset); } @Override public RunningFlags getRunningFlags() { return next.getRunningFlags(); } @Override public void setSendMessageBackHook(SendMessageBackHook sendMessageBackHook) { next.setSendMessageBackHook(sendMessageBackHook); } @Override public SendMessageBackHook getSendMessageBackHook() { return next.getSendMessageBackHook(); } @Override public GetMessageResult getMessage(String group, String topic, int queueId, long offset, int maxMsgNums, int maxTotalMsgSize, MessageFilter messageFilter) { return next.getMessage(group, topic, queueId, offset, maxMsgNums, maxTotalMsgSize, messageFilter); } @Override public CompletableFuture<GetMessageResult> getMessageAsync(String group, String topic, int queueId, long offset, int maxMsgNums, int maxTotalMsgSize, MessageFilter messageFilter) { return next.getMessageAsync(group, topic, queueId, offset, maxMsgNums, maxTotalMsgSize, messageFilter); } @Override public MessageExt lookMessageByOffset(long commitLogOffset, int size) { return next.lookMessageByOffset(commitLogOffset, size); } @Override public List<SelectMappedBufferResult> getBulkCommitLogData(long offset, int size) { return next.getBulkCommitLogData(offset, size); } @Override public void onCommitLogAppend(MessageExtBrokerInner msg, AppendMessageResult result, MappedFile commitLogFile) { next.onCommitLogAppend(msg, result, commitLogFile); } @Override public void onCommitLogDispatch(DispatchRequest dispatchRequest, boolean doDispatch, MappedFile commitLogFile, boolean isRecover, boolean isFileEnd) throws RocksDBException { next.onCommitLogDispatch(dispatchRequest, doDispatch, commitLogFile, isRecover, isFileEnd); } @Override public MessageStoreConfig getMessageStoreConfig() { return next.getMessageStoreConfig(); } @Override public StoreStatsService getStoreStatsService() { return next.getStoreStatsService(); } @Override public StoreCheckpoint getStoreCheckpoint() { return next.getStoreCheckpoint(); } @Override public SystemClock getSystemClock() { return next.getSystemClock(); } @Override public CommitLog getCommitLog() { return next.getCommitLog(); } @Override public TransientStorePool getTransientStorePool() { return next.getTransientStorePool(); } @Override public AllocateMappedFileService getAllocateMappedFileService() { return next.getAllocateMappedFileService(); } @Override public void truncateDirtyLogicFiles(long phyOffset) throws RocksDBException { next.truncateDirtyLogicFiles(phyOffset); } @Override public void unlockMappedFile(MappedFile unlockMappedFile) { next.unlockMappedFile(unlockMappedFile); } @Override public PerfCounter.Ticks getPerfCounter() { return next.getPerfCounter(); } @Override public ConsumeQueueStoreInterface getQueueStore() { return next.getQueueStore(); } @Override public boolean isSyncDiskFlush() { return next.isSyncDiskFlush(); } @Override public boolean isSyncMaster() { return next.isSyncMaster(); } @Override public void assignOffset(MessageExtBrokerInner msg) throws RocksDBException { next.assignOffset(msg); } @Override public void increaseOffset(MessageExtBrokerInner msg, short messageNum) { next.increaseOffset(msg, messageNum); } @Override public List<PutMessageHook> getPutMessageHookList() { return next.getPutMessageHookList(); } @Override public long getLastFileFromOffset() { return next.getLastFileFromOffset(); } @Override public void setPhysicalOffset(long phyOffset) { next.setPhysicalOffset(phyOffset); } @Override public boolean isMappedFilesEmpty() { return next.isMappedFilesEmpty(); } @Override public TimerMessageStore getTimerMessageStore() { return next.getTimerMessageStore(); } @Override public void setTimerMessageStore(TimerMessageStore timerMessageStore) { next.setTimerMessageStore(timerMessageStore); } @Override public long getTimingMessageCount(String topic) { return next.getTimingMessageCount(topic); } @Override public boolean isShutdown() { return next.isShutdown(); } @Override public long estimateMessageCount(String topic, int queueId, long from, long to, MessageFilter filter) { return next.estimateMessageCount(topic, queueId, from, to, filter); } @Override public List<Pair<InstrumentSelector, ViewBuilder>> getMetricsView() { return next.getMetricsView(); } @Override public void initMetrics(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier) { next.initMetrics(meter, attributesBuilderSupplier); } @Override public void finishCommitLogDispatch() { next.finishCommitLogDispatch(); } @Override public void recoverTopicQueueTable() { next.recoverTopicQueueTable(); } @Override public void notifyMessageArriveIfNecessary(DispatchRequest dispatchRequest) { next.notifyMessageArriveIfNecessary(dispatchRequest); } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/plugin/AbstractPluginMessageStore.java
2,373
404: Not Found
exteraSquad/exteraGram
TMessagesProj/src/main/java/org/telegram/ui/DilogCacheBottomSheet.java
2,374
/** * 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.hadoop.hdfs.server.datanode; import org.apache.hadoop.classification.InterfaceAudience; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_SPLIT_THRESHOLD_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_SPLIT_THRESHOLD_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CACHEREPORT_INTERVAL_MSEC_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CACHEREPORT_INTERVAL_MSEC_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_NON_LOCAL_LAZY_PERSIST; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_NON_LOCAL_LAZY_PERSIST_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SYNCONCLOSE_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SYNCONCLOSE_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATA_ENCRYPTION_ALGORITHM_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_RESTART_REPLICA_EXPIRY_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_RESTART_REPLICA_EXPIRY_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_DEFAULT; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.protocol.datatransfer.TrustedChannelResolver; import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.security.SaslPropertiesResolver; /** * Simple class encapsulating all of the configuration that the DataNode * loads at startup time. */ @InterfaceAudience.Private public class DNConf { final Configuration conf; final int socketTimeout; final int socketWriteTimeout; final int socketKeepaliveTimeout; final boolean transferToAllowed; final boolean dropCacheBehindWrites; final boolean syncBehindWrites; final boolean syncBehindWritesInBackground; final boolean dropCacheBehindReads; final boolean syncOnClose; final boolean encryptDataTransfer; final boolean connectToDnViaHostname; final long readaheadLength; final long heartBeatInterval; final long blockReportInterval; final long blockReportSplitThreshold; final long initialBlockReportDelayMs; final long cacheReportInterval; final long dfsclientSlowIoWarningThresholdMs; final long datanodeSlowIoWarningThresholdMs; final int writePacketSize; final String minimumNameNodeVersion; final String encryptionAlgorithm; final SaslPropertiesResolver saslPropsResolver; final TrustedChannelResolver trustedChannelResolver; private final boolean ignoreSecurePortsForTesting; final long xceiverStopTimeout; final long restartReplicaExpiry; final long maxLockedMemory; // Allow LAZY_PERSIST writes from non-local clients? private final boolean allowNonLocalLazyPersist; public DNConf(Configuration conf) { this.conf = conf; socketTimeout = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY, HdfsServerConstants.READ_TIMEOUT); socketWriteTimeout = conf.getInt(DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY, HdfsServerConstants.WRITE_TIMEOUT); socketKeepaliveTimeout = conf.getInt( DFSConfigKeys.DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_KEY, DFSConfigKeys.DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_DEFAULT); /* Based on results on different platforms, we might need set the default * to false on some of them. */ transferToAllowed = conf.getBoolean( DFS_DATANODE_TRANSFERTO_ALLOWED_KEY, DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT); writePacketSize = conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY, DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT); readaheadLength = conf.getLong( DFSConfigKeys.DFS_DATANODE_READAHEAD_BYTES_KEY, DFSConfigKeys.DFS_DATANODE_READAHEAD_BYTES_DEFAULT); dropCacheBehindWrites = conf.getBoolean( DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY, DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT); syncBehindWrites = conf.getBoolean( DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_KEY, DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT); syncBehindWritesInBackground = conf.getBoolean( DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_IN_BACKGROUND_KEY, DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_IN_BACKGROUND_DEFAULT); dropCacheBehindReads = conf.getBoolean( DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY, DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT); connectToDnViaHostname = conf.getBoolean( DFSConfigKeys.DFS_DATANODE_USE_DN_HOSTNAME, DFSConfigKeys.DFS_DATANODE_USE_DN_HOSTNAME_DEFAULT); this.blockReportInterval = conf.getLong(DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT); this.blockReportSplitThreshold = conf.getLong(DFS_BLOCKREPORT_SPLIT_THRESHOLD_KEY, DFS_BLOCKREPORT_SPLIT_THRESHOLD_DEFAULT); this.cacheReportInterval = conf.getLong(DFS_CACHEREPORT_INTERVAL_MSEC_KEY, DFS_CACHEREPORT_INTERVAL_MSEC_DEFAULT); this.dfsclientSlowIoWarningThresholdMs = conf.getLong( DFSConfigKeys.DFS_CLIENT_SLOW_IO_WARNING_THRESHOLD_KEY, DFSConfigKeys.DFS_CLIENT_SLOW_IO_WARNING_THRESHOLD_DEFAULT); this.datanodeSlowIoWarningThresholdMs = conf.getLong( DFSConfigKeys.DFS_DATANODE_SLOW_IO_WARNING_THRESHOLD_KEY, DFSConfigKeys.DFS_DATANODE_SLOW_IO_WARNING_THRESHOLD_DEFAULT); long initBRDelay = conf.getLong( DFS_BLOCKREPORT_INITIAL_DELAY_KEY, DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT) * 1000L; if (initBRDelay >= blockReportInterval) { initBRDelay = 0; DataNode.LOG.info("dfs.blockreport.initialDelay is " + "greater than or equal to" + "dfs.blockreport.intervalMsec." + " Setting initial delay to 0 msec:"); } initialBlockReportDelayMs = initBRDelay; heartBeatInterval = conf.getLong(DFS_HEARTBEAT_INTERVAL_KEY, DFS_HEARTBEAT_INTERVAL_DEFAULT) * 1000L; // do we need to sync block file contents to disk when blockfile is closed? this.syncOnClose = conf.getBoolean(DFS_DATANODE_SYNCONCLOSE_KEY, DFS_DATANODE_SYNCONCLOSE_DEFAULT); this.minimumNameNodeVersion = conf.get(DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY, DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT); this.encryptDataTransfer = conf.getBoolean(DFS_ENCRYPT_DATA_TRANSFER_KEY, DFS_ENCRYPT_DATA_TRANSFER_DEFAULT); this.encryptionAlgorithm = conf.get(DFS_DATA_ENCRYPTION_ALGORITHM_KEY); this.trustedChannelResolver = TrustedChannelResolver.getInstance(conf); this.saslPropsResolver = DataTransferSaslUtil.getSaslPropertiesResolver( conf); this.ignoreSecurePortsForTesting = conf.getBoolean( IGNORE_SECURE_PORTS_FOR_TESTING_KEY, IGNORE_SECURE_PORTS_FOR_TESTING_DEFAULT); this.xceiverStopTimeout = conf.getLong( DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY, DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_DEFAULT); this.maxLockedMemory = conf.getLong( DFS_DATANODE_MAX_LOCKED_MEMORY_KEY, DFS_DATANODE_MAX_LOCKED_MEMORY_DEFAULT); this.restartReplicaExpiry = conf.getLong( DFS_DATANODE_RESTART_REPLICA_EXPIRY_KEY, DFS_DATANODE_RESTART_REPLICA_EXPIRY_DEFAULT) * 1000L; this.allowNonLocalLazyPersist = conf.getBoolean( DFS_DATANODE_NON_LOCAL_LAZY_PERSIST, DFS_DATANODE_NON_LOCAL_LAZY_PERSIST_DEFAULT); } // We get minimumNameNodeVersion via a method so it can be mocked out in tests. String getMinimumNameNodeVersion() { return this.minimumNameNodeVersion; } /** * Returns the configuration. * * @return Configuration the configuration */ public Configuration getConf() { return conf; } /** * Returns true if encryption enabled for DataTransferProtocol. * * @return boolean true if encryption enabled for DataTransferProtocol */ public boolean getEncryptDataTransfer() { return encryptDataTransfer; } /** * Returns encryption algorithm configured for DataTransferProtocol, or null * if not configured. * * @return encryption algorithm configured for DataTransferProtocol */ public String getEncryptionAlgorithm() { return encryptionAlgorithm; } public long getXceiverStopTimeout() { return xceiverStopTimeout; } public long getMaxLockedMemory() { return maxLockedMemory; } /** * Returns the SaslPropertiesResolver configured for use with * DataTransferProtocol, or null if not configured. * * @return SaslPropertiesResolver configured for use with DataTransferProtocol */ public SaslPropertiesResolver getSaslPropsResolver() { return saslPropsResolver; } /** * Returns the TrustedChannelResolver configured for use with * DataTransferProtocol, or null if not configured. * * @return TrustedChannelResolver configured for use with DataTransferProtocol */ public TrustedChannelResolver getTrustedChannelResolver() { return trustedChannelResolver; } /** * Returns true if configuration is set to skip checking for proper * port configuration in a secured cluster. This is only intended for use in * dev testing. * * @return true if configured to skip checking secured port configuration */ public boolean getIgnoreSecurePortsForTesting() { return ignoreSecurePortsForTesting; } public boolean getAllowNonLocalLazyPersist() { return allowNonLocalLazyPersist; } }
apache/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DNConf.java
2,375
/* * 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.hadoop.hbase.client; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.client.metrics.ScanMetrics; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.IncompatibleFilterException; import org.apache.hadoop.hbase.io.TimeRange; import org.apache.hadoop.hbase.security.access.Permission; import org.apache.hadoop.hbase.security.visibility.Authorizations; import org.apache.hadoop.hbase.util.Bytes; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used to perform Scan operations. * <p> * All operations are identical to {@link Get} with the exception of instantiation. Rather than * specifying a single row, an optional startRow and stopRow may be defined. If rows are not * specified, the Scanner will iterate over all rows. * <p> * To get all columns from all rows of a Table, create an instance with no constraints; use the * {@link #Scan()} constructor. To constrain the scan to specific column families, call * {@link #addFamily(byte[]) addFamily} for each family to retrieve on your Scan instance. * <p> * To get specific columns, call {@link #addColumn(byte[], byte[]) addColumn} for each column to * retrieve. * <p> * To only retrieve columns within a specific range of version timestamps, call * {@link #setTimeRange(long, long) setTimeRange}. * <p> * To only retrieve columns with a specific timestamp, call {@link #setTimestamp(long) setTimestamp} * . * <p> * To limit the number of versions of each column to be returned, call {@link #readVersions(int)}. * <p> * To limit the maximum number of values returned for each call to next(), call * {@link #setBatch(int) setBatch}. * <p> * To add a filter, call {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}. * <p> * For small scan, it is deprecated in 2.0.0. Now we have a {@link #setLimit(int)} method in Scan * object which is used to tell RS how many rows we want. If the rows return reaches the limit, the * RS will close the RegionScanner automatically. And we will also fetch data when openScanner in * the new implementation, this means we can also finish a scan operation in one rpc call. And we * have also introduced a {@link #setReadType(ReadType)} method. You can use this method to tell RS * to use pread explicitly. * <p> * Expert: To explicitly disable server-side block caching for this scan, execute * {@link #setCacheBlocks(boolean)}. * <p> * <em>Note:</em> Usage alters Scan instances. Internally, attributes are updated as the Scan runs * and if enabled, metrics accumulate in the Scan instance. Be aware this is the case when you go to * clone a Scan instance or if you go to reuse a created Scan instance; safer is create a Scan * instance per usage. */ @InterfaceAudience.Public public class Scan extends Query { private static final Logger LOG = LoggerFactory.getLogger(Scan.class); private static final String RAW_ATTR = "_raw_"; private byte[] startRow = HConstants.EMPTY_START_ROW; private boolean includeStartRow = true; private byte[] stopRow = HConstants.EMPTY_END_ROW; private boolean includeStopRow = false; private int maxVersions = 1; private int batch = -1; /** * Partial {@link Result}s are {@link Result}s must be combined to form a complete {@link Result}. * The {@link Result}s had to be returned in fragments (i.e. as partials) because the size of the * cells in the row exceeded max result size on the server. Typically partial results will be * combined client side into complete results before being delivered to the caller. However, if * this flag is set, the caller is indicating that they do not mind seeing partial results (i.e. * they understand that the results returned from the Scanner may only represent part of a * particular row). In such a case, any attempt to combine the partials into a complete result on * the client side will be skipped, and the caller will be able to see the exact results returned * from the server. */ private boolean allowPartialResults = false; private int storeLimit = -1; private int storeOffset = 0; private static final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable"; // If an application wants to use multiple scans over different tables each scan must // define this attribute with the appropriate table name by calling // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName)) static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name"; /** * -1 means no caching specified and the value of {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} * (default to {@link HConstants#DEFAULT_HBASE_CLIENT_SCANNER_CACHING}) will be used */ private int caching = -1; private long maxResultSize = -1; private boolean cacheBlocks = true; private boolean reversed = false; private TimeRange tr = TimeRange.allTime(); private Map<byte[], NavigableSet<byte[]>> familyMap = new TreeMap<byte[], NavigableSet<byte[]>>(Bytes.BYTES_COMPARATOR); private Boolean asyncPrefetch = null; /** * Parameter name for client scanner sync/async prefetch toggle. When using async scanner, * prefetching data from the server is done at the background. The parameter currently won't have * any effect in the case that the user has set Scan#setSmall or Scan#setReversed */ public static final String HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = "hbase.client.scanner.async.prefetch"; /** * Default value of {@link #HBASE_CLIENT_SCANNER_ASYNC_PREFETCH}. */ public static final boolean DEFAULT_HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = false; /** * The mvcc read point to use when open a scanner. Remember to clear it after switching regions as * the mvcc is only valid within region scope. */ private long mvccReadPoint = -1L; /** * The number of rows we want for this scan. We will terminate the scan if the number of return * rows reaches this value. */ private int limit = -1; /** * Control whether to use pread at server side. */ private ReadType readType = ReadType.DEFAULT; private boolean needCursorResult = false; /** * Create a Scan operation across all rows. */ public Scan() { } /** * Creates a new instance of this class while copying all values. * @param scan The scan instance to copy from. * @throws IOException When copying the values fails. */ public Scan(Scan scan) throws IOException { startRow = scan.getStartRow(); includeStartRow = scan.includeStartRow(); stopRow = scan.getStopRow(); includeStopRow = scan.includeStopRow(); maxVersions = scan.getMaxVersions(); batch = scan.getBatch(); storeLimit = scan.getMaxResultsPerColumnFamily(); storeOffset = scan.getRowOffsetPerColumnFamily(); caching = scan.getCaching(); maxResultSize = scan.getMaxResultSize(); cacheBlocks = scan.getCacheBlocks(); filter = scan.getFilter(); // clone? loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue(); consistency = scan.getConsistency(); this.setIsolationLevel(scan.getIsolationLevel()); reversed = scan.isReversed(); asyncPrefetch = scan.isAsyncPrefetch(); allowPartialResults = scan.getAllowPartialResults(); tr = scan.getTimeRange(); // TimeRange is immutable Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap(); for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) { byte[] fam = entry.getKey(); NavigableSet<byte[]> cols = entry.getValue(); if (cols != null && cols.size() > 0) { for (byte[] col : cols) { addColumn(fam, col); } } else { addFamily(fam); } } for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) { setAttribute(attr.getKey(), attr.getValue()); } for (Map.Entry<byte[], TimeRange> entry : scan.getColumnFamilyTimeRange().entrySet()) { TimeRange tr = entry.getValue(); setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); } this.mvccReadPoint = scan.getMvccReadPoint(); this.limit = scan.getLimit(); this.needCursorResult = scan.isNeedCursorResult(); setPriority(scan.getPriority()); readType = scan.getReadType(); super.setReplicaId(scan.getReplicaId()); } /** * Builds a scan object with the same specs as get. * @param get get to model scan after */ public Scan(Get get) { this.startRow = get.getRow(); this.includeStartRow = true; this.stopRow = get.getRow(); this.includeStopRow = true; this.filter = get.getFilter(); this.cacheBlocks = get.getCacheBlocks(); this.maxVersions = get.getMaxVersions(); this.storeLimit = get.getMaxResultsPerColumnFamily(); this.storeOffset = get.getRowOffsetPerColumnFamily(); this.tr = get.getTimeRange(); this.familyMap = get.getFamilyMap(); this.asyncPrefetch = false; this.consistency = get.getConsistency(); this.setIsolationLevel(get.getIsolationLevel()); this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue(); for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) { setAttribute(attr.getKey(), attr.getValue()); } for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) { TimeRange tr = entry.getValue(); setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); } this.mvccReadPoint = -1L; setPriority(get.getPriority()); super.setReplicaId(get.getReplicaId()); } public boolean isGetScan() { return includeStartRow && includeStopRow && ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow); } /** * Get all columns from the specified family. * <p> * Overrides previous calls to addColumn for this family. * @param family family name */ public Scan addFamily(byte[] family) { familyMap.remove(family); familyMap.put(family, null); return this; } /** * Get the column from the specified family with the specified qualifier. * <p> * Overrides previous calls to addFamily for this family. * @param family family name * @param qualifier column qualifier */ public Scan addColumn(byte[] family, byte[] qualifier) { NavigableSet<byte[]> set = familyMap.get(family); if (set == null) { set = new TreeSet<>(Bytes.BYTES_COMPARATOR); familyMap.put(family, set); } if (qualifier == null) { qualifier = HConstants.EMPTY_BYTE_ARRAY; } set.add(qualifier); return this; } /** * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp). Note, * default maximum versions to return is 1. If your time range spans more than one version and you * want all versions returned, up the number of versions beyond the default. * @param minStamp minimum timestamp value, inclusive * @param maxStamp maximum timestamp value, exclusive * @see #readAllVersions() * @see #readVersions(int) */ public Scan setTimeRange(long minStamp, long maxStamp) throws IOException { tr = TimeRange.between(minStamp, maxStamp); return this; } /** * Get versions of columns with the specified timestamp. Note, default maximum versions to return * is 1. If your time range spans more than one version and you want all versions returned, up the * number of versions beyond the defaut. * @param timestamp version timestamp * @see #readAllVersions() * @see #readVersions(int) */ public Scan setTimestamp(long timestamp) { try { tr = TimeRange.at(timestamp); } catch (Exception e) { // This should never happen, unless integer overflow or something extremely wrong... LOG.error("TimeRange failed, likely caused by integer overflow. ", e); throw e; } return this; } @Override public Scan setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) { return (Scan) super.setColumnFamilyTimeRange(cf, minStamp, maxStamp); } /** * Set the start row of the scan. * <p> * If the specified row does not exist, the Scanner will start from the next closest row after the * specified row. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param startRow row to start scanner at or after * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStartRow(byte[] startRow) { return withStartRow(startRow, true); } /** * Set the start row of the scan. * <p> * If the specified row does not exist, or the {@code inclusive} is {@code false}, the Scanner * will start from the next closest row after the specified row. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param startRow row to start scanner at or after * @param inclusive whether we should include the start row when scan * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStartRow(byte[] startRow, boolean inclusive) { if (Bytes.len(startRow) > HConstants.MAX_ROW_LENGTH) { throw new IllegalArgumentException("startRow's length must be less than or equal to " + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key."); } this.startRow = startRow; this.includeStartRow = inclusive; return this; } /** * Set the stop row of the scan. * <p> * The scan will include rows that are lexicographically less than the provided stopRow. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param stopRow row to end at (exclusive) * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStopRow(byte[] stopRow) { return withStopRow(stopRow, false); } /** * Set the stop row of the scan. * <p> * The scan will include rows that are lexicographically less than (or equal to if * {@code inclusive} is {@code true}) the provided stopRow. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param stopRow row to end at * @param inclusive whether we should include the stop row when scan * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStopRow(byte[] stopRow, boolean inclusive) { if (Bytes.len(stopRow) > HConstants.MAX_ROW_LENGTH) { throw new IllegalArgumentException("stopRow's length must be less than or equal to " + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key."); } this.stopRow = stopRow; this.includeStopRow = inclusive; return this; } /** * <p> * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey * starts with the specified prefix. * </p> * <p> * This is a utility method that converts the desired rowPrefix into the appropriate values for * the startRow and stopRow to achieve the desired result. * </p> * <p> * This can safely be used in combination with setFilter. * </p> * <p> * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such * a combination will yield unexpected and even undefined results. * </p> * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.) * @deprecated since 2.5.0, will be removed in 4.0.0. The name of this method is considered to be * confusing as it does not use a {@link Filter} but uses setting the startRow and * stopRow instead. Use {@link #setStartStopRowForPrefixScan(byte[])} instead. */ @Deprecated public Scan setRowPrefixFilter(byte[] rowPrefix) { return setStartStopRowForPrefixScan(rowPrefix); } /** * <p> * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey * starts with the specified prefix. * </p> * <p> * This is a utility method that converts the desired rowPrefix into the appropriate values for * the startRow and stopRow to achieve the desired result. * </p> * <p> * This can safely be used in combination with setFilter. * </p> * <p> * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such * a combination will yield unexpected and even undefined results. * </p> * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.) */ public Scan setStartStopRowForPrefixScan(byte[] rowPrefix) { if (rowPrefix == null) { withStartRow(HConstants.EMPTY_START_ROW); withStopRow(HConstants.EMPTY_END_ROW); } else { this.withStartRow(rowPrefix); this.withStopRow(ClientUtil.calculateTheClosestNextRowKeyForPrefix(rowPrefix)); } return this; } /** * Get all available versions. */ public Scan readAllVersions() { this.maxVersions = Integer.MAX_VALUE; return this; } /** * Get up to the specified number of versions of each column. * @param versions specified number of versions for each column */ public Scan readVersions(int versions) { this.maxVersions = versions; return this; } /** * Set the maximum number of cells to return for each call to next(). Callers should be aware that * this is not equivalent to calling {@link #setAllowPartialResults(boolean)}. If you don't allow * partial results, the number of cells in each Result must equal to your batch setting unless it * is the last Result for current row. So this method is helpful in paging queries. If you just * want to prevent OOM at client, use setAllowPartialResults(true) is better. * @param batch the maximum number of values * @see Result#mayHaveMoreCellsInRow() */ public Scan setBatch(int batch) { if (this.hasFilter() && this.filter.hasFilterRow()) { throw new IncompatibleFilterException( "Cannot set batch on a scan using a filter" + " that returns true for filter.hasFilterRow"); } this.batch = batch; return this; } /** * Set the maximum number of values to return per row per Column Family * @param limit the maximum number of values returned / row / CF */ public Scan setMaxResultsPerColumnFamily(int limit) { this.storeLimit = limit; return this; } /** * Set offset for the row per Column Family. * @param offset is the number of kvs that will be skipped. */ public Scan setRowOffsetPerColumnFamily(int offset) { this.storeOffset = offset; return this; } /** * Set the number of rows for caching that will be passed to scanners. If not set, the * Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will apply. Higher * caching values will enable faster scanners but will use more memory. * @param caching the number of rows for caching */ public Scan setCaching(int caching) { this.caching = caching; return this; } /** Returns the maximum result size in bytes. See {@link #setMaxResultSize(long)} */ public long getMaxResultSize() { return maxResultSize; } /** * Set the maximum result size. The default is -1; this means that no specific maximum result size * will be set for this scan, and the global configured value will be used instead. (Defaults to * unlimited). * @param maxResultSize The maximum result size in bytes. */ public Scan setMaxResultSize(long maxResultSize) { this.maxResultSize = maxResultSize; return this; } @Override public Scan setFilter(Filter filter) { super.setFilter(filter); return this; } /** * Setting the familyMap * @param familyMap map of family to qualifier */ public Scan setFamilyMap(Map<byte[], NavigableSet<byte[]>> familyMap) { this.familyMap = familyMap; return this; } /** * Getting the familyMap */ public Map<byte[], NavigableSet<byte[]>> getFamilyMap() { return this.familyMap; } /** Returns the number of families in familyMap */ public int numFamilies() { if (hasFamilies()) { return this.familyMap.size(); } return 0; } /** Returns true if familyMap is non empty, false otherwise */ public boolean hasFamilies() { return !this.familyMap.isEmpty(); } /** Returns the keys of the familyMap */ public byte[][] getFamilies() { if (hasFamilies()) { return this.familyMap.keySet().toArray(new byte[0][0]); } return null; } /** Returns the startrow */ public byte[] getStartRow() { return this.startRow; } /** Returns if we should include start row when scan */ public boolean includeStartRow() { return includeStartRow; } /** Returns the stoprow */ public byte[] getStopRow() { return this.stopRow; } /** Returns if we should include stop row when scan */ public boolean includeStopRow() { return includeStopRow; } /** Returns the max number of versions to fetch */ public int getMaxVersions() { return this.maxVersions; } /** Returns maximum number of values to return for a single call to next() */ public int getBatch() { return this.batch; } /** Returns maximum number of values to return per row per CF */ public int getMaxResultsPerColumnFamily() { return this.storeLimit; } /** * Method for retrieving the scan's offset per row per column family (#kvs to be skipped) * @return row offset */ public int getRowOffsetPerColumnFamily() { return this.storeOffset; } /** Returns caching the number of rows fetched when calling next on a scanner */ public int getCaching() { return this.caching; } /** Returns TimeRange */ public TimeRange getTimeRange() { return this.tr; } /** Returns RowFilter */ @Override public Filter getFilter() { return filter; } /** Returns true is a filter has been specified, false if not */ public boolean hasFilter() { return filter != null; } /** * Set whether blocks should be cached for this Scan. * <p> * This is true by default. When true, default settings of the table and family are used (this * will never override caching blocks if the block cache is disabled for that family or entirely). * @param cacheBlocks if false, default settings are overridden and blocks will not be cached */ public Scan setCacheBlocks(boolean cacheBlocks) { this.cacheBlocks = cacheBlocks; return this; } /** * Get whether blocks should be cached for this Scan. * @return true if default caching should be used, false if blocks should not be cached */ public boolean getCacheBlocks() { return cacheBlocks; } /** * Set whether this scan is a reversed one * <p> * This is false by default which means forward(normal) scan. * @param reversed if true, scan will be backward order */ public Scan setReversed(boolean reversed) { this.reversed = reversed; return this; } /** * Get whether this scan is a reversed one. * @return true if backward scan, false if forward(default) scan */ public boolean isReversed() { return reversed; } /** * Setting whether the caller wants to see the partial results when server returns * less-than-expected cells. It is helpful while scanning a huge row to prevent OOM at client. By * default this value is false and the complete results will be assembled client side before being * delivered to the caller. * @see Result#mayHaveMoreCellsInRow() * @see #setBatch(int) */ public Scan setAllowPartialResults(final boolean allowPartialResults) { this.allowPartialResults = allowPartialResults; return this; } /** * Returns true when the constructor of this scan understands that the results they will see may * only represent a partial portion of a row. The entire row would be retrieved by subsequent * calls to {@link ResultScanner#next()} */ public boolean getAllowPartialResults() { return allowPartialResults; } @Override public Scan setLoadColumnFamiliesOnDemand(boolean value) { return (Scan) super.setLoadColumnFamiliesOnDemand(value); } /** * Compile the table and column family (i.e. schema) information into a String. Useful for parsing * and aggregation by debugging, logging, and administration tools. */ @Override public Map<String, Object> getFingerprint() { Map<String, Object> map = new HashMap<>(); List<String> families = new ArrayList<>(); if (this.familyMap.isEmpty()) { map.put("families", "ALL"); return map; } else { map.put("families", families); } for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { families.add(Bytes.toStringBinary(entry.getKey())); } return map; } /** * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a * Map along with the fingerprinted information. Useful for debugging, logging, and administration * tools. * @param maxCols a limit on the number of columns output prior to truncation */ @Override public Map<String, Object> toMap(int maxCols) { // start with the fingerprint map and build on top of it Map<String, Object> map = getFingerprint(); // map from families to column list replaces fingerprint's list of families Map<String, List<String>> familyColumns = new HashMap<>(); map.put("families", familyColumns); // add scalar information first map.put("startRow", Bytes.toStringBinary(this.startRow)); map.put("stopRow", Bytes.toStringBinary(this.stopRow)); map.put("maxVersions", this.maxVersions); map.put("batch", this.batch); map.put("caching", this.caching); map.put("maxResultSize", this.maxResultSize); map.put("cacheBlocks", this.cacheBlocks); map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand); List<Long> timeRange = new ArrayList<>(2); timeRange.add(this.tr.getMin()); timeRange.add(this.tr.getMax()); map.put("timeRange", timeRange); int colCount = 0; // iterate through affected families and list out up to maxCols columns for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { List<String> columns = new ArrayList<>(); familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns); if (entry.getValue() == null) { colCount++; --maxCols; columns.add("ALL"); } else { colCount += entry.getValue().size(); if (maxCols <= 0) { continue; } for (byte[] column : entry.getValue()) { if (--maxCols <= 0) { continue; } columns.add(Bytes.toStringBinary(column)); } } } map.put("totalColumns", colCount); if (this.filter != null) { map.put("filter", this.filter.toString()); } // add the id if set if (getId() != null) { map.put("id", getId()); } map.put("includeStartRow", includeStartRow); map.put("includeStopRow", includeStopRow); map.put("allowPartialResults", allowPartialResults); map.put("storeLimit", storeLimit); map.put("storeOffset", storeOffset); map.put("reversed", reversed); if (null != asyncPrefetch) { map.put("asyncPrefetch", asyncPrefetch); } map.put("mvccReadPoint", mvccReadPoint); map.put("limit", limit); map.put("readType", readType); map.put("needCursorResult", needCursorResult); map.put("targetReplicaId", targetReplicaId); map.put("consistency", consistency); if (!colFamTimeRangeMap.isEmpty()) { Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream() .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> { TimeRange value = e.getValue(); List<Long> rangeList = new ArrayList<>(); rangeList.add(value.getMin()); rangeList.add(value.getMax()); return rangeList; })); map.put("colFamTimeRangeMap", colFamTimeRangeMapStr); } map.put("priority", getPriority()); return map; } /** * Enable/disable "raw" mode for this scan. If "raw" is enabled the scan will return all delete * marker and deleted rows that have not been collected, yet. This is mostly useful for Scan on * column families that have KEEP_DELETED_ROWS enabled. It is an error to specify any column when * "raw" is set. * @param raw True/False to enable/disable "raw" mode. */ public Scan setRaw(boolean raw) { setAttribute(RAW_ATTR, Bytes.toBytes(raw)); return this; } /** Returns True if this Scan is in "raw" mode. */ public boolean isRaw() { byte[] attr = getAttribute(RAW_ATTR); return attr == null ? false : Bytes.toBoolean(attr); } @Override public Scan setAttribute(String name, byte[] value) { return (Scan) super.setAttribute(name, value); } @Override public Scan setId(String id) { return (Scan) super.setId(id); } @Override public Scan setAuthorizations(Authorizations authorizations) { return (Scan) super.setAuthorizations(authorizations); } @Override public Scan setACL(Map<String, Permission> perms) { return (Scan) super.setACL(perms); } @Override public Scan setACL(String user, Permission perms) { return (Scan) super.setACL(user, perms); } @Override public Scan setConsistency(Consistency consistency) { return (Scan) super.setConsistency(consistency); } @Override public Scan setReplicaId(int Id) { return (Scan) super.setReplicaId(Id); } @Override public Scan setIsolationLevel(IsolationLevel level) { return (Scan) super.setIsolationLevel(level); } @Override public Scan setPriority(int priority) { return (Scan) super.setPriority(priority); } /** * Enable collection of {@link ScanMetrics}. For advanced users. * @param enabled Set to true to enable accumulating scan metrics */ public Scan setScanMetricsEnabled(final boolean enabled) { setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled))); return this; } /** Returns True if collection of scan metrics is enabled. For advanced users. */ public boolean isScanMetricsEnabled() { byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE); return attr == null ? false : Bytes.toBoolean(attr); } public Boolean isAsyncPrefetch() { return asyncPrefetch; } /** * @deprecated Since 3.0.0, will be removed in 4.0.0. After building sync client upon async * client, the implementation is always 'async prefetch', so this flag is useless now. */ @Deprecated public Scan setAsyncPrefetch(boolean asyncPrefetch) { this.asyncPrefetch = asyncPrefetch; return this; } /** Returns the limit of rows for this scan */ public int getLimit() { return limit; } /** * Set the limit of rows for this scan. We will terminate the scan if the number of returned rows * reaches this value. * <p> * This condition will be tested at last, after all other conditions such as stopRow, filter, etc. * @param limit the limit of rows for this scan */ public Scan setLimit(int limit) { this.limit = limit; return this; } /** * Call this when you only want to get one row. It will set {@code limit} to {@code 1}, and also * set {@code readType} to {@link ReadType#PREAD}. */ public Scan setOneRowLimit() { return setLimit(1).setReadType(ReadType.PREAD); } @InterfaceAudience.Public public enum ReadType { DEFAULT, STREAM, PREAD } /** Returns the read type for this scan */ public ReadType getReadType() { return readType; } /** * Set the read type for this scan. * <p> * Notice that we may choose to use pread even if you specific {@link ReadType#STREAM} here. For * example, we will always use pread if this is a get scan. */ public Scan setReadType(ReadType readType) { this.readType = readType; return this; } /** * Get the mvcc read point used to open a scanner. */ long getMvccReadPoint() { return mvccReadPoint; } /** * Set the mvcc read point used to open a scanner. */ Scan setMvccReadPoint(long mvccReadPoint) { this.mvccReadPoint = mvccReadPoint; return this; } /** * Set the mvcc read point to -1 which means do not use it. */ Scan resetMvccReadPoint() { return setMvccReadPoint(-1L); } /** * When the server is slow or we scan a table with many deleted data or we use a sparse filter, * the server will response heartbeat to prevent timeout. However the scanner will return a Result * only when client can do it. So if there are many heartbeats, the blocking time on * ResultScanner#next() may be very long, which is not friendly to online services. Set this to * true then you can get a special Result whose #isCursor() returns true and is not contains any * real data. It only tells you where the server has scanned. You can call next to continue * scanning or open a new scanner with this row key as start row whenever you want. Users can get * a cursor when and only when there is a response from the server but we can not return a Result * to users, for example, this response is a heartbeat or there are partial cells but users do not * allow partial result. Now the cursor is in row level which means the special Result will only * contains a row key. {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor} */ public Scan setNeedCursorResult(boolean needCursorResult) { this.needCursorResult = needCursorResult; return this; } public boolean isNeedCursorResult() { return needCursorResult; } /** * Create a new Scan with a cursor. It only set the position information like start row key. The * others (like cfs, stop row, limit) should still be filled in by the user. * {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor} */ public static Scan createScanFromCursor(Cursor cursor) { return new Scan().withStartRow(cursor.getRow()); } }
apache/hbase
hbase-client/src/main/java/org/apache/hadoop/hbase/client/Scan.java
2,376
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.popup; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.diagnostic.LoadingState; import com.intellij.icons.AllIcons; import com.intellij.ide.*; import com.intellij.ide.actions.WindowAction; import com.intellij.ide.ui.PopupLocationTracker; import com.intellij.ide.ui.PopupLocator; import com.intellij.ide.ui.ScreenAreaConsumer; import com.intellij.ide.ui.laf.darcula.DarculaUIUtil; import com.intellij.openapi.Disposable; import com.intellij.openapi.MnemonicHelper; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.actionSystem.impl.AutoPopupSupportingListener; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.ui.ComboBoxWithWidePopup; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.HtmlChunk; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.FloatingDecorator; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.openapi.wm.impl.ModalityHelper; import com.intellij.ui.*; import com.intellij.ui.awt.AnchoredPoint; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBTextField; import com.intellij.ui.mac.touchbar.TouchbarSupport; import com.intellij.ui.popup.util.PopupImplUtil; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.speedSearch.ListWithFilter; import com.intellij.ui.speedSearch.SpeedSearch; import com.intellij.ui.speedSearch.SpeedSearchInputMethodRequests; import com.intellij.ui.speedSearch.SpeedSearchSupply; import com.intellij.util.*; import com.intellij.util.concurrency.ThreadingAssertions; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.WeakList; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.AccessibleContextUtil; import org.jetbrains.annotations.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.*; import java.awt.im.InputMethodRequests; import java.util.List; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Supplier; import static java.awt.event.MouseEvent.*; import static java.awt.event.WindowEvent.WINDOW_ACTIVATED; import static java.awt.event.WindowEvent.WINDOW_GAINED_FOCUS; public class AbstractPopup implements JBPopup, ScreenAreaConsumer, AlignedPopup { public static final @NonNls String SHOW_HINTS = "ShowHints"; // Popup size stored with DimensionService is null first time // In this case you can put Dimension in content client properties to adjust size // Zero or negative values (with/height or both) would be ignored (actual values would be obtained from preferred size) public static final @NonNls String FIRST_TIME_SIZE = "FirstTimeSize"; private static final Logger LOG = Logger.getInstance(AbstractPopup.class); private PopupComponent myPopup; private MyContentPanel myContent; private JComponent myPreferredFocusedComponent; private boolean myRequestFocus; private boolean myFocusable; private boolean myForcedHeavyweight; private boolean myLocateWithinScreen; private boolean myResizable; private WindowResizeListener myResizeListener; private WindowMoveListener myMoveListener; private JPanel myHeaderPanel; private CaptionPanel myCaption; private JComponent myComponent; private SpeedSearch mySpeedSearchFoundInRootComponent; private String myDimensionServiceKey; private Computable<Boolean> myCallBack; private Object[] modalEntitiesWhenShown; private Project myProject; private boolean myCancelOnClickOutside; private final List<JBPopupListener> myListeners = new CopyOnWriteArrayList<>(); private boolean myUseDimServiceForXYLocation; private MouseChecker myCancelOnMouseOutCallback; private Canceller myMouseOutCanceller; private boolean myCancelOnWindow; private boolean myCancelOnWindowDeactivation = true; private Dimension myForcedSize; private Point myForcedLocation; private boolean myCancelKeyEnabled; private boolean myLocateByContent; private Dimension myMinSize; private boolean myStretchToOwnerWidth; private boolean myStretchToOwnerHeight; private List<Object> myUserData; private boolean myShadowed; private float myAlpha; private float myLastAlpha; private MaskProvider myMaskProvider; private Window myWindow; private boolean myInStack; private MyWindowListener myWindowListener; private boolean myModalContext; private Component[] myFocusOwners; private PopupBorder myPopupBorder; private Color myPopupBorderColor; private Dimension myRestoreWindowSize; protected Component myOwner; private Component myRequestorComponent; private boolean myHeaderAlwaysFocusable; private boolean myMovable; private JComponent myHeaderComponent; InputEvent myDisposeEvent; private Runnable myFinalRunnable; private Runnable myOkHandler; private @Nullable BooleanFunction<? super KeyEvent> myKeyEventHandler; protected boolean myOk; private final List<Runnable> myResizeListeners = new ArrayList<>(); private static final WeakList<JBPopup> all = new WeakList<>(); private boolean mySpeedSearchAlwaysShown; protected final SpeedSearch mySpeedSearch = new SpeedSearch() { boolean searchFieldShown; @Override public void update() { updateSpeedSearchColors(false); onSpeedSearchPatternChanged(); mySpeedSearchPatternField.setText(getFilter()); if (!mySpeedSearchAlwaysShown) { if (isHoldingFilter() && !searchFieldShown) { setHeaderComponent(mySpeedSearchPatternField); searchFieldShown = true; } else if (!isHoldingFilter() && searchFieldShown) { setHeaderComponent(null); searchFieldShown = false; } } } @Override public void noHits() { updateSpeedSearchColors(true); } @Override public InputMethodRequests getInputMethodRequests() { return new SpeedSearchInputMethodRequests() { @Override protected InputMethodRequests getDelegate() { if (searchFieldShown || mySpeedSearchAlwaysShown) { return mySpeedSearchPatternField.getTextEditor().getInputMethodRequests(); } else { return null; } } @Override protected void ensurePopupIsShown() { if (!searchFieldShown && !mySpeedSearchAlwaysShown) { setHeaderComponent(mySpeedSearchPatternField); searchFieldShown = true; } } }; } }; protected void updateSpeedSearchColors(boolean error) { JBTextField textEditor = mySpeedSearchPatternField.getTextEditor(); if (ExperimentalUI.isNewUI()) { textEditor.setForeground(error ? NamedColorUtil.getErrorForeground() : UIUtil.getLabelForeground()); } else { textEditor.setBackground(error ? LightColors.RED : UIUtil.getTextFieldBackground()); } } protected SearchTextField mySpeedSearchPatternField; private PopupComponentFactory.PopupType myPopupType; private boolean myNativePopup; private boolean myMayBeParent; private JComponent myAdComponent; private boolean myDisposed; private boolean myNormalWindowLevel; private UiActivity myActivityKey; private Disposable myProjectDisposable; private volatile State myState = State.NEW; private long myOpeningTime; void setNormalWindowLevel(boolean normalWindowLevel) { myNormalWindowLevel = normalWindowLevel; } private enum State {NEW, INIT, SHOWING, SHOWN, CANCEL, DISPOSE} private void debugState(@NonNls @NotNull String message, State @NotNull ... states) { if (LOG.isDebugEnabled()) { LOG.debug(hashCode() + " - " + message); if (!ApplicationManager.getApplication().isDispatchThread()) { LOG.debug("unexpected thread"); } for (State state : states) { if (state == myState) { return; } } LOG.debug(new IllegalStateException("myState=" + myState)); } } protected AbstractPopup() { } protected @NotNull AbstractPopup init(Project project, @NotNull JComponent component, @Nullable JComponent preferredFocusedComponent, boolean requestFocus, boolean focusable, boolean movable, String dimensionServiceKey, boolean resizable, @NlsContexts.PopupTitle @Nullable String caption, @Nullable Computable<Boolean> callback, boolean cancelOnClickOutside, @NotNull Set<? extends JBPopupListener> listeners, boolean useDimServiceForXYLocation, ActiveComponent commandButton, @Nullable IconButton cancelButton, @Nullable MouseChecker cancelOnMouseOutCallback, boolean cancelOnWindow, @Nullable ActiveIcon titleIcon, boolean cancelKeyEnabled, boolean locateByContent, boolean placeWithinScreenBounds, @Nullable Dimension minSize, float alpha, @Nullable MaskProvider maskProvider, boolean inStack, boolean modalContext, Component @NotNull [] focusOwners, @Nullable @NlsContexts.PopupAdvertisement String adText, int adTextAlignment, boolean headerAlwaysFocusable, @NotNull List<? extends Pair<ActionListener, KeyStroke>> keyboardActions, Component settingsButtons, final @Nullable Processor<? super JBPopup> pinCallback, boolean mayBeParent, boolean showShadow, boolean showBorder, Color borderColor, boolean cancelOnWindowDeactivation, @Nullable BooleanFunction<? super KeyEvent> keyEventHandler) { assert !requestFocus || focusable : "Incorrect argument combination: requestFocus=true focusable=false"; all.add(this); myActivityKey = new UiActivity.Focus("Popup:" + this); myProject = project; myComponent = component; mySpeedSearchFoundInRootComponent = findInComponentHierarchy(component, it -> it instanceof ListWithFilter ? ((ListWithFilter<?>)it).getSpeedSearch() : null); myPopupBorder = showBorder ? borderColor != null ? PopupBorder.Factory.createColored(borderColor) : PopupBorder.Factory.create(true, showShadow) : PopupBorder.Factory.createEmpty(); myPopupBorder.setPopupUsed(); myShadowed = showShadow; if (showBorder) { myPopupBorderColor = borderColor == null ? JBUI.CurrentTheme.Popup.borderColor(true) : borderColor; } myContent = createContentPanel(resizable, myPopupBorder, false); myMayBeParent = mayBeParent; myCancelOnWindowDeactivation = cancelOnWindowDeactivation; myContent.add(component, BorderLayout.CENTER); if (adText != null) { setAdText(adText, adTextAlignment); } myCancelKeyEnabled = cancelKeyEnabled; myLocateByContent = locateByContent; myLocateWithinScreen = placeWithinScreenBounds && !StartupUiUtil.isWaylandToolkit(); myAlpha = alpha; myMaskProvider = maskProvider; myInStack = inStack; myModalContext = modalContext; myFocusOwners = focusOwners; myHeaderAlwaysFocusable = headerAlwaysFocusable; myMovable = movable; myHeaderPanel = new JPanel(new BorderLayout()) { @Override public Color getBackground() { return JBUI.CurrentTheme.Popup.headerBackground(true); } }; if (caption != null) { if (!caption.isEmpty()) { TitlePanel titlePanel = titleIcon == null ? new TitlePanel() : new TitlePanel(titleIcon.getRegular(), titleIcon.getInactive()); titlePanel.setText(caption); titlePanel.setPopupTitle(ExperimentalUI.isNewUI()); myCaption = titlePanel; } else { myCaption = new CaptionPanel(); } if (pinCallback != null) { Icon icon = ToolWindowManager.getInstance(myProject != null ? myProject : ProjectUtil.guessCurrentProject((JComponent)myOwner)) .getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab); myCaption.setButtonComponent(new InplaceButton( new IconButton(IdeBundle.message("show.in.find.window.button.name"), icon), e -> pinCallback.process(this) ), JBUI.Borders.empty(4)); } else if (cancelButton != null) { myCaption.setButtonComponent(new InplaceButton(cancelButton, e -> cancel()), JBUI.Borders.empty(4)); } else if (commandButton != null) { myCaption.setButtonComponent(commandButton, null); } } else { myCaption = new CaptionPanel(); myCaption.setBorder(null); myCaption.setPreferredSize(JBUI.emptySize()); } setWindowActive(myHeaderAlwaysFocusable); myHeaderPanel.add(myCaption, BorderLayout.NORTH); myContent.add(myHeaderPanel, BorderLayout.NORTH); myForcedHeavyweight = true; myResizable = resizable; myPreferredFocusedComponent = preferredFocusedComponent; myRequestFocus = requestFocus; myFocusable = focusable; myDimensionServiceKey = dimensionServiceKey; myCallBack = callback; myCancelOnClickOutside = cancelOnClickOutside; myCancelOnMouseOutCallback = cancelOnMouseOutCallback; myListeners.addAll(listeners); myUseDimServiceForXYLocation = useDimServiceForXYLocation; myCancelOnWindow = cancelOnWindow; myMinSize = minSize; if (Registry.is("ide.popup.horizontal.scroll.bar.opaque")) { forHorizontalScrollBar(bar -> bar.setOpaque(true)); } for (Pair<ActionListener, KeyStroke> pair : keyboardActions) { myContent.registerKeyboardAction(pair.getFirst(), pair.getSecond(), JComponent.WHEN_IN_FOCUSED_WINDOW); } if (settingsButtons != null) { myCaption.addSettingsComponent(settingsButtons); } myKeyEventHandler = keyEventHandler; debugState("popup initialized", State.NEW); myState = State.INIT; Component clickSource = PopupImplUtil.getClickSourceFromLastInputEvent(); if (!(clickSource instanceof JList<?> || clickSource instanceof JTree)) { PopupUtil.setPopupToggleComponent(this, clickSource); } ActionUtil.initActionContextForComponent(myContent); return this; } private void setWindowActive(boolean active) { boolean value = myHeaderAlwaysFocusable || active; if (myCaption != null) { myCaption.setActive(value); } myPopupBorder.setActive(value); myContent.repaint(); } protected @NotNull MyContentPanel createContentPanel(final boolean resizable, @NotNull PopupBorder border, boolean isToDrawMacCorner) { return new MyContentPanel(border); } public void setShowHints(boolean show) { final Window ancestor = getContentWindow(myComponent); if (ancestor instanceof RootPaneContainer) { final JRootPane rootPane = ((RootPaneContainer)ancestor).getRootPane(); if (rootPane != null) { rootPane.putClientProperty(SHOW_HINTS, show); } } } public String getDimensionServiceKey() { return myDimensionServiceKey; } public void setDimensionServiceKey(final @Nullable String dimensionServiceKey) { myDimensionServiceKey = dimensionServiceKey; } public void setAdText(@NotNull @NlsContexts.PopupAdvertisement String s) { setAdText(s, SwingConstants.LEFT); } public @NotNull PopupBorder getPopupBorder() { return myPopupBorder; } @Override public void setAdText(@NotNull @NlsContexts.PopupAdvertisement String s, int alignment) { JLabel label; if (myAdComponent == null || !(myAdComponent instanceof JLabel)) { label = HintUtil.createAdComponent(s, JBUI.CurrentTheme.Advertiser.border(), alignment); setFooterComponent(label); } else { label = (JLabel)myAdComponent; } Dimension prefSize = label.isVisible() ? myAdComponent.getPreferredSize() : JBUI.emptySize(); boolean keepSize = BasicHTML.isHTMLString(s); label.setVisible(StringUtil.isNotEmpty(s)); label.setText(keepSize ? s : wrapToSize(s)); label.setHorizontalAlignment(alignment); Dimension newPrefSize = label.isVisible() ? myAdComponent.getPreferredSize() : JBUI.emptySize(); int delta = newPrefSize.height - prefSize.height; // Resize popup to match new advertiser size. if (myPopup != null && !isBusy() && delta != 0 && !keepSize) { Window popupWindow = getContentWindow(myContent); if (popupWindow != null) { Dimension size = popupWindow.getSize(); size.height += delta; myContent.setPreferredSize(size); popupWindow.pack(); updateMaskAndAlpha(popupWindow); } } } protected void setFooterComponent(JComponent c) { if (myAdComponent != null) { myContent.remove(myAdComponent); } myContent.add(c, BorderLayout.SOUTH); pack(false, true); myAdComponent = c; } private @NotNull @Nls String wrapToSize(@NotNull @Nls String hint) { if (StringUtil.isEmpty(hint)) return hint; Dimension size = myContent.getSize(); if (size.width == 0 && size.height == 0) { size = myContent.computePreferredSize(); } JBInsets.removeFrom(size, myContent.getInsets()); JBInsets.removeFrom(size, myAdComponent.getInsets()); int width = Math.max(JBUI.CurrentTheme.Popup.minimumHintWidth(), size.width); return HtmlChunk.text(hint).wrapWith(HtmlChunk.div().attr("width", width)).wrapWith(HtmlChunk.html()).toString(); } public static @NotNull Point getCenterOf(@NotNull Component aContainer, @NotNull JComponent content) { return getCenterOf(aContainer, content.getPreferredSize()); } private static @NotNull Point getCenterOf(@NotNull Component aContainer, @NotNull Dimension contentSize) { final JComponent component = getTargetComponent(aContainer); Rectangle visibleBounds = component != null ? component.getVisibleRect() : new Rectangle(aContainer.getSize()); Point containerScreenPoint = visibleBounds.getLocation(); SwingUtilities.convertPointToScreen(containerScreenPoint, aContainer); visibleBounds.setLocation(containerScreenPoint); return UIUtil.getCenterPoint(visibleBounds, contentSize); } @Override public void showCenteredInCurrentWindow(@NotNull Project project) { if (UiInterceptors.tryIntercept(this)) return; Window window = getCurrentWindow(project); if (window != null && window.isShowing()) { showInCenterOf(window); } } @Nullable public static Window getCurrentWindow(@NotNull Project project) { Window window = null; WindowManagerEx manager = getWndManager(); if (manager != null) { window = getTargetWindow(manager.getFocusedComponent(project)); } if (window == null) { window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); } if ((window == null || !window.isShowing()) && manager != null) { window = manager.getFrame(project); } return window; } private static Window getTargetWindow(Component component) { Window res = null; while (component != null) { if (component instanceof FloatingDecorator fd) { return fd; } Component parent = component.getParent(); if (component instanceof Window w) { if (ModalityHelper.isModalBlocked(w)) break; res = w; } component = parent; } return res; } @Override public void showInCenterOf(@NotNull Component aComponent) { HelpTooltip.setMasterPopup(aComponent, this); Point popupPoint = getCenterOf(aComponent, getPreferredContentSize()); show(aComponent, popupPoint.x, popupPoint.y, false); } @Override public void showUnderneathOf(@NotNull Component aComponent) { showUnderneathOf(aComponent, true); } @Override public void showUnderneathOf(@NotNull Component aComponent, boolean useAlignment) { boolean isAlignmentUsed = ExperimentalUI.isNewUI() && Registry.is("ide.popup.align.by.content") && useAlignment && isComponentSupportsAlignment(aComponent); var point = isAlignmentUsed ? pointUnderneathOfAlignedHorizontally(aComponent) : defaultPointUnderneathOf(aComponent); show(point); } private static boolean isComponentSupportsAlignment(Component c) { if (!(c instanceof JComponent) || (c instanceof ActionButton) || (c instanceof ComboBoxWithWidePopup<?>)) { return false; } return true; } private static @NotNull RelativePoint defaultPointUnderneathOf(@NotNull Component aComponent) { Point offset = new Point(JBUIScale.scale(2), 0); return new AnchoredPoint(AnchoredPoint.Anchor.BOTTOM_LEFT, aComponent, offset); } private static @NotNull RelativePoint pointUnderneathOfAlignedHorizontally(@NotNull Component comp) { if (!(comp instanceof JComponent jcomp)) return defaultPointUnderneathOf(comp); Point offset = new Point(calcHorizontalAlignment(jcomp), 0); return new AnchoredPoint(AnchoredPoint.Anchor.BOTTOM_LEFT, comp, offset); } private static int calcHorizontalAlignment(JComponent jcomp) { int componentLeftInset; if (jcomp instanceof PopupAlignableComponent pac) { componentLeftInset = pac.getLeftGap(); } else { componentLeftInset = jcomp.getInsets().left; if (jcomp instanceof AbstractButton button) { Insets margin = button.getMargin(); if (margin != null) { componentLeftInset += margin.left; } } } int popupLeftInset = JBUI.CurrentTheme.Popup.Selection.LEFT_RIGHT_INSET.get() + JBUI.CurrentTheme.Popup.Selection.innerInsets().left; int res = componentLeftInset - popupLeftInset; return res; } private static void fitXToComponentScreen(@NotNull Point screenPoint, @NotNull Component comp) { var componentScreen = ScreenUtil.getScreenRectangle(comp); if (screenPoint.x < componentScreen.x) { if (LOG.isDebugEnabled()) { LOG.debug("Moving the popup X coordinate from " + screenPoint.x + " to " + componentScreen.x + " to fit into the component screen " + componentScreen); } screenPoint.x = componentScreen.x; } if (screenPoint.x > componentScreen.x + componentScreen.width) { if (LOG.isDebugEnabled()) { LOG.debug("Moving the popup X coordinate from " + screenPoint.x + " to " + (componentScreen.x + componentScreen.width) + " to fit into the component screen " + componentScreen); } screenPoint.x = componentScreen.x + componentScreen.width; } } @Override public void show(@NotNull RelativePoint aPoint) { if (UiInterceptors.tryIntercept(this, aPoint)) return; HelpTooltip.setMasterPopup(aPoint.getOriginalComponent(), this); Point screenPoint = aPoint.getScreenPoint(); fitXToComponentScreen(screenPoint, aPoint.getComponent()); stretchContentToOwnerIfNecessary(aPoint.getOriginalComponent()); show(aPoint.getComponent(), screenPoint.x, screenPoint.y, false); } @Override public void showInScreenCoordinates(@NotNull Component owner, @NotNull Point point) { show(owner, point.x, point.y, false); } @Override public @NotNull Point getBestPositionFor(@NotNull DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor != null && editor.getComponent().isShowing()) { return getBestPositionFor(editor).getScreenPoint(); } return relativePointByQuickSearch(dataContext).getScreenPoint(); } @Override public void showInBestPositionFor(@NotNull DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext); if (editor != null && editor.getComponent().isShowing()) { showInBestPositionFor(editor); } else { show(relativePointByQuickSearch(dataContext)); } } @Override public void showInFocusCenter() { final Component focused = getWndManager().getFocusedComponent(myProject); if (focused != null) { showInCenterOf(focused); } else { final WindowManager manager = WindowManager.getInstance(); final JFrame frame = myProject != null ? manager.getFrame(myProject) : manager.findVisibleFrame(); showInCenterOf(frame.getRootPane()); } } private @NotNull RelativePoint relativePointByQuickSearch(@NotNull DataContext dataContext) { Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(dataContext); if (dominantArea != null) { final Component focusedComponent = getWndManager().getFocusedComponent(myProject); if (focusedComponent != null) { Window window = SwingUtilities.windowForComponent(focusedComponent); JLayeredPane layeredPane; if (window instanceof JFrame) { layeredPane = ((JFrame)window).getLayeredPane(); } else if (window instanceof JDialog) { layeredPane = ((JDialog)window).getLayeredPane(); } else if (window instanceof JWindow) { layeredPane = ((JWindow)window).getLayeredPane(); } else { throw new IllegalStateException("cannot find parent window: project=" + myProject + "; window=" + window); } return relativePointWithDominantRectangle(layeredPane, dominantArea); } } RelativePoint location; Component contextComponent = dataContext.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT); if (contextComponent == myComponent) { location = new RelativePoint(myComponent, new Point()); } else { location = JBPopupFactory.getInstance().guessBestPopupLocation(dataContext); } if (myLocateWithinScreen) { Point screenPoint = location.getScreenPoint(); Rectangle rectangle = new Rectangle(screenPoint, getSizeForPositioning()); Rectangle screen = ScreenUtil.getScreenRectangle(screenPoint); ScreenUtil.moveToFit(rectangle, screen, null); location = new RelativePoint(rectangle.getLocation()).getPointOn(location.getComponent()); } return location; } public Dimension getSizeForPositioning() { Dimension size = getSize(); if (size == null) { size = getStoredSize(); } if (size == null) { Dimension contentPreferredSize = myContent.getPreferredSize(); Dimension titlePreferredSize = getTitle().getPreferredSize(); size = new JBDimension(Math.max(contentPreferredSize.width, titlePreferredSize.width), contentPreferredSize.height + titlePreferredSize.height, true); } return size; } @Override public void showInBestPositionFor(@NotNull Editor editor) { // Intercept before the following assert; otherwise assertion may fail if (UiInterceptors.tryIntercept(this)) return; assert UIUtil.isShowing(editor.getContentComponent()) : "Editor must be showing on the screen"; // Set the accessible parent so that screen readers don't announce // a window context change -- the tooltip is "logically" hosted // inside the component (e.g. editor) it appears on top of. AccessibleContextUtil.setParent(myComponent, editor.getContentComponent()); show(getBestPositionFor(editor)); } @ApiStatus.Internal public final @NotNull RelativePoint getBestPositionFor(@NotNull Editor editor) { if (editor instanceof EditorEx) { DataContext context = ((EditorEx)editor).getDataContext(); PopupLocator popupLocator = PlatformDataKeys.CONTEXT_MENU_LOCATOR.getData(context); if (popupLocator != null) { Point result = popupLocator.getPositionFor(this); if (result != null) return new RelativePoint(result); } Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(context); if (dominantArea != null && !myRequestFocus) { final JLayeredPane layeredPane = editor.getContentComponent().getRootPane().getLayeredPane(); return relativePointWithDominantRectangle(layeredPane, dominantArea); } } return guessBestPopupLocation(editor); } private @NotNull RelativePoint guessBestPopupLocation(@NotNull Editor editor) { RelativePoint preferredLocation = JBPopupFactory.getInstance().guessBestPopupLocation(editor); Dimension targetSize = getSizeForPositioning(); Point preferredPoint = preferredLocation.getScreenPoint(); Point result = getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(preferredPoint, targetSize, editor); if (myLocateWithinScreen) { Rectangle rectangle = new Rectangle(result, targetSize); Rectangle screen = ScreenUtil.getScreenRectangle(preferredPoint); ScreenUtil.moveToFit(rectangle, screen, null); result = rectangle.getLocation(); } return toRelativePoint(result, preferredLocation.getComponent()); } private static @NotNull RelativePoint toRelativePoint(@NotNull Point screenPoint, @Nullable Component component) { if (component == null) { return RelativePoint.fromScreen(screenPoint); } SwingUtilities.convertPointFromScreen(screenPoint, component); return new RelativePoint(component, screenPoint); } private static @NotNull Point getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(@NotNull Point originalLocation, @NotNull Dimension popupSize, @NotNull Editor editor) { Rectangle preferredBounds = new Rectangle(originalLocation, popupSize); Rectangle adjustedBounds = new Rectangle(preferredBounds); ScreenUtil.moveRectangleToFitTheScreen(adjustedBounds); if (preferredBounds.y - adjustedBounds.y <= 0) { return originalLocation; } int adjustedY = preferredBounds.y - editor.getLineHeight() - popupSize.height; if (adjustedY < 0) { return originalLocation; } return new Point(preferredBounds.x, adjustedY); } private @NotNull RelativePoint relativePointWithDominantRectangle(@NotNull JLayeredPane layeredPane, @NotNull Rectangle bounds) { Dimension size = getSizeForPositioning(); List<Supplier<Point>> optionsToTry = Arrays.asList(() -> new Point(bounds.x + bounds.width, bounds.y), () -> new Point(bounds.x - size.width, bounds.y)); for (Supplier<Point> option : optionsToTry) { Point location = option.get(); SwingUtilities.convertPointToScreen(location, layeredPane); Point adjustedLocation = fitToScreenAdjustingVertically(location, size); if (adjustedLocation != null) return new RelativePoint(adjustedLocation).getPointOn(layeredPane); } setDimensionServiceKey(null); // going to cut width Point rightTopCorner = new Point(bounds.x + bounds.width, bounds.y); final Point rightTopCornerScreen = (Point)rightTopCorner.clone(); SwingUtilities.convertPointToScreen(rightTopCornerScreen, layeredPane); Rectangle screen = ScreenUtil.getScreenRectangle(rightTopCornerScreen.x, rightTopCornerScreen.y); final int spaceOnTheLeft = bounds.x; final int spaceOnTheRight = screen.x + screen.width - rightTopCornerScreen.x; if (spaceOnTheLeft > spaceOnTheRight) { myComponent.setPreferredSize(new Dimension(spaceOnTheLeft, Math.max(size.height, JBUIScale.scale(200)))); return new RelativePoint(layeredPane, new Point(0, bounds.y)); } else { myComponent.setPreferredSize(new Dimension(spaceOnTheRight, Math.max(size.height, JBUIScale.scale(200)))); return new RelativePoint(layeredPane, rightTopCorner); } } // positions are relative to screen private static @Nullable Point fitToScreenAdjustingVertically(@NotNull Point position, @NotNull Dimension size) { Rectangle screenRectangle = ScreenUtil.getScreenRectangle(position); Rectangle rectangle = new Rectangle(position, size); if (rectangle.height > screenRectangle.height || rectangle.x < screenRectangle.x || rectangle.x + rectangle.width > screenRectangle.x + screenRectangle.width) { return null; } ScreenUtil.moveToFit(rectangle, screenRectangle, null); return rectangle.getLocation(); } public @NotNull Dimension getPreferredContentSize() { if (myForcedSize != null) { return myForcedSize; } Dimension size = getStoredSize(); if (size != null) return size; return myComponent.getPreferredSize(); } @Override public final void closeOk(@Nullable InputEvent e) { setOk(true); myFinalRunnable = FunctionUtil.composeRunnables(myOkHandler, myFinalRunnable); cancel(e); } @Override public final void cancel() { InputEvent inputEvent = null; AWTEvent event = IdeEventQueue.getInstance().getTrueCurrentEvent(); if (event instanceof InputEvent ie && myPopup != null) { Window window = myPopup.getWindow(); if (window != null && UIUtil.isDescendingFrom(ie.getComponent(), window)) { inputEvent = ie; } } cancel(inputEvent); } @Override public void setRequestFocus(boolean requestFocus) { myRequestFocus = requestFocus; } @Override public void cancel(InputEvent e) { if (myState == State.CANCEL || myState == State.DISPOSE) { return; } debugState("cancel popup", State.SHOWN); myState = State.CANCEL; if (isDisposed()) return; if (LOG.isTraceEnabled()) LOG.trace(new Exception("cancel popup stack trace")); if (myPopup != null) { if (!canClose()) { debugState("cannot cancel popup", State.CANCEL); myState = State.SHOWN; return; } storeDimensionSize(); if (myUseDimServiceForXYLocation) { final JRootPane root = myComponent.getRootPane(); if (root != null) { Point location = getLocationOnScreen(root.getParent()); if (location != null) { storeLocation(fixLocateByContent(location, true)); } } } if (e instanceof MouseEvent) { IdeEventQueue.getInstance().blockNextEvents((MouseEvent)e); } myPopup.hide(false); modalEntitiesWhenShown = null; if (ApplicationManager.getApplication() != null) { StackingPopupDispatcher.getInstance().onPopupHidden(this); } disposePopup(); } myListeners.forEach(listener -> listener.onClosed(new LightweightWindowEvent(this, myOk))); Disposer.dispose(this, false); if (myProjectDisposable != null) { Disposer.dispose(myProjectDisposable); } } private void disposePopup() { all.remove(this); if (myPopup != null) { resetWindow(); myPopup.hide(true); } myPopup = null; } @Override public boolean canClose() { return (!anyModalWindowsKeepPopupOpen() && (myCallBack == null || myCallBack.compute().booleanValue()) && !preventImmediateClosingAfterOpening()) || myDisposed; // check for myDisposed last to allow `myCallBack` to be executed } boolean anyModalWindowsKeepPopupOpen() { var modalEntitiesNow = LaterInvocator.getCurrentModalEntities(); var i = 0; for (; i < modalEntitiesNow.length && i < modalEntitiesWhenShown.length; ++i) { if (modalEntitiesNow[i] != modalEntitiesWhenShown[i]) { break; } } for (; i < modalEntitiesNow.length; ++i) { if (modalEntitiesNow[i] instanceof Window modalWindow && ClientProperty.isTrue(modalWindow, DialogWrapper.KEEP_POPUPS_OPEN)) { return true; } } return false; } private boolean preventImmediateClosingAfterOpening() { // this is a workaround for X.Org bug https://gitlab.freedesktop.org/xorg/xserver/-/issues/1347 // it affects only non-override-redirect windows, hence the check for myNormalWindowLevel return UIUtil.isXServerOnWindows() && myNormalWindowLevel && IdeEventQueue.getInstance().getTrueCurrentEvent().getID() == WindowEvent.WINDOW_DEACTIVATED && System.currentTimeMillis() < myOpeningTime + 1000; } @Override public boolean isVisible() { if (myPopup == null) return false; Window window = myPopup.getWindow(); if (window != null && window.isShowing()) return true; if (LOG.isDebugEnabled()) LOG.debug("window hidden, popup's state: " + myState); return false; } @Override public void show(final @NotNull Component owner) { stretchContentToOwnerIfNecessary(owner); show(owner, -1, -1, true); } public void show(@NotNull Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) { if (UiInterceptors.tryIntercept(this)) return; if (ApplicationManager.getApplication() != null && ApplicationManager.getApplication().isHeadlessEnvironment()) return; if (isDisposed()) { throw new IllegalStateException("Popup was already disposed. Recreate a new instance to show again"); } ThreadingAssertions.assertEventDispatchThread(); assert myState == State.INIT : "Popup was already shown. Recreate a new instance to show again."; debugState("show popup", State.INIT); myState = State.SHOWING; installProjectDisposer(); addActivity(); final boolean shouldShow = beforeShow(); if (!shouldShow) { removeActivity(); debugState("rejected to show popup", State.SHOWING); myState = State.INIT; return; } prepareToShow(); installWindowHook(this); Object roundedCornerParams = null; if (WindowRoundedCornersManager.isAvailable()) { PopupCornerType cornerType = getUserData(PopupCornerType.class); if (cornerType == null) { cornerType = PopupCornerType.RoundedWindow; } if (cornerType != PopupCornerType.None) { if ((SystemInfoRt.isMac && myPopupBorderColor != null && UIUtil.isUnderDarcula()) || SystemInfoRt.isWindows) { roundedCornerParams = new Object[]{cornerType, myPopupBorderColor == null ? JBUI.CurrentTheme.Popup.borderColor(true) : myPopupBorderColor}; // must set the border before calculating size below myContent.setBorder(myPopupBorder = PopupBorder.Factory.createEmpty()); } else { roundedCornerParams = cornerType; } } } if (LOG.isDebugEnabled()) { LOG.debug("START calculating bounds for a popup at (" + aScreenX + "," + aScreenY + "," + (considerForcedXY ? "forced" : "not forced") + ") for " + owner); } Dimension sizeToSet = getStoredSize(); if (LOG.isDebugEnabled()) { LOG.debug("The stored size for key " + myDimensionServiceKey + " is " + sizeToSet); } if (myForcedSize != null) { sizeToSet = myForcedSize; if (LOG.isDebugEnabled()) { LOG.debug("Forced the size to " + sizeToSet); } } Rectangle screen = ScreenUtil.getScreenRectangle(aScreenX, aScreenY); if (LOG.isDebugEnabled()) { LOG.debug("The screen rectangle for (" + aScreenX + "," + aScreenY + ") is " + screen); } if (myLocateWithinScreen) { Dimension preferredSize = myContent.getPreferredSize(); if (LOG.isDebugEnabled()) { LOG.debug("The preferred size is " + preferredSize); } Object o = myContent.getClientProperty(FIRST_TIME_SIZE); if (sizeToSet == null && o instanceof Dimension) { if (LOG.isDebugEnabled()) { LOG.debug("The size from the FIRST_TIME_SIZE property is " + o); } int w = ((Dimension)o).width; int h = ((Dimension)o).height; if (w > 0) preferredSize.width = w; if (h > 0) preferredSize.height = h; sizeToSet = preferredSize; if (LOG.isDebugEnabled()) { LOG.debug("The size is set to " + sizeToSet); } } Dimension size = sizeToSet != null ? sizeToSet : preferredSize; if (size.width > screen.width) { size.width = screen.width; sizeToSet = size; if (LOG.isDebugEnabled()) { LOG.debug("Resized to fit the screen width: " + sizeToSet); } } if (size.height > screen.height) { size.height = screen.height; sizeToSet = size; if (LOG.isDebugEnabled()) { LOG.debug("Resized to fit the screen height: " + sizeToSet); } } } if (sizeToSet != null) { Insets insets = myContent.getInsets(); JBInsets.addTo(sizeToSet, insets); if (LOG.isDebugEnabled()) { LOG.debug("Added insets (" + insets + "), the size is now: " + sizeToSet); } Dimension minimumSize = myContent.getMinimumSize(); sizeToSet.width = Math.max(sizeToSet.width, minimumSize.width); sizeToSet.height = Math.max(sizeToSet.height, minimumSize.height); if (LOG.isDebugEnabled()) { LOG.debug("Coerced to the minimum size (" + minimumSize + "): " + sizeToSet); } myContent.setSize(sizeToSet); myContent.setPreferredSize(sizeToSet); } Point xy = new Point(aScreenX, aScreenY); boolean adjustXY = true; if (myUseDimServiceForXYLocation) { Point storedLocation = getStoredLocation(); if (LOG.isDebugEnabled()) { LOG.debug("The stored location for key " + myDimensionServiceKey + " is " + storedLocation); } if (storedLocation != null) { xy = storedLocation; adjustXY = false; } } if (adjustXY) { final Insets insets = myContent.getInsets(); if (insets != null) { xy.x -= insets.left; xy.y -= insets.top; if (LOG.isDebugEnabled()) { LOG.debug("Location after adjusting by insets (" + insets + ") is " + xy); } } } if (considerForcedXY && myForcedLocation != null) { xy = myForcedLocation; if (LOG.isDebugEnabled()) { LOG.debug("Location forced to " + myForcedLocation); } } fixLocateByContent(xy, false); if (LOG.isDebugEnabled()) { LOG.debug("Location after fixing by content is " + xy); } Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize()); if (LOG.isDebugEnabled()) { LOG.debug("Target bounds " + targetBounds); } if (targetBounds.width > screen.width || targetBounds.height > screen.height) { StringBuilder sb = new StringBuilder("popup preferred size is bigger than screen: "); sb.append(targetBounds.width).append("x").append(targetBounds.height); IJSwingUtilities.appendComponentClassNames(sb, myContent); LOG.warn(sb.toString()); } Rectangle original = new Rectangle(targetBounds); if (myLocateWithinScreen) { ScreenUtil.moveToFit(targetBounds, screen, null); if (LOG.isDebugEnabled()) { LOG.debug("Target bounds after moving to fit the screen: " + targetBounds); } } else { //even when LocateWithinScreen option is disabled, popup should not be shown in invisible area fitToVisibleArea(targetBounds); if (LOG.isDebugEnabled()) { LOG.debug("Target bounds after moving to fit the visible area: " + targetBounds); } } if (LOG.isDebugEnabled()) { LOG.debug("END calculating popup bounds, the result is " + targetBounds); } if (myMouseOutCanceller != null) { myMouseOutCanceller.myEverEntered = targetBounds.equals(original); } // prevent hiding of a floating toolbar Point pointOnOwner = new Point(aScreenX, aScreenY); SwingUtilities.convertPointFromScreen(pointOnOwner, owner); if (ActionToolbarImpl.isInPopupToolbar(SwingUtilities.getDeepestComponentAt(owner, pointOnOwner.x, pointOnOwner.y))) { AutoPopupSupportingListener.installOn(this); } myOwner = getFrameOrDialog(owner); // use correct popup owner for non-modal dialogs too if (myOwner == null) { myOwner = owner; } myRequestorComponent = owner; myPopupType = getMostSuitablePopupType(); myNativePopup = myPopupType != PopupComponentFactory.PopupType.DIALOG; Component popupOwner = myOwner; if (popupOwner instanceof RootPaneContainer root && !(popupOwner instanceof IdeFrame && !Registry.is("popup.fix.ide.frame.owner"))) { // JDK uses cached heavyweight popup for a window ancestor popupOwner = root.getRootPane(); LOG.debug("popup owner fixed for JDK cache"); } if (StartupUiUtil.isWaylandToolkit()) { // targetBounds are "screen" coordinates, which in Wayland means that they // are relative to the nearest toplevel (Window). // But popups in Wayland are expected to be relative to popup's "owner"; // let's re-set the owner to be that window. popupOwner = popupOwner instanceof Window ? popupOwner : SwingUtilities.getWindowAncestor(popupOwner); // The Wayland server may refuse to show a popup whose top-left corner // is located outside of parent window's bounds Rectangle okBounds = new Rectangle(); okBounds.width = popupOwner.getWidth() + targetBounds.width; okBounds.height = popupOwner.getHeight() + targetBounds.height; ScreenUtil.moveToFit(targetBounds, okBounds, new Insets(0, 0, 1, 1)); } if (LOG.isDebugEnabled()) { LOG.debug("expected preferred size: " + myContent.getPreferredSize()); } PopupComponentFactory factory = PopupComponentFactory.getCurrentInstance(); myPopup = factory.createPopupComponent(myPopupType, popupOwner, myContent, targetBounds.x, targetBounds.y, this); if (LOG.isDebugEnabled()) { LOG.debug("START adjusting popup bounds after creation"); LOG.debug(" actual preferred size: " + myContent.getPreferredSize()); } if (targetBounds.width != myContent.getWidth() || targetBounds.height != myContent.getHeight()) { // JDK uses cached heavyweight popup that is not initialized properly LOG.debug("the expected size (" + targetBounds.getSize() + ") is not equal to the actual size (" + myContent.getSize() + ")"); Window popup = myPopup.getWindow(); if (popup != null) { popup.setSize(targetBounds.width, targetBounds.height); if (myContent.getParent().getComponentCount() != 1) { LOG.debug("unexpected count of components in heavy-weight popup"); } } else { LOG.debug("cannot fix size for non-heavy-weight popup because its window is null"); } } if (myResizable) { final JRootPane root = myContent.getRootPane(); final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root); root.setGlassPane(glass); WindowResizeListenerEx resizeListener = new WindowResizeListenerEx( glass, myComponent, myMovable ? JBUI.insets(4) : JBUI.insets(0, 0, 4, 4), null); resizeListener.install(this); resizeListener.addResizeListeners(() -> { myResizeListeners.forEach(Runnable::run); }); myResizeListener = resizeListener; } setIsMovable(myMovable); notifyListeners(); myPopup.setRequestFocus(myRequestFocus); final Window window = getContentWindow(myContent); if (window instanceof IdeFrame) { LOG.warn("Lightweight popup is shown using AbstractPopup class. But this class is not supposed to work with lightweight popups."); } window.setFocusableWindowState(myRequestFocus); window.setFocusable(myRequestFocus); // Swing popup default always on top state is set in true window.setAlwaysOnTop(false); if (myFocusable) { FocusTraversalPolicy focusTraversalPolicy = new FocusTraversalPolicy() { @Override public Component getComponentAfter(Container aContainer, Component aComponent) { return getComponent(); } private Component getComponent() { return myPreferredFocusedComponent == null ? myComponent : myPreferredFocusedComponent; } @Override public Component getComponentBefore(Container aContainer, Component aComponent) { return getComponent(); } @Override public Component getFirstComponent(Container aContainer) { return getComponent(); } @Override public Component getLastComponent(Container aContainer) { return getComponent(); } @Override public Component getDefaultComponent(Container aContainer) { return getComponent(); } }; window.setFocusTraversalPolicy(focusTraversalPolicy); Disposer.register(this, () -> window.setFocusTraversalPolicy(null)); } window.setAutoRequestFocus(myRequestFocus); if (roundedCornerParams != null) { WindowRoundedCornersManager.setRoundedCorners(window, roundedCornerParams); } if (myNormalWindowLevel && !window.isDisplayable()) { window.setType(Window.Type.NORMAL); } myWindow = window; if (LOG.isDebugEnabled()) { LOG.debug("Setting minimum size to " + myMinSize); } setMinimumSize(myMinSize); if (LOG.isDebugEnabled()) { LOG.debug("Minimum size set to " + window.getMinimumSize()); } TouchbarSupport.showPopupItems(this, myContent); modalEntitiesWhenShown = LaterInvocator.getCurrentModalEntities(); myPopup.show(); Rectangle bounds = window.getBounds(); if (LOG.isDebugEnabled()) { LOG.debug("END adjusting popup bounds after creation, the result is: " + bounds + ", starting final post-show adjustments"); } PopupLocationTracker.register(this); if (bounds.width > screen.width || bounds.height > screen.height) { if (LOG.isDebugEnabled()) { LOG.debug("Bounds won't fit into the screen, adjusting"); } ScreenUtil.fitToScreen(bounds); window.setBounds(bounds); } if (LOG.isDebugEnabled()) { GraphicsDevice device = ScreenUtil.getScreenDevice(bounds); StringBuilder sb = new StringBuilder("Popup is shown with bounds " + bounds); if (device != null) sb.append(" on screen with ID \"").append(device.getIDstring()).append("\""); LOG.debug(sb.toString()); } WindowAction.setEnabledFor(myPopup.getWindow(), myResizable); myWindowListener = new MyWindowListener(); window.addWindowListener(myWindowListener); if (myWindow != null) { // dialog wrapper-based popups do this internally through peer, // for other popups like jdialog-based we should exclude them manually, but // we still have to be able to use IdeFrame as parent if (!myMayBeParent && !(myWindow instanceof Frame)) { WindowManager.getInstance().doNotSuggestAsParent(myWindow); } } final Runnable afterShow = () -> { if (isDisposed()) { LOG.debug("popup is disposed after showing"); removeActivity(); return; } if ((myPreferredFocusedComponent instanceof AbstractButton || myPreferredFocusedComponent instanceof JTextField) && myFocusable) { IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent); } removeActivity(); afterShow(); }; if (myRequestFocus) { if (myPreferredFocusedComponent != null) { myPreferredFocusedComponent.requestFocus(); } else { _requestFocus(); } window.setAutoRequestFocus(myRequestFocus); SwingUtilities.invokeLater(afterShow); } else { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { if (isDisposed()) { removeActivity(); return; } afterShow.run(); }); } debugState("popup shown", State.SHOWING); myState = State.SHOWN; myOpeningTime = System.currentTimeMillis(); afterShowSync(); } public void notifyListeners() { myListeners.forEach(listener -> listener.beforeShown(new LightweightWindowEvent(this))); } private static void fitToVisibleArea(Rectangle targetBounds) { if (StartupUiUtil.isWaylandToolkit()) return; // Wrt screen edges, only the Wayland server can reliably position popups Point topLeft = new Point(targetBounds.x, targetBounds.y); Point bottomRight = new Point((int)targetBounds.getMaxX(), (int)targetBounds.getMaxY()); Rectangle topLeftScreen = ScreenUtil.getScreenRectangle(topLeft); Rectangle bottomRightScreen = ScreenUtil.getScreenRectangle(bottomRight); if (topLeft.x < topLeftScreen.x || topLeft.y < topLeftScreen.y || bottomRight.x > bottomRightScreen.getMaxX() || bottomRight.y > bottomRightScreen.getMaxY()) { GraphicsDevice device = ScreenUtil.getScreenDevice(targetBounds); Rectangle mostAppropriateScreenRectangle = device != null ? ScreenUtil.getScreenRectangle(device.getDefaultConfiguration()) : ScreenUtil.getMainScreenBounds(); ScreenUtil.moveToFit(targetBounds, mostAppropriateScreenRectangle, null); } } public void focusPreferredComponent() { _requestFocus(); } private void installProjectDisposer() { final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (c != null) { final DataContext context = DataManager.getInstance().getDataContext(c); final Project project = CommonDataKeys.PROJECT.getData(context); if (project != null) { myProjectDisposable = () -> { if (!isDisposed()) { Disposer.dispose(this); } }; Disposer.register(project, myProjectDisposable); } } } //Sometimes just after popup was shown the WINDOW_ACTIVATED cancels it private static void installWindowHook(final @NotNull AbstractPopup popup) { if (popup.myCancelOnWindow) { popup.myCancelOnWindow = false; new Alarm(popup).addRequest(() -> popup.myCancelOnWindow = true, 100); } } private void addActivity() { UiActivityMonitor.getInstance().addActivity(myActivityKey); } private void removeActivity() { UiActivityMonitor.getInstance().removeActivity(myActivityKey); } private void prepareToShow() { final MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Rectangle bounds = getBoundsOnScreen(myContent); if (bounds != null) { bounds.x -= 2; bounds.y -= 2; bounds.width += 4; bounds.height += 4; } if (bounds == null || !bounds.contains(e.getLocationOnScreen())) { cancel(); } } }; myContent.addMouseListener(mouseAdapter); Disposer.register(this, () -> myContent.removeMouseListener(mouseAdapter)); myContent.addKeyListener(mySpeedSearch); if (myCancelOnMouseOutCallback != null || myCancelOnWindow) { installMouseOutCanceller(); } ChildFocusWatcher focusWatcher = new ChildFocusWatcher(myContent) { @Override protected void onFocusGained(final FocusEvent event) { setWindowActive(true); } @Override protected void onFocusLost(final FocusEvent event) { setWindowActive(false); } }; Disposer.register(this, focusWatcher); mySpeedSearchPatternField = new SearchTextField(false) { @Override protected void onFieldCleared() { mySpeedSearch.reset(); } }; mySpeedSearchPatternField.getTextEditor().setFocusable(mySpeedSearchAlwaysShown); customizeSearchFieldLook(mySpeedSearchPatternField, mySpeedSearchAlwaysShown); if (mySpeedSearchAlwaysShown) { setHeaderComponent(mySpeedSearchPatternField); } } public static void customizeSearchFieldLook(@NotNull SearchTextField searchTextField, boolean isAlwaysShown) { JBTextField textField = searchTextField.getTextEditor(); if (ExperimentalUI.isNewUI()) { searchTextField.setBackground(JBUI.CurrentTheme.Popup.BACKGROUND); textField.setOpaque(false); textField.putClientProperty("TextFieldWithoutMargins", true); textField.putClientProperty(DarculaUIUtil.COMPACT_PROPERTY, true); textField.putClientProperty("TextField.NoMinHeightBounds", true); EmptyBorder outsideBorder = new EmptyBorder(JBUI.CurrentTheme.Popup.searchFieldBorderInsets()); Border lineBorder = JBUI.Borders.customLine(JBUI.CurrentTheme.Popup.separatorColor(), 0, 0, 1, 0); searchTextField.setBorder(JBUI.Borders.compound(outsideBorder, lineBorder, new EmptyBorder(JBUI.CurrentTheme.Popup.searchFieldInputInsets()))); textField.setBorder(JBUI.Borders.empty()); } else { if (isAlwaysShown) { searchTextField.setBorder(JBUI.Borders.customLine(JBUI.CurrentTheme.BigPopup.searchFieldBorderColor(), 1, 0, 1, 0)); textField.setBorder(JBUI.Borders.empty()); } } if (SystemInfo.isMac) { RelativeFont.TINY.install(searchTextField); } } private void updateMaskAndAlpha(Window window) { if (window == null) return; if (!window.isDisplayable() || !window.isShowing()) return; final WindowManagerEx wndManager = getWndManager(); if (wndManager == null) return; if (!wndManager.isAlphaModeEnabled(window)) return; if (myAlpha != myLastAlpha) { wndManager.setAlphaModeRatio(window, myAlpha); myLastAlpha = myAlpha; } if (myMaskProvider != null) { final Dimension size = window.getSize(); Shape mask = myMaskProvider.getMask(size); wndManager.setWindowMask(window, mask); } WindowManagerEx.WindowShadowMode mode = myShadowed ? WindowManagerEx.WindowShadowMode.NORMAL : WindowManagerEx.WindowShadowMode.DISABLED; WindowManagerEx.getInstanceEx().setWindowShadow(window, mode); } private static WindowManagerEx getWndManager() { return ApplicationManager.getApplication() != null ? WindowManagerEx.getInstanceEx() : null; } @Override public boolean isDisposed() { return myContent == null; } protected boolean beforeShow() { if (ApplicationManager.getApplication() == null || !LoadingState.COMPONENTS_REGISTERED.isOccurred()) return true; StackingPopupDispatcher.getInstance().onPopupShown(this, myInStack); return true; } protected void afterShow() { } protected void afterShowSync() { } protected final boolean requestFocus() { if (!myFocusable) return false; getFocusManager().doWhenFocusSettlesDown(() -> _requestFocus()); return true; } private void _requestFocus() { if (!myFocusable) return; JComponent toFocus = ObjectUtils.chooseNotNull(myPreferredFocusedComponent, mySpeedSearchAlwaysShown ? mySpeedSearchPatternField : null); if (toFocus != null) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { if (!myDisposed) { IdeFocusManager.getGlobalInstance().requestFocus(toFocus, true); } }); } } private IdeFocusManager getFocusManager() { if (myProject != null) { return IdeFocusManager.getInstance(myProject); } if (myOwner != null) { return IdeFocusManager.findInstanceByComponent(myOwner); } return IdeFocusManager.findInstance(); } private static JComponent getTargetComponent(Component aComponent) { if (aComponent instanceof JComponent) { return (JComponent)aComponent; } if (aComponent instanceof RootPaneContainer) { return ((RootPaneContainer)aComponent).getRootPane(); } LOG.error("Cannot find target for:" + aComponent); return null; } private PopupComponentFactory.PopupType getMostSuitablePopupType() { boolean forceDialog = myMayBeParent || SystemInfo.isMac && !(myOwner instanceof IdeFrame) && myOwner.isShowing(); if (Registry.is("allow.dialog.based.popups")) { boolean noFocus = !myFocusable || !myRequestFocus; boolean cannotBeDialog = noFocus; // && SystemInfo.isXWindow if (!cannotBeDialog && (isPersistent() || forceDialog)) { return PopupComponentFactory.PopupType.DIALOG; } } if (myForcedHeavyweight || myResizable) { return PopupComponentFactory.PopupType.HEAVYWEIGHT; } return PopupComponentFactory.PopupType.DEFAULT; } @Override public @NotNull JComponent getContent() { return myContent; } public void setLocation(@NotNull RelativePoint p) { if (isBusy()) return; setLocation(p, myPopup); } private static void setLocation(@NotNull RelativePoint p, @Nullable PopupComponent popup) { if (popup == null) return; final Window wnd = popup.getWindow(); assert wnd != null; wnd.setLocation(p.getScreenPoint()); } @Override public void pack(boolean width, boolean height) { Dimension size = calculateSizeForPack(width, height); if (size == null) return; final Window window = getContentWindow(myContent); if (window != null && size != null) { window.setSize(size); } } @Nullable protected Dimension calculateSizeForPack(boolean width, boolean height) { if (!isVisible() || !width && !height || isBusy()) return null; Dimension size = getSize(); Dimension prefSize = myContent.computePreferredSize(); Point location = !myLocateWithinScreen ? null : getLocationOnScreen(); Rectangle screen = location == null ? null : ScreenUtil.getScreenRectangle(location); if (width) { size.width = prefSize.width; if (screen != null) { int delta = screen.width + screen.x - location.x; if (size.width > delta) { size.width = delta; } } } if (height) { if (size.width < prefSize.width) { if (!SystemInfo.isMac || Registry.is("mac.scroll.horizontal.gap")) { // we shrank horizontally - need to increase height to fit the horizontal scrollbar forHorizontalScrollBar(bar -> prefSize.height += bar.getPreferredSize().height); } } size.height = prefSize.height; if (screen != null) { int delta = screen.height + screen.y - location.y; if (size.height > delta) { size.height = delta; } } } return size; } public JComponent getComponent() { return myComponent; } public Project getProject() { return myProject; } @Override public void dispose() { ThreadingAssertions.assertEventDispatchThread(); if (myDisposed) { return; } myDisposed = true; if (myState == State.SHOWN) { LOG.debug("shown popup must be cancelled"); cancel(); } if (myState == State.DISPOSE) { return; } debugState("dispose popup", State.INIT, State.CANCEL); myState = State.DISPOSE; if (LOG.isDebugEnabled()) { LOG.debug("start disposing " + myContent); } Disposer.dispose(this, false); if (myPopup != null) { cancel(myDisposeEvent); } if (myContent != null) { Container parent = myContent.getParent(); if (parent != null) parent.remove(myContent); myContent.removeAll(); myContent.removeKeyListener(mySpeedSearch); } myContent = null; myPreferredFocusedComponent = null; myComponent = null; mySpeedSearchFoundInRootComponent = null; myCallBack = null; myListeners.clear(); removeMouseOutCanceller(); if (myFinalRunnable != null) { Runnable finalRunnable = myFinalRunnable; getFocusManager().doWhenFocusSettlesDown(() -> { try (AccessToken ignore = SlowOperations.startSection(SlowOperations.ACTION_PERFORM)) { finalRunnable.run(); } }); myFinalRunnable = null; } if (LOG.isDebugEnabled()) { LOG.debug("stop disposing content"); } } private void resetWindow() { if (myWindow != null && getWndManager() != null) { getWndManager().resetWindow(myWindow); if (myWindowListener != null) { myWindow.removeWindowListener(myWindowListener); } if (myWindow instanceof RootPaneContainer container) { JRootPane root = container.getRootPane(); root.putClientProperty(KEY, null); if (root.getGlassPane() instanceof IdeGlassPaneImpl) { // replace installed glass pane with the default one: JRootPane.createGlassPane() JPanel glass = new JPanel(); glass.setName(root.getName() + ".glassPane"); glass.setVisible(false); glass.setOpaque(false); root.setGlassPane(glass); } } myWindow = null; myWindowListener = null; } } private @Nullable Project getProjectDependingOnKey(String key) { return !key.startsWith(WindowStateService.USE_APPLICATION_WIDE_STORE_KEY_PREFIX) ? myProject : null; } public final @NotNull Dimension getContentSize() { Dimension size = myContent.getSize(); JBInsets.removeFrom(size, myContent.getInsets()); return size; } public void storeDimensionSize() { if (myDimensionServiceKey != null) { getWindowStateService(getProjectDependingOnKey(myDimensionServiceKey)).putSize(myDimensionServiceKey, getContentSize()); } } private void storeLocation(final Point xy) { if (myDimensionServiceKey != null) { getWindowStateService(getProjectDependingOnKey(myDimensionServiceKey)).putLocation(myDimensionServiceKey, xy); } } public static class MyContentPanel extends JPanel implements DataProvider { private @Nullable DataProvider myDataProvider; public MyContentPanel(@NotNull PopupBorder border) { super(new BorderLayout()); MnemonicHelper.init(this); putClientProperty(UIUtil.TEXT_COPY_ROOT, Boolean.TRUE); setBorder(border); } public Dimension computePreferredSize() { if (isPreferredSizeSet()) { Dimension setSize = getPreferredSize(); setPreferredSize(null); Dimension result = getPreferredSize(); setPreferredSize(setSize); return result; } return getPreferredSize(); } @Override public @Nullable Object getData(@NotNull @NonNls String dataId) { return myDataProvider != null ? myDataProvider.getData(dataId) : null; } public void setDataProvider(@Nullable DataProvider dataProvider) { myDataProvider = dataProvider; } } @ApiStatus.Internal public boolean isCancelOnClickOutside() { return myCancelOnClickOutside; } @ApiStatus.Internal public void setCancelOnClickOutside(boolean cancelOnClickOutside) { myCancelOnClickOutside = cancelOnClickOutside; } @ApiStatus.Internal public void setIsMovable(boolean movable) { myMovable = movable; if (!myMovable && myMoveListener != null) { final MyContentPanel saved = myContent; ListenerUtil.removeMouseListener(saved, myMoveListener); ListenerUtil.removeMouseMotionListener(saved, myMoveListener); myMoveListener = null; } if (myCaption != null && myMovable) { final WindowMoveListener moveListener = new WindowMoveListener(myCaption) { @Override public void mousePressed(final MouseEvent e) { if (e.isConsumed()) return; if (UIUtil.isCloseClick(e) && myCaption.isWithinPanel(e)) { cancel(); } else { super.mousePressed(e); } } }; moveListener.installTo(myCaption); final MyContentPanel saved = myContent; Disposer.register(this, () -> { ListenerUtil.removeMouseListener(saved, moveListener); ListenerUtil.removeMouseMotionListener(saved, moveListener); }); myMoveListener = moveListener; } } @ApiStatus.Internal public void setCancelOnWindowDeactivation(boolean cancelOnWindowDeactivation) { myCancelOnWindowDeactivation = cancelOnWindowDeactivation; } boolean isCancelOnWindowDeactivation() { return myCancelOnWindowDeactivation; } @ApiStatus.Internal public void setCancelOnMouseOutCallback(@Nullable MouseChecker checker) { myCancelOnMouseOutCallback = checker; if (checker != null && myMouseOutCanceller == null) { installMouseOutCanceller(); } else if (checker == null && myMouseOutCanceller != null && !myCancelOnWindow) { removeMouseOutCanceller(); } } @ApiStatus.Internal public void setCancelOnOtherWindowOpen(boolean cancel) { myCancelOnWindow = cancel; if (cancel && myMouseOutCanceller == null) { installMouseOutCanceller(); } else if (!cancel && myMouseOutCanceller != null && myCancelOnMouseOutCallback == null) { removeMouseOutCanceller(); } } private void installMouseOutCanceller() { myMouseOutCanceller = new Canceller(); Toolkit.getDefaultToolkit().addAWTEventListener(myMouseOutCanceller, WINDOW_EVENT_MASK | MOUSE_EVENT_MASK | MOUSE_MOTION_EVENT_MASK); } private void removeMouseOutCanceller() { if (myMouseOutCanceller != null) { final Toolkit toolkit = Toolkit.getDefaultToolkit(); // it may happen, but have no idea how // http://www.jetbrains.net/jira/browse/IDEADEV-21265 if (toolkit != null) { toolkit.removeAWTEventListener(myMouseOutCanceller); } } myMouseOutCanceller = null; } private final class Canceller implements AWTEventListener { private boolean myEverEntered; @Override public void eventDispatched(final AWTEvent event) { switch (event.getID()) { case WINDOW_ACTIVATED, WINDOW_GAINED_FOCUS -> { if (myCancelOnWindow && myPopup != null && isCancelNeeded((WindowEvent)event, myPopup.getWindow())) { ApplicationManager.getApplication().invokeLater(() ->cancel()); } } case MOUSE_ENTERED -> { if (withinPopup(event)) { myEverEntered = true; } } case MOUSE_MOVED, MOUSE_PRESSED -> { if (myCancelOnMouseOutCallback != null && myEverEntered && !withinPopup(event)) { if (myCancelOnMouseOutCallback.check((MouseEvent)event)) { cancel(); } } } } } private boolean withinPopup(@NotNull AWTEvent event) { final MouseEvent mouse = (MouseEvent)event; Rectangle bounds = getBoundsOnScreen(myContent); return bounds != null && bounds.contains(mouse.getLocationOnScreen()); } } @Override public void setLocation(@NotNull Point screenPoint) { // do not update the bounds programmatically if the user moves or resizes the popup if (!isBusy()) setBounds(new Point(screenPoint), null); } private static Window getContentWindow(@NotNull Component content) { Window window = SwingUtilities.getWindowAncestor(content); if (window == null) { if (LOG.isDebugEnabled()) { LOG.debug("no window ancestor for " + content); } } return window; } @Override public @NotNull Point getLocationOnScreen() { Window window = getContentWindow(myContent); Point screenPoint = window == null ? new Point() : window.getLocation(); fixLocateByContent(screenPoint, false); Insets insets = myContent.getInsets(); if (insets != null) { screenPoint.x += insets.left; screenPoint.y += insets.top; } return screenPoint; } @Override public void setSize(@NotNull Dimension size) { setSize(null, size); } @Override public void setSize(@Nullable Point location, @NotNull Dimension size) { // do not update the bounds programmatically if the user moves or resizes the popup if (!isBusy()) { setBounds(location, new Dimension(size)); if (myPopup != null) Optional.ofNullable(getContentWindow(myContent)).ifPresent(Container::validate); // to adjust content size } } public int getAdComponentHeight() { return myAdComponent != null ? myAdComponent.getPreferredSize().height + JBUIScale.scale(1) : 0; } protected boolean isAdVisible() { return myAdComponent != null && myAdComponent.isVisible(); } @Override public Dimension getSize() { if (myPopup != null) { final Window popupWindow = getContentWindow(myContent); if (popupWindow != null) { Dimension size = popupWindow.getSize(); size.height -= getAdComponentHeight(); return size; } } return myForcedSize; } @Override public void moveToFitScreen() { if (myPopup == null || isBusy()) return; final Window popupWindow = getContentWindow(myContent); if (popupWindow == null) return; Rectangle bounds = popupWindow.getBounds(); ScreenUtil.moveRectangleToFitTheScreen(bounds); // calling #setLocation or #setSize makes the window move for a bit because of tricky computations // our aim here is to just move the window as-is to make it fit the screen // no tricks are included here if (LOG.isDebugEnabled()) { LOG.debug("MoveToFitScreen x = " + bounds.x + " y = " + bounds.y + " width = " + bounds.width + " height = " + bounds.height); } popupWindow.setBounds(bounds); updateMaskAndAlpha(popupWindow); } @Override public void setBounds(@NotNull Rectangle bounds) { // do not update the bounds programmatically if the user moves or resizes the popup if (!isBusy()) setBounds(bounds.getLocation(), bounds.getSize()); } private void stretchContentToOwnerIfNecessary(@NotNull Component owner) { if (myForcedSize != null) return; if (!myStretchToOwnerWidth && !myStretchToOwnerHeight) return; Dimension filledSize = myContent.getPreferredSize(); if (myStretchToOwnerWidth) filledSize.width = owner.getWidth(); if (myStretchToOwnerHeight) filledSize.height = owner.getHeight(); myContent.setPreferredSize(filledSize); } /** * Updates the popup location and size at once. * Note that this internal implementation modifies input parameters. * * @param location a new popup location if needed * @param size a new popup size if needed */ private void setBounds(@Nullable Point location, @Nullable Dimension size) { if (size != null) size.height += getAdComponentHeight(); if (myPopup == null) { // store bounds to show popup later if (location != null) myForcedLocation = location; if (size != null) myForcedSize = size; } else { MyContentPanel content = myContent; if (content == null) return; Window window = getContentWindow(content); if (window == null) return; Insets insets = content.getInsets(); if (location == null) { location = window.getLocation(); // use current window location } else { fixLocateByContent(location, false); if (insets != null) { location.x -= insets.left; location.y -= insets.top; } } if (size == null) { size = window.getSize(); // use current window size } else { JBInsets.addTo(size, insets); if (LOG.isDebugEnabled()) { LOG.debug("Update content preferred size: width = " + size.width + " height = " + size.height); } content.setPreferredSize(size); size = window.getPreferredSize(); } if (LOG.isDebugEnabled()) { LOG.debug("SetBounds x = " + location.x + " y = " + location.y + " width = " + size.width + " height = " + size.height); } window.setBounds(location.x, location.y, size.width, size.height); window.setCursor(Cursor.getDefaultCursor()); updateMaskAndAlpha(window); } } @Override public void setCaption(@NotNull @NlsContexts.PopupTitle String title) { if (myCaption instanceof TitlePanel titlePanel) { titlePanel.setText(title); } } @Override public void setCaptionIcon(@Nullable Icon icon) { if (myCaption instanceof TitlePanel titlePanel) { titlePanel.setRegularIcon(icon); titlePanel.setInactiveIcon(icon); } } @Override public void setCaptionIconPosition(boolean left) { if (myCaption instanceof TitlePanel titlePanel) { titlePanel.setHorizontalTextPosition(left ? SwingUtilities.RIGHT : SwingUtilities.LEFT); } } protected void setSpeedSearchAlwaysShown() { assert myState == State.INIT; mySpeedSearchAlwaysShown = true; } private final class MyWindowListener extends WindowAdapter { @Override public void windowOpened(WindowEvent e) { updateMaskAndAlpha(myWindow); } @Override public void windowClosing(final WindowEvent e) { resetWindow(); cancel(); } } @Override public boolean isPersistent() { return !myCancelOnClickOutside && !myCancelOnWindow; } @Override public boolean isNativePopup() { return myNativePopup; } @Override public void setUiVisible(final boolean visible) { if (myPopup != null) { if (visible) { myPopup.show(); final Window window = getPopupWindow(); if (window != null && myRestoreWindowSize != null) { window.setSize(myRestoreWindowSize); myRestoreWindowSize = null; } } else { final Window window = getPopupWindow(); if (window != null) { myRestoreWindowSize = window.getSize(); window.setVisible(false); } } } } public Window getPopupWindow() { return myPopup != null ? myPopup.getWindow() : null; } @Override public void setUserData(@NotNull List<Object> userData) { myUserData = userData; } @Override public <T> T getUserData(final @NotNull Class<T> userDataClass) { if (myUserData != null) { for (Object o : myUserData) { if (userDataClass.isInstance(o)) { @SuppressWarnings("unchecked") T t = (T)o; return t; } } } return null; } @Override public boolean isModalContext() { return myModalContext; } @Override public boolean isFocused() { if (myComponent != null && isFocused(new Component[]{SwingUtilities.getWindowAncestor(myComponent)})) { return true; } return isFocused(myFocusOwners); } private static boolean isFocused(Component @NotNull [] components) { Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; Window wnd = ComponentUtil.getWindow(owner); for (Component each : components) { if (each != null && SwingUtilities.isDescendingFrom(owner, each)) { Window eachWindow = ComponentUtil.getWindow(each); if (eachWindow == wnd) { return true; } } } return false; } @Override public boolean isCancelKeyEnabled() { return myCancelKeyEnabled; } @ApiStatus.Internal public void setCancelKeyEnabled(boolean enabled) { myCancelKeyEnabled = enabled; } public @NotNull CaptionPanel getTitle() { return myCaption; } protected void setHeaderComponent(JComponent c) { boolean doRevalidate = false; if (myHeaderComponent != null) { myHeaderPanel.remove(myHeaderComponent); myHeaderComponent = null; doRevalidate = true; } if (c != null) { myHeaderPanel.add(c, BorderLayout.CENTER); myHeaderComponent = c; if (isVisible()) { final Dimension size = myContent.getSize(); if (size.height < c.getPreferredSize().height * 2) { size.height += c.getPreferredSize().height; setSize(size); } } doRevalidate = true; } if (doRevalidate) myContent.revalidate(); } public void setWarning(@NotNull @NlsContexts.Label String text) { myHeaderPanel.add(createWarning(text), BorderLayout.SOUTH); } protected @NotNull JComponent createWarning(@NotNull @NlsContexts.Label String text) { JBLabel label = new JBLabel(text, UIUtil.getBalloonWarningIcon(), SwingConstants.CENTER); label.setOpaque(true); Color color = HintUtil.getInformationColor(); label.setBackground(color); label.setBorder(BorderFactory.createLineBorder(color, 3)); return label; } @Override public void addListener(@NotNull JBPopupListener listener) { myListeners.add(0, listener); // last added first notified } @Override public void removeListener(@NotNull JBPopupListener listener) { myListeners.remove(listener); } protected void onSpeedSearchPatternChanged() { } @Override public Component getOwner() { return myRequestorComponent; } @Override public void setMinimumSize(Dimension size) { //todo: consider changing only the caption panel minimum size Dimension sizeFromHeader = calcHeaderSize(); if (size == null) { myMinSize = sizeFromHeader; } else { final int width = Math.max(size.width, sizeFromHeader.width); final int height = Math.max(size.height, sizeFromHeader.height); myMinSize = new Dimension(width, height); } if (myWindow != null) { Rectangle screenRectangle = ScreenUtil.getScreenRectangle(myWindow.getLocation()); int width = Math.min(screenRectangle.width, myMinSize.width); int height = Math.min(screenRectangle.height, myMinSize.height); myWindow.setMinimumSize(new Dimension(width, height)); } } public Dimension getMinimumSize() { return myMinSize != null ? myMinSize : calcHeaderSize(); } /** * Use this method if you need the popup to have the same width as the owner * @see JBPopup#show(Component) for the meaning of the owner * * Note that setting owner.getWidth() to popup beforehand won't work in remote development scenario */ public void setStretchToOwnerWidth(boolean stretchToOwnerWidth) { myStretchToOwnerWidth = stretchToOwnerWidth; } /** * Use this method if you need the popup to have the same height as the owner * @see JBPopup#show(Component) for the meaning of the owner * * Note that setting owner.getHeight() to popup beforehand won't work in remote development scenario */ public void setStretchToOwnerHeight(boolean stretchToOwnerHeight) { myStretchToOwnerHeight = stretchToOwnerHeight; } private @NotNull Dimension calcHeaderSize() { Dimension sizeFromHeader = myHeaderPanel.getPreferredSize(); if (sizeFromHeader == null) { sizeFromHeader = myHeaderPanel.getMinimumSize(); } if (sizeFromHeader == null) { int minimumSize = myWindow.getFontMetrics(myHeaderPanel.getFont()).getHeight(); sizeFromHeader = new Dimension(minimumSize, minimumSize); } return sizeFromHeader; } public void setOkHandler(Runnable okHandler) { myOkHandler = okHandler; } @Override public void setFinalRunnable(Runnable finalRunnable) { myFinalRunnable = finalRunnable; } public void setOk(boolean ok) { myOk = ok; } @Override public void setDataProvider(@NotNull DataProvider dataProvider) { if (myContent != null) { myContent.setDataProvider(dataProvider); } } @Override public boolean dispatchKeyEvent(@NotNull KeyEvent e) { BooleanFunction<? super KeyEvent> handler = myKeyEventHandler; if (handler != null && handler.fun(e)) { return true; } if (isCloseRequest(e) && myCancelKeyEnabled && !mySpeedSearch.isHoldingFilter()) { if (mySpeedSearchFoundInRootComponent != null && mySpeedSearchFoundInRootComponent.isHoldingFilter()) { mySpeedSearchFoundInRootComponent.reset(); } else { cancel(e); } return true; } return false; } public @NotNull Dimension getHeaderPreferredSize() { return myHeaderPanel.getPreferredSize(); } public @NotNull Dimension getFooterPreferredSize() { return myAdComponent == null ? new Dimension(0,0) : myAdComponent.getPreferredSize(); } public static boolean isCloseRequest(KeyEvent e) { if (e != null && e.getID() == KeyEvent.KEY_PRESSED) { KeymapManager keymapManager = KeymapManager.getInstance(); if (keymapManager != null) { Shortcut[] shortcuts = keymapManager.getActiveKeymap().getShortcuts(IdeActions.ACTION_EDITOR_ESCAPE); for (Shortcut shortcut : shortcuts) { if (shortcut instanceof KeyboardShortcut keyboardShortcut) { if (keyboardShortcut.getFirstKeyStroke().getKeyCode() == e.getKeyCode() && keyboardShortcut.getSecondKeyStroke() == null) { int m1 = keyboardShortcut.getFirstKeyStroke().getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); int m2 = e.getModifiers(); return m1 == m2; } } } } return e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getModifiers() == 0; } return false; } private @NotNull Point fixLocateByContent(@NotNull Point location, boolean save) { Dimension size = !myLocateByContent ? null : myHeaderPanel.getPreferredSize(); if (size != null) location.y -= save ? -size.height : size.height; return location; } protected boolean isBusy() { return myResizeListener != null && myResizeListener.isBusy() || myMoveListener != null && myMoveListener.isBusy(); } /** * Returns the first frame (or dialog) ancestor of the component. * Note that this method returns the component itself if it is a frame (or dialog). * * @param component the component used to find corresponding frame (or dialog) * @return the first frame (or dialog) ancestor of the component; or {@code null} * if the component is not a frame (or dialog) and is not contained inside a frame (or dialog) * * @see ComponentUtil#getWindow */ private static Component getFrameOrDialog(Component component) { while (component != null) { if (component instanceof Window) return component; component = UIUtil.getParent(component); } return null; } private static @Nullable Point getLocationOnScreen(@Nullable Component component) { return component == null || !component.isShowing() ? null : component.getLocationOnScreen(); } private static @Nullable Rectangle getBoundsOnScreen(@Nullable Component component) { Point point = getLocationOnScreen(component); return point == null ? null : new Rectangle(point, component.getSize()); } public static @NotNull List<JBPopup> getChildPopups(final @NotNull Component component) { return ContainerUtil.filter(all.toStrongList(), popup -> { Component owner = popup.getOwner(); while (owner != null) { if (owner.equals(component)) { return true; } owner = owner.getParent(); } return false; }); } @Override public boolean canShow() { return myState == State.INIT; } @Override public @NotNull Rectangle getConsumedScreenBounds() { return myWindow.getBounds(); } @Override public Window getUnderlyingWindow() { return myWindow.getOwner(); } /** * Passed listener will be notified if popup is resized by user (using mouse) */ public void addResizeListener(@NotNull Runnable runnable, @NotNull Disposable parentDisposable) { myResizeListeners.add(runnable); Disposer.register(parentDisposable, () -> myResizeListeners.remove(runnable)); } /** * Tells whether popup should be closed when some window becomes activated/focused */ private boolean isCancelNeeded(@NotNull WindowEvent event, @Nullable Window popup) { Window window = event.getWindow(); // the activated or focused window return window == null || popup == null || !SwingUtilities.isDescendingFrom(window, popup) && (myFocusable || !SwingUtilities.isDescendingFrom(popup, window)); } private @Nullable Point getStoredLocation() { if (myDimensionServiceKey == null) return null; return getWindowStateService(getProjectDependingOnKey(myDimensionServiceKey)).getLocation(myDimensionServiceKey); } private @Nullable Dimension getStoredSize() { if (myDimensionServiceKey == null) return null; return getWindowStateService(getProjectDependingOnKey(myDimensionServiceKey)).getSize(myDimensionServiceKey); } private static @NotNull WindowStateService getWindowStateService(@Nullable Project project) { return project == null ? WindowStateService.getInstance() : WindowStateService.getInstance(project); } private static <T> T findInComponentHierarchy(@NotNull Component component, Function<? super @NotNull Component, ? extends @Nullable T> mapper) { T found = mapper.fun(component); if (found != null) { return found; } if (component instanceof JComponent) { for (Component child : ((JComponent)component).getComponents()) { found = findInComponentHierarchy(child, mapper); if (found != null) { return found; } } } return null; } private @Nullable JScrollBar findHorizontalScrollBar() { JScrollPane pane = ScrollUtil.findScrollPane(myContent); if (pane == null || ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER == pane.getHorizontalScrollBarPolicy()) return null; return pane.getHorizontalScrollBar(); } private void forHorizontalScrollBar(@NotNull Consumer<? super JScrollBar> consumer) { JScrollBar bar = findHorizontalScrollBar(); if (bar != null) consumer.consume(bar); } @Override public final boolean dispatchInputMethodEvent(InputMethodEvent event) { if (anyModalWindowsKeepPopupOpen()) { return false; } if (myComponent != null) { var prop = myComponent.getClientProperty(UIUtil.ENABLE_IME_FORWARDING_IN_POPUP); if (prop != null && (Boolean)prop) { // Don't handle the event, so that it can be forwarded to the popup return event.isConsumed(); } } // Try forwarding the input method event to various possible speed search handlers JComponent comp = myPreferredFocusedComponent == null ? myComponent : myPreferredFocusedComponent; SpeedSearchSupply supply = SpeedSearchSupply.getSupply(comp, true); if (!event.isConsumed() && supply instanceof SpeedSearchBase<?>) { ((SpeedSearchBase<?>)supply).processInputMethodEvent(event); } if (!event.isConsumed() && comp instanceof ListWithFilter<?>) { ((ListWithFilter<?>)comp).processInputMethodEvent(event); } // Don't try to attempt to pass IMEs to speed search if the popup is a text field boolean isText = comp instanceof EditorTextField || comp instanceof JTextComponent; if (!event.isConsumed() && !isText && mySpeedSearchPatternField != null) { mySpeedSearchPatternField.getTextEditor().dispatchEvent(event); mySpeedSearch.updatePattern(mySpeedSearchPatternField.getText()); mySpeedSearch.update(); } return event.isConsumed(); } }
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java
2,377
package org.telegram.ui; import static org.telegram.ui.CacheControlActivity.KEEP_MEDIA_TYPE_STORIES; import android.content.Context; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.CacheByChatsController; import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AvatarsDrawable; import org.telegram.ui.Components.AvatarsImageView; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LinkSpanDrawable; import java.util.ArrayList; public class KeepMediaPopupView extends ActionBarPopupWindow.ActionBarPopupWindowLayout { private final TextView description; ActionBarMenuSubItem delete; ActionBarMenuSubItem forever; ActionBarMenuSubItem oneMonth; ActionBarMenuSubItem oneWeek; ActionBarMenuSubItem oneDay; ActionBarMenuSubItem twoDay; ActionBarMenuSubItem oneMinute; ArrayList<CheckItem> checkItems = new ArrayList<>(); ExceptionsView exceptionsView; int time; int currentType; private final CacheByChatsController cacheByChatsController; Callback callback; private ArrayList<CacheByChatsController.KeepMediaException> exceptions; BaseFragment parentFragment; FrameLayout gap; public KeepMediaPopupView(BaseFragment baseFragment, Context context) { super(context, null); parentFragment = baseFragment; cacheByChatsController = baseFragment.getMessagesController().getCacheByChatsController(); setFitItems(true); // if (BuildVars.DEBUG_PRIVATE_VERSION) { // oneMinute = ActionBarMenuItem.addItem(this, R.drawable.msg_autodelete, LocaleController.formatPluralString("Minutes", 1), false, null); // checkItems.add(new CheckItem(oneMinute, CacheByChatsController.KEEP_MEDIA_ONE_MINUTE)); // } oneDay = ActionBarMenuItem.addItem(this, R.drawable.msg_autodelete_1d, LocaleController.formatPluralString("Days", 1), false, null); twoDay = ActionBarMenuItem.addItem(this, R.drawable.msg_autodelete_2d, LocaleController.formatPluralString("Days", 2), false, null); oneWeek = ActionBarMenuItem.addItem(this, R.drawable.msg_autodelete_1w, LocaleController.formatPluralString("Weeks", 1), false, null); oneMonth = ActionBarMenuItem.addItem(this, R.drawable.msg_autodelete_1m, LocaleController.formatPluralString("Months", 1), false, null); forever = ActionBarMenuItem.addItem(this, R.drawable.msg_cancel, LocaleController.getString("AutoDeleteMediaNever", R.string.AutoDeleteMediaNever), false, null); delete = ActionBarMenuItem.addItem(this, R.drawable.msg_delete, LocaleController.getString("DeleteException", R.string.DeleteException), false, null); delete.setColors(Theme.getColor(Theme.key_text_RedRegular), Theme.getColor(Theme.key_text_RedRegular)); checkItems.add(new CheckItem(oneDay, CacheByChatsController.KEEP_MEDIA_ONE_DAY)); checkItems.add(new CheckItem(twoDay, CacheByChatsController.KEEP_MEDIA_TWO_DAY)); checkItems.add(new CheckItem(oneWeek, CacheByChatsController.KEEP_MEDIA_ONE_WEEK)); checkItems.add(new CheckItem(oneMonth, CacheByChatsController.KEEP_MEDIA_ONE_MONTH)); checkItems.add(new CheckItem(forever, CacheByChatsController.KEEP_MEDIA_FOREVER)); checkItems.add(new CheckItem(delete, CacheByChatsController.KEEP_MEDIA_DELETE)); gap = new FrameLayout(context); gap.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuSeparator)); View gapShadow = new View(context); gapShadow.setBackground(Theme.getThemedDrawableByKey(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow, null)); gap.addView(gapShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); gap.setTag(R.id.fit_width_tag, 1); addView(gap, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8)); exceptionsView = new ExceptionsView(context); addView(exceptionsView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); exceptionsView.setOnClickListener(v -> { window.dismiss(); if (exceptions.isEmpty()) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putBoolean("onlySelect", true); args.putBoolean("checkCanWrite", false); if (currentType == CacheControlActivity.KEEP_MEDIA_TYPE_GROUP) { args.putInt("dialogsType", DialogsActivity.DIALOGS_TYPE_GROUPS_ONLY); } else if (currentType == CacheControlActivity.KEEP_MEDIA_TYPE_CHANNEL) { args.putInt("dialogsType", DialogsActivity.DIALOGS_TYPE_CHANNELS_ONLY); } else { args.putInt("dialogsType", DialogsActivity.DIALOGS_TYPE_USERS_ONLY); } args.putBoolean("allowGlobalSearch", false); DialogsActivity activity = new DialogsActivity(args); activity.setDelegate((fragment, dids, message, param, topicsFragment) -> { CacheByChatsController.KeepMediaException newException = null; for (int i = 0; i < dids.size(); i++) { exceptions.add(newException = new CacheByChatsController.KeepMediaException(dids.get(i).dialogId, CacheByChatsController.KEEP_MEDIA_ONE_DAY)); } cacheByChatsController.saveKeepMediaExceptions(currentType, exceptions); Bundle bundle = new Bundle(); bundle.putInt("type", currentType); CacheByChatsController.KeepMediaException finalNewException = newException; CacheChatsExceptionsFragment cacheChatsExceptionsFragment = new CacheChatsExceptionsFragment(bundle) { @Override public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { super.onTransitionAnimationEnd(isOpen, backward); if (isOpen && !backward) { activity.removeSelfFromStack(); } } }; cacheChatsExceptionsFragment.setExceptions(exceptions); parentFragment.presentFragment(cacheChatsExceptionsFragment); AndroidUtilities.runOnUIThread(() -> cacheChatsExceptionsFragment.showPopupFor(finalNewException), 150); return true; }); baseFragment.presentFragment(activity); } else { Bundle bundle = new Bundle(); bundle.putInt("type", currentType); CacheChatsExceptionsFragment cacheChatsExceptionsFragment = new CacheChatsExceptionsFragment(bundle); cacheChatsExceptionsFragment.setExceptions(exceptions); baseFragment.presentFragment(cacheChatsExceptionsFragment); } }); for (int i = 0; i < checkItems.size(); i++) { int keepMedia = checkItems.get(i).type; checkItems.get(i).item.setOnClickListener(v -> { window.dismiss(); if (currentType >= 0) { cacheByChatsController.setKeepMedia(currentType, keepMedia); if (callback != null) { callback.onKeepMediaChange(currentType, keepMedia); } } else { if (callback != null) { callback.onKeepMediaChange(currentType, keepMedia); } } }); } description = new LinkSpanDrawable.LinksTextView(context); description.setTag(R.id.fit_width_tag, 1); description.setPadding(AndroidUtilities.dp(13), 0, AndroidUtilities.dp(13), AndroidUtilities.dp(8)); description.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); description.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); description.setMovementMethod(LinkMovementMethod.getInstance()); description.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText)); description.setText(LocaleController.getString("KeepMediaPopupDescription", R.string.KeepMediaPopupDescription)); addView(description, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 8, 0, 0)); } public void update(int type) { currentType = type; if (type == KEEP_MEDIA_TYPE_STORIES) { twoDay.setVisibility(View.VISIBLE); oneMonth.setVisibility(View.GONE); gap.setVisibility(View.GONE); exceptionsView.setVisibility(View.GONE); description.setVisibility(View.GONE); } else { twoDay.setVisibility(View.GONE); oneMonth.setVisibility(View.VISIBLE); gap.setVisibility(View.VISIBLE); exceptionsView.setVisibility(View.VISIBLE); description.setVisibility(View.VISIBLE); } exceptions = cacheByChatsController.getKeepMediaExceptions(type); if (exceptions.isEmpty()) { exceptionsView.titleView.setText(LocaleController.getString("AddAnException", R.string.AddAnException)); exceptionsView.titleView.setRightPadding(AndroidUtilities.dp(8)); exceptionsView.avatarsImageView.setObject(0, parentFragment.getCurrentAccount(), null); exceptionsView.avatarsImageView.setObject(1, parentFragment.getCurrentAccount(), null); exceptionsView.avatarsImageView.setObject(2, parentFragment.getCurrentAccount(), null); exceptionsView.avatarsImageView.commitTransition(false); } else { int count = Math.min(3, exceptions.size()); exceptionsView.titleView.setRightPadding(AndroidUtilities.dp(64 + Math.max(0, count - 1) * 12)); exceptionsView.titleView.setText(LocaleController.formatPluralString("ExceptionShort", exceptions.size(), exceptions.size())); for (int i = 0; i < count; i++) { exceptionsView.avatarsImageView.setObject(i, parentFragment.getCurrentAccount(), parentFragment.getMessagesController().getUserOrChat(exceptions.get(i).dialogId)); } exceptionsView.avatarsImageView.commitTransition(false); } delete.setVisibility(View.GONE); description.setVisibility(View.GONE); updateAvatarsPosition(); } public void updateForDialog(boolean addedRecently) { currentType = -1; gap.setVisibility(View.VISIBLE); delete.setVisibility(addedRecently ? View.GONE : View.VISIBLE); description.setVisibility(View.VISIBLE); exceptionsView.setVisibility(View.GONE); } private class ExceptionsView extends FrameLayout { SimpleTextView titleView; AvatarsImageView avatarsImageView; public ExceptionsView(Context context) { super(context); titleView = new SimpleTextView(context); titleView.setTextSize(16); titleView.setEllipsizeByGradient(true); titleView.setRightPadding(AndroidUtilities.dp(68)); titleView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); addView(titleView, LayoutHelper.createFrame(0, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 19, 0, 19, 0)); avatarsImageView = new AvatarsImageView(context, false); avatarsImageView.avatarsDrawable.setShowSavedMessages(true); avatarsImageView.setStyle(AvatarsDrawable.STYLE_MESSAGE_SEEN); avatarsImageView.setAvatarsTextSize(AndroidUtilities.dp(22)); addView(avatarsImageView, LayoutHelper.createFrame(24 + 12 + 12 + 8, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 4, 0)); setBackground(Theme.createRadSelectorDrawable(Theme.getColor(Theme.key_listSelector), 0, 4)); } boolean ignoreLayout; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { View parent = (View) getParent(); if (parent != null && parent.getWidth() > 0) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(parent.getWidth(), MeasureSpec.EXACTLY); } ignoreLayout = true; titleView.setVisibility(View.GONE); super.onMeasure(widthMeasureSpec, heightMeasureSpec); titleView.setVisibility(View.VISIBLE); titleView.getLayoutParams().width = getMeasuredWidth();//- AndroidUtilities.dp(40); ignoreLayout = false; updateAvatarsPosition(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public void requestLayout() { if (ignoreLayout) { return; } super.requestLayout(); } } private void updateAvatarsPosition() { if (exceptions != null) { exceptionsView.avatarsImageView.setTranslationX(AndroidUtilities.dp(12) * (3 - Math.min(3, exceptions.size()))); } } private static class CheckItem { final ActionBarMenuSubItem item; final int type; private CheckItem(ActionBarMenuSubItem item, int type) { this.item = item; this.type = type; } } public void setCallback(Callback callback) { this.callback = callback; } public interface Callback { void onKeepMediaChange(int type, int keepMedia); } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/KeepMediaPopupView.java
2,378
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.tieredstore.metrics; import com.github.benmanes.caffeine.cache.Policy; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.api.metrics.LongHistogram; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.ObservableLongGauge; import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.ViewBuilder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import org.apache.rocketmq.common.Pair; import org.apache.rocketmq.common.message.MessageQueue; import org.apache.rocketmq.common.metrics.NopLongCounter; import org.apache.rocketmq.common.metrics.NopLongHistogram; import org.apache.rocketmq.common.metrics.NopObservableLongGauge; import org.apache.rocketmq.logging.org.slf4j.Logger; import org.apache.rocketmq.logging.org.slf4j.LoggerFactory; import org.apache.rocketmq.store.MessageStore; import org.apache.rocketmq.tieredstore.TieredMessageFetcher; import org.apache.rocketmq.tieredstore.common.FileSegmentType; import org.apache.rocketmq.tieredstore.common.MessageCacheKey; import org.apache.rocketmq.tieredstore.common.SelectBufferResultWrapper; import org.apache.rocketmq.tieredstore.common.TieredMessageStoreConfig; import org.apache.rocketmq.tieredstore.file.CompositeQueueFlatFile; import org.apache.rocketmq.tieredstore.file.TieredFlatFileManager; import org.apache.rocketmq.tieredstore.metadata.TieredMetadataStore; import org.apache.rocketmq.tieredstore.util.TieredStoreUtil; import static org.apache.rocketmq.store.metrics.DefaultStoreMetricsConstant.GAUGE_STORAGE_SIZE; import static org.apache.rocketmq.store.metrics.DefaultStoreMetricsConstant.LABEL_STORAGE_MEDIUM; import static org.apache.rocketmq.store.metrics.DefaultStoreMetricsConstant.LABEL_STORAGE_TYPE; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.COUNTER_CACHE_ACCESS; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.COUNTER_CACHE_HIT; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.COUNTER_GET_MESSAGE_FALLBACK_TOTAL; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.COUNTER_MESSAGES_DISPATCH_TOTAL; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.COUNTER_MESSAGES_OUT_TOTAL; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.GAUGE_CACHE_BYTES; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.GAUGE_CACHE_COUNT; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.GAUGE_DISPATCH_BEHIND; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.GAUGE_DISPATCH_LATENCY; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.GAUGE_STORAGE_MESSAGE_RESERVE_TIME; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.HISTOGRAM_API_LATENCY; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.HISTOGRAM_DOWNLOAD_BYTES; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.HISTOGRAM_PROVIDER_RPC_LATENCY; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.HISTOGRAM_UPLOAD_BYTES; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.LABEL_FILE_TYPE; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.LABEL_QUEUE_ID; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.LABEL_TOPIC; import static org.apache.rocketmq.tieredstore.metrics.TieredStoreMetricsConstant.STORAGE_MEDIUM_BLOB; public class TieredStoreMetricsManager { private static final Logger logger = LoggerFactory.getLogger(TieredStoreUtil.TIERED_STORE_LOGGER_NAME); public static Supplier<AttributesBuilder> attributesBuilderSupplier; private static String storageMedium = STORAGE_MEDIUM_BLOB; public static LongHistogram apiLatency = new NopLongHistogram(); // tiered store provider metrics public static LongHistogram providerRpcLatency = new NopLongHistogram(); public static LongHistogram uploadBytes = new NopLongHistogram(); public static LongHistogram downloadBytes = new NopLongHistogram(); public static ObservableLongGauge dispatchBehind = new NopObservableLongGauge(); public static ObservableLongGauge dispatchLatency = new NopObservableLongGauge(); public static LongCounter messagesDispatchTotal = new NopLongCounter(); public static LongCounter messagesOutTotal = new NopLongCounter(); public static LongCounter fallbackTotal = new NopLongCounter(); public static ObservableLongGauge cacheCount = new NopObservableLongGauge(); public static ObservableLongGauge cacheBytes = new NopObservableLongGauge(); public static LongCounter cacheAccess = new NopLongCounter(); public static LongCounter cacheHit = new NopLongCounter(); public static ObservableLongGauge storageSize = new NopObservableLongGauge(); public static ObservableLongGauge storageMessageReserveTime = new NopObservableLongGauge(); public static List<Pair<InstrumentSelector, ViewBuilder>> getMetricsView() { ArrayList<Pair<InstrumentSelector, ViewBuilder>> res = new ArrayList<>(); InstrumentSelector providerRpcLatencySelector = InstrumentSelector.builder() .setType(InstrumentType.HISTOGRAM) .setName(HISTOGRAM_PROVIDER_RPC_LATENCY) .build(); InstrumentSelector rpcLatencySelector = InstrumentSelector.builder() .setType(InstrumentType.HISTOGRAM) .setName(HISTOGRAM_API_LATENCY) .build(); ViewBuilder rpcLatencyViewBuilder = View.builder() .setAggregation(Aggregation.explicitBucketHistogram(Arrays.asList(1d, 3d, 5d, 7d, 10d, 100d, 200d, 400d, 600d, 800d, 1d * 1000, 1d * 1500, 1d * 3000))) .setDescription("tiered_store_rpc_latency_view"); InstrumentSelector uploadBufferSizeSelector = InstrumentSelector.builder() .setType(InstrumentType.HISTOGRAM) .setName(HISTOGRAM_UPLOAD_BYTES) .build(); InstrumentSelector downloadBufferSizeSelector = InstrumentSelector.builder() .setType(InstrumentType.HISTOGRAM) .setName(HISTOGRAM_DOWNLOAD_BYTES) .build(); ViewBuilder bufferSizeViewBuilder = View.builder() .setAggregation(Aggregation.explicitBucketHistogram(Arrays.asList(1d * TieredStoreUtil.KB, 10d * TieredStoreUtil.KB, 100d * TieredStoreUtil.KB, 1d * TieredStoreUtil.MB, 10d * TieredStoreUtil.MB, 32d * TieredStoreUtil.MB, 50d * TieredStoreUtil.MB, 100d * TieredStoreUtil.MB))) .setDescription("tiered_store_buffer_size_view"); res.add(new Pair<>(rpcLatencySelector, rpcLatencyViewBuilder)); res.add(new Pair<>(providerRpcLatencySelector, rpcLatencyViewBuilder)); res.add(new Pair<>(uploadBufferSizeSelector, bufferSizeViewBuilder)); res.add(new Pair<>(downloadBufferSizeSelector, bufferSizeViewBuilder)); return res; } public static void setStorageMedium(String storageMedium) { TieredStoreMetricsManager.storageMedium = storageMedium; } public static void init(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier, TieredMessageStoreConfig storeConfig, TieredMessageFetcher fetcher, MessageStore next) { TieredStoreMetricsManager.attributesBuilderSupplier = attributesBuilderSupplier; apiLatency = meter.histogramBuilder(HISTOGRAM_API_LATENCY) .setDescription("Tiered store rpc latency") .setUnit("milliseconds") .ofLongs() .build(); providerRpcLatency = meter.histogramBuilder(HISTOGRAM_PROVIDER_RPC_LATENCY) .setDescription("Tiered store rpc latency") .setUnit("milliseconds") .ofLongs() .build(); uploadBytes = meter.histogramBuilder(HISTOGRAM_UPLOAD_BYTES) .setDescription("Tiered store upload buffer size") .setUnit("bytes") .ofLongs() .build(); downloadBytes = meter.histogramBuilder(HISTOGRAM_DOWNLOAD_BYTES) .setDescription("Tiered store download buffer size") .setUnit("bytes") .ofLongs() .build(); dispatchBehind = meter.gaugeBuilder(GAUGE_DISPATCH_BEHIND) .setDescription("Tiered store dispatch behind message count") .ofLongs() .buildWithCallback(measurement -> { for (CompositeQueueFlatFile flatFile : TieredFlatFileManager.getInstance(storeConfig).deepCopyFlatFileToList()) { MessageQueue mq = flatFile.getMessageQueue(); long maxOffset = next.getMaxOffsetInQueue(mq.getTopic(), mq.getQueueId()); long maxTimestamp = next.getMessageStoreTimeStamp(mq.getTopic(), mq.getQueueId(), maxOffset - 1); if (maxTimestamp > 0 && System.currentTimeMillis() - maxTimestamp > (long) storeConfig.getTieredStoreFileReservedTime() * 60 * 60 * 1000) { continue; } Attributes commitLogAttributes = newAttributesBuilder() .put(LABEL_TOPIC, mq.getTopic()) .put(LABEL_QUEUE_ID, mq.getQueueId()) .put(LABEL_FILE_TYPE, FileSegmentType.COMMIT_LOG.name().toLowerCase()) .build(); measurement.record(Math.max(maxOffset - flatFile.getDispatchOffset(), 0), commitLogAttributes); Attributes consumeQueueAttributes = newAttributesBuilder() .put(LABEL_TOPIC, mq.getTopic()) .put(LABEL_QUEUE_ID, mq.getQueueId()) .put(LABEL_FILE_TYPE, FileSegmentType.CONSUME_QUEUE.name().toLowerCase()) .build(); measurement.record(Math.max(maxOffset - flatFile.getConsumeQueueMaxOffset(), 0), consumeQueueAttributes); } }); dispatchLatency = meter.gaugeBuilder(GAUGE_DISPATCH_LATENCY) .setDescription("Tiered store dispatch latency") .setUnit("seconds") .ofLongs() .buildWithCallback(measurement -> { for (CompositeQueueFlatFile flatFile : TieredFlatFileManager.getInstance(storeConfig).deepCopyFlatFileToList()) { MessageQueue mq = flatFile.getMessageQueue(); long maxOffset = next.getMaxOffsetInQueue(mq.getTopic(), mq.getQueueId()); long maxTimestamp = next.getMessageStoreTimeStamp(mq.getTopic(), mq.getQueueId(), maxOffset - 1); if (maxTimestamp > 0 && System.currentTimeMillis() - maxTimestamp > (long) storeConfig.getTieredStoreFileReservedTime() * 60 * 60 * 1000) { continue; } Attributes commitLogAttributes = newAttributesBuilder() .put(LABEL_TOPIC, mq.getTopic()) .put(LABEL_QUEUE_ID, mq.getQueueId()) .put(LABEL_FILE_TYPE, FileSegmentType.COMMIT_LOG.name().toLowerCase()) .build(); long commitLogDispatchLatency = next.getMessageStoreTimeStamp(mq.getTopic(), mq.getQueueId(), flatFile.getDispatchOffset()); if (maxOffset <= flatFile.getDispatchOffset() || commitLogDispatchLatency < 0) { measurement.record(0, commitLogAttributes); } else { measurement.record(System.currentTimeMillis() - commitLogDispatchLatency, commitLogAttributes); } Attributes consumeQueueAttributes = newAttributesBuilder() .put(LABEL_TOPIC, mq.getTopic()) .put(LABEL_QUEUE_ID, mq.getQueueId()) .put(LABEL_FILE_TYPE, FileSegmentType.CONSUME_QUEUE.name().toLowerCase()) .build(); long consumeQueueDispatchOffset = flatFile.getConsumeQueueMaxOffset(); long consumeQueueDispatchLatency = next.getMessageStoreTimeStamp(mq.getTopic(), mq.getQueueId(), consumeQueueDispatchOffset); if (maxOffset <= consumeQueueDispatchOffset || consumeQueueDispatchLatency < 0) { measurement.record(0, consumeQueueAttributes); } else { measurement.record(System.currentTimeMillis() - consumeQueueDispatchLatency, consumeQueueAttributes); } } }); messagesDispatchTotal = meter.counterBuilder(COUNTER_MESSAGES_DISPATCH_TOTAL) .setDescription("Total number of dispatch messages") .build(); messagesOutTotal = meter.counterBuilder(COUNTER_MESSAGES_OUT_TOTAL) .setDescription("Total number of outgoing messages") .build(); fallbackTotal = meter.counterBuilder(COUNTER_GET_MESSAGE_FALLBACK_TOTAL) .setDescription("Total times of fallback to next store when getting message") .build(); cacheCount = meter.gaugeBuilder(GAUGE_CACHE_COUNT) .setDescription("Tiered store cache message count") .ofLongs() .buildWithCallback(measurement -> measurement.record(fetcher.getMessageCache().estimatedSize(), newAttributesBuilder().build())); cacheBytes = meter.gaugeBuilder(GAUGE_CACHE_BYTES) .setDescription("Tiered store cache message bytes") .setUnit("bytes") .ofLongs() .buildWithCallback(measurement -> { Optional<Policy.Eviction<MessageCacheKey, SelectBufferResultWrapper>> eviction = fetcher.getMessageCache().policy().eviction(); eviction.ifPresent(resultEviction -> measurement.record(resultEviction.weightedSize().orElse(0), newAttributesBuilder().build())); }); cacheAccess = meter.counterBuilder(COUNTER_CACHE_ACCESS) .setDescription("Tiered store cache access count") .build(); cacheHit = meter.counterBuilder(COUNTER_CACHE_HIT) .setDescription("Tiered store cache hit count") .build(); storageSize = meter.gaugeBuilder(GAUGE_STORAGE_SIZE) .setDescription("Broker storage size") .setUnit("bytes") .ofLongs() .buildWithCallback(measurement -> { Map<String, Map<FileSegmentType, Long>> topicFileSizeMap = new HashMap<>(); try { TieredMetadataStore metadataStore = TieredStoreUtil.getMetadataStore(storeConfig); metadataStore.iterateFileSegment(fileSegment -> { Map<FileSegmentType, Long> subMap = topicFileSizeMap.computeIfAbsent(fileSegment.getPath(), k -> new HashMap<>()); FileSegmentType fileSegmentType = FileSegmentType.valueOf(fileSegment.getType()); Long size = subMap.computeIfAbsent(fileSegmentType, k -> 0L); subMap.put(fileSegmentType, size + fileSegment.getSize()); }); } catch (Exception e) { logger.error("Failed to get storage size", e); } topicFileSizeMap.forEach((topic, subMap) -> { subMap.forEach((fileSegmentType, size) -> { Attributes attributes = newAttributesBuilder() .put(LABEL_TOPIC, topic) .put(LABEL_FILE_TYPE, fileSegmentType.name().toLowerCase()) .build(); measurement.record(size, attributes); }); }); }); storageMessageReserveTime = meter.gaugeBuilder(GAUGE_STORAGE_MESSAGE_RESERVE_TIME) .setDescription("Broker message reserve time") .setUnit("milliseconds") .ofLongs() .buildWithCallback(measurement -> { for (CompositeQueueFlatFile flatFile : TieredFlatFileManager.getInstance(storeConfig).deepCopyFlatFileToList()) { long timestamp = flatFile.getCommitLogBeginTimestamp(); if (timestamp > 0) { MessageQueue mq = flatFile.getMessageQueue(); Attributes attributes = newAttributesBuilder() .put(LABEL_TOPIC, mq.getTopic()) .put(LABEL_QUEUE_ID, mq.getQueueId()) .build(); measurement.record(System.currentTimeMillis() - timestamp, attributes); } } }); } public static AttributesBuilder newAttributesBuilder() { AttributesBuilder builder = attributesBuilderSupplier != null ? attributesBuilderSupplier.get() : Attributes.builder(); return builder.put(LABEL_STORAGE_TYPE, "tiered") .put(LABEL_STORAGE_MEDIUM, storageMedium); } }
apache/rocketmq
tieredstore/src/main/java/org/apache/rocketmq/tieredstore/metrics/TieredStoreMetricsManager.java
2,379
package cn.hutool.core.text.escape; import cn.hutool.core.text.replacer.LookupReplacer; /** * HTML4的ESCAPE * 参考:Commons Lang3 * * @author looly * */ public class Html4Escape extends XmlEscape { private static final long serialVersionUID = 1L; protected static final String[][] ISO8859_1_ESCAPE = { // { "\u00A0", "&nbsp;" }, // non-breaking space { "\u00A1", "&iexcl;" }, // inverted exclamation mark { "\u00A2", "&cent;" }, // cent sign { "\u00A3", "&pound;" }, // pound sign { "\u00A4", "&curren;" }, // currency sign { "\u00A5", "&yen;" }, // yen sign = yuan sign { "\u00A6", "&brvbar;" }, // broken bar = broken vertical bar { "\u00A7", "&sect;" }, // section sign { "\u00A8", "&uml;" }, // diaeresis = spacing diaeresis { "\u00A9", "&copy;" }, // � - copyright sign { "\u00AA", "&ordf;" }, // feminine ordinal indicator { "\u00AB", "&laquo;" }, // left-pointing double angle quotation mark = left pointing guillemet { "\u00AC", "&not;" }, // not sign { "\u00AD", "&shy;" }, // soft hyphen = discretionary hyphen { "\u00AE", "&reg;" }, // � - registered trademark sign { "\u00AF", "&macr;" }, // macron = spacing macron = overline = APL overbar { "\u00B0", "&deg;" }, // degree sign { "\u00B1", "&plusmn;" }, // plus-minus sign = plus-or-minus sign { "\u00B2", "&sup2;" }, // superscript two = superscript digit two = squared { "\u00B3", "&sup3;" }, // superscript three = superscript digit three = cubed { "\u00B4", "&acute;" }, // acute accent = spacing acute { "\u00B5", "&micro;" }, // micro sign { "\u00B6", "&para;" }, // pilcrow sign = paragraph sign { "\u00B7", "&middot;" }, // middle dot = Georgian comma = Greek middle dot { "\u00B8", "&cedil;" }, // cedilla = spacing cedilla { "\u00B9", "&sup1;" }, // superscript one = superscript digit one { "\u00BA", "&ordm;" }, // masculine ordinal indicator { "\u00BB", "&raquo;" }, // right-pointing double angle quotation mark = right pointing guillemet { "\u00BC", "&frac14;" }, // vulgar fraction one quarter = fraction one quarter { "\u00BD", "&frac12;" }, // vulgar fraction one half = fraction one half { "\u00BE", "&frac34;" }, // vulgar fraction three quarters = fraction three quarters { "\u00BF", "&iquest;" }, // inverted question mark = turned question mark { "\u00C0", "&Agrave;" }, // � - uppercase A, grave accent { "\u00C1", "&Aacute;" }, // � - uppercase A, acute accent { "\u00C2", "&Acirc;" }, // � - uppercase A, circumflex accent { "\u00C3", "&Atilde;" }, // � - uppercase A, tilde { "\u00C4", "&Auml;" }, // � - uppercase A, umlaut { "\u00C5", "&Aring;" }, // � - uppercase A, ring { "\u00C6", "&AElig;" }, // � - uppercase AE { "\u00C7", "&Ccedil;" }, // � - uppercase C, cedilla { "\u00C8", "&Egrave;" }, // � - uppercase E, grave accent { "\u00C9", "&Eacute;" }, // � - uppercase E, acute accent { "\u00CA", "&Ecirc;" }, // � - uppercase E, circumflex accent { "\u00CB", "&Euml;" }, // � - uppercase E, umlaut { "\u00CC", "&Igrave;" }, // � - uppercase I, grave accent { "\u00CD", "&Iacute;" }, // � - uppercase I, acute accent { "\u00CE", "&Icirc;" }, // � - uppercase I, circumflex accent { "\u00CF", "&Iuml;" }, // � - uppercase I, umlaut { "\u00D0", "&ETH;" }, // � - uppercase Eth, Icelandic { "\u00D1", "&Ntilde;" }, // � - uppercase N, tilde { "\u00D2", "&Ograve;" }, // � - uppercase O, grave accent { "\u00D3", "&Oacute;" }, // � - uppercase O, acute accent { "\u00D4", "&Ocirc;" }, // � - uppercase O, circumflex accent { "\u00D5", "&Otilde;" }, // � - uppercase O, tilde { "\u00D6", "&Ouml;" }, // � - uppercase O, umlaut { "\u00D7", "&times;" }, // multiplication sign { "\u00D8", "&Oslash;" }, // � - uppercase O, slash { "\u00D9", "&Ugrave;" }, // � - uppercase U, grave accent { "\u00DA", "&Uacute;" }, // � - uppercase U, acute accent { "\u00DB", "&Ucirc;" }, // � - uppercase U, circumflex accent { "\u00DC", "&Uuml;" }, // � - uppercase U, umlaut { "\u00DD", "&Yacute;" }, // � - uppercase Y, acute accent { "\u00DE", "&THORN;" }, // � - uppercase THORN, Icelandic { "\u00DF", "&szlig;" }, // � - lowercase sharps, German { "\u00E0", "&agrave;" }, // � - lowercase a, grave accent { "\u00E1", "&aacute;" }, // � - lowercase a, acute accent { "\u00E2", "&acirc;" }, // � - lowercase a, circumflex accent { "\u00E3", "&atilde;" }, // � - lowercase a, tilde { "\u00E4", "&auml;" }, // � - lowercase a, umlaut { "\u00E5", "&aring;" }, // � - lowercase a, ring { "\u00E6", "&aelig;" }, // � - lowercase ae { "\u00E7", "&ccedil;" }, // � - lowercase c, cedilla { "\u00E8", "&egrave;" }, // � - lowercase e, grave accent { "\u00E9", "&eacute;" }, // � - lowercase e, acute accent { "\u00EA", "&ecirc;" }, // � - lowercase e, circumflex accent { "\u00EB", "&euml;" }, // � - lowercase e, umlaut { "\u00EC", "&igrave;" }, // � - lowercase i, grave accent { "\u00ED", "&iacute;" }, // � - lowercase i, acute accent { "\u00EE", "&icirc;" }, // � - lowercase i, circumflex accent { "\u00EF", "&iuml;" }, // � - lowercase i, umlaut { "\u00F0", "&eth;" }, // � - lowercase eth, Icelandic { "\u00F1", "&ntilde;" }, // � - lowercase n, tilde { "\u00F2", "&ograve;" }, // � - lowercase o, grave accent { "\u00F3", "&oacute;" }, // � - lowercase o, acute accent { "\u00F4", "&ocirc;" }, // � - lowercase o, circumflex accent { "\u00F5", "&otilde;" }, // � - lowercase o, tilde { "\u00F6", "&ouml;" }, // � - lowercase o, umlaut { "\u00F7", "&divide;" }, // division sign { "\u00F8", "&oslash;" }, // � - lowercase o, slash { "\u00F9", "&ugrave;" }, // � - lowercase u, grave accent { "\u00FA", "&uacute;" }, // � - lowercase u, acute accent { "\u00FB", "&ucirc;" }, // � - lowercase u, circumflex accent { "\u00FC", "&uuml;" }, // � - lowercase u, umlaut { "\u00FD", "&yacute;" }, // � - lowercase y, acute accent { "\u00FE", "&thorn;" }, // � - lowercase thorn, Icelandic { "\u00FF", "&yuml;" }, // � - lowercase y, umlaut }; protected static final String[][] HTML40_EXTENDED_ESCAPE = { // <!-- Latin Extended-B --> { "\u0192", "&fnof;" }, // latin small f with hook = function= florin, U+0192 ISOtech --> // <!-- Greek --> { "\u0391", "&Alpha;" }, // greek capital letter alpha, U+0391 --> { "\u0392", "&Beta;" }, // greek capital letter beta, U+0392 --> { "\u0393", "&Gamma;" }, // greek capital letter gamma,U+0393 ISOgrk3 --> { "\u0394", "&Delta;" }, // greek capital letter delta,U+0394 ISOgrk3 --> { "\u0395", "&Epsilon;" }, // greek capital letter epsilon, U+0395 --> { "\u0396", "&Zeta;" }, // greek capital letter zeta, U+0396 --> { "\u0397", "&Eta;" }, // greek capital letter eta, U+0397 --> { "\u0398", "&Theta;" }, // greek capital letter theta,U+0398 ISOgrk3 --> { "\u0399", "&Iota;" }, // greek capital letter iota, U+0399 --> { "\u039A", "&Kappa;" }, // greek capital letter kappa, U+039A --> { "\u039B", "&Lambda;" }, // greek capital letter lambda,U+039B ISOgrk3 --> { "\u039C", "&Mu;" }, // greek capital letter mu, U+039C --> { "\u039D", "&Nu;" }, // greek capital letter nu, U+039D --> { "\u039E", "&Xi;" }, // greek capital letter xi, U+039E ISOgrk3 --> { "\u039F", "&Omicron;" }, // greek capital letter omicron, U+039F --> { "\u03A0", "&Pi;" }, // greek capital letter pi, U+03A0 ISOgrk3 --> { "\u03A1", "&Rho;" }, // greek capital letter rho, U+03A1 --> // <!-- there is no Sigmaf, and no U+03A2 character either --> { "\u03A3", "&Sigma;" }, // greek capital letter sigma,U+03A3 ISOgrk3 --> { "\u03A4", "&Tau;" }, // greek capital letter tau, U+03A4 --> { "\u03A5", "&Upsilon;" }, // greek capital letter upsilon,U+03A5 ISOgrk3 --> { "\u03A6", "&Phi;" }, // greek capital letter phi,U+03A6 ISOgrk3 --> { "\u03A7", "&Chi;" }, // greek capital letter chi, U+03A7 --> { "\u03A8", "&Psi;" }, // greek capital letter psi,U+03A8 ISOgrk3 --> { "\u03A9", "&Omega;" }, // greek capital letter omega,U+03A9 ISOgrk3 --> { "\u03B1", "&alpha;" }, // greek small letter alpha,U+03B1 ISOgrk3 --> { "\u03B2", "&beta;" }, // greek small letter beta, U+03B2 ISOgrk3 --> { "\u03B3", "&gamma;" }, // greek small letter gamma,U+03B3 ISOgrk3 --> { "\u03B4", "&delta;" }, // greek small letter delta,U+03B4 ISOgrk3 --> { "\u03B5", "&epsilon;" }, // greek small letter epsilon,U+03B5 ISOgrk3 --> { "\u03B6", "&zeta;" }, // greek small letter zeta, U+03B6 ISOgrk3 --> { "\u03B7", "&eta;" }, // greek small letter eta, U+03B7 ISOgrk3 --> { "\u03B8", "&theta;" }, // greek small letter theta,U+03B8 ISOgrk3 --> { "\u03B9", "&iota;" }, // greek small letter iota, U+03B9 ISOgrk3 --> { "\u03BA", "&kappa;" }, // greek small letter kappa,U+03BA ISOgrk3 --> { "\u03BB", "&lambda;" }, // greek small letter lambda,U+03BB ISOgrk3 --> { "\u03BC", "&mu;" }, // greek small letter mu, U+03BC ISOgrk3 --> { "\u03BD", "&nu;" }, // greek small letter nu, U+03BD ISOgrk3 --> { "\u03BE", "&xi;" }, // greek small letter xi, U+03BE ISOgrk3 --> { "\u03BF", "&omicron;" }, // greek small letter omicron, U+03BF NEW --> { "\u03C0", "&pi;" }, // greek small letter pi, U+03C0 ISOgrk3 --> { "\u03C1", "&rho;" }, // greek small letter rho, U+03C1 ISOgrk3 --> { "\u03C2", "&sigmaf;" }, // greek small letter final sigma,U+03C2 ISOgrk3 --> { "\u03C3", "&sigma;" }, // greek small letter sigma,U+03C3 ISOgrk3 --> { "\u03C4", "&tau;" }, // greek small letter tau, U+03C4 ISOgrk3 --> { "\u03C5", "&upsilon;" }, // greek small letter upsilon,U+03C5 ISOgrk3 --> { "\u03C6", "&phi;" }, // greek small letter phi, U+03C6 ISOgrk3 --> { "\u03C7", "&chi;" }, // greek small letter chi, U+03C7 ISOgrk3 --> { "\u03C8", "&psi;" }, // greek small letter psi, U+03C8 ISOgrk3 --> { "\u03C9", "&omega;" }, // greek small letter omega,U+03C9 ISOgrk3 --> { "\u03D1", "&thetasym;" }, // greek small letter theta symbol,U+03D1 NEW --> { "\u03D2", "&upsih;" }, // greek upsilon with hook symbol,U+03D2 NEW --> { "\u03D6", "&piv;" }, // greek pi symbol, U+03D6 ISOgrk3 --> // <!-- General Punctuation --> { "\u2022", "&bull;" }, // bullet = black small circle,U+2022 ISOpub --> // <!-- bullet is NOT the same as bullet operator, U+2219 --> { "\u2026", "&hellip;" }, // horizontal ellipsis = three dot leader,U+2026 ISOpub --> { "\u2032", "&prime;" }, // prime = minutes = feet, U+2032 ISOtech --> { "\u2033", "&Prime;" }, // double prime = seconds = inches,U+2033 ISOtech --> { "\u203E", "&oline;" }, // overline = spacing overscore,U+203E NEW --> { "\u2044", "&frasl;" }, // fraction slash, U+2044 NEW --> // <!-- Letterlike Symbols --> { "\u2118", "&weierp;" }, // script capital P = power set= Weierstrass p, U+2118 ISOamso --> { "\u2111", "&image;" }, // blackletter capital I = imaginary part,U+2111 ISOamso --> { "\u211C", "&real;" }, // blackletter capital R = real part symbol,U+211C ISOamso --> { "\u2122", "&trade;" }, // trade mark sign, U+2122 ISOnum --> { "\u2135", "&alefsym;" }, // alef symbol = first transfinite cardinal,U+2135 NEW --> // <!-- alef symbol is NOT the same as hebrew letter alef,U+05D0 although the // same glyph could be used to depict both characters --> // <!-- Arrows --> { "\u2190", "&larr;" }, // leftwards arrow, U+2190 ISOnum --> { "\u2191", "&uarr;" }, // upwards arrow, U+2191 ISOnum--> { "\u2192", "&rarr;" }, // rightwards arrow, U+2192 ISOnum --> { "\u2193", "&darr;" }, // downwards arrow, U+2193 ISOnum --> { "\u2194", "&harr;" }, // left right arrow, U+2194 ISOamsa --> { "\u21B5", "&crarr;" }, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW --> { "\u21D0", "&lArr;" }, // leftwards double arrow, U+21D0 ISOtech --> // <!-- ISO 10646 does not say that lArr is the same as the 'is implied by' // arrow but also does not have any other character for that function. // So ? lArr canbe used for 'is implied by' as ISOtech suggests --> { "\u21D1", "&uArr;" }, // upwards double arrow, U+21D1 ISOamsa --> { "\u21D2", "&rArr;" }, // rightwards double arrow,U+21D2 ISOtech --> // <!-- ISO 10646 does not say this is the 'implies' character but does not // have another character with this function so ?rArr can be used for // 'implies' as ISOtech suggests --> { "\u21D3", "&dArr;" }, // downwards double arrow, U+21D3 ISOamsa --> { "\u21D4", "&hArr;" }, // left right double arrow,U+21D4 ISOamsa --> // <!-- Mathematical Operators --> { "\u2200", "&forall;" }, // for all, U+2200 ISOtech --> { "\u2202", "&part;" }, // partial differential, U+2202 ISOtech --> { "\u2203", "&exist;" }, // there exists, U+2203 ISOtech --> { "\u2205", "&empty;" }, // empty set = null set = diameter,U+2205 ISOamso --> { "\u2207", "&nabla;" }, // nabla = backward difference,U+2207 ISOtech --> { "\u2208", "&isin;" }, // element of, U+2208 ISOtech --> { "\u2209", "&notin;" }, // not an element of, U+2209 ISOtech --> { "\u220B", "&ni;" }, // contains as member, U+220B ISOtech --> // <!-- should there be a more memorable name than 'ni'? --> { "\u220F", "&prod;" }, // n-ary product = product sign,U+220F ISOamsb --> // <!-- prod is NOT the same character as U+03A0 'greek capital letter pi' // though the same glyph might be used for both --> { "\u2211", "&sum;" }, // n-ary summation, U+2211 ISOamsb --> // <!-- sum is NOT the same character as U+03A3 'greek capital letter sigma' // though the same glyph might be used for both --> { "\u2212", "&minus;" }, // minus sign, U+2212 ISOtech --> { "\u2217", "&lowast;" }, // asterisk operator, U+2217 ISOtech --> { "\u221A", "&radic;" }, // square root = radical sign,U+221A ISOtech --> { "\u221D", "&prop;" }, // proportional to, U+221D ISOtech --> { "\u221E", "&infin;" }, // infinity, U+221E ISOtech --> { "\u2220", "&ang;" }, // angle, U+2220 ISOamso --> { "\u2227", "&and;" }, // logical and = wedge, U+2227 ISOtech --> { "\u2228", "&or;" }, // logical or = vee, U+2228 ISOtech --> { "\u2229", "&cap;" }, // intersection = cap, U+2229 ISOtech --> { "\u222A", "&cup;" }, // union = cup, U+222A ISOtech --> { "\u222B", "&int;" }, // integral, U+222B ISOtech --> { "\u2234", "&there4;" }, // therefore, U+2234 ISOtech --> { "\u223C", "&sim;" }, // tilde operator = varies with = similar to,U+223C ISOtech --> // <!-- tilde operator is NOT the same character as the tilde, U+007E,although // the same glyph might be used to represent both --> { "\u2245", "&cong;" }, // approximately equal to, U+2245 ISOtech --> { "\u2248", "&asymp;" }, // almost equal to = asymptotic to,U+2248 ISOamsr --> { "\u2260", "&ne;" }, // not equal to, U+2260 ISOtech --> { "\u2261", "&equiv;" }, // identical to, U+2261 ISOtech --> { "\u2264", "&le;" }, // less-than or equal to, U+2264 ISOtech --> { "\u2265", "&ge;" }, // greater-than or equal to,U+2265 ISOtech --> { "\u2282", "&sub;" }, // subset of, U+2282 ISOtech --> { "\u2283", "&sup;" }, // superset of, U+2283 ISOtech --> // <!-- note that nsup, 'not a superset of, U+2283' is not covered by the // Symbol font encoding and is not included. Should it be, for symmetry? // It is in ISOamsn --> <!ENTITY nsub", "8836"}, // not a subset of, U+2284 ISOamsn --> { "\u2286", "&sube;" }, // subset of or equal to, U+2286 ISOtech --> { "\u2287", "&supe;" }, // superset of or equal to,U+2287 ISOtech --> { "\u2295", "&oplus;" }, // circled plus = direct sum,U+2295 ISOamsb --> { "\u2297", "&otimes;" }, // circled times = vector product,U+2297 ISOamsb --> { "\u22A5", "&perp;" }, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech --> { "\u22C5", "&sdot;" }, // dot operator, U+22C5 ISOamsb --> // <!-- dot operator is NOT the same character as U+00B7 middle dot --> // <!-- Miscellaneous Technical --> { "\u2308", "&lceil;" }, // left ceiling = apl upstile,U+2308 ISOamsc --> { "\u2309", "&rceil;" }, // right ceiling, U+2309 ISOamsc --> { "\u230A", "&lfloor;" }, // left floor = apl downstile,U+230A ISOamsc --> { "\u230B", "&rfloor;" }, // right floor, U+230B ISOamsc --> { "\u2329", "&lang;" }, // left-pointing angle bracket = bra,U+2329 ISOtech --> // <!-- lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation // mark' --> { "\u232A", "&rang;" }, // right-pointing angle bracket = ket,U+232A ISOtech --> // <!-- rang is NOT the same character as U+003E 'greater than' or U+203A // 'single right-pointing angle quotation mark' --> // <!-- Geometric Shapes --> { "\u25CA", "&loz;" }, // lozenge, U+25CA ISOpub --> // <!-- Miscellaneous Symbols --> { "\u2660", "&spades;" }, // black spade suit, U+2660 ISOpub --> // <!-- black here seems to mean filled as opposed to hollow --> { "\u2663", "&clubs;" }, // black club suit = shamrock,U+2663 ISOpub --> { "\u2665", "&hearts;" }, // black heart suit = valentine,U+2665 ISOpub --> { "\u2666", "&diams;" }, // black diamond suit, U+2666 ISOpub --> // <!-- Latin Extended-A --> { "\u0152", "&OElig;" }, // -- latin capital ligature OE,U+0152 ISOlat2 --> { "\u0153", "&oelig;" }, // -- latin small ligature oe, U+0153 ISOlat2 --> // <!-- ligature is a misnomer, this is a separate character in some languages --> { "\u0160", "&Scaron;" }, // -- latin capital letter S with caron,U+0160 ISOlat2 --> { "\u0161", "&scaron;" }, // -- latin small letter s with caron,U+0161 ISOlat2 --> { "\u0178", "&Yuml;" }, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 --> // <!-- Spacing Modifier Letters --> { "\u02C6", "&circ;" }, // -- modifier letter circumflex accent,U+02C6 ISOpub --> { "\u02DC", "&tilde;" }, // small tilde, U+02DC ISOdia --> // <!-- General Punctuation --> { "\u2002", "&ensp;" }, // en space, U+2002 ISOpub --> { "\u2003", "&emsp;" }, // em space, U+2003 ISOpub --> { "\u2009", "&thinsp;" }, // thin space, U+2009 ISOpub --> { "\u200C", "&zwnj;" }, // zero width non-joiner,U+200C NEW RFC 2070 --> { "\u200D", "&zwj;" }, // zero width joiner, U+200D NEW RFC 2070 --> { "\u200E", "&lrm;" }, // left-to-right mark, U+200E NEW RFC 2070 --> { "\u200F", "&rlm;" }, // right-to-left mark, U+200F NEW RFC 2070 --> { "\u2013", "&ndash;" }, // en dash, U+2013 ISOpub --> { "\u2014", "&mdash;" }, // em dash, U+2014 ISOpub --> { "\u2018", "&lsquo;" }, // left single quotation mark,U+2018 ISOnum --> { "\u2019", "&rsquo;" }, // right single quotation mark,U+2019 ISOnum --> { "\u201A", "&sbquo;" }, // single low-9 quotation mark, U+201A NEW --> { "\u201C", "&ldquo;" }, // left double quotation mark,U+201C ISOnum --> { "\u201D", "&rdquo;" }, // right double quotation mark,U+201D ISOnum --> { "\u201E", "&bdquo;" }, // double low-9 quotation mark, U+201E NEW --> { "\u2020", "&dagger;" }, // dagger, U+2020 ISOpub --> { "\u2021", "&Dagger;" }, // double dagger, U+2021 ISOpub --> { "\u2030", "&permil;" }, // per mille sign, U+2030 ISOtech --> { "\u2039", "&lsaquo;" }, // single left-pointing angle quotation mark,U+2039 ISO proposed --> // <!-- lsaquo is proposed but not yet ISO standardized --> { "\u203A", "&rsaquo;" }, // single right-pointing angle quotation mark,U+203A ISO proposed --> // <!-- rsaquo is proposed but not yet ISO standardized --> { "\u20AC", "&euro;" }, // -- euro sign, U+20AC NEW --> }; public Html4Escape() { super(); addChain(new LookupReplacer(ISO8859_1_ESCAPE)); addChain(new LookupReplacer(HTML40_EXTENDED_ESCAPE)); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/text/escape/Html4Escape.java
2,380
/* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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.goide.regexp; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.intellij.lang.regexp.RegExpLanguageHost; import org.intellij.lang.regexp.psi.RegExpChar; import org.intellij.lang.regexp.psi.RegExpGroup; import org.intellij.lang.regexp.psi.RegExpNamedGroupRef; import org.intellij.lang.regexp.psi.RegExpSimpleClass; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; // see https://golang.org/pkg/regexp/syntax/ public class GoRegexHost implements RegExpLanguageHost { @Override public boolean characterNeedsEscaping(char c) { return false; } @Override public boolean supportsPerl5EmbeddedComments() { return false; } @Override public boolean supportsPossessiveQuantifiers() { return false; } @Override public boolean supportsPythonConditionalRefs() { return false; } @Override public boolean supportsNamedGroupSyntax(RegExpGroup group) { return group.isPythonNamedGroup(); // only (?P<name>) group is supported } @Override public boolean supportsNamedGroupRefSyntax(RegExpNamedGroupRef ref) { return false; } @Override public boolean supportsExtendedHexCharacter(RegExpChar regExpChar) { return true; } @Override public boolean isValidCategory(@NotNull String category) { return Lazy.KNOWN_PROPERTIES.contains(category); } @NotNull @Override public String[][] getAllKnownProperties() { return Lazy.KNOWN_PROPERTIES_ARRAY; } @Nullable @Override public String getPropertyDescription(@Nullable String name) { return name; } @NotNull @Override public String[][] getKnownCharacterClasses() { return Lazy.CHARACTER_CLASSES; } @Override public boolean supportsSimpleClass(RegExpSimpleClass simpleClass) { switch (simpleClass.getKind()) { case HORIZONTAL_SPACE: case NON_HORIZONTAL_SPACE: case NON_VERTICAL_SPACE: case XML_NAME_START: case NON_XML_NAME_START: case XML_NAME_PART: case NON_XML_NAME_PART: case UNICODE_GRAPHEME: case UNICODE_LINEBREAK: return false; case ANY: case DIGIT: case NON_DIGIT: case WORD: case NON_WORD: case SPACE: case NON_SPACE: case VERTICAL_SPACE: return true; } return false; } @Override public boolean supportsLiteralBackspace(RegExpChar aChar) { return false; } @Override public boolean supportsInlineOptionFlag(char flag, PsiElement context) { return StringUtil.containsChar("imsU", flag); } private interface Lazy { // SDK/unicode/tables.go Set<String> KNOWN_PROPERTIES = ContainerUtil.immutableSet("C", "Cc", "Cf", "Co", "Cs", "L", "Ll", "Lm", "Lo", "Lt", "Lu", "M", "Mc", "Me", "Mn", "N", "Nd", "Nl", "No", "P", "Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps", "S", "Sc", "Sk", "Sm", "So", "Z", "Zl", "Zp", "Zs", "Ahom", "Anatolian_Hieroglyphs", "Arabic", "Armenian", "Avestan", "Balinese", "Bamum", "Bassa_Vah", "Batak", "Bengali", "Bopomofo", "Brahmi", "Braille", "Buginese", "Buhid", "Canadian_Aboriginal", "Carian", "Caucasian_Albanian", "Chakma", "Cham", "Cherokee", "Common", "Coptic", "Cuneiform", "Cypriot", "Cyrillic", "Deseret", "Devanagari", "Duployan", "Egyptian_Hieroglyphs", "Elbasan", "Ethiopic", "Georgian", "Glagolitic", "Gothic", "Grantha", "Greek", "Gujarati", "Gurmukhi", "Han", "Hangul", "Hanunoo", "Hatran", "Hebrew", "Hiragana", "Imperial_Aramaic", "Inherited", "Inscriptional_Pahlavi", "Inscriptional_Parthian", "Javanese", "Kaithi", "Kannada", "Katakana", "Kayah_Li", "Kharoshthi", "Khmer", "Khojki", "Khudawadi", "Lao", "Latin", "Lepcha", "Limbu", "Linear_A", "Linear_B", "Lisu", "Lycian", "Lydian", "Mahajani", "Malayalam", "Mandaic", "Manichaean", "Meetei_Mayek", "Mende_Kikakui", "Meroitic_Cursive", "Meroitic_Hieroglyphs", "Miao", "Modi", "Mongolian", "Mro", "Multani", "Myanmar", "Nabataean", "New_Tai_Lue", "Nko", "Ogham", "Ol_Chiki", "Old_Hungarian", "Old_Italic", "Old_North_Arabian", "Old_Permic", "Old_Persian", "Old_South_Arabian", "Old_Turkic", "Oriya", "Osmanya", "Pahawh_Hmong", "Palmyrene", "Pau_Cin_Hau", "Phags_Pa", "Phoenician", "Psalter_Pahlavi", "Rejang", "Runic", "Samaritan", "Saurashtra", "Sharada", "Shavian", "Siddham", "SignWriting", "Sinhala", "Sora_Sompeng", "Sundanese", "Syloti_Nagri", "Syriac", "Tagalog", "Tagbanwa", "Tai_Le", "Tai_Tham", "Tai_Viet", "Takri", "Tamil", "Telugu", "Thaana", "Thai", "Tibetan", "Tifinagh", "Tirhuta", "Ugaritic", "Vai", "Warang_Citi", "Yi"); String[][] KNOWN_PROPERTIES_ARRAY = ContainerUtil.map2Array(KNOWN_PROPERTIES, new String[KNOWN_PROPERTIES.size()][2], s -> new String[]{s, ""}); String[][] CHARACTER_CLASSES = { // Empty strings {"A", "at beginning of text"}, {"b", "at ASCII word boundary (\\w on one side and \\W, \\A, or \\z on the other)"}, {"B", "not at ASCII word boundary"}, {"z", "at end of text"}, {"Z", "end of the text but for the final terminator, if any"}, // Escape sequences {"a", "bell (== \007)"}, {"f", "form feed (== \014)"}, {"t", "horizontal tab (== \011)"}, {"n", "newline (== \012)"}, {"r", "carriage return (== \015)"}, {"v", "vertical tab character (== \013)"}, {"*", "literal *, for any punctuation character *"}, {"Q", "nothing, but quotes all characters until \\E"}, {"E", "nothing, but ends quoting started by \\Q"}, // Perl character classes (all ASCII-only): {"d", "digits (== [0-9])"}, {"D", "not digits (== [^0-9])"}, {"s", "whitespace (== [\t\n\f\r ])"}, {"S", "not whitespace (== [^\t\n\f\r ])"}, {"w", "word characters (== [0-9A-Za-z_])"}, {"W", "not word characters (== [^0-9A-Za-z_])"}, }; } }
go-lang-plugin-org/go-lang-idea-plugin
src/com/goide/regexp/GoRegexHost.java
2,381
package the.bytecode.club.bytecodeviewer.translation; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.map.LinkedMap; import the.bytecode.club.bytecodeviewer.BytecodeViewer; import the.bytecode.club.bytecodeviewer.Constants; import the.bytecode.club.bytecodeviewer.api.BCV; import the.bytecode.club.bytecodeviewer.resources.IconResources; import the.bytecode.club.bytecodeviewer.resources.Resource; /*************************************************************************** * Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite * * Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.com * * * * 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/>. * ***************************************************************************/ /** * All of the supported languages * * TODO: Hindi, Bengali, Korean, Thai & Javanese need fonts to be supplied for them to show. * The default font should be saved so it can be restored for latin-character based languages * * @author Konloch * @since 6/28/2021 */ public enum Language { ENGLISH("/translations/english.json", "English", "English", "en"), ARABIC("/translations/arabic.json", "عربى", "English", "ar"), CROATIAN("/translations/croatian.json", "hrvatski", "English", "hr"), CZECH("/translations/czech.json", "čeština", "English", "cs"), BULGARIAN("/translations/bulgarian.json", "български", "English", "bg"), DANISH("/translations/danish.json", "dansk", "English", "da"), ESTONIAN("/translations/estonian.json", "Eesti", "English", "et"), FARSI("/translations/farsi.json", "فارسی ", "English", "fa"), FINNISH("/translations/finnish.json", "Suomen Kieli", "English", "fi"), FRENCH("/translations/french.json", "Français", "English", "fr"), GERMAN("/translations/german.json", "Deutsch", "German", "de"), GEORGIAN("/translations/georgian.json", "ქართული ენა", "English", "ka"), GREEK("/translations/greek.json", "ελληνικά", "English", "el"), HAUSA("/translations/hausa.json", "Hausa", "English", "ha"), HEBREW("/translations/hebrew.json", "עִבְרִית\u200E", "English", "iw", "he"), //HINDI("/translations/hindi.json", "हिंदी", "English", "hi"), //BENGALI("/translations/bengali.json", "বাংলা", "English", "bn"), HUNGARIAN("/translations/hungarian.json", "Magyar Nyelv", "English", "hu"), INDONESIAN("/translations/indonesian.json", "bahasa Indonesia", "English", "id"), ITALIAN("/translations/italian.json", "Italiano", "English", "it"), JAPANESE("/translations/japanese.json", "日本語", "English", "ja"), LATIVAN("/translations/lativan.json", "Lativan", "English", "lv"), LITHUANIAN("/translations/lithuanian.json", "Lietuvių", "English", "lt"), //JAVANESE("/translations/javanese.json", "ꦧꦱꦗꦮ", "English", "jw", "jv"), //KOREAN("/translations/korean.json", "Korean", "English", "ko"), MALAY("/translations/malay.json", "Bahasa Melayu", "English", "ms"), MANDARIN("/translations/mandarin.json", "普通话", "Mandarin", "zh-CN", "zh_cn", "zh"), NEDERLANDS("/translations/nederlands.json", "Nederlands", "English", "nl"), //dutch NORWEGIAN("/translations/norwegian.json", "Norsk", "English", "no"), POLISH("/translations/polish.json", "Polski", "English", "pl"), PORTUGUESE("/translations/portuguese.json", "Português", "English", "pt"), ROMANIAN("/translations/romanian.json", "Română", "English", "ro"), RUSSIAN("/translations/russian.json", "русский", "English", "ru"), SLOVAK("/translations/slovak.json", "Slovensky", "English", "sk"), SLOVENIAN("/translations/slovenian.json", "Slovenščina", "English", "sl"), SPANISH("/translations/spanish.json", "Español", "English", "es"), SERBIAN("/translations/serbian.json", "српски језик", "English", "sr"), SWAHILI("/translations/swahili.json", "Kiswahili", "English", "sw"), SWEDISH("/translations/swedish.json", "svenska", "English", "sv"), //THAI("/translations/thai.json", "ภาษาไทย", "English", "th"), TURKISH("/translations/turkish.json", "Türkçe", "English", "tr"), UKRAINIAN("/translations/ukrainian.json", "украї́нська мо́ва", "English", "uk"), VIETNAMESE("/translations/vietnamese.json", "Tiếng Việt", "English", "vi"), ; private static final Map<String, Language> languageCodeLookup; static { languageCodeLookup = new LinkedHashMap<>(); for(Language l : values()) l.languageCode.forEach((langCode)-> languageCodeLookup.put(langCode, l)); } private final String resourcePath; private final String readableName; private final String htmlIdentifier; private final Set<String> languageCode; private Map<String, String> translationMap; Language(String resourcePath, String readableName, String htmlIdentifier, String... languageCodes) { this.resourcePath = resourcePath; this.readableName = readableName; this.htmlIdentifier = htmlIdentifier.toLowerCase(); this.languageCode = new LinkedHashSet<>(Arrays.asList(languageCodes)); } public void setLanguageTranslations() throws IOException { printMissingLanguageKeys(); Map<String, String> translationMap = getTranslation(); for(TranslatedComponents translatedComponents : TranslatedComponents.values()) { TranslatedComponentReference text = translatedComponents.getTranslatedComponentReference(); //skip translating if the language config is missing the translation key if(!translationMap.containsKey(text.key)) { BCV.logE(true, resourcePath + " -> " + text.key + " - Missing Translation Key"); continue; } //update translation text value text.value = translationMap.get(text.key); //translate constant strings try { TranslatedStrings str = TranslatedStrings.valueOf(text.key); str.setText(text.value); } catch (IllegalArgumentException ignored) { } //check if translation key has been assigned to a component, //on fail print an error alerting the devs if(translatedComponents.getTranslatedComponentReference().runOnUpdate.isEmpty()) //&& TranslatedStrings.nameSet.contains(translation.name())) { BCV.logE(true, "TranslatedComponents:" + translatedComponents.name() + " is missing component attachment, skipping..."); continue; } //trigger translation event translatedComponents.getTranslatedComponentReference().translate(); } } public Map<String, String> getTranslation() throws IOException { if(translationMap == null) { translationMap = BytecodeViewer.gson.fromJson( Resource.loadResourceAsString(resourcePath), new TypeToken<HashMap<String, String>>() {}.getType()); } return translationMap; } //TODO // When adding new Translation Components: // 1) start by adding the strings into the english.json // 2) run this function to get the keys and add them into the Translation.java enum // 3) replace the swing component (MainViewerGUI) with a translated component // and reference the correct translation key // 4) add the translation key to the rest of the translation files public void printMissingLanguageKeys() throws IOException { if(this != ENGLISH) return; LinkedMap<String, String> translationMap = BytecodeViewer.gson.fromJson( Resource.loadResourceAsString(resourcePath), new TypeToken<LinkedMap<String, String>>(){}.getType()); Set<String> existingKeys = new HashSet<>(); for(TranslatedComponents t : TranslatedComponents.values()) existingKeys.add(t.name()); for(String key : translationMap.keySet()) if(!existingKeys.contains(key)) BCV.logE(true, key + ","); } public String getResourcePath() { return resourcePath; } public Set<String> getLanguageCode() { return languageCode; } public String getReadableName() { return readableName; } public String getHTMLPath(String identifier) { return "translations/html/" + identifier + "." + htmlIdentifier + ".html"; } public static Map<String, Language> getLanguageCodeLookup() { return languageCodeLookup; } }
Konloch/bytecode-viewer
src/main/java/the/bytecode/club/bytecodeviewer/translation/Language.java
2,382
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app.tools; import processing.app.*; import processing.app.ui.Editor; import processing.app.ui.Toolkit; import processing.core.*; import java.awt.Component; import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; /** * GUI tool for font creation heaven/hell. */ public class CreateFont extends JFrame implements Tool { Base base; JList<String> fontSelector; JTextField sizeSelector; JButton charsetButton; JCheckBox smoothBox; JComponent sample; JButton okButton; JTextField filenameField; Map<String,Font> table; boolean smooth = true; Font font; String[] list; int selection = -1; CharacterSelector charSelector; public CreateFont() { super(Language.text("create_font")); } public String getMenuTitle() { return Language.text("menu.tools.create_font"); } public void init(Base base) { this.base = base; Container paine = getContentPane(); paine.setLayout(new BorderLayout()); //10, 10)); JPanel pain = new JPanel(); pain.setBorder(new EmptyBorder(13, 13, 13, 13)); paine.add(pain, BorderLayout.CENTER); pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS)); String labelText = Language.text("create_font.label"); JTextArea textarea = new JTextArea(labelText); textarea.setBorder(new EmptyBorder(10, 10, 20, 10)); textarea.setBackground(null); textarea.setEditable(false); textarea.setHighlighter(null); textarea.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(textarea); // don't care about families starting with . or # // also ignore dialog, dialoginput, monospaced, serif, sansserif // getFontList is deprecated in 1.4, so this has to be used //long t = System.currentTimeMillis(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font[] fonts = ge.getAllFonts(); //System.out.println("font startup took " + (System.currentTimeMillis() - t) + " ms"); /* if (false) { ArrayList<Font> fontList = new ArrayList<Font>(); File folderList = new File("/Users/fry/coconut/sys/fonts/web"); for (File folder : folderList.listFiles()) { if (folder.isDirectory()) { File[] items = folder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.charAt(0) == '.') return false; return (name.toLowerCase().endsWith(".ttf") || name.toLowerCase().endsWith(".otf")); } }); for (File fontFile : items) { try { FileInputStream fis = new FileInputStream(fontFile); BufferedInputStream input = new BufferedInputStream(fis); Font font = Font.createFont(Font.TRUETYPE_FONT, input); input.close(); fontList.add(font); } catch (Exception e) { System.out.println("Ignoring " + fontFile.getName()); } } } } // fonts = new Font[fontList.size()]; // fontList.toArray(fonts); fonts = fontList.toArray(new Font[fontList.size()]); } */ String[] fontList = new String[fonts.length]; table = new HashMap<String,Font>(); int index = 0; for (int i = 0; i < fonts.length; i++) { //String psname = fonts[i].getPSName(); //if (psname == null) System.err.println("ps name is null"); try { fontList[index++] = fonts[i].getPSName(); table.put(fonts[i].getPSName(), fonts[i]); // Checking into http://processing.org/bugs/bugzilla/407.html // and https://github.com/processing/processing/issues/1727 // if (fonts[i].getPSName().contains("Helv")) { // System.out.println(fonts[i].getPSName() + " -> " + fonts[i]); // } } catch (Exception e) { // Sometimes fonts cause lots of trouble. // http://code.google.com/p/processing/issues/detail?id=442 e.printStackTrace(); } } list = new String[index]; System.arraycopy(fontList, 0, list, 0, index); fontSelector = new JList<String>(list); fontSelector.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { selection = fontSelector.getSelectedIndex(); okButton.setEnabled(true); update(); } } }); fontSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSelector.setVisibleRowCount(12); JScrollPane fontScroller = new JScrollPane(fontSelector); pain.add(fontScroller); Dimension d1 = new Dimension(13, 13); pain.add(new Box.Filler(d1, d1, d1)); sample = new SampleComponent(this); // Seems that in some instances, no default font is set // http://dev.processing.org/bugs/show_bug.cgi?id=777 sample.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(sample); Dimension d2 = new Dimension(6, 6); pain.add(new Box.Filler(d2, d2, d2)); JPanel panel = new JPanel(); panel.add(new JLabel(Language.text("create_font.size") + ":" )); sizeSelector = new JTextField(" 48 "); sizeSelector.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } public void changedUpdate(DocumentEvent e) { } }); panel.add(sizeSelector); smoothBox = new JCheckBox(Language.text("create_font.smooth")); smoothBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { smooth = smoothBox.isSelected(); update(); } }); smoothBox.setSelected(smooth); panel.add(smoothBox); // allBox = new JCheckBox("All Characters"); // allBox.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // all = allBox.isSelected(); // } // }); // allBox.setSelected(all); // panel.add(allBox); charsetButton = new JButton(Language.text("create_font.characters")); charsetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //showCharacterList(); charSelector.setVisible(true); } }); panel.add(charsetButton); pain.add(panel); JPanel filestuff = new JPanel(); filestuff.add(new JLabel(Language.text("create_font.filename") + ":")); filestuff.add(filenameField = new JTextField(20)); filestuff.add(new JLabel(".vlw")); pain.add(filestuff); JPanel buttons = new JPanel(); JButton cancelButton = new JButton(Language.text("prompt.cancel")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton = new JButton(Language.text("prompt.ok")); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { build(); } }); okButton.setEnabled(false); buttons.add(cancelButton); buttons.add(okButton); pain.add(buttons); JRootPane root = getRootPane(); root.setDefaultButton(okButton); ActionListener disposer = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; Toolkit.registerWindowCloseKeys(root, disposer); Toolkit.setIcon(this); pack(); setResizable(false); //System.out.println(getPreferredSize()); // do this after pack so it doesn't affect layout sample.setFont(new Font(list[0], Font.PLAIN, 48)); fontSelector.setSelectedIndex(0); // Dimension screen = Toolkit.getScreenSize(); // windowSize = getSize(); // setLocation((screen.width - windowSize.width) / 2, // (screen.height - windowSize.height) / 2); setLocationRelativeTo(null); // create this behind the scenes charSelector = new CharacterSelector(); } public void run() { setVisible(true); } public void update() { int fontsize = 0; try { fontsize = Integer.parseInt(sizeSelector.getText().trim()); //System.out.println("'" + sizeSelector.getText() + "'"); } catch (NumberFormatException e2) { } // if a deselect occurred, selection will be -1 if ((fontsize > 0) && (fontsize < 256) && (selection != -1)) { //font = new Font(list[selection], Font.PLAIN, fontsize); Font instance = table.get(list[selection]); // font = instance.deriveFont(Font.PLAIN, fontsize); font = instance.deriveFont((float) fontsize); //System.out.println("setting font to " + font); sample.setFont(font); String filenameSuggestion = list[selection].replace(' ', '_'); filenameSuggestion += "-" + fontsize; filenameField.setText(filenameSuggestion); } } public void build() { int fontsize = 0; try { fontsize = Integer.parseInt(sizeSelector.getText().trim()); } catch (NumberFormatException e) { } if (fontsize <= 0) { JOptionPane.showMessageDialog(this, "Bad font size, try again.", "Badness", JOptionPane.WARNING_MESSAGE); return; } String filename = filenameField.getText().trim(); if (filename.length() == 0) { JOptionPane.showMessageDialog(this, "Enter a file name for the font.", "Lameness", JOptionPane.WARNING_MESSAGE); return; } if (!filename.endsWith(".vlw")) { filename += ".vlw"; } try { Font instance = table.get(list[selection]); font = instance.deriveFont(Font.PLAIN, fontsize); //PFont f = new PFont(font, smooth, all ? null : PFont.CHARSET); PFont f = new PFont(font, smooth, charSelector.getCharacters()); // the editor may have changed while the window was open Editor editor = base.getActiveEditor(); // make sure the 'data' folder exists File folder = editor.getSketch().prepareDataFolder(); f.save(new FileOutputStream(new File(folder, filename))); } catch (IOException e) { JOptionPane.showMessageDialog(CreateFont.this, "An error occurred while creating font.", "No font for you", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } setVisible(false); } // /** // * make the window vertically resizable // */ // public Dimension getMaximumSize() { // return new Dimension(windowSize.width, 2000); // } // // // public Dimension getMinimumSize() { // return windowSize; // } /* public void show(File targetFolder) { this.targetFolder = targetFolder; show(); } */ } /** * Component that draws the sample text. This is its own subclassed component * because Mac OS X controls seem to reset the RenderingHints for smoothing * so that they cannot be overridden properly for JLabel or JTextArea. * @author fry */ class SampleComponent extends JComponent { // see http://rinkworks.com/words/pangrams.shtml String text = "Forsaking monastic tradition, twelve jovial friars gave up their " + "vocation for a questionable existence on the flying trapeze."; int high = 80; CreateFont parent; public SampleComponent(CreateFont p) { this.parent = p; // and yet, we still need an inner class to handle the basics. // or no, maybe i'll refactor this as a separate class! // maybe a few getters and setters? mmm? addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { String input = (String) JOptionPane.showInputDialog(parent, "Enter new sample text:", "Sample Text", JOptionPane.PLAIN_MESSAGE, null, // icon null, // choices text); if (input != null) { text = input; parent.repaint(); } } }); } public void paintComponent(Graphics g) { // System.out.println("smoothing set to " + smooth); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.WHITE); Dimension dim = getSize(); g2.fillRect(0, 0, dim.width, dim.height); g2.setColor(Color.BLACK); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, parent.smooth ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // add this one as well (after 1.0.9) g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, parent.smooth ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); //super.paintComponent(g2); Font font = getFont(); int ascent = g2.getFontMetrics().getAscent(); // System.out.println(f.getName()); g2.setFont(font); g2.drawString(text, 5, dim.height - (dim.height - ascent) / 2); } public Dimension getPreferredSize() { return new Dimension(400, high); } public Dimension getMaximumSize() { return new Dimension(10000, high); } public Dimension getMinimumSize() { return new Dimension(100, high); } } /** * Frame for selecting which characters will be included with the font. */ class CharacterSelector extends JFrame { JRadioButton defaultCharsButton; JRadioButton allCharsButton; JRadioButton unicodeCharsButton; JScrollPane unicodeBlockScroller; JList<JCheckBox> charsetList; public CharacterSelector() { super(Language.text("create_font.character_selector")); charsetList = new CheckBoxList(); DefaultListModel<JCheckBox> model = new DefaultListModel<JCheckBox>(); charsetList.setModel(model); for (String item : blockNames) { model.addElement(new JCheckBox(item)); } unicodeBlockScroller = new JScrollPane(charsetList, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Container outer = getContentPane(); outer.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setBorder(new EmptyBorder(13, 13, 13, 13)); outer.add(pain, BorderLayout.CENTER); pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS)); String labelText = Language.text("create_font.character_selector.label"); JTextArea textarea = new JTextArea(labelText); textarea.setBorder(new EmptyBorder(13, 8, 13, 8)); textarea.setBackground(null); textarea.setEditable(false); textarea.setHighlighter(null); textarea.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(textarea); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { //System.out.println("action " + unicodeCharsButton.isSelected()); //unicodeBlockScroller.setEnabled(unicodeCharsButton.isSelected()); charsetList.setEnabled(unicodeCharsButton.isSelected()); } }; defaultCharsButton = new JRadioButton(Language.text("create_font.default_characters")); allCharsButton = new JRadioButton(Language.text("create_font.all_characters")); unicodeCharsButton = new JRadioButton(Language.text("create_font.specific_unicode")); defaultCharsButton.addActionListener(listener); allCharsButton.addActionListener(listener); unicodeCharsButton.addActionListener(listener); ButtonGroup group = new ButtonGroup(); group.add(defaultCharsButton); group.add(allCharsButton); group.add(unicodeCharsButton); JPanel radioPanel = new JPanel(); //radioPanel.setBackground(Color.red); radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS)); radioPanel.add(defaultCharsButton); radioPanel.add(allCharsButton); radioPanel.add(unicodeCharsButton); JPanel rightStuff = new JPanel(); rightStuff.setLayout(new BoxLayout(rightStuff, BoxLayout.X_AXIS)); rightStuff.add(radioPanel); rightStuff.add(Box.createHorizontalGlue()); pain.add(rightStuff); pain.add(Box.createVerticalStrut(13)); // pain.add(radioPanel); // pain.add(defaultCharsButton); // pain.add(allCharsButton); // pain.add(unicodeCharsButton); defaultCharsButton.setSelected(true); charsetList.setEnabled(false); //frame.getContentPane().add(scroller); pain.add(unicodeBlockScroller); pain.add(Box.createVerticalStrut(8)); JPanel buttons = new JPanel(); JButton okButton = new JButton(Language.text("prompt.ok")); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton.setEnabled(true); buttons.add(okButton); pain.add(buttons); JRootPane root = getRootPane(); root.setDefaultButton(okButton); ActionListener disposer = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; Toolkit.registerWindowCloseKeys(root, disposer); Toolkit.setIcon(this); pack(); Dimension screen = Toolkit.getScreenSize(); Dimension windowSize = getSize(); setLocation((screen.width - windowSize.width) / 2, (screen.height - windowSize.height) / 2); } protected char[] getCharacters() { if (defaultCharsButton.isSelected()) { return PFont.CHARSET; } char[] charset = new char[65536]; if (allCharsButton.isSelected()) { for (int i = 0; i < 0xFFFF; i++) { charset[i] = (char) i; } } else { DefaultListModel model = (DefaultListModel) charsetList.getModel(); int index = 0; for (int i = 0; i < BLOCKS.length; i++) { if (((JCheckBox) model.get(i)).isSelected()) { for (int j = blockStart[i]; j <= blockStop[i]; j++) { charset[index++] = (char) j; } } } charset = PApplet.subset(charset, 0, index); } //System.out.println("Creating font with " + charset.length + " characters."); return charset; } // http://www.unicode.org/Public/UNIDATA/Blocks.txt static final String[] BLOCKS = { "0000..007F; Basic Latin", "0080..00FF; Latin-1 Supplement", "0100..017F; Latin Extended-A", "0180..024F; Latin Extended-B", "0250..02AF; IPA Extensions", "02B0..02FF; Spacing Modifier Letters", "0300..036F; Combining Diacritical Marks", "0370..03FF; Greek and Coptic", "0400..04FF; Cyrillic", "0500..052F; Cyrillic Supplement", "0530..058F; Armenian", "0590..05FF; Hebrew", "0600..06FF; Arabic", "0700..074F; Syriac", "0750..077F; Arabic Supplement", "0780..07BF; Thaana", "07C0..07FF; NKo", "0800..083F; Samaritan", "0900..097F; Devanagari", "0980..09FF; Bengali", "0A00..0A7F; Gurmukhi", "0A80..0AFF; Gujarati", "0B00..0B7F; Oriya", "0B80..0BFF; Tamil", "0C00..0C7F; Telugu", "0C80..0CFF; Kannada", "0D00..0D7F; Malayalam", "0D80..0DFF; Sinhala", "0E00..0E7F; Thai", "0E80..0EFF; Lao", "0F00..0FFF; Tibetan", "1000..109F; Myanmar", "10A0..10FF; Georgian", "1100..11FF; Hangul Jamo", "1200..137F; Ethiopic", "1380..139F; Ethiopic Supplement", "13A0..13FF; Cherokee", "1400..167F; Unified Canadian Aboriginal Syllabics", "1680..169F; Ogham", "16A0..16FF; Runic", "1700..171F; Tagalog", "1720..173F; Hanunoo", "1740..175F; Buhid", "1760..177F; Tagbanwa", "1780..17FF; Khmer", "1800..18AF; Mongolian", "18B0..18FF; Unified Canadian Aboriginal Syllabics Extended", "1900..194F; Limbu", "1950..197F; Tai Le", "1980..19DF; New Tai Lue", "19E0..19FF; Khmer Symbols", "1A00..1A1F; Buginese", "1A20..1AAF; Tai Tham", "1B00..1B7F; Balinese", "1B80..1BBF; Sundanese", "1C00..1C4F; Lepcha", "1C50..1C7F; Ol Chiki", "1CD0..1CFF; Vedic Extensions", "1D00..1D7F; Phonetic Extensions", "1D80..1DBF; Phonetic Extensions Supplement", "1DC0..1DFF; Combining Diacritical Marks Supplement", "1E00..1EFF; Latin Extended Additional", "1F00..1FFF; Greek Extended", "2000..206F; General Punctuation", "2070..209F; Superscripts and Subscripts", "20A0..20CF; Currency Symbols", "20D0..20FF; Combining Diacritical Marks for Symbols", "2100..214F; Letterlike Symbols", "2150..218F; Number Forms", "2190..21FF; Arrows", "2200..22FF; Mathematical Operators", "2300..23FF; Miscellaneous Technical", "2400..243F; Control Pictures", "2440..245F; Optical Character Recognition", "2460..24FF; Enclosed Alphanumerics", "2500..257F; Box Drawing", "2580..259F; Block Elements", "25A0..25FF; Geometric Shapes", "2600..26FF; Miscellaneous Symbols", "2700..27BF; Dingbats", "27C0..27EF; Miscellaneous Mathematical Symbols-A", "27F0..27FF; Supplemental Arrows-A", "2800..28FF; Braille Patterns", "2900..297F; Supplemental Arrows-B", "2980..29FF; Miscellaneous Mathematical Symbols-B", "2A00..2AFF; Supplemental Mathematical Operators", "2B00..2BFF; Miscellaneous Symbols and Arrows", "2C00..2C5F; Glagolitic", "2C60..2C7F; Latin Extended-C", "2C80..2CFF; Coptic", "2D00..2D2F; Georgian Supplement", "2D30..2D7F; Tifinagh", "2D80..2DDF; Ethiopic Extended", "2DE0..2DFF; Cyrillic Extended-A", "2E00..2E7F; Supplemental Punctuation", "2E80..2EFF; CJK Radicals Supplement", "2F00..2FDF; Kangxi Radicals", "2FF0..2FFF; Ideographic Description Characters", "3000..303F; CJK Symbols and Punctuation", "3040..309F; Hiragana", "30A0..30FF; Katakana", "3100..312F; Bopomofo", "3130..318F; Hangul Compatibility Jamo", "3190..319F; Kanbun", "31A0..31BF; Bopomofo Extended", "31C0..31EF; CJK Strokes", "31F0..31FF; Katakana Phonetic Extensions", "3200..32FF; Enclosed CJK Letters and Months", "3300..33FF; CJK Compatibility", "3400..4DBF; CJK Unified Ideographs Extension A", "4DC0..4DFF; Yijing Hexagram Symbols", "4E00..9FFF; CJK Unified Ideographs", "A000..A48F; Yi Syllables", "A490..A4CF; Yi Radicals", "A4D0..A4FF; Lisu", "A500..A63F; Vai", "A640..A69F; Cyrillic Extended-B", "A6A0..A6FF; Bamum", "A700..A71F; Modifier Tone Letters", "A720..A7FF; Latin Extended-D", "A800..A82F; Syloti Nagri", "A830..A83F; Common Indic Number Forms", "A840..A87F; Phags-pa", "A880..A8DF; Saurashtra", "A8E0..A8FF; Devanagari Extended", "A900..A92F; Kayah Li", "A930..A95F; Rejang", "A960..A97F; Hangul Jamo Extended-A", "A980..A9DF; Javanese", "AA00..AA5F; Cham", "AA60..AA7F; Myanmar Extended-A", "AA80..AADF; Tai Viet", "ABC0..ABFF; Meetei Mayek", "AC00..D7AF; Hangul Syllables", "D7B0..D7FF; Hangul Jamo Extended-B", "D800..DB7F; High Surrogates", "DB80..DBFF; High Private Use Surrogates", "DC00..DFFF; Low Surrogates", "E000..F8FF; Private Use Area", "F900..FAFF; CJK Compatibility Ideographs", "FB00..FB4F; Alphabetic Presentation Forms", "FB50..FDFF; Arabic Presentation Forms-A", "FE00..FE0F; Variation Selectors", "FE10..FE1F; Vertical Forms", "FE20..FE2F; Combining Half Marks", "FE30..FE4F; CJK Compatibility Forms", "FE50..FE6F; Small Form Variants", "FE70..FEFF; Arabic Presentation Forms-B", "FF00..FFEF; Halfwidth and Fullwidth Forms", "FFF0..FFFF; Specials" }; static String[] blockNames; static int[] blockStart; static int[] blockStop; static { int count = BLOCKS.length; blockNames = new String[count]; blockStart = new int[count]; blockStop = new int[count]; for (int i = 0; i < count; i++) { String line = BLOCKS[i]; blockStart[i] = PApplet.unhex(line.substring(0, 4)); blockStop[i] = PApplet.unhex(line.substring(6, 10)); blockNames[i] = line.substring(12); } // PApplet.println(codePointStop); // PApplet.println(codePoints); } } // Code for this CheckBoxList class found on the net, though I've lost the // link. If you run across the original version, please let me know so that // the original author can be credited properly. It was from a snippet // collection, but it seems to have been picked up so many places with others // placing their copyright on it, that I haven't been able to determine the // original author. [fry 20100216] class CheckBoxList extends JList<JCheckBox> { protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); public CheckBoxList() { setCellRenderer(new CellRenderer()); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (isEnabled()) { int index = locationToIndex(e.getPoint()); if (index != -1) { JCheckBox checkbox = getModel().getElementAt(index); checkbox.setSelected(!checkbox.isSelected()); repaint(); } } } }); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } protected class CellRenderer implements ListCellRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JCheckBox checkbox = (JCheckBox) value; checkbox.setBackground(isSelected ? getSelectionBackground() : getBackground()); checkbox.setForeground(isSelected ? getSelectionForeground() : getForeground()); //checkbox.setEnabled(isEnabled()); checkbox.setEnabled(list.isEnabled()); checkbox.setFont(getFont()); checkbox.setFocusPainted(false); checkbox.setBorderPainted(true); checkbox.setBorder(isSelected ? UIManager.getBorder("List.focusCellHighlightBorder") : noFocusBorder); return checkbox; } } }
processing/processing
app/src/processing/app/tools/CreateFont.java
2,383
// 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.qe; import org.apache.doris.analysis.SetVar; import org.apache.doris.analysis.StringLiteral; import org.apache.doris.catalog.Env; import org.apache.doris.common.Config; import org.apache.doris.common.DdlException; import org.apache.doris.common.VariableAnnotation; import org.apache.doris.common.io.Text; import org.apache.doris.common.io.Writable; import org.apache.doris.common.util.TimeUtils; import org.apache.doris.nereids.metrics.Event; import org.apache.doris.nereids.metrics.EventSwitchParser; import org.apache.doris.nereids.parser.Dialect; import org.apache.doris.nereids.rules.RuleType; import org.apache.doris.planner.GroupCommitBlockSink; import org.apache.doris.qe.VariableMgr.VarAttr; import org.apache.doris.thrift.TGroupCommitMode; import org.apache.doris.thrift.TQueryOptions; import org.apache.doris.thrift.TResourceLimit; import org.apache.doris.thrift.TRuntimeFilterType; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.thrift.TConfiguration; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.security.SecureRandom; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; /** * System variable. **/ public class SessionVariable implements Serializable, Writable { public static final Logger LOG = LogManager.getLogger(SessionVariable.class); public static final String EXEC_MEM_LIMIT = "exec_mem_limit"; public static final String LOCAL_EXCHANGE_FREE_BLOCKS_LIMIT = "local_exchange_free_blocks_limit"; public static final String SCAN_QUEUE_MEM_LIMIT = "scan_queue_mem_limit"; public static final String NUM_SCANNER_THREADS = "num_scanner_threads"; public static final String SCANNER_SCALE_UP_RATIO = "scanner_scale_up_ratio"; public static final String QUERY_TIMEOUT = "query_timeout"; public static final String ANALYZE_TIMEOUT = "analyze_timeout"; public static final String MAX_EXECUTION_TIME = "max_execution_time"; public static final String INSERT_TIMEOUT = "insert_timeout"; public static final String ENABLE_PROFILE = "enable_profile"; public static final String AUTO_PROFILE_THRESHOLD_MS = "auto_profile_threshold_ms"; public static final String SQL_MODE = "sql_mode"; public static final String WORKLOAD_VARIABLE = "workload_group"; public static final String RESOURCE_VARIABLE = "resource_group"; public static final String AUTO_COMMIT = "autocommit"; public static final String TX_ISOLATION = "tx_isolation"; public static final String TX_READ_ONLY = "tx_read_only"; public static final String TRANSACTION_READ_ONLY = "transaction_read_only"; public static final String TRANSACTION_ISOLATION = "transaction_isolation"; public static final String CHARACTER_SET_CLIENT = "character_set_client"; public static final String CHARACTER_SET_CONNNECTION = "character_set_connection"; public static final String CHARACTER_SET_RESULTS = "character_set_results"; public static final String CHARACTER_SET_SERVER = "character_set_server"; public static final String COLLATION_CONNECTION = "collation_connection"; public static final String COLLATION_DATABASE = "collation_database"; public static final String COLLATION_SERVER = "collation_server"; public static final String SQL_AUTO_IS_NULL = "sql_auto_is_null"; public static final String SQL_SELECT_LIMIT = "sql_select_limit"; public static final String MAX_ALLOWED_PACKET = "max_allowed_packet"; public static final String AUTO_INCREMENT_INCREMENT = "auto_increment_increment"; public static final String QUERY_CACHE_TYPE = "query_cache_type"; public static final String INTERACTIVE_TIMTOUT = "interactive_timeout"; public static final String WAIT_TIMEOUT = "wait_timeout"; public static final String NET_WRITE_TIMEOUT = "net_write_timeout"; public static final String NET_READ_TIMEOUT = "net_read_timeout"; public static final String TIME_ZONE = "time_zone"; public static final String SQL_SAFE_UPDATES = "sql_safe_updates"; public static final String NET_BUFFER_LENGTH = "net_buffer_length"; public static final String CODEGEN_LEVEL = "codegen_level"; public static final String HAVE_QUERY_CACHE = "have_query_cache"; // mem limit can't smaller than bufferpool's default page size public static final int MIN_EXEC_MEM_LIMIT = 2097152; public static final String BATCH_SIZE = "batch_size"; public static final String DISABLE_STREAMING_PREAGGREGATIONS = "disable_streaming_preaggregations"; public static final String ENABLE_DISTINCT_STREAMING_AGGREGATION = "enable_distinct_streaming_aggregation"; public static final String DISABLE_COLOCATE_PLAN = "disable_colocate_plan"; public static final String ENABLE_BUCKET_SHUFFLE_JOIN = "enable_bucket_shuffle_join"; public static final String PARALLEL_FRAGMENT_EXEC_INSTANCE_NUM = "parallel_fragment_exec_instance_num"; public static final String PARALLEL_PIPELINE_TASK_NUM = "parallel_pipeline_task_num"; public static final String PROFILE_LEVEL = "profile_level"; public static final String MAX_INSTANCE_NUM = "max_instance_num"; public static final String ENABLE_INSERT_STRICT = "enable_insert_strict"; public static final String ENABLE_SPILLING = "enable_spilling"; public static final String ENABLE_EXCHANGE_NODE_PARALLEL_MERGE = "enable_exchange_node_parallel_merge"; public static final String ENABLE_SERVER_SIDE_PREPARED_STATEMENT = "enable_server_side_prepared_statement"; public static final String PREFER_JOIN_METHOD = "prefer_join_method"; public static final String ENABLE_FOLD_CONSTANT_BY_BE = "enable_fold_constant_by_be"; public static final String ENABLE_REWRITE_ELEMENT_AT_TO_SLOT = "enable_rewrite_element_at_to_slot"; public static final String ENABLE_ODBC_TRANSCATION = "enable_odbc_transcation"; public static final String ENABLE_SQL_CACHE = "enable_sql_cache"; public static final String ENABLE_COST_BASED_JOIN_REORDER = "enable_cost_based_join_reorder"; // if set to true, some of stmt will be forwarded to master FE to get result public static final String FORWARD_TO_MASTER = "forward_to_master"; // user can set instance num after exchange, no need to be equal to nums of before exchange public static final String PARALLEL_EXCHANGE_INSTANCE_NUM = "parallel_exchange_instance_num"; public static final String SHOW_HIDDEN_COLUMNS = "show_hidden_columns"; public static final String USE_V2_ROLLUP = "use_v2_rollup"; public static final String REWRITE_COUNT_DISTINCT_TO_BITMAP_HLL = "rewrite_count_distinct_to_bitmap_hll"; public static final String EVENT_SCHEDULER = "event_scheduler"; public static final String STORAGE_ENGINE = "storage_engine"; // Compatible with datagrip mysql public static final String DEFAULT_STORAGE_ENGINE = "default_storage_engine"; public static final String DEFAULT_TMP_STORAGE_ENGINE = "default_tmp_storage_engine"; // Compatible with mysql public static final String PROFILLING = "profiling"; public static final String DIV_PRECISION_INCREMENT = "div_precision_increment"; // see comment of `doris_max_scan_key_num` and `max_pushdown_conditions_per_column` in BE config public static final String MAX_SCAN_KEY_NUM = "max_scan_key_num"; public static final String MAX_PUSHDOWN_CONDITIONS_PER_COLUMN = "max_pushdown_conditions_per_column"; // when true, the partition column must be set to NOT NULL. public static final String ALLOW_PARTITION_COLUMN_NULLABLE = "allow_partition_column_nullable"; // runtime filter run mode public static final String RUNTIME_FILTER_MODE = "runtime_filter_mode"; // Size in bytes of Bloom Filters used for runtime filters. Actual size of filter will // be rounded up to the nearest power of two. public static final String RUNTIME_BLOOM_FILTER_SIZE = "runtime_bloom_filter_size"; // Minimum runtime bloom filter size, in bytes public static final String RUNTIME_BLOOM_FILTER_MIN_SIZE = "runtime_bloom_filter_min_size"; // Maximum runtime bloom filter size, in bytes public static final String RUNTIME_BLOOM_FILTER_MAX_SIZE = "runtime_bloom_filter_max_size"; public static final String USE_RF_DEFAULT = "use_rf_default"; // Time in ms to wait until runtime filters are delivered. public static final String RUNTIME_FILTER_WAIT_TIME_MS = "runtime_filter_wait_time_ms"; public static final String runtime_filter_wait_infinitely = "runtime_filter_wait_infinitely"; // Maximum number of bloom runtime filters allowed per query public static final String RUNTIME_FILTERS_MAX_NUM = "runtime_filters_max_num"; // Runtime filter type used, For testing, Corresponds to TRuntimeFilterType public static final String RUNTIME_FILTER_TYPE = "runtime_filter_type"; // if the right table is greater than this value in the hash join, we will ignore IN filter public static final String RUNTIME_FILTER_MAX_IN_NUM = "runtime_filter_max_in_num"; public static final String ENABLE_SYNC_RUNTIME_FILTER_SIZE = "enable_sync_runtime_filter_size"; public static final String BE_NUMBER_FOR_TEST = "be_number_for_test"; // max ms to wait transaction publish finish when exec insert stmt. public static final String INSERT_VISIBLE_TIMEOUT_MS = "insert_visible_timeout_ms"; public static final String DELETE_WITHOUT_PARTITION = "delete_without_partition"; public static final String ENABLE_VARIANT_ACCESS_IN_ORIGINAL_PLANNER = "enable_variant_access_in_original_planner"; // set the default parallelism for send batch when execute InsertStmt operation, // if the value for parallelism exceed `max_send_batch_parallelism_per_job` in BE config, // then the coordinator be will use the value of `max_send_batch_parallelism_per_job` public static final String SEND_BATCH_PARALLELISM = "send_batch_parallelism"; // turn off all automatic join reorder algorithms public static final String DISABLE_JOIN_REORDER = "disable_join_reorder"; public static final String MAX_JOIN_NUMBER_OF_REORDER = "max_join_number_of_reorder"; public static final String ENABLE_NEREIDS_DML = "enable_nereids_dml"; public static final String ENABLE_NEREIDS_DML_WITH_PIPELINE = "enable_nereids_dml_with_pipeline"; public static final String ENABLE_STRICT_CONSISTENCY_DML = "enable_strict_consistency_dml"; public static final String ENABLE_BUSHY_TREE = "enable_bushy_tree"; public static final String MAX_JOIN_NUMBER_BUSHY_TREE = "max_join_number_bushy_tree"; public static final String ENABLE_PARTITION_TOPN = "enable_partition_topn"; public static final String GLOBAL_PARTITION_TOPN_THRESHOLD = "global_partition_topn_threshold"; public static final String ENABLE_INFER_PREDICATE = "enable_infer_predicate"; public static final long DEFAULT_INSERT_VISIBLE_TIMEOUT_MS = 10_000; public static final String ENABLE_VECTORIZED_ENGINE = "enable_vectorized_engine"; public static final String EXTRACT_WIDE_RANGE_EXPR = "extract_wide_range_expr"; // If user set a very small value, use this value instead. public static final long MIN_INSERT_VISIBLE_TIMEOUT_MS = 1000; public static final String ENABLE_PIPELINE_ENGINE = "enable_pipeline_engine"; public static final String ENABLE_PIPELINE_X_ENGINE = "enable_pipeline_x_engine"; public static final String ENABLE_SHARED_SCAN = "enable_shared_scan"; public static final String IGNORE_STORAGE_DATA_DISTRIBUTION = "ignore_storage_data_distribution"; public static final String ENABLE_PARALLEL_SCAN = "enable_parallel_scan"; // Limit the max count of scanners to prevent generate too many scanners. public static final String PARALLEL_SCAN_MAX_SCANNERS_COUNT = "parallel_scan_max_scanners_count"; // Avoid splitting small segments, each scanner should scan `parallel_scan_min_rows_per_scanner` rows. public static final String PARALLEL_SCAN_MIN_ROWS_PER_SCANNER = "parallel_scan_min_rows_per_scanner"; public static final String ENABLE_LOCAL_SHUFFLE = "enable_local_shuffle"; public static final String FORCE_TO_LOCAL_SHUFFLE = "force_to_local_shuffle"; public static final String ENABLE_AGG_STATE = "enable_agg_state"; public static final String ENABLE_BUCKET_SHUFFLE_DOWNGRADE = "enable_bucket_shuffle_downgrade"; public static final String ENABLE_RPC_OPT_FOR_PIPELINE = "enable_rpc_opt_for_pipeline"; public static final String ENABLE_SINGLE_DISTINCT_COLUMN_OPT = "enable_single_distinct_column_opt"; public static final String CPU_RESOURCE_LIMIT = "cpu_resource_limit"; public static final String CLOUD_ENABLE_MULTI_CLUSTER_SYNC_LOAD = "enable_multi_cluster_sync_load"; public static final String ENABLE_PARALLEL_OUTFILE = "enable_parallel_outfile"; public static final String SQL_QUOTE_SHOW_CREATE = "sql_quote_show_create"; public static final String RETURN_OBJECT_DATA_AS_BINARY = "return_object_data_as_binary"; public static final String BLOCK_ENCRYPTION_MODE = "block_encryption_mode"; public static final String AUTO_BROADCAST_JOIN_THRESHOLD = "auto_broadcast_join_threshold"; public static final String ENABLE_PROJECTION = "enable_projection"; public static final String CHECK_OVERFLOW_FOR_DECIMAL = "check_overflow_for_decimal"; public static final String DECIMAL_OVERFLOW_SCALE = "decimal_overflow_scale"; public static final String TRIM_TAILING_SPACES_FOR_EXTERNAL_TABLE_QUERY = "trim_tailing_spaces_for_external_table_query"; public static final String ENABLE_DPHYP_OPTIMIZER = "enable_dphyp_optimizer"; public static final String ENABLE_LEFT_ZIG_ZAG = "enable_left_zig_zag"; public static final String NTH_OPTIMIZED_PLAN = "nth_optimized_plan"; public static final String ENABLE_NEREIDS_PLANNER = "enable_nereids_planner"; public static final String DISABLE_NEREIDS_RULES = "disable_nereids_rules"; public static final String ENABLE_NEREIDS_RULES = "enable_nereids_rules"; public static final String ENABLE_NEW_COST_MODEL = "enable_new_cost_model"; public static final String ENABLE_FALLBACK_TO_ORIGINAL_PLANNER = "enable_fallback_to_original_planner"; public static final String ENABLE_NEREIDS_TIMEOUT = "enable_nereids_timeout"; public static final String NEREIDS_TIMEOUT_SECOND = "nereids_timeout_second"; public static final String FORBID_UNKNOWN_COLUMN_STATS = "forbid_unknown_col_stats"; public static final String BROADCAST_RIGHT_TABLE_SCALE_FACTOR = "broadcast_right_table_scale_factor"; public static final String BROADCAST_ROW_COUNT_LIMIT = "broadcast_row_count_limit"; // percentage of EXEC_MEM_LIMIT public static final String BROADCAST_HASHTABLE_MEM_LIMIT_PERCENTAGE = "broadcast_hashtable_mem_limit_percentage"; public static final String REWRITE_OR_TO_IN_PREDICATE_THRESHOLD = "rewrite_or_to_in_predicate_threshold"; public static final String NEREIDS_STAR_SCHEMA_SUPPORT = "nereids_star_schema_support"; public static final String NEREIDS_CBO_PENALTY_FACTOR = "nereids_cbo_penalty_factor"; public static final String ENABLE_NEREIDS_TRACE = "enable_nereids_trace"; public static final String ENABLE_EXPR_TRACE = "enable_expr_trace"; public static final String ENABLE_DPHYP_TRACE = "enable_dphyp_trace"; public static final String ENABLE_FOLD_NONDETERMINISTIC_FN = "enable_fold_nondeterministic_fn"; public static final String ENABLE_RUNTIME_FILTER_PRUNE = "enable_runtime_filter_prune"; static final String SESSION_CONTEXT = "session_context"; public static final String DEFAULT_ORDER_BY_LIMIT = "default_order_by_limit"; public static final String ENABLE_SINGLE_REPLICA_INSERT = "enable_single_replica_insert"; public static final String ENABLE_FUNCTION_PUSHDOWN = "enable_function_pushdown"; public static final String ENABLE_EXT_FUNC_PRED_PUSHDOWN = "enable_ext_func_pred_pushdown"; public static final String ENABLE_COMMON_EXPR_PUSHDOWN = "enable_common_expr_pushdown"; public static final String FRAGMENT_TRANSMISSION_COMPRESSION_CODEC = "fragment_transmission_compression_codec"; public static final String ENABLE_LOCAL_EXCHANGE = "enable_local_exchange"; public static final String SKIP_STORAGE_ENGINE_MERGE = "skip_storage_engine_merge"; public static final String SKIP_DELETE_PREDICATE = "skip_delete_predicate"; public static final String SKIP_DELETE_SIGN = "skip_delete_sign"; public static final String SKIP_DELETE_BITMAP = "skip_delete_bitmap"; public static final String SKIP_MISSING_VERSION = "skip_missing_version"; public static final String SKIP_BAD_TABLET = "skip_bad_tablet"; public static final String ENABLE_PUSH_DOWN_NO_GROUP_AGG = "enable_push_down_no_group_agg"; public static final String ENABLE_CBO_STATISTICS = "enable_cbo_statistics"; public static final String ENABLE_SAVE_STATISTICS_SYNC_JOB = "enable_save_statistics_sync_job"; public static final String ENABLE_ELIMINATE_SORT_NODE = "enable_eliminate_sort_node"; public static final String NEREIDS_TRACE_EVENT_MODE = "nereids_trace_event_mode"; public static final String INTERNAL_SESSION = "internal_session"; public static final String PARTITIONED_HASH_JOIN_ROWS_THRESHOLD = "partitioned_hash_join_rows_threshold"; public static final String PARTITIONED_HASH_AGG_ROWS_THRESHOLD = "partitioned_hash_agg_rows_threshold"; public static final String PARTITION_PRUNING_EXPAND_THRESHOLD = "partition_pruning_expand_threshold"; public static final String ENABLE_SHARE_HASH_TABLE_FOR_BROADCAST_JOIN = "enable_share_hash_table_for_broadcast_join"; // Optimize when probe side has no data for some hash join types public static final String ENABLE_HASH_JOIN_EARLY_START_PROBE = "enable_hash_join_early_start_probe"; // support unicode in label, table, column, common name check public static final String ENABLE_UNICODE_NAME_SUPPORT = "enable_unicode_name_support"; public static final String REPEAT_MAX_NUM = "repeat_max_num"; public static final String GROUP_CONCAT_MAX_LEN = "group_concat_max_len"; public static final String ENABLE_TWO_PHASE_READ_OPT = "enable_two_phase_read_opt"; public static final String TOPN_OPT_LIMIT_THRESHOLD = "topn_opt_limit_threshold"; public static final String ENABLE_SNAPSHOT_POINT_QUERY = "enable_snapshot_point_query"; public static final String ENABLE_FILE_CACHE = "enable_file_cache"; public static final String DISABLE_FILE_CACHE = "disable_file_cache"; public static final String FILE_CACHE_BASE_PATH = "file_cache_base_path"; public static final String ENABLE_INVERTED_INDEX_QUERY = "enable_inverted_index_query"; public static final String ENABLE_COMMON_EXPR_PUSHDOWN_FOR_INVERTED_INDEX = "enable_common_expr_pushdown_for_inverted_index"; public static final String ENABLE_PUSHDOWN_COUNT_ON_INDEX = "enable_count_on_index_pushdown"; public static final String GROUP_BY_AND_HAVING_USE_ALIAS_FIRST = "group_by_and_having_use_alias_first"; public static final String DROP_TABLE_IF_CTAS_FAILED = "drop_table_if_ctas_failed"; public static final String MAX_TABLE_COUNT_USE_CASCADES_JOIN_REORDER = "max_table_count_use_cascades_join_reorder"; public static final int MIN_JOIN_REORDER_TABLE_COUNT = 2; public static final String JOIN_REORDER_TIME_LIMIT = "join_order_time_limit"; public static final String SHOW_USER_DEFAULT_ROLE = "show_user_default_role"; public static final String ENABLE_MINIDUMP = "enable_minidump"; public static final String ENABLE_PAGE_CACHE = "enable_page_cache"; public static final String MINIDUMP_PATH = "minidump_path"; public static final String TRACE_NEREIDS = "trace_nereids"; public static final String PLAN_NEREIDS_DUMP = "plan_nereids_dump"; public static final String DUMP_NEREIDS_MEMO = "dump_nereids_memo"; // fix replica to query. If num = 1, query the smallest replica, if 2 is the second smallest replica. public static final String USE_FIX_REPLICA = "use_fix_replica"; public static final String DRY_RUN_QUERY = "dry_run_query"; // Split size for ExternalFileScanNode. Default value 0 means use the block size of HDFS/S3. public static final String FILE_SPLIT_SIZE = "file_split_size"; public static final String NUM_PARTITIONS_IN_BATCH_MODE = "num_partitions_in_batch_mode"; /** * use insert stmt as the unified backend for all loads */ public static final String ENABLE_UNIFIED_LOAD = "enable_unified_load"; public static final String ENABLE_PARQUET_LAZY_MAT = "enable_parquet_lazy_materialization"; public static final String ENABLE_ORC_LAZY_MAT = "enable_orc_lazy_materialization"; public static final String INLINE_CTE_REFERENCED_THRESHOLD = "inline_cte_referenced_threshold"; public static final String ENABLE_CTE_MATERIALIZE = "enable_cte_materialize"; public static final String ENABLE_SCAN_RUN_SERIAL = "enable_scan_node_run_serial"; public static final String ENABLE_ANALYZE_COMPLEX_TYPE_COLUMN = "enable_analyze_complex_type_column"; public static final String EXTERNAL_TABLE_ANALYZE_PART_NUM = "external_table_analyze_part_num"; public static final String ENABLE_STRONG_CONSISTENCY = "enable_strong_consistency_read"; public static final String GROUP_COMMIT = "group_commit"; public static final String PARALLEL_SYNC_ANALYZE_TASK_NUM = "parallel_sync_analyze_task_num"; public static final String TRUNCATE_CHAR_OR_VARCHAR_COLUMNS = "truncate_char_or_varchar_columns"; public static final String CBO_CPU_WEIGHT = "cbo_cpu_weight"; public static final String CBO_MEM_WEIGHT = "cbo_mem_weight"; public static final String CBO_NET_WEIGHT = "cbo_net_weight"; public static final String ROUND_PRECISE_DECIMALV2_VALUE = "round_precise_decimalv2_value"; public static final String ENABLE_DELETE_SUB_PREDICATE_V2 = "enable_delete_sub_predicate_v2"; public static final String JDBC_CLICKHOUSE_QUERY_FINAL = "jdbc_clickhouse_query_final"; public static final String ENABLE_MEMTABLE_ON_SINK_NODE = "enable_memtable_on_sink_node"; public static final String LOAD_STREAM_PER_NODE = "load_stream_per_node"; public static final String ENABLE_UNIQUE_KEY_PARTIAL_UPDATE = "enable_unique_key_partial_update"; public static final String INVERTED_INDEX_CONJUNCTION_OPT_THRESHOLD = "inverted_index_conjunction_opt_threshold"; public static final String INVERTED_INDEX_MAX_EXPANSIONS = "inverted_index_max_expansions"; public static final String INVERTED_INDEX_SKIP_THRESHOLD = "inverted_index_skip_threshold"; public static final String AUTO_ANALYZE_START_TIME = "auto_analyze_start_time"; public static final String AUTO_ANALYZE_END_TIME = "auto_analyze_end_time"; public static final String SQL_DIALECT = "sql_dialect"; public static final String EXPAND_RUNTIME_FILTER_BY_INNER_JION = "expand_runtime_filter_by_inner_join"; public static final String TEST_QUERY_CACHE_HIT = "test_query_cache_hit"; public static final String ENABLE_AUTO_ANALYZE = "enable_auto_analyze"; public static final String FORCE_SAMPLE_ANALYZE = "force_sample_analyze"; public static final String ENABLE_AUTO_ANALYZE_INTERNAL_CATALOG = "enable_auto_analyze_internal_catalog"; public static final String ENABLE_PARTITION_ANALYZE = "enable_partition_analyze"; public static final String AUTO_ANALYZE_TABLE_WIDTH_THRESHOLD = "auto_analyze_table_width_threshold"; public static final String ENABLE_DECIMAL256 = "enable_decimal256"; public static final String STATS_INSERT_MERGE_ITEM_COUNT = "stats_insert_merge_item_count"; public static final String HUGE_TABLE_DEFAULT_SAMPLE_ROWS = "huge_table_default_sample_rows"; public static final String HUGE_TABLE_LOWER_BOUND_SIZE_IN_BYTES = "huge_table_lower_bound_size_in_bytes"; // for spill to disk public static final String EXTERNAL_SORT_BYTES_THRESHOLD = "external_sort_bytes_threshold"; public static final String EXTERNAL_AGG_BYTES_THRESHOLD = "external_agg_bytes_threshold"; public static final String EXTERNAL_AGG_PARTITION_BITS = "external_agg_partition_bits"; public static final String SPILL_STREAMING_AGG_MEM_LIMIT = "spill_streaming_agg_mem_limit"; public static final String MIN_REVOCABLE_MEM = "min_revocable_mem"; public static final String ENABLE_JOIN_SPILL = "enable_join_spill"; public static final String ENABLE_SORT_SPILL = "enable_sort_spill"; public static final String ENABLE_AGG_SPILL = "enable_agg_spill"; public static final String ENABLE_FORCE_SPILL = "enable_force_spill"; public static final String DATA_QUEUE_MAX_BLOCKS = "data_queue_max_blocks"; public static final String GENERATE_STATS_FACTOR = "generate_stats_factor"; public static final String HUGE_TABLE_AUTO_ANALYZE_INTERVAL_IN_MILLIS = "huge_table_auto_analyze_interval_in_millis"; public static final String EXTERNAL_TABLE_AUTO_ANALYZE_INTERVAL_IN_MILLIS = "external_table_auto_analyze_interval_in_millis"; public static final String TABLE_STATS_HEALTH_THRESHOLD = "table_stats_health_threshold"; public static final String ENABLE_MATERIALIZED_VIEW_REWRITE = "enable_materialized_view_rewrite"; public static final String MATERIALIZED_VIEW_REWRITE_ENABLE_CONTAIN_EXTERNAL_TABLE = "materialized_view_rewrite_enable_contain_external_table"; public static final String MATERIALIZED_VIEW_REWRITE_SUCCESS_CANDIDATE_NUM = "materialized_view_rewrite_success_candidate_num"; public static final String ENABLE_MATERIALIZED_VIEW_UNION_REWRITE = "enable_materialized_view_union_rewrite"; public static final String ENABLE_MATERIALIZED_VIEW_NEST_REWRITE = "enable_materialized_view_nest_rewrite"; public static final String MATERIALIZED_VIEW_RELATION_MAPPING_MAX_COUNT = "materialized_view_relation_mapping_max_count"; public static final String CREATE_TABLE_PARTITION_MAX_NUM = "create_table_partition_max_num"; public static final String ENABLE_PUSHDOWN_MINMAX_ON_UNIQUE = "enable_pushdown_minmax_on_unique"; public static final String ENABLE_PUSHDOWN_STRING_MINMAX = "enable_pushdown_string_minmax"; // When set use fix replica = true, the fixed replica maybe bad, try to use the health one if // this session variable is set to true. public static final String FALLBACK_OTHER_REPLICA_WHEN_FIXED_CORRUPT = "fallback_other_replica_when_fixed_corrupt"; public static final String WAIT_FULL_BLOCK_SCHEDULE_TIMES = "wait_full_block_schedule_times"; public static final String DESCRIBE_EXTEND_VARIANT_COLUMN = "describe_extend_variant_column"; public static final String FORCE_JNI_SCANNER = "force_jni_scanner"; public static final String SHOW_ALL_FE_CONNECTION = "show_all_fe_connection"; public static final String MAX_MSG_SIZE_OF_RESULT_RECEIVER = "max_msg_size_of_result_receiver"; public static final String BYPASS_WORKLOAD_GROUP = "bypass_workload_group"; public static final List<String> DEBUG_VARIABLES = ImmutableList.of( SKIP_DELETE_PREDICATE, SKIP_DELETE_BITMAP, SKIP_DELETE_SIGN, SKIP_STORAGE_ENGINE_MERGE, SHOW_HIDDEN_COLUMNS ); public static final String ENABLE_STATS = "enable_stats"; public static final String LIMIT_ROWS_FOR_SINGLE_INSTANCE = "limit_rows_for_single_instance"; // CLOUD_VARIABLES_BEGIN public static final String CLOUD_CLUSTER = "cloud_cluster"; public static final String DISABLE_EMPTY_PARTITION_PRUNE = "disable_empty_partition_prune"; // CLOUD_VARIABLES_BEGIN /** * If set false, user couldn't submit analyze SQL and FE won't allocate any related resources. */ @VariableMgr.VarAttr(name = ENABLE_STATS) public boolean enableStats = true; // session origin value public Map<SessionVariableField, String> sessionOriginValue = new HashMap<>(); // check stmt is or not [select /*+ SET_VAR(...)*/ ...] // if it is setStmt, we needn't collect session origin value public boolean isSingleSetVar = false; @VariableMgr.VarAttr(name = EXPAND_RUNTIME_FILTER_BY_INNER_JION) public boolean expandRuntimeFilterByInnerJoin = true; @VariableMgr.VarAttr(name = JDBC_CLICKHOUSE_QUERY_FINAL, needForward = true, description = {"是否在查询 ClickHouse JDBC 外部表时,对查询 SQL 添加 FINAL 关键字。", "Whether to add the FINAL keyword to the query SQL when querying ClickHouse JDBC external tables."}) public boolean jdbcClickhouseQueryFinal = false; @VariableMgr.VarAttr(name = ROUND_PRECISE_DECIMALV2_VALUE) public boolean roundPreciseDecimalV2Value = false; @VariableMgr.VarAttr(name = INSERT_VISIBLE_TIMEOUT_MS, needForward = true) public long insertVisibleTimeoutMs = DEFAULT_INSERT_VISIBLE_TIMEOUT_MS; // max memory used on every backend. @VariableMgr.VarAttr(name = EXEC_MEM_LIMIT) public long maxExecMemByte = 2147483648L; @VariableMgr.VarAttr(name = SCAN_QUEUE_MEM_LIMIT) public long maxScanQueueMemByte = 2147483648L / 20; @VariableMgr.VarAttr(name = NUM_SCANNER_THREADS, needForward = true, description = { "ScanNode扫描数据的最大并发,默认为0,采用BE的doris_scanner_thread_pool_thread_num", "The max threads to read data of ScanNode, " + "default 0, use doris_scanner_thread_pool_thread_num in be.conf" }) public int numScannerThreads = 0; @VariableMgr.VarAttr(name = LOCAL_EXCHANGE_FREE_BLOCKS_LIMIT) public int localExchangeFreeBlocksLimit = 4; @VariableMgr.VarAttr(name = SCANNER_SCALE_UP_RATIO, needForward = true, description = { "ScanNode自适应的增加扫描并发,最大允许增长的并发倍率,默认为0,关闭该功能", "The max multiple of increasing the concurrency of scanners adaptively, " + "default 0, turn off scaling up" }) public double scannerScaleUpRatio = 0; @VariableMgr.VarAttr(name = ENABLE_SPILLING) public boolean enableSpilling = false; @VariableMgr.VarAttr(name = ENABLE_EXCHANGE_NODE_PARALLEL_MERGE) public boolean enableExchangeNodeParallelMerge = false; // By default, the number of Limit items after OrderBy is changed from 65535 items // before v1.2.0 (not included), to return all items by default @VariableMgr.VarAttr(name = DEFAULT_ORDER_BY_LIMIT) private long defaultOrderByLimit = -1; // query timeout in second. @VariableMgr.VarAttr(name = QUERY_TIMEOUT, checker = "checkQueryTimeoutValid", setter = "setQueryTimeoutS") private int queryTimeoutS = 900; // query timeout in second. @VariableMgr.VarAttr(name = ANALYZE_TIMEOUT, flag = VariableMgr.GLOBAL, needForward = true) public int analyzeTimeoutS = 43200; // The global max_execution_time value provides the default for the session value for new connections. // The session value applies to SELECT executions executed within the session that include // no MAX_EXECUTION_TIME(N) optimizer hint or for which N is 0. // https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html // So that it is == query timeout in doris @VariableMgr.VarAttr(name = MAX_EXECUTION_TIME, checker = "checkMaxExecutionTimeMSValid", setter = "setMaxExecutionTimeMS") public int maxExecutionTimeMS = 900000; @VariableMgr.VarAttr(name = INSERT_TIMEOUT) public int insertTimeoutS = 14400; // if true, need report to coordinator when plan fragment execute successfully. @VariableMgr.VarAttr(name = ENABLE_PROFILE, needForward = true) public boolean enableProfile = false; // if true, need report to coordinator when plan fragment execute successfully. @VariableMgr.VarAttr(name = AUTO_PROFILE_THRESHOLD_MS, needForward = true) public int autoProfileThresholdMs = -1; @VariableMgr.VarAttr(name = "runtime_filter_prune_for_external") public boolean runtimeFilterPruneForExternal = true; @VariableMgr.VarAttr(name = "runtime_filter_jump_threshold") public int runtimeFilterJumpThreshold = 2; // using hashset instead of group by + count can improve performance // but may cause rpc failed when cluster has less BE // Whether this switch is turned on depends on the BE number @VariableMgr.VarAttr(name = ENABLE_SINGLE_DISTINCT_COLUMN_OPT) public boolean enableSingleDistinctColumnOpt = false; // Set sqlMode to empty string @VariableMgr.VarAttr(name = SQL_MODE, needForward = true) public long sqlMode = SqlModeHelper.MODE_DEFAULT; @VariableMgr.VarAttr(name = WORKLOAD_VARIABLE, needForward = true) public String workloadGroup = ""; @VariableMgr.VarAttr(name = BYPASS_WORKLOAD_GROUP, needForward = true, description = { "查询是否绕开WorkloadGroup的限制,目前仅支持绕开查询排队的逻辑", "whether bypass workload group's limitation, currently only support bypass query queue"}) public boolean bypassWorkloadGroup = false; @VariableMgr.VarAttr(name = RESOURCE_VARIABLE) public String resourceGroup = ""; // this is used to make mysql client happy // autocommit is actually a boolean value, but @@autocommit is type of BIGINT. // So we need to set convertBoolToLongMethod to make "select @@autocommit" happy. @VariableMgr.VarAttr(name = AUTO_COMMIT, convertBoolToLongMethod = "convertBoolToLong") public boolean autoCommit = true; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = TX_ISOLATION) public String txIsolation = "REPEATABLE-READ"; // this is used to make mysql client happy @VariableMgr.VarAttr(name = TX_READ_ONLY) public boolean txReadonly = false; // this is used to make mysql client happy @VariableMgr.VarAttr(name = TRANSACTION_READ_ONLY) public boolean transactionReadonly = false; // this is used to make mysql client happy @VariableMgr.VarAttr(name = TRANSACTION_ISOLATION) public String transactionIsolation = "REPEATABLE-READ"; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = CHARACTER_SET_CLIENT) public String charsetClient = "utf8mb4"; @VariableMgr.VarAttr(name = CHARACTER_SET_CONNNECTION) public String charsetConnection = "utf8mb4"; @VariableMgr.VarAttr(name = CHARACTER_SET_RESULTS) public String charsetResults = "utf8mb4"; @VariableMgr.VarAttr(name = CHARACTER_SET_SERVER) public String charsetServer = "utf8mb4"; @VariableMgr.VarAttr(name = COLLATION_CONNECTION) public String collationConnection = "utf8mb4_0900_bin"; @VariableMgr.VarAttr(name = COLLATION_DATABASE) public String collationDatabase = "utf8mb4_0900_bin"; @VariableMgr.VarAttr(name = COLLATION_SERVER) public String collationServer = "utf8mb4_0900_bin"; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = SQL_AUTO_IS_NULL) public boolean sqlAutoIsNull = false; @VariableMgr.VarAttr(name = SQL_SELECT_LIMIT) private long sqlSelectLimit = Long.MAX_VALUE; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = MAX_ALLOWED_PACKET) public int maxAllowedPacket = 1048576; @VariableMgr.VarAttr(name = AUTO_INCREMENT_INCREMENT) public int autoIncrementIncrement = 1; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = QUERY_CACHE_TYPE) public int queryCacheType = 0; // The number of seconds the server waits for activity on an interactive connection before closing it @VariableMgr.VarAttr(name = INTERACTIVE_TIMTOUT) public int interactiveTimeout = 3600; // The number of seconds the server waits for activity on a noninteractive connection before closing it. @VariableMgr.VarAttr(name = WAIT_TIMEOUT) public int waitTimeoutS = 28800; // The number of seconds to wait for a block to be written to a connection before aborting the write @VariableMgr.VarAttr(name = NET_WRITE_TIMEOUT) public int netWriteTimeout = 600; // The number of seconds to wait for a block to be written to a connection before aborting the write @VariableMgr.VarAttr(name = NET_READ_TIMEOUT) public int netReadTimeout = 600; // The current time zone @VariableMgr.VarAttr(name = TIME_ZONE, needForward = true) public String timeZone = TimeUtils.getSystemTimeZone().getID(); @VariableMgr.VarAttr(name = PARALLEL_EXCHANGE_INSTANCE_NUM) public int exchangeInstanceParallel = -1; @VariableMgr.VarAttr(name = SQL_SAFE_UPDATES) public int sqlSafeUpdates = 0; // only @VariableMgr.VarAttr(name = NET_BUFFER_LENGTH, flag = VariableMgr.READ_ONLY) public int netBufferLength = 16384; // if true, need report to coordinator when plan fragment execute successfully. @VariableMgr.VarAttr(name = CODEGEN_LEVEL) public int codegenLevel = 0; @VariableMgr.VarAttr(name = HAVE_QUERY_CACHE, flag = VariableMgr.READ_ONLY) public boolean haveQueryCache = false; // 4096 minus 16 + 16 bytes padding that in padding pod array @VariableMgr.VarAttr(name = BATCH_SIZE, fuzzy = true) public int batchSize = 4064; @VariableMgr.VarAttr(name = DISABLE_STREAMING_PREAGGREGATIONS, fuzzy = true) public boolean disableStreamPreaggregations = false; @VariableMgr.VarAttr(name = ENABLE_DISTINCT_STREAMING_AGGREGATION, fuzzy = true) public boolean enableDistinctStreamingAggregation = true; @VariableMgr.VarAttr(name = DISABLE_COLOCATE_PLAN) public boolean disableColocatePlan = false; @VariableMgr.VarAttr(name = ENABLE_BUCKET_SHUFFLE_JOIN, varType = VariableAnnotation.EXPERIMENTAL_ONLINE) public boolean enableBucketShuffleJoin = true; @VariableMgr.VarAttr(name = ENABLE_BUCKET_SHUFFLE_DOWNGRADE, needForward = true) public boolean enableBucketShuffleDownGrade = false; /** * explode function row count enlarge factor. */ @VariableMgr.VarAttr(name = GENERATE_STATS_FACTOR, checker = "checkGenerateStatsFactor", setter = "setGenerateStatsFactor") public int generateStatsFactor = 5; @VariableMgr.VarAttr(name = PREFER_JOIN_METHOD) public String preferJoinMethod = "broadcast"; @VariableMgr.VarAttr(name = FRAGMENT_TRANSMISSION_COMPRESSION_CODEC) public String fragmentTransmissionCompressionCodec = "none"; // whether sync load to other cluster @VariableMgr.VarAttr(name = CLOUD_ENABLE_MULTI_CLUSTER_SYNC_LOAD, needForward = true) public static boolean cloudEnableMultiClusterSyncLoad = false; /* * the parallel exec instance num for one Fragment in one BE * 1 means disable this feature */ @VariableMgr.VarAttr(name = PARALLEL_FRAGMENT_EXEC_INSTANCE_NUM, needForward = true, fuzzy = true, setter = "setFragmentInstanceNum") public int parallelExecInstanceNum = 8; @VariableMgr.VarAttr(name = PARALLEL_PIPELINE_TASK_NUM, fuzzy = true, needForward = true, setter = "setPipelineTaskNum") public int parallelPipelineTaskNum = 0; @VariableMgr.VarAttr(name = PROFILE_LEVEL, fuzzy = true) public int profileLevel = 1; @VariableMgr.VarAttr(name = MAX_INSTANCE_NUM) public int maxInstanceNum = 64; @VariableMgr.VarAttr(name = ENABLE_INSERT_STRICT, needForward = true) public boolean enableInsertStrict = true; @VariableMgr.VarAttr(name = ENABLE_ODBC_TRANSCATION) public boolean enableOdbcTransaction = false; @VariableMgr.VarAttr(name = ENABLE_SCAN_RUN_SERIAL, description = { "是否开启ScanNode串行读,以避免limit较小的情况下的读放大,可以提高查询的并发能力", "Whether to enable ScanNode serial reading to avoid read amplification in cases of small limits" + "which can improve query concurrency. default is false."}) public boolean enableScanRunSerial = false; @VariableMgr.VarAttr(name = ENABLE_SQL_CACHE) public boolean enableSqlCache = false; @VariableMgr.VarAttr(name = FORWARD_TO_MASTER) public boolean forwardToMaster = true; @VariableMgr.VarAttr(name = USE_V2_ROLLUP) public boolean useV2Rollup = false; @VariableMgr.VarAttr(name = REWRITE_COUNT_DISTINCT_TO_BITMAP_HLL) public boolean rewriteCountDistinct = true; // compatible with some mysql client connect, say DataGrip of JetBrains @VariableMgr.VarAttr(name = EVENT_SCHEDULER) public String eventScheduler = "OFF"; @VariableMgr.VarAttr(name = STORAGE_ENGINE) public String storageEngine = "olap"; @VariableMgr.VarAttr(name = DEFAULT_STORAGE_ENGINE) public String defaultStorageEngine = "olap"; @VariableMgr.VarAttr(name = DEFAULT_TMP_STORAGE_ENGINE) public String defaultTmpStorageEngine = "olap"; @VariableMgr.VarAttr(name = DIV_PRECISION_INCREMENT) public int divPrecisionIncrement = 4; // -1 means unset, BE will use its config value @VariableMgr.VarAttr(name = MAX_SCAN_KEY_NUM) public int maxScanKeyNum = -1; @VariableMgr.VarAttr(name = MAX_PUSHDOWN_CONDITIONS_PER_COLUMN) public int maxPushdownConditionsPerColumn = -1; @VariableMgr.VarAttr(name = SHOW_HIDDEN_COLUMNS, flag = VariableMgr.SESSION_ONLY) public boolean showHiddenColumns = false; @VariableMgr.VarAttr(name = ALLOW_PARTITION_COLUMN_NULLABLE, description = { "是否允许 NULLABLE 列作为 PARTITION 列。开启后,RANGE PARTITION 允许 NULLABLE PARTITION 列" + "(LIST PARTITION当前不支持)。默认开。", "Whether to allow NULLABLE columns as PARTITION columns. When ON, RANGE PARTITION allows " + "NULLABLE PARTITION columns (LIST PARTITION is not supported currently). ON by default." }) public boolean allowPartitionColumnNullable = true; @VariableMgr.VarAttr(name = DELETE_WITHOUT_PARTITION, needForward = true) public boolean deleteWithoutPartition = false; @VariableMgr.VarAttr(name = SEND_BATCH_PARALLELISM, needForward = true) public int sendBatchParallelism = 1; @VariableMgr.VarAttr(name = ENABLE_VARIANT_ACCESS_IN_ORIGINAL_PLANNER) public boolean enableVariantAccessInOriginalPlanner = false; @VariableMgr.VarAttr(name = EXTRACT_WIDE_RANGE_EXPR, needForward = true) public boolean extractWideRangeExpr = true; @VariableMgr.VarAttr(name = ENABLE_NEREIDS_DML, needForward = true) public boolean enableNereidsDML = true; @VariableMgr.VarAttr(name = ENABLE_NEREIDS_DML_WITH_PIPELINE, needForward = true, varType = VariableAnnotation.EXPERIMENTAL, description = {"在新优化器中,使用pipeline引擎执行DML", "execute DML with pipeline engine in Nereids"}) public boolean enableNereidsDmlWithPipeline = true; @VariableMgr.VarAttr(name = ENABLE_STRICT_CONSISTENCY_DML, needForward = true) public boolean enableStrictConsistencyDml = true; @VariableMgr.VarAttr(name = ENABLE_VECTORIZED_ENGINE, varType = VariableAnnotation.EXPERIMENTAL_ONLINE) public boolean enableVectorizedEngine = true; @VariableMgr.VarAttr(name = ENABLE_PIPELINE_ENGINE, fuzzy = true, needForward = true, varType = VariableAnnotation.EXPERIMENTAL) private boolean enablePipelineEngine = true; @VariableMgr.VarAttr(name = ENABLE_PIPELINE_X_ENGINE, fuzzy = false, varType = VariableAnnotation.EXPERIMENTAL) private boolean enablePipelineXEngine = true; @VariableMgr.VarAttr(name = ENABLE_SHARED_SCAN, fuzzy = false, varType = VariableAnnotation.EXPERIMENTAL, needForward = true) private boolean enableSharedScan = false; @VariableMgr.VarAttr(name = ENABLE_PARALLEL_SCAN, fuzzy = true, varType = VariableAnnotation.EXPERIMENTAL, needForward = true) private boolean enableParallelScan = true; @VariableMgr.VarAttr(name = PARALLEL_SCAN_MAX_SCANNERS_COUNT, fuzzy = true, varType = VariableAnnotation.EXPERIMENTAL, needForward = true) private int parallelScanMaxScannersCount = 48; @VariableMgr.VarAttr(name = PARALLEL_SCAN_MIN_ROWS_PER_SCANNER, fuzzy = true, varType = VariableAnnotation.EXPERIMENTAL, needForward = true) private long parallelScanMinRowsPerScanner = 16384; // 16K @VariableMgr.VarAttr(name = IGNORE_STORAGE_DATA_DISTRIBUTION, fuzzy = false, varType = VariableAnnotation.EXPERIMENTAL, needForward = true) private boolean ignoreStorageDataDistribution = true; @VariableMgr.VarAttr( name = ENABLE_LOCAL_SHUFFLE, fuzzy = false, varType = VariableAnnotation.EXPERIMENTAL, description = {"是否在pipelineX引擎上开启local shuffle优化", "Whether to enable local shuffle on pipelineX engine."}) private boolean enableLocalShuffle = true; @VariableMgr.VarAttr( name = FORCE_TO_LOCAL_SHUFFLE, fuzzy = false, varType = VariableAnnotation.EXPERIMENTAL, description = {"是否在pipelineX引擎上强制开启local shuffle优化", "Whether to force to local shuffle on pipelineX engine."}) private boolean forceToLocalShuffle = false; @VariableMgr.VarAttr(name = ENABLE_AGG_STATE, fuzzy = false, varType = VariableAnnotation.EXPERIMENTAL, needForward = true) public boolean enableAggState = false; @VariableMgr.VarAttr(name = ENABLE_PARALLEL_OUTFILE) public boolean enableParallelOutfile = false; @VariableMgr.VarAttr(name = CPU_RESOURCE_LIMIT) public int cpuResourceLimit = -1; @VariableMgr.VarAttr(name = SQL_QUOTE_SHOW_CREATE) public boolean sqlQuoteShowCreate = true; @VariableMgr.VarAttr(name = TRIM_TAILING_SPACES_FOR_EXTERNAL_TABLE_QUERY, needForward = true) public boolean trimTailingSpacesForExternalTableQuery = false; // the maximum size in bytes for a table that will be broadcast to all be nodes // when performing a join, By setting this value to -1 broadcasting can be disabled. // Default value is 1Gto @VariableMgr.VarAttr(name = AUTO_BROADCAST_JOIN_THRESHOLD) public double autoBroadcastJoinThreshold = 0.8; @VariableMgr.VarAttr(name = ENABLE_COST_BASED_JOIN_REORDER) private boolean enableJoinReorderBasedCost = false; @VariableMgr.VarAttr(name = ENABLE_FOLD_CONSTANT_BY_BE, fuzzy = true) public boolean enableFoldConstantByBe = true; @VariableMgr.VarAttr(name = ENABLE_REWRITE_ELEMENT_AT_TO_SLOT, fuzzy = true) private boolean enableRewriteElementAtToSlot = true; @VariableMgr.VarAttr(name = RUNTIME_FILTER_MODE, needForward = true) private String runtimeFilterMode = "GLOBAL"; @VariableMgr.VarAttr(name = RUNTIME_BLOOM_FILTER_SIZE, needForward = true) private int runtimeBloomFilterSize = 2097152; @VariableMgr.VarAttr(name = RUNTIME_BLOOM_FILTER_MIN_SIZE, needForward = true) private int runtimeBloomFilterMinSize = 2048; @VariableMgr.VarAttr(name = RUNTIME_BLOOM_FILTER_MAX_SIZE, needForward = true) private int runtimeBloomFilterMaxSize = 16777216; @VariableMgr.VarAttr(name = RUNTIME_FILTER_WAIT_TIME_MS, needForward = true) private int runtimeFilterWaitTimeMs = 1000; @VariableMgr.VarAttr(name = runtime_filter_wait_infinitely, needForward = true) private boolean runtimeFilterWaitInfinitely = false; @VariableMgr.VarAttr(name = RUNTIME_FILTERS_MAX_NUM, needForward = true) private int runtimeFiltersMaxNum = 10; // Set runtimeFilterType to IN_OR_BLOOM filter @VariableMgr.VarAttr(name = RUNTIME_FILTER_TYPE, fuzzy = true, needForward = true) private int runtimeFilterType = 12; @VariableMgr.VarAttr(name = RUNTIME_FILTER_MAX_IN_NUM, needForward = true) private int runtimeFilterMaxInNum = 1024; @VariableMgr.VarAttr(name = ENABLE_SYNC_RUNTIME_FILTER_SIZE, needForward = true) private boolean enableSyncRuntimeFilterSize = true; @VariableMgr.VarAttr(name = USE_RF_DEFAULT) public boolean useRuntimeFilterDefaultSize = false; @VariableMgr.VarAttr(name = WAIT_FULL_BLOCK_SCHEDULE_TIMES) public int waitFullBlockScheduleTimes = 2; public int getBeNumberForTest() { return beNumberForTest; } @VariableMgr.VarAttr(name = DESCRIBE_EXTEND_VARIANT_COLUMN, needForward = true) public boolean enableDescribeExtendVariantColumn = false; @VariableMgr.VarAttr(name = PROFILLING) public boolean profiling = false; public void setBeNumberForTest(int beNumberForTest) { this.beNumberForTest = beNumberForTest; } @VariableMgr.VarAttr(name = BE_NUMBER_FOR_TEST) private int beNumberForTest = -1; public double getCboCpuWeight() { return cboCpuWeight; } public void setCboCpuWeight(double cboCpuWeight) { this.cboCpuWeight = cboCpuWeight; } public double getCboMemWeight() { return cboMemWeight; } public void setCboMemWeight(double cboMemWeight) { this.cboMemWeight = cboMemWeight; } public double getCboNetWeight() { return cboNetWeight; } public void setCboNetWeight(double cboNetWeight) { this.cboNetWeight = cboNetWeight; } @VariableMgr.VarAttr(name = CBO_CPU_WEIGHT) private double cboCpuWeight = 1.0; @VariableMgr.VarAttr(name = CBO_MEM_WEIGHT) private double cboMemWeight = 1.0; @VariableMgr.VarAttr(name = CBO_NET_WEIGHT) private double cboNetWeight = 1.5; @VariableMgr.VarAttr(name = DISABLE_JOIN_REORDER) private boolean disableJoinReorder = false; @VariableMgr.VarAttr(name = MAX_JOIN_NUMBER_OF_REORDER) private int maxJoinNumberOfReorder = 63; @VariableMgr.VarAttr(name = ENABLE_BUSHY_TREE, needForward = true) private boolean enableBushyTree = false; public int getMaxJoinNumBushyTree() { return maxJoinNumBushyTree; } public void setMaxJoinNumBushyTree(int maxJoinNumBushyTree) { this.maxJoinNumBushyTree = maxJoinNumBushyTree; } public int getMaxJoinNumberOfReorder() { return maxJoinNumberOfReorder; } public void setMaxJoinNumberOfReorder(int maxJoinNumberOfReorder) { this.maxJoinNumberOfReorder = maxJoinNumberOfReorder; } @VariableMgr.VarAttr(name = MAX_JOIN_NUMBER_BUSHY_TREE) private int maxJoinNumBushyTree = 8; @VariableMgr.VarAttr(name = ENABLE_PARTITION_TOPN) private boolean enablePartitionTopN = true; @VariableMgr.VarAttr(name = GLOBAL_PARTITION_TOPN_THRESHOLD) private double globalPartitionTopNThreshold = 100; @VariableMgr.VarAttr(name = ENABLE_INFER_PREDICATE) private boolean enableInferPredicate = true; @VariableMgr.VarAttr(name = RETURN_OBJECT_DATA_AS_BINARY) private boolean returnObjectDataAsBinary = false; @VariableMgr.VarAttr(name = BLOCK_ENCRYPTION_MODE) private String blockEncryptionMode = ""; @VariableMgr.VarAttr(name = ENABLE_PROJECTION) private boolean enableProjection = true; @VariableMgr.VarAttr(name = CHECK_OVERFLOW_FOR_DECIMAL) private boolean checkOverflowForDecimal = true; @VariableMgr.VarAttr(name = DECIMAL_OVERFLOW_SCALE, needForward = true, description = { "当decimal数值计算结果精度溢出时,计算结果最多可保留的小数位数", "When the precision of the result of" + " a decimal numerical calculation overflows," + "the maximum number of decimal scale that the result can be retained" }) public int decimalOverflowScale = 6; @VariableMgr.VarAttr(name = ENABLE_DPHYP_OPTIMIZER) public boolean enableDPHypOptimizer = false; /** * This variable is used to select n-th optimized plan in memo. * It can allow us select different plans for the same SQL statement * and these plans can be used to evaluate the cost model. */ @VariableMgr.VarAttr(name = NTH_OPTIMIZED_PLAN) private int nthOptimizedPlan = 1; @VariableMgr.VarAttr(name = LIMIT_ROWS_FOR_SINGLE_INSTANCE, description = {"当一个 ScanNode 上没有过滤条件,且 limit 值小于这个阈值时," + "系统会将这个算子的并发度调整为1,以减少简单查询的扇出", "When a ScanNode has no filter conditions and the limit value is less than this threshold, " + "the system will adjust the concurrency of this operator to 1 " + "to reduce the fan-out of simple queries"}) public long limitRowsForSingleInstance = 10000; public boolean isEnableLeftZigZag() { return enableLeftZigZag; } public void setEnableLeftZigZag(boolean enableLeftZigZag) { this.enableLeftZigZag = enableLeftZigZag; } @VariableMgr.VarAttr(name = ENABLE_LEFT_ZIG_ZAG) private boolean enableLeftZigZag = false; /** * as the new optimizer is not mature yet, use this var * to control whether to use new optimizer, remove it when * the new optimizer is fully developed. I hope that day * would be coming soon. */ @VariableMgr.VarAttr(name = ENABLE_NEREIDS_PLANNER, needForward = true, fuzzy = true, varType = VariableAnnotation.EXPERIMENTAL) private boolean enableNereidsPlanner = true; @VariableMgr.VarAttr(name = DISABLE_NEREIDS_RULES, needForward = true) private String disableNereidsRules = ""; @VariableMgr.VarAttr(name = ENABLE_NEREIDS_RULES, needForward = true) public String enableNereidsRules = ""; @VariableMgr.VarAttr(name = ENABLE_NEW_COST_MODEL, needForward = true) private boolean enableNewCostModel = false; @VariableMgr.VarAttr(name = NEREIDS_STAR_SCHEMA_SUPPORT) private boolean nereidsStarSchemaSupport = true; @VariableMgr.VarAttr(name = REWRITE_OR_TO_IN_PREDICATE_THRESHOLD, fuzzy = true) private int rewriteOrToInPredicateThreshold = 2; @VariableMgr.VarAttr(name = NEREIDS_CBO_PENALTY_FACTOR, needForward = true) private double nereidsCboPenaltyFactor = 0.7; @VariableMgr.VarAttr(name = ENABLE_NEREIDS_TRACE) private boolean enableNereidsTrace = false; @VariableMgr.VarAttr(name = ENABLE_EXPR_TRACE) private boolean enableExprTrace = false; @VariableMgr.VarAttr(name = ENABLE_DPHYP_TRACE, needForward = true) public boolean enableDpHypTrace = false; @VariableMgr.VarAttr(name = BROADCAST_RIGHT_TABLE_SCALE_FACTOR) private double broadcastRightTableScaleFactor = 0.0; @VariableMgr.VarAttr(name = BROADCAST_ROW_COUNT_LIMIT, needForward = true) private double broadcastRowCountLimit = 30000000; @VariableMgr.VarAttr(name = BROADCAST_HASHTABLE_MEM_LIMIT_PERCENTAGE, needForward = true) private double broadcastHashtableMemLimitPercentage = 0.2; @VariableMgr.VarAttr(name = ENABLE_RUNTIME_FILTER_PRUNE, needForward = true) public boolean enableRuntimeFilterPrune = true; /** * The client can pass some special information by setting this session variable in the format: "k1:v1;k2:v2". * For example, trace_id can be passed to trace the query request sent by the user. * set session_context="trace_id:1234565678"; */ @VariableMgr.VarAttr(name = SESSION_CONTEXT, needForward = true) public String sessionContext = ""; @VariableMgr.VarAttr(name = ENABLE_SINGLE_REPLICA_INSERT, needForward = true, varType = VariableAnnotation.EXPERIMENTAL) public boolean enableSingleReplicaInsert = false; @VariableMgr.VarAttr(name = ENABLE_FUNCTION_PUSHDOWN, fuzzy = true) public boolean enableFunctionPushdown = false; @VariableMgr.VarAttr(name = ENABLE_EXT_FUNC_PRED_PUSHDOWN, needForward = true, description = {"启用外部表(如通过ODBC或JDBC访问的表)查询中谓词的函数下推", "Enable function pushdown for predicates in queries to external tables " + "(such as tables accessed via ODBC or JDBC)"}) public boolean enableExtFuncPredPushdown = true; @VariableMgr.VarAttr(name = FORBID_UNKNOWN_COLUMN_STATS) public boolean forbidUnknownColStats = false; @VariableMgr.VarAttr(name = ENABLE_COMMON_EXPR_PUSHDOWN, fuzzy = true) public boolean enableCommonExprPushdown = true; @VariableMgr.VarAttr(name = ENABLE_LOCAL_EXCHANGE, fuzzy = true, varType = VariableAnnotation.DEPRECATED) public boolean enableLocalExchange = true; /** * For debug purpose, don't merge unique key and agg key when reading data. */ @VariableMgr.VarAttr(name = SKIP_STORAGE_ENGINE_MERGE) public boolean skipStorageEngineMerge = false; /** * For debug purpose, skip delete predicate when reading data. */ @VariableMgr.VarAttr(name = SKIP_DELETE_PREDICATE) public boolean skipDeletePredicate = false; /** * For debug purpose, skip delete sign when reading data. */ @VariableMgr.VarAttr(name = SKIP_DELETE_SIGN) public boolean skipDeleteSign = false; /** * For debug purpose, skip delete bitmap when reading data. */ @VariableMgr.VarAttr(name = SKIP_DELETE_BITMAP) public boolean skipDeleteBitmap = false; // This variable replace the original FE config `recover_with_skip_missing_version`. // In some scenarios, all replicas of tablet are having missing versions, and the tablet is unable to recover. // This config can control the behavior of query. When it is set to `true`, the query will ignore the // visible version recorded in FE partition, use the replica version. If the replica on BE has missing versions, // the query will directly skip this missing version, and only return the data of the existing versions. // Besides, the query will always try to select the one with the highest lastSuccessVersion among all surviving // BE replicas, so as to recover as much data as possible. // You should only open it in the emergency scenarios mentioned above, only used for temporary recovery queries. // This variable conflicts with the use_fix_replica variable, when the use_fix_replica variable is not -1, // this variable will not work. @VariableMgr.VarAttr(name = SKIP_MISSING_VERSION) public boolean skipMissingVersion = false; // This variable is used to control whether to skip the bad tablet. // In some scenarios, user has a huge amount of data and only a single replica was specified when creating // the table, if one of the tablet is damaged, the table will not be able to be select. If the user does not care // about the integrity of the data, they can use this variable to temporarily skip the bad tablet for querying and // load the remaining data into a new table. @VariableMgr.VarAttr(name = SKIP_BAD_TABLET) public boolean skipBadTablet = false; // This variable is used to avoid FE fallback to the original parser. When we execute SQL in regression tests // for nereids, fallback will cause the Doris return the correct result although the syntax is unsupported // in nereids for some mistaken modification. You should set it on the @VariableMgr.VarAttr(name = ENABLE_FALLBACK_TO_ORIGINAL_PLANNER, needForward = true) public boolean enableFallbackToOriginalPlanner = false; @VariableMgr.VarAttr(name = ENABLE_NEREIDS_TIMEOUT, needForward = true) public boolean enableNereidsTimeout = true; @VariableMgr.VarAttr(name = "nereids_timeout_second", needForward = true) public int nereidsTimeoutSecond = 30; @VariableMgr.VarAttr(name = ENABLE_PUSH_DOWN_NO_GROUP_AGG) public boolean enablePushDownNoGroupAgg = true; /** * The current statistics are only used for CBO test, * and are not available to users. (work in progress) */ @VariableMgr.VarAttr(name = ENABLE_CBO_STATISTICS) public boolean enableCboStatistics = false; @VariableMgr.VarAttr(name = ENABLE_ELIMINATE_SORT_NODE) public boolean enableEliminateSortNode = true; @VariableMgr.VarAttr(name = INTERNAL_SESSION) public boolean internalSession = false; // Use partitioned hash join if build side row count >= the threshold . 0 - the threshold is not set. @VariableMgr.VarAttr(name = PARTITIONED_HASH_JOIN_ROWS_THRESHOLD, fuzzy = true) public int partitionedHashJoinRowsThreshold = 0; // Use partitioned hash join if build side row count >= the threshold . 0 - the threshold is not set. @VariableMgr.VarAttr(name = PARTITIONED_HASH_AGG_ROWS_THRESHOLD, fuzzy = true) public int partitionedHashAggRowsThreshold = 0; @VariableMgr.VarAttr(name = PARTITION_PRUNING_EXPAND_THRESHOLD, fuzzy = true) public int partitionPruningExpandThreshold = 10; @VariableMgr.VarAttr(name = ENABLE_SHARE_HASH_TABLE_FOR_BROADCAST_JOIN, fuzzy = true) public boolean enableShareHashTableForBroadcastJoin = true; @VariableMgr.VarAttr(name = ENABLE_HASH_JOIN_EARLY_START_PROBE, fuzzy = false) public boolean enableHashJoinEarlyStartProbe = false; @VariableMgr.VarAttr(name = ENABLE_UNICODE_NAME_SUPPORT, needForward = true) public boolean enableUnicodeNameSupport = false; @VariableMgr.VarAttr(name = REPEAT_MAX_NUM, needForward = true) public int repeatMaxNum = 10000; @VariableMgr.VarAttr(name = GROUP_CONCAT_MAX_LEN) public long groupConcatMaxLen = 2147483646; // Whether enable two phase read optimization // 1. read related rowids along with necessary column data // 2. spawn fetch RPC to other nodes to get related data by sorted rowids @VariableMgr.VarAttr(name = ENABLE_TWO_PHASE_READ_OPT, fuzzy = true) public boolean enableTwoPhaseReadOpt = true; @VariableMgr.VarAttr(name = TOPN_OPT_LIMIT_THRESHOLD) public long topnOptLimitThreshold = 1024; @VariableMgr.VarAttr(name = ENABLE_SNAPSHOT_POINT_QUERY) public boolean enableSnapshotPointQuery = true; @VariableMgr.VarAttr(name = ENABLE_SERVER_SIDE_PREPARED_STATEMENT, needForward = true, description = { "是否启用开启服务端prepared statement", "Set whether to enable server side prepared statement."}) public boolean enableServeSidePreparedStatement = false; // Default value is false, which means the group by and having clause // should first use column name not alias. According to mysql. @VariableMgr.VarAttr(name = GROUP_BY_AND_HAVING_USE_ALIAS_FIRST, varType = VariableAnnotation.DEPRECATED) public boolean groupByAndHavingUseAliasFirst = false; // Whether disable block file cache. Block cache only works when FE's query options sets disableFileCache false // along with BE's config `enable_file_cache` true @VariableMgr.VarAttr(name = DISABLE_FILE_CACHE, needForward = true) public boolean disableFileCache = false; // Whether enable block file cache. Only take effect when BE config item enable_file_cache is true. @VariableMgr.VarAttr(name = ENABLE_FILE_CACHE, needForward = true, description = { "是否启用file cache。该变量只有在be.conf中enable_file_cache=true时才有效," + "如果be.conf中enable_file_cache=false,该BE节点的file cache处于禁用状态。", "Set wether to use file cache. This variable takes effect only if the BE config enable_file_cache=true. " + "The cache is not used when BE config enable_file_cache=false."}) public boolean enableFileCache = false; // Specify base path for file cache, or chose a random path. @VariableMgr.VarAttr(name = FILE_CACHE_BASE_PATH, needForward = true, description = { "指定block file cache在BE上的存储路径,默认 'random',随机选择BE配置的存储路径。", "Specify the storage path of the block file cache on BE, default 'random', " + "and randomly select the storage path configured by BE."}) public String fileCacheBasePath = "random"; // Whether enable query with inverted index. @VariableMgr.VarAttr(name = ENABLE_INVERTED_INDEX_QUERY, needForward = true, description = { "是否启用inverted index query。", "Set whether to use inverted index query."}) public boolean enableInvertedIndexQuery = true; // Whether enable query expr with inverted index. @VariableMgr.VarAttr(name = ENABLE_COMMON_EXPR_PUSHDOWN_FOR_INVERTED_INDEX, needForward = true, description = { "是否启用表达式上使用 inverted index。", "Set whether to use inverted index query for expr."}) public boolean enableCommonExpPushDownForInvertedIndex = false; // Whether enable pushdown count agg to scan node when using inverted index match. @VariableMgr.VarAttr(name = ENABLE_PUSHDOWN_COUNT_ON_INDEX, needForward = true, description = { "是否启用count_on_index pushdown。", "Set whether to pushdown count_on_index."}) public boolean enablePushDownCountOnIndex = true; // Whether enable pushdown minmax to scan node of unique table. @VariableMgr.VarAttr(name = ENABLE_PUSHDOWN_MINMAX_ON_UNIQUE, needForward = true, description = { "是否启用pushdown minmax on unique table。", "Set whether to pushdown minmax on unique table."}) public boolean enablePushDownMinMaxOnUnique = false; // Whether enable push down string type minmax to scan node. @VariableMgr.VarAttr(name = ENABLE_PUSHDOWN_STRING_MINMAX, needForward = true, description = { "是否启用string类型min max下推。", "Set whether to enable push down string type minmax."}) public boolean enablePushDownStringMinMax = false; // Whether drop table when create table as select insert data appear error. @VariableMgr.VarAttr(name = DROP_TABLE_IF_CTAS_FAILED, needForward = true) public boolean dropTableIfCtasFailed = true; @VariableMgr.VarAttr(name = MAX_TABLE_COUNT_USE_CASCADES_JOIN_REORDER, needForward = true) public int maxTableCountUseCascadesJoinReorder = 10; @VariableMgr.VarAttr(name = JOIN_REORDER_TIME_LIMIT, needForward = true) public long joinReorderTimeLimit = 1000; // If this is true, the result of `show roles` will return all user default role @VariableMgr.VarAttr(name = SHOW_USER_DEFAULT_ROLE, needForward = true) public boolean showUserDefaultRole = false; // Default value is -1, which means not fix replica @VariableMgr.VarAttr(name = USE_FIX_REPLICA) public int useFixReplica = -1; @VariableMgr.VarAttr(name = DUMP_NEREIDS_MEMO) public boolean dumpNereidsMemo = false; @VariableMgr.VarAttr(name = "memo_max_group_expression_size") public int memoMaxGroupExpressionSize = 10000; @VariableMgr.VarAttr(name = ENABLE_MINIDUMP) public boolean enableMinidump = false; @VariableMgr.VarAttr( name = ENABLE_PAGE_CACHE, description = {"控制是否启用page cache。默认为 true。", "Controls whether to use page cache. " + "The default value is true."}, needForward = true) public boolean enablePageCache = true; @VariableMgr.VarAttr(name = ENABLE_FOLD_NONDETERMINISTIC_FN) public boolean enableFoldNondeterministicFn = false; @VariableMgr.VarAttr(name = MINIDUMP_PATH) public String minidumpPath = ""; @VariableMgr.VarAttr(name = TRACE_NEREIDS) public boolean traceNereids = false; @VariableMgr.VarAttr(name = PLAN_NEREIDS_DUMP) public boolean planNereidsDump = false; // If set to true, all query will be executed without returning result @VariableMgr.VarAttr(name = DRY_RUN_QUERY, needForward = true) public boolean dryRunQuery = false; @VariableMgr.VarAttr(name = FILE_SPLIT_SIZE, needForward = true) public long fileSplitSize = 0; @VariableMgr.VarAttr( name = NUM_PARTITIONS_IN_BATCH_MODE, description = {"如果分区数量超过阈值,BE将通过batch方式获取scan ranges", "If the number of partitions exceeds the threshold, scan ranges will be got through batch mode."}, needForward = true) public int numPartitionsInBatchMode = 1024; @VariableMgr.VarAttr( name = ENABLE_PARQUET_LAZY_MAT, description = {"控制 parquet reader 是否启用延迟物化技术。默认为 true。", "Controls whether to use lazy materialization technology in parquet reader. " + "The default value is true."}, needForward = true) public boolean enableParquetLazyMat = true; @VariableMgr.VarAttr( name = ENABLE_ORC_LAZY_MAT, description = {"控制 orc reader 是否启用延迟物化技术。默认为 true。", "Controls whether to use lazy materialization technology in orc reader. " + "The default value is true."}, needForward = true) public boolean enableOrcLazyMat = true; @VariableMgr.VarAttr( name = EXTERNAL_TABLE_ANALYZE_PART_NUM, description = {"收集外表统计信息行数时选取的采样分区数,默认-1表示全部分区", "Number of sample partition for collecting external table line number, " + "default -1 means all partitions"}, needForward = false) public int externalTableAnalyzePartNum = -1; @VariableMgr.VarAttr(name = INLINE_CTE_REFERENCED_THRESHOLD) public int inlineCTEReferencedThreshold = 1; @VariableMgr.VarAttr(name = ENABLE_CTE_MATERIALIZE) public boolean enableCTEMaterialize = true; @VariableMgr.VarAttr(name = ENABLE_ANALYZE_COMPLEX_TYPE_COLUMN) public boolean enableAnalyzeComplexTypeColumn = false; @VariableMgr.VarAttr(name = ENABLE_STRONG_CONSISTENCY, description = {"用以开启强一致读。Doris 默认支持同一个会话内的" + "强一致性,即同一个会话内对数据的变更操作是实时可见的。如需要会话间的强一致读,则需将此变量设置为true。", "Used to enable strong consistent reading. By default, Doris supports strong consistency " + "within the same session, that is, changes to data within the same session are visible in " + "real time. If you want strong consistent reads between sessions, set this variable to true. " }) public boolean enableStrongConsistencyRead = false; @VariableMgr.VarAttr(name = PARALLEL_SYNC_ANALYZE_TASK_NUM) public int parallelSyncAnalyzeTaskNum = 2; @VariableMgr.VarAttr(name = ENABLE_DELETE_SUB_PREDICATE_V2, fuzzy = true, needForward = true) public boolean enableDeleteSubPredicateV2 = true; @VariableMgr.VarAttr(name = TRUNCATE_CHAR_OR_VARCHAR_COLUMNS, description = {"是否按照表的 schema 来截断 char 或者 varchar 列。默认为 false。\n" + "因为外表会存在表的 schema 中 char 或者 varchar 列的最大长度和底层 parquet 或者 orc 文件中的 schema 不一致" + "的情况。此时开启改选项,会按照表的 schema 中的最大长度进行截断。", "Whether to truncate char or varchar columns according to the table's schema. " + "The default is false.\n" + "Because the maximum length of the char or varchar column in the schema of the table" + " is inconsistent with the schema in the underlying parquet or orc file." + " At this time, if the option is turned on, it will be truncated according to the maximum length" + " in the schema of the table."}, needForward = true) public boolean truncateCharOrVarcharColumns = false; @VariableMgr.VarAttr(name = ENABLE_MEMTABLE_ON_SINK_NODE, needForward = true) public boolean enableMemtableOnSinkNode = true; @VariableMgr.VarAttr(name = LOAD_STREAM_PER_NODE) public int loadStreamPerNode = 2; @VariableMgr.VarAttr(name = GROUP_COMMIT) public String groupCommit = "off_mode"; @VariableMgr.VarAttr(name = INVERTED_INDEX_CONJUNCTION_OPT_THRESHOLD, description = {"在match_all中求取多个倒排索引的交集时,如果最大的倒排索引中的总数是最小倒排索引中的总数的整数倍," + "则使用跳表来优化交集操作。", "When intersecting multiple inverted indexes in match_all," + " if the maximum total count of the largest inverted index" + " is a multiple of the minimum total count of the smallest inverted index," + " use a skiplist to optimize the intersection."}) public int invertedIndexConjunctionOptThreshold = 1000; @VariableMgr.VarAttr(name = INVERTED_INDEX_MAX_EXPANSIONS, description = {"这个参数用来限制查询时扩展的词项(terms)的数量,以此来控制查询的性能", "This parameter is used to limit the number of term expansions during a query," + " thereby controlling query performance"}) public int invertedIndexMaxExpansions = 50; @VariableMgr.VarAttr(name = INVERTED_INDEX_SKIP_THRESHOLD, description = {"在倒排索引中如果预估命中量占比总量超过百分比阈值,则跳过索引直接进行匹配。", "In the inverted index," + " if the estimated hit ratio exceeds the percentage threshold of the total amount, " + " then skip the index and proceed directly to matching."}) public int invertedIndexSkipThreshold = 50; @VariableMgr.VarAttr(name = SQL_DIALECT, needForward = true, checker = "checkSqlDialect", description = {"解析sql使用的方言", "The dialect used to parse sql."}) public String sqlDialect = "doris"; @VariableMgr.VarAttr(name = ENABLE_UNIQUE_KEY_PARTIAL_UPDATE, needForward = true) public boolean enableUniqueKeyPartialUpdate = false; @VariableMgr.VarAttr(name = TEST_QUERY_CACHE_HIT, description = { "用于测试查询缓存是否命中,如果未命中指定类型的缓存,则会报错", "Used to test whether the query cache is hit. " + "If the specified type of cache is not hit, an error will be reported."}, options = {"none", "sql_cache", "partition_cache"}) public String testQueryCacheHit = "none"; @VariableMgr.VarAttr(name = ENABLE_AUTO_ANALYZE, description = {"该参数控制是否开启自动收集", "Set false to disable auto analyze"}, flag = VariableMgr.GLOBAL) public boolean enableAutoAnalyze = true; @VariableMgr.VarAttr(name = FORCE_SAMPLE_ANALYZE, needForward = true, description = {"是否将 full analyze 自动转换成 sample analyze", "Set true to force sample analyze"}, flag = VariableMgr.GLOBAL) public boolean forceSampleAnalyze = Config.force_sample_analyze; @VariableMgr.VarAttr(name = ENABLE_AUTO_ANALYZE_INTERNAL_CATALOG, description = {"临时参数,收否自动收集所有内表", "Temp variable, enable to auto collect all OlapTable."}, flag = VariableMgr.GLOBAL) public boolean enableAutoAnalyzeInternalCatalog = true; @VariableMgr.VarAttr(name = ENABLE_PARTITION_ANALYZE, description = {"临时参数,收否收集分区级别统计信息", "Temp variable, enable to collect partition level statistics."}, flag = VariableMgr.GLOBAL) public boolean enablePartitionAnalyze = false; @VariableMgr.VarAttr(name = AUTO_ANALYZE_TABLE_WIDTH_THRESHOLD, description = {"参与自动收集的最大表宽度,列数多于这个参数的表不参与自动收集", "Maximum table width to enable auto analyze, " + "table with more columns than this value will not be auto analyzed."}, flag = VariableMgr.GLOBAL) public int autoAnalyzeTableWidthThreshold = 100; @VariableMgr.VarAttr(name = AUTO_ANALYZE_START_TIME, needForward = true, checker = "checkAnalyzeTimeFormat", description = {"该参数定义自动ANALYZE例程的开始时间", "This parameter defines the start time for the automatic ANALYZE routine."}, flag = VariableMgr.GLOBAL) public String autoAnalyzeStartTime = "00:00:00"; @VariableMgr.VarAttr(name = AUTO_ANALYZE_END_TIME, needForward = true, checker = "checkAnalyzeTimeFormat", description = {"该参数定义自动ANALYZE例程的结束时间", "This parameter defines the end time for the automatic ANALYZE routine."}, flag = VariableMgr.GLOBAL) public String autoAnalyzeEndTime = "23:59:59"; @VariableMgr.VarAttr(name = IGNORE_RUNTIME_FILTER_IDS, description = {"在IGNORE_RUNTIME_FILTER_IDS列表中的runtime filter将不会被生成", "the runtime filter id in IGNORE_RUNTIME_FILTER_IDS list will not be generated"}) public String ignoreRuntimeFilterIds = ""; @VariableMgr.VarAttr(name = STATS_INSERT_MERGE_ITEM_COUNT, flag = VariableMgr.GLOBAL, description = { "控制统计信息相关INSERT攒批数量", "Controls the batch size for stats INSERT merging." } ) public int statsInsertMergeItemCount = 200; @VariableMgr.VarAttr(name = HUGE_TABLE_DEFAULT_SAMPLE_ROWS, flag = VariableMgr.GLOBAL, description = { "定义开启开启大表自动sample后,对大表的采样比例", "This defines the number of sample percent for large tables when automatic sampling for" + "large tables is enabled" }) public long hugeTableDefaultSampleRows = 4194304; @VariableMgr.VarAttr(name = HUGE_TABLE_LOWER_BOUND_SIZE_IN_BYTES, flag = VariableMgr.GLOBAL, description = { "大小超过该值的表将会自动通过采样收集统计信息", "This defines the lower size bound for large tables. " + "When enable_auto_sample is enabled, tables" + "larger than this value will automatically collect " + "statistics through sampling"}) public long hugeTableLowerBoundSizeInBytes = 0; @VariableMgr.VarAttr(name = HUGE_TABLE_AUTO_ANALYZE_INTERVAL_IN_MILLIS, flag = VariableMgr.GLOBAL, description = {"控制对大表的自动ANALYZE的最小时间间隔," + "在该时间间隔内大小超过huge_table_lower_bound_size_in_bytes的表仅ANALYZE一次", "This controls the minimum time interval for automatic ANALYZE on large tables." + "Within this interval," + "tables larger than huge_table_lower_bound_size_in_bytes are analyzed only once."}) public long hugeTableAutoAnalyzeIntervalInMillis = TimeUnit.HOURS.toMillis(0); @VariableMgr.VarAttr(name = EXTERNAL_TABLE_AUTO_ANALYZE_INTERVAL_IN_MILLIS, flag = VariableMgr.GLOBAL, description = {"控制对外表的自动ANALYZE的最小时间间隔,在该时间间隔内的外表仅ANALYZE一次", "This controls the minimum time interval for automatic ANALYZE on external tables." + "Within this interval, external tables are analyzed only once."}) public long externalTableAutoAnalyzeIntervalInMillis = TimeUnit.HOURS.toMillis(24); @VariableMgr.VarAttr(name = TABLE_STATS_HEALTH_THRESHOLD, flag = VariableMgr.GLOBAL, description = {"取值在0-100之间,当自上次统计信息收集操作之后" + "数据更新量达到 (100 - table_stats_health_threshold)% ,认为该表的统计信息已过时", "The value should be between 0 and 100. When the data update quantity " + "exceeds (100 - table_stats_health_threshold)% since the last " + "statistics collection operation, the statistics for this table are" + "considered outdated."}) public int tableStatsHealthThreshold = 60; @VariableMgr.VarAttr(name = ENABLE_MATERIALIZED_VIEW_REWRITE, needForward = true, description = {"是否开启基于结构信息的物化视图透明改写", "Whether to enable materialized view rewriting based on struct info"}) public boolean enableMaterializedViewRewrite = false; @VariableMgr.VarAttr(name = MATERIALIZED_VIEW_REWRITE_ENABLE_CONTAIN_EXTERNAL_TABLE, needForward = true, description = {"基于结构信息的透明改写,是否使用包含外表的物化视图", "Whether to use a materialized view that contains the foreign table " + "when using rewriting based on struct info"}) public boolean materializedViewRewriteEnableContainExternalTable = false; @VariableMgr.VarAttr(name = MATERIALIZED_VIEW_REWRITE_SUCCESS_CANDIDATE_NUM, needForward = true, description = {"异步物化视图透明改写成功的结果集合,允许参与到CBO候选的最大数量", "The max candidate num which participate in CBO when using asynchronous materialized views"}) public int materializedViewRewriteSuccessCandidateNum = 3; @VariableMgr.VarAttr(name = MATERIALIZED_VIEW_RELATION_MAPPING_MAX_COUNT, needForward = true, description = {"透明改写过程中,relation mapping最大允许数量,如果超过,进行截取", "During transparent rewriting, relation mapping specifies the maximum allowed number. " + "If the number exceeds the allowed number, the number is intercepted"}) public int materializedViewRelationMappingMaxCount = 8; @VariableMgr.VarAttr(name = ENABLE_MATERIALIZED_VIEW_UNION_REWRITE, needForward = true, description = {"当物化视图不足以提供查询的全部数据时,是否允许基表和物化视图 union 来响应查询", "When the materialized view is not enough to provide all the data for the query, " + "whether to allow the union of the base table and the materialized view to " + "respond to the query"}) public boolean enableMaterializedViewUnionRewrite = false; @VariableMgr.VarAttr(name = ENABLE_MATERIALIZED_VIEW_NEST_REWRITE, needForward = true, description = {"是否允许嵌套物化视图改写", "Whether enable materialized view nest rewrite"}) public boolean enableMaterializedViewNestRewrite = false; @VariableMgr.VarAttr(name = CREATE_TABLE_PARTITION_MAX_NUM, needForward = true, description = {"建表时创建分区的最大数量", "The maximum number of partitions created during table creation"}) public int createTablePartitionMaxNum = 10000; @VariableMgr.VarAttr(name = FORCE_JNI_SCANNER, description = {"强制使用jni方式读取外表", "Force the use of jni mode to read external table"}) private boolean forceJniScanner = false; public static final String IGNORE_RUNTIME_FILTER_IDS = "ignore_runtime_filter_ids"; public Set<Integer> getIgnoredRuntimeFilterIds() { Set<Integer> ids = Sets.newLinkedHashSet(); if (ignoreRuntimeFilterIds.isEmpty()) { return ImmutableSet.of(); } for (String v : ignoreRuntimeFilterIds.split(",[\\s]*")) { int res = -1; if (!v.isEmpty()) { boolean isNumber = true; for (int i = 0; i < v.length(); ++i) { char c = v.charAt(i); if (c < '0' || c > '9') { isNumber = false; break; } } if (isNumber) { try { res = Integer.parseInt(v); } catch (Throwable t) { // ignore } } } ids.add(res); } return ids; } public void setIgnoreRuntimeFilterIds(String ignoreRuntimeFilterIds) { this.ignoreRuntimeFilterIds = ignoreRuntimeFilterIds; } public static final String IGNORE_SHAPE_NODE = "ignore_shape_nodes"; public Set<String> getIgnoreShapePlanNodes() { return Arrays.stream(ignoreShapePlanNodes.split(",[\\s]*")).collect(ImmutableSet.toImmutableSet()); } public void setIgnoreShapePlanNodes(String ignoreShapePlanNodes) { this.ignoreShapePlanNodes = ignoreShapePlanNodes; } @VariableMgr.VarAttr(name = IGNORE_SHAPE_NODE, description = {"'explain shape plan' 命令中忽略的PlanNode 类型", "the plan node type which is ignored in 'explain shape plan' command"}) public String ignoreShapePlanNodes = ""; @VariableMgr.VarAttr(name = ENABLE_DECIMAL256, needForward = true, description = { "控制是否在计算过程中使用Decimal256类型", "Set to true to enable Decimal256 type" }) public boolean enableDecimal256 = false; @VariableMgr.VarAttr(name = FALLBACK_OTHER_REPLICA_WHEN_FIXED_CORRUPT, needForward = true, description = { "当开启use_fix_replica时遇到故障,是否漂移到其他健康的副本", "use other health replica when the use_fix_replica meet error" }) public boolean fallbackOtherReplicaWhenFixedCorrupt = false; @VariableMgr.VarAttr(name = SHOW_ALL_FE_CONNECTION, description = {"when it's true show processlist statement list all fe's connection", "当变量为true时,show processlist命令展示所有fe的连接"}) public boolean showAllFeConnection = false; @VariableMgr.VarAttr(name = MAX_MSG_SIZE_OF_RESULT_RECEIVER, description = {"Max message size during result deserialization, change this if you meet error" + " like \"MaxMessageSize reached\"", "用于控制结果反序列化时 thrift 字段的最大值,当遇到类似\"MaxMessageSize reached\"这样的错误时可以考虑修改该参数"}) public int maxMsgSizeOfResultReceiver = TConfiguration.DEFAULT_MAX_MESSAGE_SIZE; // CLOUD_VARIABLES_BEGIN @VariableMgr.VarAttr(name = CLOUD_CLUSTER) public String cloudCluster = ""; @VariableMgr.VarAttr(name = DISABLE_EMPTY_PARTITION_PRUNE) public boolean disableEmptyPartitionPrune = false; // CLOUD_VARIABLES_END // for spill to disk @VariableMgr.VarAttr(name = MIN_REVOCABLE_MEM, fuzzy = true) public long minRevocableMem = 32 * 1024 * 1024; @VariableMgr.VarAttr( name = ENABLE_JOIN_SPILL, description = {"控制是否启用join算子落盘。默认为 false。", "Controls whether to enable spill to disk of join operation. " + "The default value is false."}, needForward = true, fuzzy = true) public boolean enableJoinSpill = false; @VariableMgr.VarAttr( name = ENABLE_SORT_SPILL, description = {"控制是否启用排序算子落盘。默认为 false。", "Controls whether to enable spill to disk of sort operation. " + "The default value is false."}, needForward = true, fuzzy = true) public boolean enableSortSpill = false; @VariableMgr.VarAttr( name = ENABLE_AGG_SPILL, description = {"控制是否启用聚合算子落盘。默认为 false。", "Controls whether to enable spill to disk of aggregation operation. " + "The default value is false."}, needForward = true, fuzzy = true) public boolean enableAggSpill = false; @VariableMgr.VarAttr( name = ENABLE_FORCE_SPILL, description = {"控制是否开启强制落盘(即使在内存足够的情况),默认为 false。", "Controls whether enable force spill." }, needForward = true, fuzzy = true ) public boolean enableForceSpill = false; @VariableMgr.VarAttr( name = DATA_QUEUE_MAX_BLOCKS, description = {"DataQueue 中每个子队列允许最大的 block 个数", "Max blocks in DataQueue."}, needForward = true, fuzzy = true) public long dataQueueMaxBlocks = 1; // If the memory consumption of sort node exceed this limit, will trigger spill to disk; // Set to 0 to disable; min: 128M public static final long MIN_EXTERNAL_SORT_BYTES_THRESHOLD = 2097152; @VariableMgr.VarAttr(name = EXTERNAL_SORT_BYTES_THRESHOLD, checker = "checkExternalSortBytesThreshold", varType = VariableAnnotation.DEPRECATED) public long externalSortBytesThreshold = 0; // Set to 0 to disable; min: 128M public static final long MIN_EXTERNAL_AGG_BYTES_THRESHOLD = 134217728; @VariableMgr.VarAttr(name = EXTERNAL_AGG_BYTES_THRESHOLD, checker = "checkExternalAggBytesThreshold", fuzzy = true, varType = VariableAnnotation.DEPRECATED) public long externalAggBytesThreshold = 0; // The memory limit of streaming agg when spilling is enabled // NOTE: streaming agg operator will not spill to disk. @VariableMgr.VarAttr(name = SPILL_STREAMING_AGG_MEM_LIMIT, fuzzy = true) public long spillStreamingAggMemLimit = 268435456; //256MB public static final int MIN_EXTERNAL_AGG_PARTITION_BITS = 4; public static final int MAX_EXTERNAL_AGG_PARTITION_BITS = 20; @VariableMgr.VarAttr(name = EXTERNAL_AGG_PARTITION_BITS, checker = "checkExternalAggPartitionBits", fuzzy = true) public int externalAggPartitionBits = 5; // means that the hash table will be partitioned into 32 blocks. public boolean isEnableJoinSpill() { return enableJoinSpill; } public void setEnableJoinSpill(boolean enableJoinSpill) { this.enableJoinSpill = enableJoinSpill; } public boolean isEnableSortSpill() { return enableSortSpill; } // If this fe is in fuzzy mode, then will use initFuzzyModeVariables to generate some variables, // not the default value set in the code. @SuppressWarnings("checkstyle:Indentation") public void initFuzzyModeVariables() { Random random = new SecureRandom(); this.parallelExecInstanceNum = random.nextInt(8) + 1; this.parallelPipelineTaskNum = random.nextInt(8); this.enableCommonExprPushdown = random.nextBoolean(); this.enableLocalExchange = random.nextBoolean(); // This will cause be dead loop, disable it first // this.disableJoinReorder = random.nextBoolean(); this.disableStreamPreaggregations = random.nextBoolean(); this.partitionedHashJoinRowsThreshold = random.nextBoolean() ? 8 : 1048576; this.partitionedHashAggRowsThreshold = random.nextBoolean() ? 8 : 1048576; this.enableShareHashTableForBroadcastJoin = random.nextBoolean(); // this.enableHashJoinEarlyStartProbe = random.nextBoolean(); int randomInt = random.nextInt(4); if (randomInt % 2 == 0) { this.rewriteOrToInPredicateThreshold = 100000; this.enableFunctionPushdown = false; this.enableDeleteSubPredicateV2 = false; } else { this.rewriteOrToInPredicateThreshold = 2; this.enableFunctionPushdown = true; this.enableDeleteSubPredicateV2 = true; } /* switch (randomInt) { case 0: this.externalSortBytesThreshold = 0; this.externalAggBytesThreshold = 0; break; case 1: this.externalSortBytesThreshold = 1; this.externalAggBytesThreshold = 1; this.externalAggPartitionBits = 6; break; case 2: this.externalSortBytesThreshold = 1024 * 1024; this.externalAggBytesThreshold = 1024 * 1024; this.externalAggPartitionBits = 8; break; default: this.externalSortBytesThreshold = 100 * 1024 * 1024 * 1024; this.externalAggBytesThreshold = 100 * 1024 * 1024 * 1024; this.externalAggPartitionBits = 4; break; } */ // pull_request_id default value is 0. When it is 0, use default (global) session variable. if (Config.pull_request_id > 0) { this.enablePipelineEngine = true; this.enableNereidsPlanner = true; switch (Config.pull_request_id % 4) { case 0: this.runtimeFilterType |= TRuntimeFilterType.BITMAP.getValue(); break; case 1: this.runtimeFilterType |= TRuntimeFilterType.BITMAP.getValue(); break; case 2: this.runtimeFilterType &= ~TRuntimeFilterType.BITMAP.getValue(); break; case 3: this.runtimeFilterType &= ~TRuntimeFilterType.BITMAP.getValue(); break; default: break; } switch (Config.pull_request_id % 3) { case 0: this.fragmentTransmissionCompressionCodec = "snappy"; break; case 1: this.fragmentTransmissionCompressionCodec = "lz4"; break; default: this.fragmentTransmissionCompressionCodec = "none"; } this.runtimeFilterType = 1 << randomInt; this.enableParallelScan = Config.pull_request_id % 2 == 0 ? randomInt % 2 == 0 : randomInt % 1 == 0; switch (randomInt) { case 0: this.parallelScanMaxScannersCount = 32; this.parallelScanMinRowsPerScanner = 64; break; case 1: this.parallelScanMaxScannersCount = 16; this.parallelScanMinRowsPerScanner = 128; break; case 2: this.parallelScanMaxScannersCount = 8; this.parallelScanMinRowsPerScanner = 256; break; case 3: default: break; } } if (Config.fuzzy_test_type.equals("p0")) { if (Config.pull_request_id > 0) { if (Config.pull_request_id % 2 == 1) { this.batchSize = 4064; this.enableFoldConstantByBe = true; } else { this.batchSize = 1024; this.enableFoldConstantByBe = false; } } } // set random 1, 10, 100, 1000, 10000 this.topnOptLimitThreshold = (int) Math.pow(10, random.nextInt(5)); // for spill to disk if (Config.pull_request_id > 10000) { if (Config.pull_request_id % 2 == 1) { this.enableJoinSpill = true; this.enableSortSpill = true; this.enableAggSpill = true; randomInt = random.nextInt(4); switch (randomInt) { case 0: this.minRevocableMem = 0; break; case 1: this.minRevocableMem = 1; break; case 2: this.minRevocableMem = 1024 * 1024; break; default: this.minRevocableMem = 100L * 1024 * 1024 * 1024; break; } } else { this.enableJoinSpill = false; this.enableSortSpill = false; this.enableAggSpill = false; } } } public String printFuzzyVariables() { if (!Config.use_fuzzy_session_variable) { return ""; } List<String> res = Lists.newArrayList(); for (Field field : SessionVariable.class.getDeclaredFields()) { VarAttr attr = field.getAnnotation(VarAttr.class); if (attr == null || !attr.fuzzy()) { continue; } field.setAccessible(true); try { Object val = field.get(this); res.add(attr.name() + "=" + val.toString()); } catch (IllegalAccessException e) { LOG.warn("failed to get fuzzy session variable {}", attr.name(), e); } } return Joiner.on(",").join(res); } /** * syntax: * all -> use all event * all except event_1, event_2, ..., event_n -> use all events excluding the event_1~n * event_1, event_2, ..., event_n -> use event_1~n */ @VariableMgr.VarAttr(name = NEREIDS_TRACE_EVENT_MODE, checker = "checkNereidsTraceEventMode") public String nereidsTraceEventMode = "all"; private Set<Class<? extends Event>> parsedNereidsEventMode = EventSwitchParser.parse(Lists.newArrayList("all")); public boolean isInDebugMode() { return showHiddenColumns || skipDeleteBitmap || skipDeletePredicate || skipDeleteSign || skipStorageEngineMerge; } public String printDebugModeVariables() { List<String> res = Lists.newArrayList(); for (Field field : SessionVariable.class.getDeclaredFields()) { VarAttr attr = field.getAnnotation(VarAttr.class); if (attr == null) { continue; } boolean shouldPrint = false; for (String debugVariable : DEBUG_VARIABLES) { if (attr.name().equalsIgnoreCase(debugVariable)) { shouldPrint = true; break; } } if (shouldPrint) { field.setAccessible(true); try { Object val = field.get(this); res.add(attr.name() + "=" + val.toString()); } catch (IllegalAccessException e) { LOG.warn("failed to get debug mode session variable {}", attr.name(), e); } } } return Joiner.on(",").join(res); } public void setEnableNereidsTrace(boolean enableNereidsTrace) { this.enableNereidsTrace = enableNereidsTrace; } public void setNereidsTraceEventMode(String nereidsTraceEventMode) { checkNereidsTraceEventMode(nereidsTraceEventMode); this.nereidsTraceEventMode = nereidsTraceEventMode; } public void checkNereidsTraceEventMode(String nereidsTraceEventMode) { List<String> strings = EventSwitchParser.checkEventModeStringAndSplit(nereidsTraceEventMode); if (strings != null) { parsedNereidsEventMode = EventSwitchParser.parse(strings); } if (parsedNereidsEventMode == null) { throw new UnsupportedOperationException("nereids_trace_event_mode syntax error, please check"); } } public Set<Class<? extends Event>> getParsedNereidsEventMode() { return parsedNereidsEventMode; } public String getBlockEncryptionMode() { return blockEncryptionMode; } public void setBlockEncryptionMode(String blockEncryptionMode) { this.blockEncryptionMode = blockEncryptionMode; } public void setRewriteOrToInPredicateThreshold(int threshold) { this.rewriteOrToInPredicateThreshold = threshold; } public int getRewriteOrToInPredicateThreshold() { return rewriteOrToInPredicateThreshold; } public long getMaxExecMemByte() { return maxExecMemByte; } public long getMaxScanQueueExecMemByte() { return maxScanQueueMemByte; } public int getNumScannerThreads() { return numScannerThreads; } public double getScannerScaleUpRatio() { return scannerScaleUpRatio; } public int getQueryTimeoutS() { return queryTimeoutS; } public int getAnalyzeTimeoutS() { return analyzeTimeoutS; } public void setEnableTwoPhaseReadOpt(boolean enable) { enableTwoPhaseReadOpt = enable; } public int getMaxExecutionTimeMS() { return maxExecutionTimeMS; } public int getInsertTimeoutS() { return insertTimeoutS; } public void setInsertTimeoutS(int insertTimeoutS) { this.insertTimeoutS = insertTimeoutS; } public boolean enableProfile() { return enableProfile; } public int getAutoProfileThresholdMs() { return this.autoProfileThresholdMs; } public boolean enableSingleDistinctColumnOpt() { return enableSingleDistinctColumnOpt; } public int getWaitTimeoutS() { return waitTimeoutS; } public long getSqlMode() { return sqlMode; } public void setSqlMode(long sqlMode) { this.sqlMode = sqlMode; } public boolean isEnableJoinReorderBasedCost() { return enableJoinReorderBasedCost; } public boolean enableMultiClusterSyncLoad() { return cloudEnableMultiClusterSyncLoad; } public void setEnableMultiClusterSyncLoad(boolean cloudEnableMultiClusterSyncLoad) { this.cloudEnableMultiClusterSyncLoad = cloudEnableMultiClusterSyncLoad; } public boolean isTxReadonly() { return txReadonly; } public boolean isTransactionReadonly() { return transactionReadonly; } public String getTransactionIsolation() { return transactionIsolation; } public String getTxIsolation() { return txIsolation; } public String getCharsetClient() { return charsetClient; } public String getCharsetConnection() { return charsetConnection; } public String getCharsetResults() { return charsetResults; } public String getCharsetServer() { return charsetServer; } public String getCollationConnection() { return collationConnection; } public String getCollationDatabase() { return collationDatabase; } public String getCollationServer() { return collationServer; } public boolean isSqlAutoIsNull() { return sqlAutoIsNull; } public long getSqlSelectLimit() { if (sqlSelectLimit < 0 || sqlSelectLimit >= Long.MAX_VALUE) { return -1; } return sqlSelectLimit; } public long getDefaultOrderByLimit() { return defaultOrderByLimit; } public int getMaxAllowedPacket() { return maxAllowedPacket; } public int getAutoIncrementIncrement() { return autoIncrementIncrement; } public int getQueryCacheType() { return queryCacheType; } public int getInteractiveTimeout() { return interactiveTimeout; } public int getNetWriteTimeout() { return netWriteTimeout; } public int getNetReadTimeout() { return netReadTimeout; } public String getTimeZone() { return timeZone; } public void setTimeZone(String timeZone) { this.timeZone = timeZone; } public int getSqlSafeUpdates() { return sqlSafeUpdates; } public int getNetBufferLength() { return netBufferLength; } public int getCodegenLevel() { return codegenLevel; } public boolean getHaveQueryCache() { return haveQueryCache; } /** * setMaxExecMemByte. **/ public void setMaxExecMemByte(long maxExecMemByte) { if (maxExecMemByte < MIN_EXEC_MEM_LIMIT) { this.maxExecMemByte = MIN_EXEC_MEM_LIMIT; } else { this.maxExecMemByte = maxExecMemByte; } } public void setMaxScanQueueMemByte(long scanQueueMemByte) { this.maxScanQueueMemByte = scanQueueMemByte; } public void setNumScannerThreads(int numScannerThreads) { this.numScannerThreads = numScannerThreads; } public void setScannerScaleUpRatio(double scannerScaleUpRatio) { this.scannerScaleUpRatio = scannerScaleUpRatio; } public boolean isSqlQuoteShowCreate() { return sqlQuoteShowCreate; } public void setSqlQuoteShowCreate(boolean sqlQuoteShowCreate) { this.sqlQuoteShowCreate = sqlQuoteShowCreate; } public void setQueryTimeoutS(int queryTimeoutS) { if (queryTimeoutS <= 0) { LOG.warn("Setting invalid query timeout", new RuntimeException("")); } this.queryTimeoutS = queryTimeoutS; } // This method will be called by VariableMgr.replayGlobalVariableV2 // We dont want any potential exception is thrown during replay oplog // so we do not check its validation. Here potential excaption // will become real in cases where user set global query timeout 0 before // upgrading to this version. public void setQueryTimeoutS(String queryTimeoutS) { int newQueryTimeoutS = Integer.valueOf(queryTimeoutS); if (newQueryTimeoutS <= 0) { LOG.warn("Invalid query timeout: {}", newQueryTimeoutS, new RuntimeException("")); } this.queryTimeoutS = newQueryTimeoutS; } public void setAnalyzeTimeoutS(int analyzeTimeoutS) { this.analyzeTimeoutS = analyzeTimeoutS; } public void setMaxExecutionTimeMS(int maxExecutionTimeMS) { this.maxExecutionTimeMS = maxExecutionTimeMS; this.queryTimeoutS = this.maxExecutionTimeMS / 1000; if (queryTimeoutS <= 0) { LOG.warn("Invalid query timeout: {}", queryTimeoutS, new RuntimeException("")); } } public void setMaxExecutionTimeMS(String maxExecutionTimeMS) { this.maxExecutionTimeMS = Integer.valueOf(maxExecutionTimeMS); this.queryTimeoutS = this.maxExecutionTimeMS / 1000; if (queryTimeoutS <= 0) { LOG.warn("Invalid query timeout: {}", queryTimeoutS, new RuntimeException("")); } } public void setPipelineTaskNum(String value) throws Exception { int val = checkFieldValue(PARALLEL_PIPELINE_TASK_NUM, 0, value); this.parallelPipelineTaskNum = val; } public void setFragmentInstanceNum(String value) throws Exception { int val = checkFieldValue(PARALLEL_FRAGMENT_EXEC_INSTANCE_NUM, 1, value); this.parallelExecInstanceNum = val; } private int checkFieldValue(String variableName, int minValue, String value) throws Exception { int val = Integer.valueOf(value); if (val < minValue) { throw new Exception( variableName + " value should greater than or equal " + String.valueOf(minValue) + ", you set value is: " + value); } return val; } public String getWorkloadGroup() { return workloadGroup; } public void setWorkloadGroup(String workloadGroup) { this.workloadGroup = workloadGroup; } public boolean getBypassWorkloadGroup() { return this.bypassWorkloadGroup; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public boolean isDisableFileCache() { return Config.isCloudMode() ? disableFileCache : false; } public void setDisableFileCache(boolean disableFileCache) { this.disableFileCache = disableFileCache; } public boolean isDisableColocatePlan() { return disableColocatePlan; } public boolean isEnableBucketShuffleJoin() { return enableBucketShuffleJoin; } public boolean isEnableBucketShuffleDownGrade() { return enableBucketShuffleDownGrade; } public boolean isEnableOdbcTransaction() { return enableOdbcTransaction; } public String getPreferJoinMethod() { return preferJoinMethod; } public void setPreferJoinMethod(String preferJoinMethod) { this.preferJoinMethod = preferJoinMethod; } public boolean isEnableFoldConstantByBe() { return enableFoldConstantByBe; } public boolean isEnableRewriteElementAtToSlot() { return enableRewriteElementAtToSlot; } public void setEnableRewriteElementAtToSlot(boolean rewriteElementAtToSlot) { enableRewriteElementAtToSlot = rewriteElementAtToSlot; } public boolean isEnableNereidsDML() { return enableNereidsDML; } public void setEnableFoldConstantByBe(boolean foldConstantByBe) { this.enableFoldConstantByBe = foldConstantByBe; } public int getParallelExecInstanceNum() { ConnectContext connectContext = ConnectContext.get(); if (connectContext != null && connectContext.getEnv() != null && connectContext.getEnv().getAuth() != null) { int userParallelExecInstanceNum = connectContext.getEnv().getAuth() .getParallelFragmentExecInstanceNum(connectContext.getQualifiedUser()); if (userParallelExecInstanceNum > 0) { return userParallelExecInstanceNum; } } if (getEnablePipelineEngine() && parallelPipelineTaskNum == 0) { int size = Env.getCurrentSystemInfo().getMinPipelineExecutorSize(); int autoInstance = (size + 1) / 2; return Math.min(autoInstance, maxInstanceNum); } else if (getEnablePipelineEngine()) { return parallelPipelineTaskNum; } else { return parallelExecInstanceNum; } } public int getExchangeInstanceParallel() { return exchangeInstanceParallel; } public boolean getEnableInsertStrict() { return enableInsertStrict; } public void setEnableInsertStrict(boolean enableInsertStrict) { this.enableInsertStrict = enableInsertStrict; } public boolean isEnableSqlCache() { return enableSqlCache; } public void setEnableSqlCache(boolean enableSqlCache) { this.enableSqlCache = enableSqlCache; } public int getPartitionedHashJoinRowsThreshold() { return partitionedHashJoinRowsThreshold; } public void setPartitionedHashJoinRowsThreshold(int threshold) { this.partitionedHashJoinRowsThreshold = threshold; } // Serialize to thrift object public boolean getForwardToMaster() { return forwardToMaster; } public boolean isUseV2Rollup() { return useV2Rollup; } // for unit test public void setUseV2Rollup(boolean useV2Rollup) { this.useV2Rollup = useV2Rollup; } public boolean isRewriteCountDistinct() { return rewriteCountDistinct; } public void setRewriteCountDistinct(boolean rewriteCountDistinct) { this.rewriteCountDistinct = rewriteCountDistinct; } public String getEventScheduler() { return eventScheduler; } public void setEventScheduler(String eventScheduler) { this.eventScheduler = eventScheduler; } public String getStorageEngine() { return storageEngine; } public void setStorageEngine(String storageEngine) { this.storageEngine = storageEngine; } public int getDivPrecisionIncrement() { return divPrecisionIncrement; } public int getMaxScanKeyNum() { return maxScanKeyNum; } public void setMaxScanKeyNum(int maxScanKeyNum) { this.maxScanKeyNum = maxScanKeyNum; } public int getMaxPushdownConditionsPerColumn() { return maxPushdownConditionsPerColumn; } public void setMaxPushdownConditionsPerColumn(int maxPushdownConditionsPerColumn) { this.maxPushdownConditionsPerColumn = maxPushdownConditionsPerColumn; } public double getBroadcastRightTableScaleFactor() { return broadcastRightTableScaleFactor; } public void setBroadcastRightTableScaleFactor(double broadcastRightTableScaleFactor) { this.broadcastRightTableScaleFactor = broadcastRightTableScaleFactor; } public double getBroadcastRowCountLimit() { return broadcastRowCountLimit; } public void setBroadcastRowCountLimit(double broadcastRowCountLimit) { this.broadcastRowCountLimit = broadcastRowCountLimit; } public double getBroadcastHashtableMemLimitPercentage() { return broadcastHashtableMemLimitPercentage; } public void setBroadcastHashtableMemLimitPercentage(double broadcastHashtableMemLimitPercentage) { this.broadcastHashtableMemLimitPercentage = broadcastHashtableMemLimitPercentage; } public boolean showHiddenColumns() { return showHiddenColumns; } public void setShowHiddenColumns(boolean showHiddenColumns) { this.showHiddenColumns = showHiddenColumns; } public boolean isEnableScanRunSerial() { return enableScanRunSerial; } public boolean skipStorageEngineMerge() { return skipStorageEngineMerge; } public boolean skipDeleteSign() { return skipDeleteSign; } public boolean isAllowPartitionColumnNullable() { return allowPartitionColumnNullable; } public String getRuntimeFilterMode() { return runtimeFilterMode; } public void setRuntimeFilterMode(String runtimeFilterMode) { this.runtimeFilterMode = runtimeFilterMode; } public int getRuntimeBloomFilterSize() { return runtimeBloomFilterSize; } public void setRuntimeBloomFilterSize(int runtimeBloomFilterSize) { this.runtimeBloomFilterSize = runtimeBloomFilterSize; } public int getRuntimeBloomFilterMinSize() { return runtimeBloomFilterMinSize; } public void setRuntimeBloomFilterMinSize(int runtimeBloomFilterMinSize) { this.runtimeBloomFilterMinSize = runtimeBloomFilterMinSize; } public int getRuntimeBloomFilterMaxSize() { return runtimeBloomFilterMaxSize; } public void setRuntimeBloomFilterMaxSize(int runtimeBloomFilterMaxSize) { this.runtimeBloomFilterMaxSize = runtimeBloomFilterMaxSize; } public int getRuntimeFilterWaitTimeMs() { return runtimeFilterWaitTimeMs; } public void setRuntimeFilterWaitTimeMs(int runtimeFilterWaitTimeMs) { this.runtimeFilterWaitTimeMs = runtimeFilterWaitTimeMs; } public int getRuntimeFiltersMaxNum() { return runtimeFiltersMaxNum; } public void setRuntimeFiltersMaxNum(int runtimeFiltersMaxNum) { this.runtimeFiltersMaxNum = runtimeFiltersMaxNum; } public int getRuntimeFilterType() { return runtimeFilterType; } public boolean allowedRuntimeFilterType(TRuntimeFilterType type) { return (runtimeFilterType & type.getValue()) != 0; } public boolean isRuntimeFilterTypeEnabled(TRuntimeFilterType type) { return (runtimeFilterType & type.getValue()) == type.getValue(); } public void setRuntimeFilterType(int runtimeFilterType) { this.runtimeFilterType = runtimeFilterType; } public int getRuntimeFilterMaxInNum() { return runtimeFilterMaxInNum; } public void setRuntimeFilterMaxInNum(int runtimeFilterMaxInNum) { this.runtimeFilterMaxInNum = runtimeFilterMaxInNum; } public void setEnablePipelineEngine(boolean enablePipelineEngine) { this.enablePipelineEngine = enablePipelineEngine; } public void setEnablePipelineXEngine(boolean enablePipelineXEngine) { this.enablePipelineXEngine = enablePipelineXEngine; } public void setEnableLocalShuffle(boolean enableLocalShuffle) { this.enableLocalShuffle = enableLocalShuffle; } public boolean enablePushDownNoGroupAgg() { return enablePushDownNoGroupAgg; } public boolean getEnableFunctionPushdown() { return this.enableFunctionPushdown; } public boolean getForbidUnknownColStats() { return forbidUnknownColStats; } public void setForbidUnknownColStats(boolean forbid) { forbidUnknownColStats = forbid; } public boolean getEnableLocalExchange() { return enableLocalExchange; } public boolean getEnableCboStatistics() { return enableCboStatistics; } public long getFileSplitSize() { return fileSplitSize; } public void setFileSplitSize(long fileSplitSize) { this.fileSplitSize = fileSplitSize; } public int getNumPartitionsInBatchMode() { return numPartitionsInBatchMode; } public void setNumSplitsInBatchMode(int numPartitionsInBatchMode) { this.numPartitionsInBatchMode = numPartitionsInBatchMode; } public boolean isEnableParquetLazyMat() { return enableParquetLazyMat; } public void setEnableParquetLazyMat(boolean enableParquetLazyMat) { this.enableParquetLazyMat = enableParquetLazyMat; } public boolean isEnableOrcLazyMat() { return enableOrcLazyMat; } public void setEnableOrcLazyMat(boolean enableOrcLazyMat) { this.enableOrcLazyMat = enableOrcLazyMat; } public String getSqlDialect() { return sqlDialect; } public int getWaitFullBlockScheduleTimes() { return waitFullBlockScheduleTimes; } public Dialect getSqlParseDialect() { return Dialect.getByName(sqlDialect); } public void setSqlDialect(String sqlDialect) { this.sqlDialect = sqlDialect == null ? null : sqlDialect.toLowerCase(); } /** * getInsertVisibleTimeoutMs. **/ public long getInsertVisibleTimeoutMs() { if (insertVisibleTimeoutMs < MIN_INSERT_VISIBLE_TIMEOUT_MS) { return MIN_INSERT_VISIBLE_TIMEOUT_MS; } else { return insertVisibleTimeoutMs; } } /** * setInsertVisibleTimeoutMs. **/ public void setInsertVisibleTimeoutMs(long insertVisibleTimeoutMs) { if (insertVisibleTimeoutMs < MIN_INSERT_VISIBLE_TIMEOUT_MS) { this.insertVisibleTimeoutMs = MIN_INSERT_VISIBLE_TIMEOUT_MS; } else { this.insertVisibleTimeoutMs = insertVisibleTimeoutMs; } } public boolean getIsSingleSetVar() { return isSingleSetVar; } public void setIsSingleSetVar(boolean issinglesetvar) { this.isSingleSetVar = issinglesetvar; } public Map<SessionVariableField, String> getSessionOriginValue() { return sessionOriginValue; } public void addSessionOriginValue(SessionVariableField key, String value) { if (sessionOriginValue.containsKey(key)) { // If we already set the origin value, just skip the reset. return; } sessionOriginValue.put(key, value); } public void clearSessionOriginValue() { sessionOriginValue.clear(); } public boolean isDeleteWithoutPartition() { return deleteWithoutPartition; } public boolean isExtractWideRangeExpr() { return extractWideRangeExpr; } public boolean isGroupByAndHavingUseAliasFirst() { return groupByAndHavingUseAliasFirst; } public int getCpuResourceLimit() { return cpuResourceLimit; } public int getSendBatchParallelism() { return sendBatchParallelism; } public boolean isEnableParallelOutfile() { return enableParallelOutfile; } public boolean isDisableJoinReorder() { return disableJoinReorder; } public boolean isEnableBushyTree() { return enableBushyTree; } public void setEnableBushyTree(boolean enableBushyTree) { this.enableBushyTree = enableBushyTree; } public boolean isEnablePartitionTopN() { return enablePartitionTopN; } public void setEnablePartitionTopN(boolean enablePartitionTopN) { this.enablePartitionTopN = enablePartitionTopN; } public double getGlobalPartitionTopNThreshold() { return globalPartitionTopNThreshold; } public void setGlobalPartitionTopnThreshold(int threshold) { this.globalPartitionTopNThreshold = threshold; } public boolean isEnableFoldNondeterministicFn() { return enableFoldNondeterministicFn; } public void setEnableFoldNondeterministicFn(boolean enableFoldNondeterministicFn) { this.enableFoldNondeterministicFn = enableFoldNondeterministicFn; } public boolean isReturnObjectDataAsBinary() { return returnObjectDataAsBinary; } public void setReturnObjectDataAsBinary(boolean returnObjectDataAsBinary) { this.returnObjectDataAsBinary = returnObjectDataAsBinary; } public boolean isEnableInferPredicate() { return enableInferPredicate; } public void setEnableInferPredicate(boolean enableInferPredicate) { this.enableInferPredicate = enableInferPredicate; } public boolean isEnableProjection() { return enableProjection; } public boolean checkOverflowForDecimal() { return checkOverflowForDecimal; } public boolean isTrimTailingSpacesForExternalTableQuery() { return trimTailingSpacesForExternalTableQuery; } public void setTrimTailingSpacesForExternalTableQuery(boolean trimTailingSpacesForExternalTableQuery) { this.trimTailingSpacesForExternalTableQuery = trimTailingSpacesForExternalTableQuery; } public void setEnableJoinReorderBasedCost(boolean enableJoinReorderBasedCost) { this.enableJoinReorderBasedCost = enableJoinReorderBasedCost; } public void setDisableJoinReorder(boolean disableJoinReorder) { this.disableJoinReorder = disableJoinReorder; } public boolean isEnablePushDownMinMaxOnUnique() { return enablePushDownMinMaxOnUnique; } public void setEnablePushDownMinMaxOnUnique(boolean enablePushDownMinMaxOnUnique) { this.enablePushDownMinMaxOnUnique = enablePushDownMinMaxOnUnique; } public boolean isEnablePushDownStringMinMax() { return enablePushDownStringMinMax; } /** * Nereids only support vectorized engine. * * @return true if both nereids and vectorized engine are enabled */ public boolean isEnableNereidsPlanner() { return enableNereidsPlanner; } public void setEnableNereidsPlanner(boolean enableNereidsPlanner) { this.enableNereidsPlanner = enableNereidsPlanner; } public int getNthOptimizedPlan() { return nthOptimizedPlan; } public Set<String> getDisableNereidsRuleNames() { String checkPrivilege = RuleType.CHECK_PRIVILEGES.name(); String checkRowPolicy = RuleType.CHECK_ROW_POLICY.name(); return Arrays.stream(disableNereidsRules.split(",[\\s]*")) .map(rule -> rule.toUpperCase(Locale.ROOT)) .filter(rule -> !StringUtils.equalsIgnoreCase(rule, checkPrivilege) && !StringUtils.equalsIgnoreCase(rule, checkRowPolicy)) .collect(ImmutableSet.toImmutableSet()); } public BitSet getDisableNereidsRules() { BitSet bitSet = new BitSet(); for (String ruleName : disableNereidsRules.split(",[\\s]*")) { if (ruleName.isEmpty()) { continue; } ruleName = ruleName.toUpperCase(Locale.ROOT); RuleType ruleType = RuleType.valueOf(ruleName); if (ruleType == RuleType.CHECK_PRIVILEGES || ruleType == RuleType.CHECK_ROW_POLICY) { continue; } bitSet.set(ruleType.type()); } return bitSet; } public Set<Integer> getEnableNereidsRules() { return Arrays.stream(enableNereidsRules.split(",[\\s]*")) .filter(rule -> !rule.isEmpty()) .map(rule -> rule.toUpperCase(Locale.ROOT)) .map(rule -> RuleType.valueOf(rule).type()) .collect(ImmutableSet.toImmutableSet()); } public void setEnableNewCostModel(boolean enable) { this.enableNewCostModel = enable; } public boolean getEnableNewCostModel() { return this.enableNewCostModel; } public void setDisableNereidsRules(String disableNereidsRules) { this.disableNereidsRules = disableNereidsRules; } public double getNereidsCboPenaltyFactor() { return nereidsCboPenaltyFactor; } public void setNereidsCboPenaltyFactor(double penaltyFactor) { this.nereidsCboPenaltyFactor = penaltyFactor; } public boolean isEnableNereidsTrace() { return isEnableNereidsPlanner() && enableNereidsTrace; } public void setEnableExprTrace(boolean enableExprTrace) { this.enableExprTrace = enableExprTrace; } public boolean isEnableExprTrace() { return enableExprTrace; } public boolean isEnableSingleReplicaInsert() { return enableSingleReplicaInsert; } public void setEnableSingleReplicaInsert(boolean enableSingleReplicaInsert) { this.enableSingleReplicaInsert = enableSingleReplicaInsert; } public boolean isEnableMemtableOnSinkNode() { return enableMemtableOnSinkNode; } public void setEnableMemtableOnSinkNode(boolean enableMemtableOnSinkNode) { this.enableMemtableOnSinkNode = enableMemtableOnSinkNode; } public boolean isEnableRuntimeFilterPrune() { return enableRuntimeFilterPrune; } public void setEnableRuntimeFilterPrune(boolean enableRuntimeFilterPrune) { this.enableRuntimeFilterPrune = enableRuntimeFilterPrune; } public void setFragmentTransmissionCompressionCodec(String codec) { this.fragmentTransmissionCompressionCodec = codec; } public boolean isEnableUnicodeNameSupport() { return enableUnicodeNameSupport; } public void setEnableUnicodeNameSupport(boolean enableUnicodeNameSupport) { this.enableUnicodeNameSupport = enableUnicodeNameSupport; } public boolean isDropTableIfCtasFailed() { return dropTableIfCtasFailed; } public void checkExternalSortBytesThreshold(String externalSortBytesThreshold) { long value = Long.valueOf(externalSortBytesThreshold); if (value > 0 && value < MIN_EXTERNAL_SORT_BYTES_THRESHOLD) { LOG.warn("external sort bytes threshold: {}, min: {}", value, MIN_EXTERNAL_SORT_BYTES_THRESHOLD); throw new UnsupportedOperationException("minimum value is " + MIN_EXTERNAL_SORT_BYTES_THRESHOLD); } } public void checkExternalAggBytesThreshold(String externalAggBytesThreshold) { long value = Long.valueOf(externalAggBytesThreshold); if (value > 0 && value < MIN_EXTERNAL_AGG_BYTES_THRESHOLD) { LOG.warn("external agg bytes threshold: {}, min: {}", value, MIN_EXTERNAL_AGG_BYTES_THRESHOLD); throw new UnsupportedOperationException("minimum value is " + MIN_EXTERNAL_AGG_BYTES_THRESHOLD); } } public void checkExternalAggPartitionBits(String externalAggPartitionBits) { int value = Integer.valueOf(externalAggPartitionBits); if (value < MIN_EXTERNAL_AGG_PARTITION_BITS || value > MAX_EXTERNAL_AGG_PARTITION_BITS) { LOG.warn("external agg bytes threshold: {}, min: {}, max: {}", value, MIN_EXTERNAL_AGG_PARTITION_BITS, MAX_EXTERNAL_AGG_PARTITION_BITS); throw new UnsupportedOperationException("min value is " + MIN_EXTERNAL_AGG_PARTITION_BITS + " max value is " + MAX_EXTERNAL_AGG_PARTITION_BITS); } } public void checkQueryTimeoutValid(String newQueryTimeout) { int value = Integer.valueOf(newQueryTimeout); if (value <= 0) { UnsupportedOperationException exception = new UnsupportedOperationException( "query_timeout can not be set to " + newQueryTimeout + ", it must be greater than 0"); LOG.warn("Check query_timeout failed", exception); throw exception; } } public void checkMaxExecutionTimeMSValid(String newValue) { int value = Integer.valueOf(newValue); if (value < 1000) { UnsupportedOperationException exception = new UnsupportedOperationException( "max_execution_time can not be set to " + newValue + ", it must be greater or equal to 1000, the time unit is millisecond"); LOG.warn("Check max_execution_time failed", exception); throw exception; } } public long convertBoolToLong(Boolean val) { return val ? 1 : 0; } public boolean isEnableFileCache() { return enableFileCache; } public void setEnableFileCache(boolean enableFileCache) { this.enableFileCache = enableFileCache; } public String getFileCacheBasePath() { return fileCacheBasePath; } public void setFileCacheBasePath(String basePath) { this.fileCacheBasePath = basePath; } public boolean isEnableInvertedIndexQuery() { return enableInvertedIndexQuery; } public void setEnableInvertedIndexQuery(boolean enableInvertedIndexQuery) { this.enableInvertedIndexQuery = enableInvertedIndexQuery; } public boolean isEnableCommonExprPushdownForInvertedIndex() { return enableCommonExpPushDownForInvertedIndex; } public void setEnableCommonExprPushdownForInvertedIndex(boolean enableCommonExpPushDownForInvertedIndex) { this.enableCommonExpPushDownForInvertedIndex = enableCommonExpPushDownForInvertedIndex; } public boolean isEnablePushDownCountOnIndex() { return enablePushDownCountOnIndex; } public void setEnablePushDownCountOnIndex(boolean enablePushDownCountOnIndex) { this.enablePushDownCountOnIndex = enablePushDownCountOnIndex; } public int getMaxTableCountUseCascadesJoinReorder() { return this.maxTableCountUseCascadesJoinReorder; } public void setMaxTableCountUseCascadesJoinReorder(int maxTableCountUseCascadesJoinReorder) { this.maxTableCountUseCascadesJoinReorder = maxTableCountUseCascadesJoinReorder < MIN_JOIN_REORDER_TABLE_COUNT ? MIN_JOIN_REORDER_TABLE_COUNT : maxTableCountUseCascadesJoinReorder; } public boolean isShowUserDefaultRole() { return showUserDefaultRole; } public int getExternalTableAnalyzePartNum() { return externalTableAnalyzePartNum; } public boolean isTruncateCharOrVarcharColumns() { return truncateCharOrVarcharColumns; } public void setTruncateCharOrVarcharColumns(boolean truncateCharOrVarcharColumns) { this.truncateCharOrVarcharColumns = truncateCharOrVarcharColumns; } public boolean isEnableUniqueKeyPartialUpdate() { return enableUniqueKeyPartialUpdate; } public void setEnableUniqueKeyPartialUpdate(boolean enableUniqueKeyPartialUpdate) { this.enableUniqueKeyPartialUpdate = enableUniqueKeyPartialUpdate; } public int getLoadStreamPerNode() { return loadStreamPerNode; } public void setLoadStreamPerNode(int loadStreamPerNode) { this.loadStreamPerNode = loadStreamPerNode; } /** * Serialize to thrift object. * Used for rest api. */ public TQueryOptions toThrift() { TQueryOptions tResult = new TQueryOptions(); tResult.setMemLimit(maxExecMemByte); tResult.setLocalExchangeFreeBlocksLimit(localExchangeFreeBlocksLimit); tResult.setScanQueueMemLimit(maxScanQueueMemByte); tResult.setNumScannerThreads(numScannerThreads); tResult.setScannerScaleUpRatio(scannerScaleUpRatio); // TODO chenhao, reservation will be calculated by cost tResult.setMinReservation(0); tResult.setMaxReservation(maxExecMemByte); tResult.setInitialReservationTotalClaims(maxExecMemByte); tResult.setBufferPoolLimit(maxExecMemByte); tResult.setQueryTimeout(queryTimeoutS); tResult.setEnableProfile(enableProfile); if (enableProfile) { // If enable profile == true, then also set report success to true // be need report success to start report thread. But it is very tricky // we should modify BE in the future. tResult.setIsReportSuccess(true); } tResult.setCodegenLevel(codegenLevel); tResult.setBeExecVersion(Config.be_exec_version); tResult.setEnablePipelineEngine(enablePipelineEngine); tResult.setEnablePipelineXEngine(enablePipelineXEngine || enablePipelineEngine); tResult.setEnableLocalShuffle(enableLocalShuffle && enableNereidsPlanner); tResult.setParallelInstance(getParallelExecInstanceNum()); tResult.setReturnObjectDataAsBinary(returnObjectDataAsBinary); tResult.setTrimTailingSpacesForExternalTableQuery(trimTailingSpacesForExternalTableQuery); tResult.setEnableShareHashTableForBroadcastJoin(enableShareHashTableForBroadcastJoin); tResult.setEnableHashJoinEarlyStartProbe(enableHashJoinEarlyStartProbe); tResult.setBatchSize(batchSize); tResult.setDisableStreamPreaggregations(disableStreamPreaggregations); tResult.setEnableDistinctStreamingAggregation(enableDistinctStreamingAggregation); if (maxScanKeyNum > -1) { tResult.setMaxScanKeyNum(maxScanKeyNum); } if (maxPushdownConditionsPerColumn > -1) { tResult.setMaxPushdownConditionsPerColumn(maxPushdownConditionsPerColumn); } tResult.setEnableSpilling(enableSpilling); tResult.setEnableEnableExchangeNodeParallelMerge(enableExchangeNodeParallelMerge); tResult.setRuntimeFilterWaitTimeMs(runtimeFilterWaitTimeMs); tResult.setRuntimeFilterMaxInNum(runtimeFilterMaxInNum); tResult.setRuntimeFilterWaitInfinitely(runtimeFilterWaitInfinitely); if (cpuResourceLimit > 0) { TResourceLimit resourceLimit = new TResourceLimit(); resourceLimit.setCpuLimit(cpuResourceLimit); tResult.setResourceLimit(resourceLimit); } tResult.setEnableFunctionPushdown(enableFunctionPushdown); tResult.setEnableCommonExprPushdown(enableCommonExprPushdown); tResult.setCheckOverflowForDecimal(checkOverflowForDecimal); tResult.setFragmentTransmissionCompressionCodec(fragmentTransmissionCompressionCodec.trim().toLowerCase()); tResult.setEnableLocalExchange(enableLocalExchange); tResult.setSkipStorageEngineMerge(skipStorageEngineMerge); tResult.setSkipDeletePredicate(skipDeletePredicate); tResult.setSkipDeleteBitmap(skipDeleteBitmap); tResult.setPartitionedHashJoinRowsThreshold(partitionedHashJoinRowsThreshold); tResult.setPartitionedHashAggRowsThreshold(partitionedHashAggRowsThreshold); tResult.setRepeatMaxNum(repeatMaxNum); tResult.setExternalSortBytesThreshold(externalSortBytesThreshold); tResult.setExternalAggBytesThreshold(0); // disable for now tResult.setSpillStreamingAggMemLimit(spillStreamingAggMemLimit); tResult.setExternalAggPartitionBits(externalAggPartitionBits); tResult.setEnableFileCache(enableFileCache); tResult.setEnablePageCache(enablePageCache); tResult.setFileCacheBasePath(fileCacheBasePath); tResult.setEnableInvertedIndexQuery(enableInvertedIndexQuery); tResult.setEnableCommonExprPushdownForInvertedIndex(enableCommonExpPushDownForInvertedIndex); if (dryRunQuery) { tResult.setDryRunQuery(true); } tResult.setEnableParquetLazyMat(enableParquetLazyMat); tResult.setEnableOrcLazyMat(enableOrcLazyMat); tResult.setEnableDeleteSubPredicateV2(enableDeleteSubPredicateV2); tResult.setTruncateCharOrVarcharColumns(truncateCharOrVarcharColumns); tResult.setEnableMemtableOnSinkNode(enableMemtableOnSinkNode); tResult.setInvertedIndexConjunctionOptThreshold(invertedIndexConjunctionOptThreshold); tResult.setInvertedIndexMaxExpansions(invertedIndexMaxExpansions); tResult.setEnableDecimal256(enableNereidsPlanner && enableDecimal256); tResult.setSkipMissingVersion(skipMissingVersion); tResult.setInvertedIndexSkipThreshold(invertedIndexSkipThreshold); tResult.setEnableParallelScan(enableParallelScan); tResult.setParallelScanMaxScannersCount(parallelScanMaxScannersCount); tResult.setParallelScanMinRowsPerScanner(parallelScanMinRowsPerScanner); tResult.setSkipBadTablet(skipBadTablet); tResult.setDisableFileCache(disableFileCache); tResult.setEnableJoinSpill(enableJoinSpill); tResult.setEnableSortSpill(enableSortSpill); tResult.setEnableAggSpill(enableAggSpill); tResult.setEnableForceSpill(enableForceSpill); tResult.setMinRevocableMem(minRevocableMem); tResult.setDataQueueMaxBlocks(dataQueueMaxBlocks); return tResult; } public JSONObject toJson() throws IOException { JSONObject root = new JSONObject(); try { for (Field field : SessionVariable.class.getDeclaredFields()) { VarAttr attr = field.getAnnotation(VarAttr.class); if (attr == null) { continue; } switch (field.getType().getSimpleName()) { case "boolean": root.put(attr.name(), (Boolean) field.get(this)); break; case "int": root.put(attr.name(), (Integer) field.get(this)); break; case "long": root.put(attr.name(), (Long) field.get(this)); break; case "float": root.put(attr.name(), (Float) field.get(this)); break; case "double": root.put(attr.name(), (Double) field.get(this)); break; case "String": root.put(attr.name(), (String) field.get(this)); break; default: // Unsupported type variable. throw new IOException("invalid type: " + field.getType().getSimpleName()); } } } catch (Exception e) { throw new IOException("failed to write session variable: " + e.getMessage()); } return root; } @Override public void write(DataOutput out) throws IOException { JSONObject root = toJson(); Text.writeString(out, root.toString()); } public void readFields(DataInput in) throws IOException { String json = Text.readString(in); readFromJson(json); } public void readFromJson(String json) throws IOException { JSONObject root = (JSONObject) JSONValue.parse(json); try { for (Field field : SessionVariable.class.getDeclaredFields()) { VarAttr attr = field.getAnnotation(VarAttr.class); if (attr == null) { continue; } if (!root.containsKey(attr.name())) { continue; } switch (field.getType().getSimpleName()) { case "boolean": field.set(this, root.get(attr.name())); break; case "int": // root.get(attr.name()) always return Long type, so need to convert it. field.set(this, Integer.valueOf(root.get(attr.name()).toString())); break; case "long": field.set(this, (Long) root.get(attr.name())); break; case "float": field.set(this, root.get(attr.name())); break; case "double": field.set(this, root.get(attr.name())); break; case "String": field.set(this, root.get(attr.name())); break; default: // Unsupported type variable. throw new IOException("invalid type: " + field.getType().getSimpleName()); } } } catch (Exception e) { throw new IOException("failed to read session variable: " + e.getMessage()); } } /** * Get all variables which need to forward along with statement. **/ public Map<String, String> getForwardVariables() { HashMap<String, String> map = new HashMap<String, String>(); try { Field[] fields = SessionVariable.class.getDeclaredFields(); for (Field f : fields) { VarAttr varAttr = f.getAnnotation(VarAttr.class); if (varAttr == null || !varAttr.needForward()) { continue; } map.put(varAttr.name(), String.valueOf(f.get(this))); } } catch (IllegalAccessException e) { LOG.error("failed to get forward variables", e); } return map; } /** * Set forwardedSessionVariables for variables. **/ public void setForwardedSessionVariables(Map<String, String> variables) { try { Field[] fields = SessionVariable.class.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); VarAttr varAttr = f.getAnnotation(VarAttr.class); if (varAttr == null || !varAttr.needForward()) { continue; } String val = variables.get(varAttr.name()); if (val == null) { continue; } if (LOG.isDebugEnabled()) { LOG.debug("set forward variable: {} = {}", varAttr.name(), val); } // set config field switch (f.getType().getSimpleName()) { case "short": f.setShort(this, Short.parseShort(val)); break; case "int": f.setInt(this, Integer.parseInt(val)); break; case "long": f.setLong(this, Long.parseLong(val)); break; case "double": f.setDouble(this, Double.parseDouble(val)); break; case "boolean": f.setBoolean(this, Boolean.parseBoolean(val)); break; case "String": f.set(this, val); break; default: throw new IllegalArgumentException("Unknown field type: " + f.getType().getSimpleName()); } } } catch (IllegalAccessException e) { LOG.error("failed to set forward variables", e); } } /** * Set forwardedSessionVariables for queryOptions. **/ public void setForwardedSessionVariables(TQueryOptions queryOptions) { if (queryOptions.isSetMemLimit()) { setMaxExecMemByte(queryOptions.getMemLimit()); } if (queryOptions.isSetQueryTimeout()) { setQueryTimeoutS(queryOptions.getQueryTimeout()); } if (queryOptions.isSetInsertTimeout()) { setInsertTimeoutS(queryOptions.getInsertTimeout()); } if (queryOptions.isSetAnalyzeTimeout()) { setAnalyzeTimeoutS(queryOptions.getAnalyzeTimeout()); } } /** * Get all variables which need to be set in TQueryOptions. **/ public TQueryOptions getQueryOptionVariables() { TQueryOptions queryOptions = new TQueryOptions(); queryOptions.setMemLimit(maxExecMemByte); queryOptions.setScanQueueMemLimit(maxScanQueueMemByte); queryOptions.setNumScannerThreads(numScannerThreads); queryOptions.setScannerScaleUpRatio(scannerScaleUpRatio); queryOptions.setQueryTimeout(queryTimeoutS); queryOptions.setInsertTimeout(insertTimeoutS); queryOptions.setAnalyzeTimeout(analyzeTimeoutS); return queryOptions; } /** * The sessionContext is as follows: * "k1:v1;k2:v2;..." * Here we want to get value with key named "trace_id", * Return empty string is not found. * * @return */ public String getTraceId() { if (Strings.isNullOrEmpty(sessionContext)) { return ""; } String[] parts = sessionContext.split(";"); for (String part : parts) { String[] innerParts = part.split(":"); if (innerParts.length != 2) { continue; } if (innerParts[0].equals("trace_id")) { return innerParts[1]; } } return ""; } public boolean isEnableMinidump() { return enableMinidump; } public void setEnableMinidump(boolean enableMinidump) { this.enableMinidump = enableMinidump; } public String getMinidumpPath() { return minidumpPath; } public void setMinidumpPath(String minidumpPath) { this.minidumpPath = minidumpPath; } public boolean isTraceNereids() { return traceNereids; } public void setTraceNereids(boolean traceNereids) { this.traceNereids = traceNereids; } public boolean isPlayNereidsDump() { return planNereidsDump; } public void setPlanNereidsDump(boolean planNereidsDump) { this.planNereidsDump = planNereidsDump; } public boolean isDumpNereidsMemo() { return dumpNereidsMemo; } public void setDumpNereidsMemo(boolean dumpNereidsMemo) { this.dumpNereidsMemo = dumpNereidsMemo; } public boolean isEnableStrictConsistencyDml() { return this.enableStrictConsistencyDml; } public void setEnableStrictConsistencyDml(boolean value) { this.enableStrictConsistencyDml = value; } public void disableStrictConsistencyDmlOnce() throws DdlException { if (!enableStrictConsistencyDml) { return; } setIsSingleSetVar(true); VariableMgr.setVar(this, new SetVar(SessionVariable.ENABLE_STRICT_CONSISTENCY_DML, new StringLiteral("false"))); } public void enableFallbackToOriginalPlannerOnce() throws DdlException { if (enableFallbackToOriginalPlanner) { return; } setIsSingleSetVar(true); VariableMgr.setVar(this, new SetVar(SessionVariable.ENABLE_FALLBACK_TO_ORIGINAL_PLANNER, new StringLiteral("true"))); } public void disableNereidsPlannerOnce() throws DdlException { if (!enableNereidsPlanner) { return; } setIsSingleSetVar(true); VariableMgr.setVar(this, new SetVar(SessionVariable.ENABLE_NEREIDS_PLANNER, new StringLiteral("false"))); } public void disableNereidsJoinReorderOnce() throws DdlException { if (!enableNereidsPlanner) { return; } setIsSingleSetVar(true); VariableMgr.setVar(this, new SetVar(SessionVariable.DISABLE_JOIN_REORDER, new StringLiteral("true"))); } // return number of variables by given variable annotation public int getVariableNumByVariableAnnotation(VariableAnnotation type) { int num = 0; Field[] fields = SessionVariable.class.getDeclaredFields(); for (Field f : fields) { VarAttr varAttr = f.getAnnotation(VarAttr.class); if (varAttr == null) { continue; } if (varAttr.varType() == type) { ++num; } } return num; } public boolean getEnablePipelineEngine() { return enablePipelineEngine || enablePipelineXEngine; } public boolean getEnableSharedScan() { return enableSharedScan; } public void setEnableSharedScan(boolean value) { enableSharedScan = value; } public boolean getEnableParallelScan() { return enableParallelScan; } public boolean getEnablePipelineXEngine() { return enablePipelineXEngine || enablePipelineEngine; } public boolean enableSyncRuntimeFilterSize() { return enableSyncRuntimeFilterSize; } public static boolean enablePipelineEngine() { ConnectContext connectContext = ConnectContext.get(); if (connectContext == null) { return false; } return connectContext.getSessionVariable().enablePipelineEngine || connectContext.getSessionVariable().enablePipelineXEngine; } public static boolean enablePipelineEngineX() { ConnectContext connectContext = ConnectContext.get(); if (connectContext == null) { return false; } return connectContext.getSessionVariable().enablePipelineXEngine || connectContext.getSessionVariable().enablePipelineEngine; } public static boolean enableAggState() { ConnectContext connectContext = ConnectContext.get(); if (connectContext == null) { return true; } return connectContext.getSessionVariable().enableAggState; } public static boolean getEnableDecimal256() { ConnectContext connectContext = ConnectContext.get(); if (connectContext == null) { return false; } SessionVariable sessionVariable = connectContext.getSessionVariable(); return sessionVariable.isEnableNereidsPlanner() && sessionVariable.isEnableDecimal256(); } public boolean isEnableDecimal256() { return enableDecimal256; } public void checkAnalyzeTimeFormat(String time) { try { DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); timeFormatter.parse(time); } catch (DateTimeParseException e) { LOG.warn("Parse analyze start/end time format fail", e); throw new UnsupportedOperationException("Expect format: HH:mm:ss"); } } public void checkGenerateStatsFactor(String generateStatsFactor) { int value = Integer.valueOf(generateStatsFactor); if (value <= 0) { UnsupportedOperationException exception = new UnsupportedOperationException("Generate stats factor " + value + " should greater than 0"); LOG.warn("Check generate stats factor failed", exception); throw exception; } } public void setGenerateStatsFactor(int factor) { this.generateStatsFactor = factor; if (factor <= 0) { LOG.warn("Invalid generate stats factor: {}", factor, new RuntimeException("")); } } public void setGenerateStatsFactor(String factor) { this.generateStatsFactor = Integer.valueOf(factor); if (generateStatsFactor <= 0) { LOG.warn("Invalid generate stats factor: {}", generateStatsFactor, new RuntimeException("")); } } public boolean getEnableDescribeExtendVariantColumn() { return enableDescribeExtendVariantColumn; } public void setEnableDescribeExtendVariantColumn(boolean enableDescribeExtendVariantColumn) { this.enableDescribeExtendVariantColumn = enableDescribeExtendVariantColumn; } public static boolean enableDescribeExtendVariantColumn() { ConnectContext connectContext = ConnectContext.get(); if (connectContext == null) { return false; } return connectContext.getSessionVariable().enableDescribeExtendVariantColumn; } public int getProfileLevel() { return this.profileLevel; } public void checkSqlDialect(String sqlDialect) { if (StringUtils.isEmpty(sqlDialect)) { LOG.warn("sqlDialect value is empty"); throw new UnsupportedOperationException("sqlDialect value is empty"); } if (Arrays.stream(Dialect.values()) .noneMatch(dialect -> dialect.getDialectName().equalsIgnoreCase(sqlDialect))) { LOG.warn("sqlDialect value is invalid, the invalid value is {}", sqlDialect); throw new UnsupportedOperationException("sqlDialect value is invalid, the invalid value is " + sqlDialect); } } public boolean isEnableInsertGroupCommit() { return Config.wait_internal_group_commit_finish || GroupCommitBlockSink.parseGroupCommit(groupCommit) == TGroupCommitMode.ASYNC_MODE || GroupCommitBlockSink.parseGroupCommit(groupCommit) == TGroupCommitMode.SYNC_MODE; } public String getGroupCommit() { if (Config.wait_internal_group_commit_finish) { return "sync_mode"; } return groupCommit; } public boolean isEnableMaterializedViewRewrite() { return enableMaterializedViewRewrite; } public boolean isMaterializedViewRewriteEnableContainExternalTable() { return materializedViewRewriteEnableContainExternalTable; } public int getMaterializedViewRewriteSuccessCandidateNum() { return materializedViewRewriteSuccessCandidateNum; } public boolean isEnableMaterializedViewUnionRewrite() { return enableMaterializedViewUnionRewrite; } public boolean isEnableMaterializedViewNestRewrite() { return enableMaterializedViewNestRewrite; } public int getMaterializedViewRelationMappingMaxCount() { return materializedViewRelationMappingMaxCount; } public int getCreateTablePartitionMaxNum() { return createTablePartitionMaxNum; } public boolean isIgnoreStorageDataDistribution() { return ignoreStorageDataDistribution && getEnablePipelineXEngine() && enableLocalShuffle && enableNereidsPlanner; } public void setIgnoreStorageDataDistribution(boolean ignoreStorageDataDistribution) { this.ignoreStorageDataDistribution = ignoreStorageDataDistribution; } // CLOUD_VARIABLES_BEGIN public String getCloudCluster() { return cloudCluster; } public String setCloudCluster(String cloudCluster) { return this.cloudCluster = cloudCluster; } public boolean getDisableEmptyPartitionPrune() { return disableEmptyPartitionPrune; } public void setDisableEmptyPartitionPrune(boolean val) { disableEmptyPartitionPrune = val; } // CLOUD_VARIABLES_END public boolean isForceJniScanner() { return forceJniScanner; } public void setForceJniScanner(boolean force) { forceJniScanner = force; } public boolean isForceToLocalShuffle() { return getEnablePipelineXEngine() && enableLocalShuffle && enableNereidsPlanner && forceToLocalShuffle; } public void setForceToLocalShuffle(boolean forceToLocalShuffle) { this.forceToLocalShuffle = forceToLocalShuffle; } public boolean getShowAllFeConnection() { return this.showAllFeConnection; } public int getMaxMsgSizeOfResultReceiver() { return this.maxMsgSizeOfResultReceiver; } }
apache/doris
fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
2,384
/* * 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.cassandra.io.sstable.format; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import com.google.common.primitives.Longs; import com.google.common.util.concurrent.RateLimiter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.clearspring.analytics.stream.cardinality.CardinalityMergeException; import com.clearspring.analytics.stream.cardinality.ICardinality; import org.apache.cassandra.concurrent.ExecutorPlus; import org.apache.cassandra.concurrent.ScheduledExecutorPlus; import org.apache.cassandra.concurrent.ScheduledExecutors; import org.apache.cassandra.config.CassandraRelevantProperties; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.PartitionPosition; import org.apache.cassandra.db.SerializationHeader; import org.apache.cassandra.db.SystemKeyspace; import org.apache.cassandra.db.rows.Cell; import org.apache.cassandra.db.rows.EncodingStats; import org.apache.cassandra.db.rows.UnfilteredRowIterator; import org.apache.cassandra.db.rows.UnfilteredSource; import org.apache.cassandra.dht.AbstractBounds; import org.apache.cassandra.dht.Bounds; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.io.FSError; import org.apache.cassandra.io.FSWriteError; import org.apache.cassandra.io.compress.CompressionMetadata; import org.apache.cassandra.io.sstable.AbstractRowIndexEntry; import org.apache.cassandra.io.sstable.Component; import org.apache.cassandra.io.sstable.CorruptSSTableException; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.IVerifier; import org.apache.cassandra.io.sstable.KeyIterator; import org.apache.cassandra.io.sstable.KeyReader; import org.apache.cassandra.io.sstable.SSTable; import org.apache.cassandra.io.sstable.SSTableIdFactory; import org.apache.cassandra.io.sstable.SSTableIdentityIterator; import org.apache.cassandra.io.sstable.SSTableReadsListener; import org.apache.cassandra.io.sstable.format.SSTableFormat.Components; import org.apache.cassandra.io.sstable.metadata.CompactionMetadata; import org.apache.cassandra.io.sstable.metadata.StatsMetadata; import org.apache.cassandra.io.util.ChannelProxy; import org.apache.cassandra.io.util.CheckedFunction; import org.apache.cassandra.io.util.DataIntegrityMetadata; import org.apache.cassandra.io.util.File; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.FileHandle; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.io.util.RandomAccessReader; import org.apache.cassandra.metrics.RestorableMeter; import org.apache.cassandra.schema.SchemaConstants; import org.apache.cassandra.schema.TableMetadataRef; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.utils.EstimatedHistogram; import org.apache.cassandra.utils.ExecutorUtils; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.JVMStabilityInspector; import org.apache.cassandra.utils.NativeLibrary; import org.apache.cassandra.utils.OutputHandler; import org.apache.cassandra.utils.Throwables; import org.apache.cassandra.utils.TimeUUID; import org.apache.cassandra.utils.concurrent.OpOrder; import org.apache.cassandra.utils.concurrent.Ref; import org.apache.cassandra.utils.concurrent.SelfRefCounted; import org.apache.cassandra.utils.concurrent.SharedCloseable; import org.apache.cassandra.utils.concurrent.UncheckedInterruptedException; import static org.apache.cassandra.concurrent.ExecutorFactory.Global.executorFactory; import static org.apache.cassandra.utils.concurrent.BlockingQueues.newBlockingQueue; import static org.apache.cassandra.utils.concurrent.SharedCloseable.sharedCopyOrNull; /** * An SSTableReader can be constructed in a number of places, but typically is either read from disk at startup, or * constructed from a flushed memtable, or after compaction to replace some existing sstables. However once created, * an sstablereader may also be modified. * <p> * A reader's {@link OpenReason} describes its current stage in its lifecycle. Note that in parallel to this, there are * two different Descriptor types; TMPLINK and FINAL; the latter corresponds to {@link OpenReason#NORMAL} state readers * and all readers that replace a {@link OpenReason#NORMAL} one. TMPLINK is used for {@link OpenReason#EARLY} state * readers and no others. * <p> * When a reader is being compacted, if the result is large its replacement may be opened as {@link OpenReason#EARLY} * before compaction completes in order to present the result to consumers earlier. In this case the reader will itself * be changed to a {@link OpenReason#MOVED_START} state, where its start no longer represents its on-disk minimum key. * This is to permit reads to be directed to only one reader when the two represent the same data. * The {@link OpenReason#EARLY} file can represent a compaction result that is either partially complete and still * in-progress, or a complete and immutable sstable that is part of a larger macro compaction action that has not yet * fully completed. * <p> * Currently ALL compaction results at least briefly go through an {@link OpenReason#EARLY} open state prior to completion, * regardless of if early opening is enabled. * <p> * Since a reader can be created multiple times over the same shared underlying resources, and the exact resources it * shares between each instance differ subtly, we track the lifetime of any underlying resource with its own reference * count, which each instance takes a {@link Ref} to. Each instance then tracks references to itself, and once these * all expire it releases all its {@link Ref} to these underlying resources. * <p> * There is some shared cleanup behaviour needed only once all readers in a certain stage of their lifecycle * (i.e. {@link OpenReason#EARLY} or {@link OpenReason#NORMAL} opening), and some that must only occur once all readers * of any kind over a single logical sstable have expired. These are managed by the {@link InstanceTidier} and * {@link GlobalTidy} classes at the bottom, and are effectively managed as another resource each instance tracks its * own {@link Ref} instance to, to ensure all of these resources are cleaned up safely and can be debugged otherwise. * <p> * TODO: fill in details about Tracker and lifecycle interactions for tools, and for compaction strategies */ public abstract class SSTableReader extends SSTable implements UnfilteredSource, SelfRefCounted<SSTableReader> { private static final Logger logger = LoggerFactory.getLogger(SSTableReader.class); private static final boolean TRACK_ACTIVITY = CassandraRelevantProperties.DISABLE_SSTABLE_ACTIVITY_TRACKING.getBoolean(); private static final ScheduledExecutorPlus syncExecutor = initSyncExecutor(); private static ScheduledExecutorPlus initSyncExecutor() { if (DatabaseDescriptor.isClientOrToolInitialized()) return null; // Do NOT start this thread pool in client mode ScheduledExecutorPlus syncExecutor = executorFactory().scheduled("read-hotness-tracker"); // Immediately remove readMeter sync task when cancelled. // TODO: should we set this by default on all scheduled executors? if (syncExecutor instanceof ScheduledThreadPoolExecutor) ((ScheduledThreadPoolExecutor) syncExecutor).setRemoveOnCancelPolicy(true); return syncExecutor; } private static final RateLimiter meterSyncThrottle = RateLimiter.create(100.0); public static final Comparator<SSTableReader> maxTimestampAscending = Comparator.comparingLong(SSTableReader::getMaxTimestamp); public static final Comparator<SSTableReader> maxTimestampDescending = maxTimestampAscending.reversed(); // it's just an object, which we use regular Object equality on; we introduce a special class just for easy recognition public static final class UniqueIdentifier { } public final UniqueIdentifier instanceId = new UniqueIdentifier(); public static final Comparator<SSTableReader> firstKeyComparator = (o1, o2) -> o1.getFirst().compareTo(o2.getFirst()); public static final Ordering<SSTableReader> firstKeyOrdering = Ordering.from(firstKeyComparator); public static final Comparator<SSTableReader> lastKeyComparator = (o1, o2) -> o1.getLast().compareTo(o2.getLast()); public static final Comparator<SSTableReader> idComparator = Comparator.comparing(t -> t.descriptor.id, SSTableIdFactory.COMPARATOR); public static final Comparator<SSTableReader> idReverseComparator = idComparator.reversed(); public static final Comparator<SSTableReader> sizeComparator = (o1, o2) -> Longs.compare(o1.onDiskLength(), o2.onDiskLength()); /** * maxDataAge is a timestamp in local server time (e.g. Global.currentTimeMilli) which represents an upper bound * to the newest piece of data stored in the sstable. In other words, this sstable does not contain items created * later than maxDataAge. * <p> * The field is not serialized to disk, so relying on it for more than what truncate does is not advised. * <p> * When a new sstable is flushed, maxDataAge is set to the time of creation. * When a sstable is created from compaction, maxDataAge is set to max of all merged sstables. * <p> * The age is in milliseconds since epoc and is local to this host. */ public final long maxDataAge; public enum OpenReason { /** * <ul> * <li>From {@code None} - Reader has been read from disk, either at startup or from a flushed memtable</li> * <li>From {@link #EARLY} - Reader is the final result of a compaction</li> * <li>From {@link #MOVED_START} - Reader WAS being compacted, but this failed and it has been restored * to {code NORMAL}status</li> * </ul> */ NORMAL, /** * <ul> * <li>From {@code None} - Reader is a compaction replacement that is either incomplete and has been opened * to represent its partial result status, or has been finished but the compaction it is a part of has not * yet completed fully</li> * <li>From {@link #EARLY} - Same as from {@code None}, only it is not the first time it has been * </ul> */ EARLY, /** * From: * <ul> * <li>From {@link #NORMAL} - Reader has seen low traffic and the amount of memory available for index summaries * is constrained, so its index summary has been downsampled</li> * <li>From {@link #METADATA_CHANGE} - Same * </ul> */ METADATA_CHANGE, /** * <ul> * <li>From {@link #NORMAL} - Reader is being compacted. This compaction has not finished, but the compaction * result is either partially or fully opened, to either partially or fully replace this reader. This reader's * start key has been updated to represent this, so that reads only hit one or the other reader.</li> * </ul> */ MOVED_START } public final OpenReason openReason; protected final FileHandle dfile; // technically isCompacted is not necessary since it should never be unreferenced unless it is also compacted, // but it seems like a good extra layer of protection against reference counting bugs to not delete data based on that alone public final AtomicBoolean isSuspect = new AtomicBoolean(false); // not final since we need to be able to change level on a file. protected volatile StatsMetadata sstableMetadata; public final SerializationHeader header; private final InstanceTidier tidy; private final Ref<SSTableReader> selfRef; private RestorableMeter readMeter; private volatile double crcCheckChance; protected final DecoratedKey first; protected final DecoratedKey last; public final AbstractBounds<Token> bounds; /** * Calculate approximate key count. * If cardinality estimator is available on all given sstables, then this method use them to estimate * key count. * If not, then this uses index summaries. * * @param sstables SSTables to calculate key count * @return estimated key count */ public static long getApproximateKeyCount(Iterable<SSTableReader> sstables) { long count = -1; if (Iterables.isEmpty(sstables)) return count; boolean failed = false; ICardinality cardinality = null; for (SSTableReader sstable : sstables) { if (sstable.openReason == OpenReason.EARLY) continue; try { CompactionMetadata metadata = StatsComponent.load(sstable.descriptor).compactionMetadata(); // If we can't load the CompactionMetadata, we are forced to estimate the keys using the index // summary. (CASSANDRA-10676) if (metadata == null) { logger.warn("Reading cardinality from Statistics.db failed for {}", sstable.getFilename()); failed = true; break; } if (cardinality == null) cardinality = metadata.cardinalityEstimator; else cardinality = cardinality.merge(metadata.cardinalityEstimator); } catch (IOException e) { logger.warn("Reading cardinality from Statistics.db failed.", e); failed = true; break; } catch (CardinalityMergeException e) { logger.warn("Cardinality merge failed.", e); failed = true; break; } } if (cardinality != null && !failed) count = cardinality.cardinality(); // if something went wrong above or cardinality is not available, calculate using index summary if (count < 0) { count = 0; for (SSTableReader sstable : sstables) count += sstable.estimatedKeys(); } return count; } public static SSTableReader open(SSTable.Owner owner, Descriptor descriptor) { return open(owner, descriptor, null); } public static SSTableReader open(SSTable.Owner owner, Descriptor desc, TableMetadataRef metadata) { return open(owner, desc, null, metadata); } public static SSTableReader open(SSTable.Owner owner, Descriptor descriptor, Set<Component> components, TableMetadataRef metadata) { return open(owner, descriptor, components, metadata, true, false); } // use only for offline or "Standalone" operations public static SSTableReader openNoValidation(Descriptor descriptor, Set<Component> components, ColumnFamilyStore cfs) { return open(cfs, descriptor, components, cfs.metadata, false, true); } // use only for offline or "Standalone" operations public static SSTableReader openNoValidation(SSTable.Owner owner, Descriptor descriptor, TableMetadataRef metadata) { return open(owner, descriptor, null, metadata, false, true); } /** * Open SSTable reader to be used in batch mode(such as sstableloader). */ public static SSTableReader openForBatch(SSTable.Owner owner, Descriptor descriptor, Set<Component> components, TableMetadataRef metadata) { return open(owner, descriptor, components, metadata, true, true); } /** * Open an SSTable for reading * * @param owner owning entity * @param descriptor SSTable to open * @param components Components included with this SSTable * @param metadata for this SSTables CF * @param validate Check SSTable for corruption (limited) * @param isOffline Whether we are opening this SSTable "offline", for example from an external tool or not for inclusion in queries (validations) * This stops regenerating BF + Summaries and also disables tracking of hotness for the SSTable. * @return {@link SSTableReader} */ public static SSTableReader open(Owner owner, Descriptor descriptor, Set<Component> components, TableMetadataRef metadata, boolean validate, boolean isOffline) { SSTableReaderLoadingBuilder<?, ?> builder = descriptor.getFormat().getReaderFactory().loadingBuilder(descriptor, metadata, components); return builder.build(owner, validate, !isOffline); } public static Collection<SSTableReader> openAll(SSTable.Owner owner, Set<Map.Entry<Descriptor, Set<Component>>> entries, final TableMetadataRef metadata) { final Collection<SSTableReader> sstables = newBlockingQueue(); ExecutorPlus executor = executorFactory().pooled("SSTableBatchOpen", FBUtilities.getAvailableProcessors()); try { for (final Map.Entry<Descriptor, Set<Component>> entry : entries) { Runnable runnable = () -> { SSTableReader sstable; try { sstable = open(owner, entry.getKey(), entry.getValue(), metadata); } catch (CorruptSSTableException ex) { JVMStabilityInspector.inspectThrowable(ex); logger.error("Corrupt sstable {}; skipping table", entry, ex); return; } catch (FSError ex) { JVMStabilityInspector.inspectThrowable(ex); logger.error("Cannot read sstable {}; file system error, skipping table", entry, ex); return; } sstables.add(sstable); }; executor.submit(runnable); } } finally { executor.shutdown(); } try { executor.awaitTermination(7, TimeUnit.DAYS); } catch (InterruptedException e) { throw new UncheckedInterruptedException(e); } return sstables; } protected SSTableReader(Builder<?, ?> builder, Owner owner) { super(builder, owner); this.sstableMetadata = builder.getStatsMetadata(); this.header = builder.getSerializationHeader(); this.dfile = builder.getDataFile(); this.maxDataAge = builder.getMaxDataAge(); this.openReason = builder.getOpenReason(); this.first = builder.getFirst(); this.last = builder.getLast(); this.bounds = first == null || last == null || AbstractBounds.strictlyWrapsAround(first.getToken(), last.getToken()) ? null // this will cause the validation to fail, but the reader is opened with no validation, // e.g. for scrubbing, we should accept screwed bounds : AbstractBounds.bounds(first.getToken(), true, last.getToken(), true); tidy = new InstanceTidier(descriptor, owner); selfRef = new Ref<>(this, tidy); } @Override public DecoratedKey getFirst() { return first; } @Override public DecoratedKey getLast() { return last; } @Override public AbstractBounds<Token> getBounds() { return Objects.requireNonNull(bounds, "Bounds were not created because the sstable is out of order"); } public DataIntegrityMetadata.ChecksumValidator maybeGetChecksumValidator() throws IOException { if (descriptor.fileFor(Components.CRC).exists()) return new DataIntegrityMetadata.ChecksumValidator(descriptor.fileFor(Components.DATA), descriptor.fileFor(Components.CRC)); else return null; } public DataIntegrityMetadata.FileDigestValidator maybeGetDigestValidator() throws IOException { if (descriptor.fileFor(Components.DIGEST).exists()) return new DataIntegrityMetadata.FileDigestValidator(descriptor.fileFor(Components.DATA), descriptor.fileFor(Components.DIGEST)); else return null; } public static long getTotalBytes(Iterable<SSTableReader> sstables) { long sum = 0; for (SSTableReader sstable : sstables) sum += sstable.onDiskLength(); return sum; } public static long getTotalUncompressedBytes(Iterable<SSTableReader> sstables) { long sum = 0; for (SSTableReader sstable : sstables) sum += sstable.uncompressedLength(); return sum; } public boolean equals(Object that) { return that instanceof SSTableReader && ((SSTableReader) that).descriptor.equals(this.descriptor); } public int hashCode() { return this.descriptor.hashCode(); } public String getFilename() { return dfile.path(); } public void setupOnline() { owner().ifPresent(o -> setCrcCheckChance(o.getCrcCheckChance())); } /** * Execute provided task with sstable lock to avoid racing with index summary redistribution, SEE CASSANDRA-15861. * * @param task to be guarded by sstable lock */ public <R, E extends Exception> R runWithLock(CheckedFunction<Descriptor, R, E> task) throws E { synchronized (tidy.global) { return task.apply(descriptor); } } public void setReplaced() { synchronized (tidy.global) { assert !tidy.isReplaced; tidy.isReplaced = true; } } public boolean isReplaced() { synchronized (tidy.global) { return tidy.isReplaced; } } /** * The runnable passed to this method must not be an anonymous or non-static inner class. It can be a lambda or a * method reference provided that it does not retain a reference chain to this reader. */ public void runOnClose(final Runnable runOnClose) { if (runOnClose == null) return; synchronized (tidy.global) { final Runnable existing = tidy.runOnClose; if (existing == null) tidy.runOnClose = runOnClose; else tidy.runOnClose = () -> { existing.run(); runOnClose.run(); }; } } /** * The method sets fields specific to this {@link SSTableReader} and the parent {@link SSTable} on the provided * {@link Builder}. The method is intended to be called from the overloaded {@code unbuildTo} method in subclasses. * * @param builder the builder on which the fields should be set * @param sharedCopy whether the {@link SharedCloseable} resources should be passed as shared copies or directly; * note that the method will overwrite the fields representing {@link SharedCloseable} only if * they are not set in the builder yet (the relevant fields in the builder are {@code null}). * @return the same instance of builder as provided */ protected final <B extends Builder<?, B>> B unbuildTo(B builder, boolean sharedCopy) { B b = super.unbuildTo(builder, sharedCopy); if (builder.getDataFile() == null) b.setDataFile(sharedCopy ? sharedCopyOrNull(dfile) : dfile); b.setStatsMetadata(sstableMetadata); b.setSerializationHeader(header); b.setMaxDataAge(maxDataAge); b.setOpenReason(openReason); b.setFirst(first); b.setLast(last); b.setSuspected(isSuspect.get()); return b; } public abstract SSTableReader cloneWithRestoredStart(DecoratedKey restoredStart); public abstract SSTableReader cloneWithNewStart(DecoratedKey newStart); public RestorableMeter getReadMeter() { return readMeter; } /** * All the resources which should be released upon closing this sstable reader are registered with in * {@link GlobalTidy}. This method lets close a provided resource explicitly any time and unregister it from * {@link GlobalTidy} so that it is not tried to be released twice. * * @param closeable a resource to be closed */ protected void closeInternalComponent(AutoCloseable closeable) { synchronized (tidy.global) { boolean removed = tidy.closeables.remove(closeable); Preconditions.checkState(removed); try { closeable.close(); } catch (Exception ex) { throw new RuntimeException("Failed to close " + closeable, ex); } } } /** * This method is expected to close the components which occupy memory but are not needed when we just want to * stream the components (for example, when SSTable is opened with SSTableLoader). The method should call * {@link #closeInternalComponent(AutoCloseable)} for each such component. Leaving the implementation empty is * valid given there are not such resources to release. */ public abstract void releaseInMemoryComponents(); /** * Perform any validation needed for the reader upon creation before returning it from the {@link Builder}. */ public void validate() { if (this.first.compareTo(this.last) > 0 || bounds == null) { throw new CorruptSSTableException(new IllegalStateException(String.format("SSTable first key %s > last key %s", this.first, this.last)), getFilename()); } } /** * Returns the compression metadata for this sstable. Note that the compression metdata is a resource and should not * be closed by the caller. * TODO do not return a closeable resource or return a shared copy * * @throws IllegalStateException if the sstable is not compressed */ public CompressionMetadata getCompressionMetadata() { if (!compression) throw new IllegalStateException(this + " is not compressed"); return dfile.compressionMetadata().get(); } /** * Returns the amount of memory in bytes used off heap by the compression meta-data. * * @return the amount of memory in bytes used off heap by the compression meta-data */ public long getCompressionMetadataOffHeapSize() { if (!compression) return 0; return getCompressionMetadata().offHeapSize(); } /** * Calculates an estimate of the number of keys in the sstable represented by this reader. */ public abstract long estimatedKeys(); /** * Calculates an estimate of the number of keys for the given ranges in the sstable represented by this reader. */ public abstract long estimatedKeysForRanges(Collection<Range<Token>> ranges); /** * Returns whether methods like {@link #estimatedKeys()} or {@link #estimatedKeysForRanges(Collection)} can return * sensible estimations. */ public abstract boolean isEstimationInformative(); /** * Returns sample keys for the provided token range. */ public abstract Iterable<DecoratedKey> getKeySamples(final Range<Token> range); /** * Determine the minimal set of sections that can be extracted from this SSTable to cover the given ranges. * * @return A sorted list of (offset,end) pairs that cover the given ranges in the datafile for this SSTable. */ public List<PartitionPositionBounds> getPositionsForRanges(Collection<Range<Token>> ranges) { // use the index to determine a minimal section for each range List<PartitionPositionBounds> positions = new ArrayList<>(); for (Range<Token> range : Range.normalize(ranges)) { assert !range.isWrapAround() || range.right.isMinimum(); // truncate the range so it at most covers the sstable AbstractBounds<PartitionPosition> bounds = Range.makeRowRange(range); PartitionPosition leftBound = bounds.left.compareTo(first) > 0 ? bounds.left : first.getToken().minKeyBound(); PartitionPosition rightBound = bounds.right.isMinimum() ? last.getToken().maxKeyBound() : bounds.right; if (leftBound.compareTo(last) > 0 || rightBound.compareTo(first) < 0) continue; long left = getPosition(leftBound, Operator.GT); long right = (rightBound.compareTo(last) > 0) ? uncompressedLength() : getPosition(rightBound, Operator.GT); if (left == right) // empty range continue; assert left < right : String.format("Range=%s openReason=%s first=%s last=%s left=%d right=%d", range, openReason, first, last, left, right); positions.add(new PartitionPositionBounds(left, right)); } return positions; } /** * Retrieves the position while updating the key cache and the stats. * * @param key The key to apply as the rhs to the given Operator. A 'fake' key is allowed to * allow key selection by token bounds but only if op != * EQ * @param op The Operator defining matching keys: the nearest key to the target matching the operator wins. */ public final long getPosition(PartitionPosition key, Operator op) { return getPosition(key, op, SSTableReadsListener.NOOP_LISTENER); } public final long getPosition(PartitionPosition key, Operator op, SSTableReadsListener listener) { return getPosition(key, op, true, listener); } public final long getPosition(PartitionPosition key, Operator op, boolean updateStats) { return getPosition(key, op, updateStats, SSTableReadsListener.NOOP_LISTENER); } /** * Retrieve a position in data file according to the provided key and operator. * * @param key The key to apply as the rhs to the given Operator. A 'fake' key is allowed to * allow key selection by token bounds but only if op != * EQ * @param op The Operator defining matching keys: the nearest key to the target matching the operator wins. * @param updateStats true if updating stats and cache * @param listener a listener used to handle internal events * @return The index entry corresponding to the key, or null if the key is not present */ protected long getPosition(PartitionPosition key, Operator op, boolean updateStats, SSTableReadsListener listener) { AbstractRowIndexEntry rie = getRowIndexEntry(key, op, updateStats, listener); return rie != null ? rie.position : -1; } /** * Retrieve an index entry for the partition found according to the provided key and operator. * * @param key The key to apply as the rhs to the given Operator. A 'fake' key is allowed to * allow key selection by token bounds but only if op != * EQ * @param op The Operator defining matching keys: the nearest key to the target matching the operator wins. * @param updateStats true if updating stats and cache * @param listener a listener used to handle internal events * @return The index entry corresponding to the key, or null if the key is not present */ @VisibleForTesting protected abstract AbstractRowIndexEntry getRowIndexEntry(PartitionPosition key, Operator op, boolean updateStats, SSTableReadsListener listener); public UnfilteredRowIterator simpleIterator(FileDataInput file, DecoratedKey key, long dataPosition, boolean tombstoneOnly) { return SSTableIdentityIterator.create(this, file, dataPosition, key, tombstoneOnly); } /** * Returns a {@link KeyReader} over all keys in the sstable. */ public abstract KeyReader keyReader() throws IOException; /** * Returns a {@link KeyIterator} over all keys in the sstable. */ public KeyIterator keyIterator() throws IOException { return new KeyIterator(keyReader(), getPartitioner(), uncompressedLength(), new ReentrantReadWriteLock()); } /** * Finds and returns the first key beyond a given token in this SSTable or null if no such key exists. */ public abstract DecoratedKey firstKeyBeyond(PartitionPosition token); /** * Returns the length in bytes of the (uncompressed) data for this SSTable. For compressed files, this is not * the same thing as the on disk size (see {@link #onDiskLength()}). */ public long uncompressedLength() { return dfile.dataLength(); } /** * @return the fraction of the token space for which this sstable has content. In the simplest case this is just the * size of the interval returned by {@link #getBounds()}, but the sstable may contain "holes" when the locally-owned * range is not contiguous (e.g. with vnodes). * As this is affected by the local ranges which can change, the token space fraction is calculated at the time of * writing the sstable and stored with its metadata. * For older sstables that do not contain this metadata field, this method returns NaN. */ public double tokenSpaceCoverage() { return sstableMetadata.tokenSpaceCoverage; } /** * The length in bytes of the on disk size for this SSTable. For compressed files, this is not the same thing * as the data length (see {@link #uncompressedLength()}). */ public long onDiskLength() { return dfile.onDiskLength; } @VisibleForTesting public double getCrcCheckChance() { return crcCheckChance; } /** * Set the value of CRC check chance. The argument supplied is obtained from the property of the owning CFS. * Called when either the SSTR is initialized, or the CFS's property is updated via JMX */ public void setCrcCheckChance(double crcCheckChance) { this.crcCheckChance = crcCheckChance; } /** * Mark the sstable as obsolete, i.e., compacted into newer sstables. * <p> * When calling this function, the caller must ensure that the SSTableReader is not referenced anywhere except for * threads holding a reference. * <p> * Calling it multiple times is usually buggy. */ public void markObsolete(Runnable tidier) { if (logger.isTraceEnabled()) logger.trace("Marking {} compacted", getFilename()); synchronized (tidy.global) { assert !tidy.isReplaced; assert tidy.global.obsoletion == null : this + " was already marked compacted"; tidy.global.obsoletion = tidier; tidy.global.stopReadMeterPersistence(); } } public boolean isMarkedCompacted() { return tidy.global.obsoletion != null; } public void markSuspect() { if (logger.isTraceEnabled()) logger.trace("Marking {} as a suspect to be excluded from reads.", getFilename()); isSuspect.getAndSet(true); } @VisibleForTesting public void unmarkSuspect() { isSuspect.getAndSet(false); } public boolean isMarkedSuspect() { return isSuspect.get(); } /** * Direct I/O SSTableScanner over a defined range of tokens. * * @param range the range of keys to cover * @return A Scanner for seeking over the rows of the SSTable. */ public ISSTableScanner getScanner(Range<Token> range) { if (range == null) return getScanner(); return getScanner(Collections.singletonList(range)); } /** * Direct I/O SSTableScanner over the entirety of the sstable.. * * @return A Scanner over the full content of the SSTable. */ public abstract ISSTableScanner getScanner(); /** * Direct I/O SSTableScanner over a defined collection of ranges of tokens. * * @param ranges the range of keys to cover * @return A Scanner for seeking over the rows of the SSTable. */ public abstract ISSTableScanner getScanner(Collection<Range<Token>> ranges); /** * Direct I/O SSTableScanner over an iterator of bounds. * * @param rangeIterator the keys to cover * @return A Scanner for seeking over the rows of the SSTable. */ public abstract ISSTableScanner getScanner(Iterator<AbstractBounds<PartitionPosition>> rangeIterator); /** * Create a {@link FileDataInput} for the data file of the sstable represented by this reader. This method returns * a newly opened resource which must be closed by the caller. * * @param position the data input will be opened and seek to this position */ public FileDataInput getFileDataInput(long position) { return dfile.createReader(position); } /** * Tests if the sstable contains data newer than the given age param (in localhost currentMillis time). * This works in conjunction with maxDataAge which is an upper bound on the data in the sstable represented * by this reader. * * @return {@code true} iff this sstable contains data that's newer than the given timestamp */ public boolean newSince(long timestampMillis) { return maxDataAge > timestampMillis; } public void createLinks(String snapshotDirectoryPath) { createLinks(snapshotDirectoryPath, null); } public void createLinks(String snapshotDirectoryPath, RateLimiter rateLimiter) { createLinks(descriptor, components, snapshotDirectoryPath, rateLimiter); } public static void createLinks(Descriptor descriptor, Set<Component> components, String snapshotDirectoryPath) { createLinks(descriptor, components, snapshotDirectoryPath, null); } public static void createLinks(Descriptor descriptor, Set<Component> components, String snapshotDirectoryPath, RateLimiter limiter) { for (Component component : components) { File sourceFile = descriptor.fileFor(component); if (!sourceFile.exists()) continue; if (null != limiter) limiter.acquire(); File targetLink = new File(snapshotDirectoryPath, sourceFile.name()); FileUtils.createHardLink(sourceFile, targetLink); } } public boolean isRepaired() { return sstableMetadata.repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE; } /** * Reads the key stored at the position saved in SASI. * <p> * When SASI is created, it uses key locations retrieved from {@link KeyReader#keyPositionForSecondaryIndex()}. * This method is to read the key stored at such position. It is up to the concrete SSTable format implementation * what that position means and which file it refers. The only requirement is that it is consistent with what * {@link KeyReader#keyPositionForSecondaryIndex()} returns. * * @return key if found, {@code null} otherwise */ public abstract DecoratedKey keyAtPositionFromSecondaryIndex(long keyPositionFromSecondaryIndex) throws IOException; public boolean isPendingRepair() { return sstableMetadata.pendingRepair != ActiveRepairService.NO_PENDING_REPAIR; } public TimeUUID getPendingRepair() { return sstableMetadata.pendingRepair; } public long getRepairedAt() { return sstableMetadata.repairedAt; } public boolean isTransient() { return sstableMetadata.isTransient; } public boolean intersects(Collection<Range<Token>> ranges) { Bounds<Token> range = new Bounds<>(first.getToken(), last.getToken()); return Iterables.any(ranges, r -> r.intersects(range)); } /** * TODO: Move someplace reusable */ public abstract static class Operator { public static final Operator EQ = new Equals(); public static final Operator GE = new GreaterThanOrEqualTo(); public static final Operator GT = new GreaterThan(); /** * @param comparison The result of a call to compare/compareTo, with the desired field on the rhs. * @return less than 0 if the operator cannot match forward, 0 if it matches, greater than 0 if it might match forward. */ public abstract int apply(int comparison); final static class Equals extends Operator { public int apply(int comparison) { return -comparison; } } final static class GreaterThanOrEqualTo extends Operator { public int apply(int comparison) { return comparison >= 0 ? 0 : 1; } } final static class GreaterThan extends Operator { public int apply(int comparison) { return comparison > 0 ? 0 : 1; } } } public EstimatedHistogram getEstimatedPartitionSize() { return sstableMetadata.estimatedPartitionSize; } public EstimatedHistogram getEstimatedCellPerPartitionCount() { return sstableMetadata.estimatedCellPerPartitionCount; } public double getEstimatedDroppableTombstoneRatio(long gcBefore) { return sstableMetadata.getEstimatedDroppableTombstoneRatio(gcBefore); } public double getDroppableTombstonesBefore(long gcBefore) { return sstableMetadata.getDroppableTombstonesBefore(gcBefore); } public double getCompressionRatio() { return sstableMetadata.compressionRatio; } public long getMinTimestamp() { return sstableMetadata.minTimestamp; } public long getMaxTimestamp() { return sstableMetadata.maxTimestamp; } public long getMinLocalDeletionTime() { return sstableMetadata.minLocalDeletionTime; } public long getMaxLocalDeletionTime() { return sstableMetadata.maxLocalDeletionTime; } /** * Whether the sstable may contain tombstones or if it is guaranteed to not contain any. * <p> * Note that having that method return {@code false} guarantees the sstable has no tombstones whatsoever (so no * cell tombstone, no range tombstone maker and no expiring columns), but having it return {@code true} doesn't * guarantee it contains any as it may simply have non-expired cells. */ public boolean mayHaveTombstones() { // A sstable is guaranteed to have no tombstones if minLocalDeletionTime is still set to its default, // Cell.NO_DELETION_TIME, which is bigger than any valid deletion times. return getMinLocalDeletionTime() != Cell.NO_DELETION_TIME; } public int getMinTTL() { return sstableMetadata.minTTL; } public int getMaxTTL() { return sstableMetadata.maxTTL; } public long getTotalColumnsSet() { return sstableMetadata.totalColumnsSet; } public long getTotalRows() { return sstableMetadata.totalRows; } public int getAvgColumnSetPerRow() { return sstableMetadata.totalRows < 0 ? -1 : (sstableMetadata.totalRows == 0 ? 0 : (int) (sstableMetadata.totalColumnsSet / sstableMetadata.totalRows)); } public int getSSTableLevel() { return sstableMetadata.sstableLevel; } /** * Mutate sstable level with a lock to avoid racing with entire-sstable-streaming and then reload sstable metadata */ public void mutateLevelAndReload(int newLevel) throws IOException { synchronized (tidy.global) { descriptor.getMetadataSerializer().mutateLevel(descriptor, newLevel); reloadSSTableMetadata(); } } /** * Mutate sstable repair metadata with a lock to avoid racing with entire-sstable-streaming and then reload sstable metadata */ public void mutateRepairedAndReload(long newRepairedAt, TimeUUID newPendingRepair, boolean isTransient) throws IOException { synchronized (tidy.global) { descriptor.getMetadataSerializer().mutateRepairMetadata(descriptor, newRepairedAt, newPendingRepair, isTransient); reloadSSTableMetadata(); } } /** * Reloads the sstable metadata from disk. * <p> * Called after level is changed on sstable, for example if the sstable is dropped to L0 * <p> * Might be possible to remove in future versions * * @throws IOException */ public void reloadSSTableMetadata() throws IOException { this.sstableMetadata = StatsComponent.load(descriptor).statsMetadata(); } public StatsMetadata getSSTableMetadata() { return sstableMetadata; } public RandomAccessReader openDataReader(RateLimiter limiter) { assert limiter != null; return dfile.createReader(limiter); } public RandomAccessReader openDataReader() { return dfile.createReader(); } public void trySkipFileCacheBefore(DecoratedKey key) { long position = getPosition(key, SSTableReader.Operator.GE); NativeLibrary.trySkipCache(descriptor.fileFor(Components.DATA).absolutePath(), 0, position < 0 ? 0 : position); } public ChannelProxy getDataChannel() { return dfile.channel; } /** * @return last modified time for data component. 0 if given component does not exist or IO error occurs. */ public long getDataCreationTime() { return descriptor.fileFor(Components.DATA).lastModified(); } /** * Increment the total read count and read rate for this SSTable. This should not be incremented for non-query reads, * like compaction. */ public void incrementReadCount() { if (readMeter != null) readMeter.mark(); } public EncodingStats stats() { // We could return sstable.header.stats(), but this may not be as accurate than the actual sstable stats (see // SerializationHeader.make() for details) so we use the latter instead. return sstableMetadata.encodingStats; } public Ref<SSTableReader> tryRef() { return selfRef.tryRef(); } public Ref<SSTableReader> selfRef() { return selfRef; } public Ref<SSTableReader> ref() { return selfRef.ref(); } protected List<AutoCloseable> setupInstance(boolean trackHotness) { return Collections.singletonList(dfile); } public void setup(boolean trackHotness) { assert tidy.closeables == null; trackHotness &= TRACK_ACTIVITY; tidy.setup(this, trackHotness, setupInstance(trackHotness)); this.readMeter = tidy.global.readMeter; } @VisibleForTesting public void overrideReadMeter(RestorableMeter readMeter) { this.readMeter = tidy.global.readMeter = readMeter; } public void addTo(Ref.IdentityCollection identities) { identities.add(this); identities.add(tidy.globalRef); tidy.closeables.forEach(c -> { if (c instanceof SharedCloseable) ((SharedCloseable) c).addTo(identities); }); } /** * The method verifies whether the sstable may contain the provided key. The method does approximation using * Bloom filter if it is present and if it is not, performs accurate check in the index. */ public abstract boolean mayContainAssumingKeyIsInRange(DecoratedKey key); /** * One instance per SSTableReader we create. * <p> * We can create many InstanceTidiers (one for every time we reopen an sstable with MOVED_START for example), * but there can only be one GlobalTidy for one single logical sstable. * <p> * When the InstanceTidier cleansup, it releases its reference to its GlobalTidy; when all InstanceTidiers * for that type have run, the GlobalTidy cleans up. */ protected static final class InstanceTidier implements Tidy { private final Descriptor descriptor; private final WeakReference<Owner> owner; private List<? extends AutoCloseable> closeables; private Runnable runOnClose; private boolean isReplaced = false; // a reference to our shared tidy instance, that // we will release when we are ourselves released private Ref<GlobalTidy> globalRef; private GlobalTidy global; private volatile boolean setup; public void setup(SSTableReader reader, boolean trackHotness, Collection<? extends AutoCloseable> closeables) { // get a new reference to the shared descriptor-type tidy this.globalRef = GlobalTidy.get(reader); this.global = globalRef.get(); if (trackHotness) global.ensureReadMeter(); this.closeables = new ArrayList<>(closeables); // to avoid tidy seeing partial state, set setup=true at the end this.setup = true; } private InstanceTidier(Descriptor descriptor, Owner owner) { this.descriptor = descriptor; this.owner = new WeakReference<>(owner); } @Override public void tidy() { if (logger.isTraceEnabled()) logger.trace("Running instance tidier for {} with setup {}", descriptor, setup); // don't try to cleanup if the sstablereader was never fully constructed if (!setup) return; final OpOrder.Barrier barrier; Owner owner = this.owner.get(); if (owner != null) { barrier = owner.newReadOrderingBarrier(); barrier.issue(); } else { barrier = null; } ScheduledExecutors.nonPeriodicTasks.execute(new Runnable() { public void run() { if (logger.isTraceEnabled()) logger.trace("Async instance tidier for {}, before barrier", descriptor); if (barrier != null) barrier.await(); if (logger.isTraceEnabled()) logger.trace("Async instance tidier for {}, after barrier", descriptor); Throwable exceptions = null; if (runOnClose != null) try { runOnClose.run(); } catch (RuntimeException | Error ex) { logger.error("Failed to run on-close listeners for sstable " + descriptor.baseFile(), ex); exceptions = ex; } Throwable closeExceptions = Throwables.close(null, Iterables.filter(closeables, Objects::nonNull)); if (closeExceptions != null) { logger.error("Failed to close some sstable components of " + descriptor.baseFile(), closeExceptions); exceptions = Throwables.merge(exceptions, closeExceptions); } try { globalRef.release(); } catch (RuntimeException | Error ex) { logger.error("Failed to release the global ref of " + descriptor.baseFile(), ex); exceptions = Throwables.merge(exceptions, ex); } if (exceptions != null) JVMStabilityInspector.inspectThrowable(exceptions); if (logger.isTraceEnabled()) logger.trace("Async instance tidier for {}, completed", descriptor); } @Override public String toString() { return "Tidy " + descriptor.ksname + '.' + descriptor.cfname + '-' + descriptor.id; } }); } @Override public String name() { return descriptor.toString(); } } /** * One instance per logical sstable. This both tracks shared cleanup and some shared state related * to the sstable's lifecycle. * <p> * All InstanceTidiers, on setup(), ask the static get() method for their shared state, * and stash a reference to it to be released when they are. Once all such references are * released, this shared tidy will be performed. */ static final class GlobalTidy implements Tidy { static final WeakReference<ScheduledFuture<?>> NULL = new WeakReference<>(null); // keyed by descriptor, mapping to the shared GlobalTidy for that descriptor static final ConcurrentMap<Descriptor, Ref<GlobalTidy>> lookup = new ConcurrentHashMap<>(); private final Descriptor desc; // the readMeter that is shared between all instances of the sstable, and can be overridden in all of them // at once also, for testing purposes private RestorableMeter readMeter; // the scheduled persistence of the readMeter, that we will cancel once all instances of this logical // sstable have been released private WeakReference<ScheduledFuture<?>> readMeterSyncFuture = NULL; // shared state managing if the logical sstable has been compacted; this is used in cleanup private volatile Runnable obsoletion; GlobalTidy(final SSTableReader reader) { this.desc = reader.descriptor; } void ensureReadMeter() { if (readMeter != null) return; // Don't track read rates for tables in the system keyspace and don't bother trying to load or persist // the read meter when in client mode. // Also, do not track read rates when running in client or tools mode (syncExecuter isn't available in these modes) if (!TRACK_ACTIVITY || SchemaConstants.isLocalSystemKeyspace(desc.ksname) || DatabaseDescriptor.isClientOrToolInitialized()) { readMeter = null; readMeterSyncFuture = NULL; return; } readMeter = SystemKeyspace.getSSTableReadMeter(desc.ksname, desc.cfname, desc.id); // sync the average read rate to system.sstable_activity every five minutes, starting one minute from now readMeterSyncFuture = new WeakReference<>(syncExecutor.scheduleAtFixedRate(this::maybePersistSSTableReadMeter, 1, 5, TimeUnit.MINUTES)); } void maybePersistSSTableReadMeter() { if (obsoletion == null && DatabaseDescriptor.getSStableReadRatePersistenceEnabled()) { meterSyncThrottle.acquire(); SystemKeyspace.persistSSTableReadMeter(desc.ksname, desc.cfname, desc.id, readMeter); } } private void stopReadMeterPersistence() { ScheduledFuture<?> readMeterSyncFutureLocal = readMeterSyncFuture.get(); if (readMeterSyncFutureLocal != null) { readMeterSyncFutureLocal.cancel(true); readMeterSyncFuture = NULL; } } public void tidy() { lookup.remove(desc); if (obsoletion != null) obsoletion.run(); // don't ideally want to dropPageCache for the file until all instances have been released for (Component c : desc.discoverComponents()) NativeLibrary.trySkipCache(desc.fileFor(c).absolutePath(), 0, 0); } public String name() { return desc.toString(); } // get a new reference to the shared GlobalTidy for this sstable public static Ref<GlobalTidy> get(SSTableReader sstable) { Descriptor descriptor = sstable.descriptor; while (true) { Ref<GlobalTidy> ref = lookup.get(descriptor); if (ref == null) { final GlobalTidy tidy = new GlobalTidy(sstable); ref = new Ref<>(tidy, tidy); Ref<GlobalTidy> ex = lookup.putIfAbsent(descriptor, ref); if (ex == null) return ref; ref = ex; } Ref<GlobalTidy> newRef = ref.tryRef(); if (newRef != null) return newRef; // raced with tidy lookup.remove(descriptor, ref); } } } @VisibleForTesting public static void resetTidying() { GlobalTidy.lookup.clear(); } public static class PartitionPositionBounds { public final long lowerPosition; public final long upperPosition; public PartitionPositionBounds(long lower, long upper) { this.lowerPosition = lower; this.upperPosition = upper; } @Override public final int hashCode() { int hashCode = (int) lowerPosition ^ (int) (lowerPosition >>> 32); return 31 * (hashCode ^ (int) ((int) upperPosition ^ (upperPosition >>> 32))); } @Override public final boolean equals(Object o) { if (!(o instanceof PartitionPositionBounds)) return false; PartitionPositionBounds that = (PartitionPositionBounds) o; return lowerPosition == that.lowerPosition && upperPosition == that.upperPosition; } } public static class IndexesBounds { public final int lowerPosition; public final int upperPosition; public IndexesBounds(int lower, int upper) { this.lowerPosition = lower; this.upperPosition = upper; } @Override public final int hashCode() { return 31 * lowerPosition * upperPosition; } @Override public final boolean equals(Object o) { if (!(o instanceof IndexesBounds)) return false; IndexesBounds that = (IndexesBounds) o; return lowerPosition == that.lowerPosition && upperPosition == that.upperPosition; } } /** * Moves the sstable in oldDescriptor to a new place (with generation etc) in newDescriptor. * <p> * All components given will be moved/renamed */ public static SSTableReader moveAndOpenSSTable(ColumnFamilyStore cfs, Descriptor oldDescriptor, Descriptor newDescriptor, Set<Component> components, boolean copyData) { if (!oldDescriptor.isCompatible()) throw new RuntimeException(String.format("Can't open incompatible SSTable! Current version %s, found file: %s", oldDescriptor.getFormat().getLatestVersion(), oldDescriptor)); boolean isLive = cfs.getLiveSSTables().stream().anyMatch(r -> r.descriptor.equals(newDescriptor) || r.descriptor.equals(oldDescriptor)); if (isLive) { String message = String.format("Can't move and open a file that is already in use in the table %s -> %s", oldDescriptor, newDescriptor); logger.error(message); throw new RuntimeException(message); } if (newDescriptor.fileFor(Components.DATA).exists()) { String msg = String.format("File %s already exists, can't move the file there", newDescriptor.fileFor(Components.DATA)); logger.error(msg); throw new RuntimeException(msg); } if (copyData) { try { logger.info("Hardlinking new SSTable {} to {}", oldDescriptor, newDescriptor); hardlink(oldDescriptor, newDescriptor, components); } catch (FSWriteError ex) { logger.warn("Unable to hardlink new SSTable {} to {}, falling back to copying", oldDescriptor, newDescriptor, ex); copy(oldDescriptor, newDescriptor, components); } } else { logger.info("Moving new SSTable {} to {}", oldDescriptor, newDescriptor); rename(oldDescriptor, newDescriptor, components); } SSTableReader reader; try { reader = open(cfs, newDescriptor, components, cfs.metadata); } catch (Throwable t) { logger.error("Aborting import of sstables. {} was corrupt", newDescriptor); throw new RuntimeException(newDescriptor + " is corrupt, can't import", t); } return reader; } public static void shutdownBlocking(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { ExecutorUtils.shutdownNowAndWait(timeout, unit, syncExecutor); resetTidying(); } /** * @return the physical size on disk of all components for this SSTable in bytes */ public long bytesOnDisk() { return bytesOnDisk(false); } /** * @return the total logical/uncompressed size in bytes of all components for this SSTable */ public long logicalBytesOnDisk() { return bytesOnDisk(true); } private long bytesOnDisk(boolean logical) { long bytes = 0; for (Component component : components) { // Only the data file is compressable. bytes += logical && component == Components.DATA && compression ? getCompressionMetadata().dataLength : descriptor.fileFor(component).length(); } return bytes; } @VisibleForTesting public void maybePersistSSTableReadMeter() { tidy.global.maybePersistSSTableReadMeter(); } /** * Returns a new verifier for this sstable. Note that the reader must match the provided cfs. */ public abstract IVerifier getVerifier(ColumnFamilyStore cfs, OutputHandler outputHandler, boolean isOffline, IVerifier.Options options); /** * A method to be called by {@link #getPosition(PartitionPosition, Operator, boolean, SSTableReadsListener)} * and {@link #getRowIndexEntry(PartitionPosition, Operator, boolean, SSTableReadsListener)} methods when * a searched key is found. It adds a trace message and notify the provided listener. */ protected void notifySelected(SSTableReadsListener.SelectionReason reason, SSTableReadsListener localListener, Operator op, boolean updateStats, AbstractRowIndexEntry entry) { reason.trace(descriptor, entry); if (localListener != null) localListener.onSSTableSelected(this, reason); } /** * A method to be called by {@link #getPosition(PartitionPosition, Operator, boolean, SSTableReadsListener)} * and {@link #getRowIndexEntry(PartitionPosition, Operator, boolean, SSTableReadsListener)} methods when * a searched key is not found. It adds a trace message and notify the provided listener. */ protected void notifySkipped(SSTableReadsListener.SkippingReason reason, SSTableReadsListener localListener, Operator op, boolean updateStats) { reason.trace(descriptor); if (localListener != null) localListener.onSSTableSkipped(this, reason); } /** * A builder of this sstable reader. It should be extended for each implementation of {@link SSTableReader} with * the implementation specific fields. * * @param <R> type of the reader the builder creates * @param <B> type of this builder */ public abstract static class Builder<R extends SSTableReader, B extends Builder<R, B>> extends SSTable.Builder<R, B> { private long maxDataAge; private StatsMetadata statsMetadata; private OpenReason openReason; private SerializationHeader serializationHeader; private FileHandle dataFile; private DecoratedKey first; private DecoratedKey last; private boolean suspected; public Builder(Descriptor descriptor) { super(descriptor); } public B setMaxDataAge(long maxDataAge) { Preconditions.checkArgument(maxDataAge >= 0); this.maxDataAge = maxDataAge; return (B) this; } public B setStatsMetadata(StatsMetadata statsMetadata) { Preconditions.checkNotNull(statsMetadata); this.statsMetadata = statsMetadata; return (B) this; } public B setOpenReason(OpenReason openReason) { Preconditions.checkNotNull(openReason); this.openReason = openReason; return (B) this; } public B setSerializationHeader(SerializationHeader serializationHeader) { this.serializationHeader = serializationHeader; return (B) this; } public B setDataFile(FileHandle dataFile) { this.dataFile = dataFile; return (B) this; } public B setFirst(DecoratedKey first) { this.first = first != null ? first.retainable() : null; return (B) this; } public B setLast(DecoratedKey last) { this.last = last != null ? last.retainable() : null; return (B) this; } public B setSuspected(boolean suspected) { this.suspected = suspected; return (B) this; } public long getMaxDataAge() { return maxDataAge; } public StatsMetadata getStatsMetadata() { return statsMetadata; } public OpenReason getOpenReason() { return openReason; } public SerializationHeader getSerializationHeader() { return serializationHeader; } public FileHandle getDataFile() { return dataFile; } public DecoratedKey getFirst() { return first; } public DecoratedKey getLast() { return last; } public boolean isSuspected() { return suspected; } protected abstract R buildInternal(Owner owner); public R build(Owner owner, boolean validate, boolean online) { R reader = buildInternal(owner); try { if (isSuspected()) reader.markSuspect(); reader.setup(online); if (validate) reader.validate(); } catch (RuntimeException | Error ex) { JVMStabilityInspector.inspectThrowable(ex); reader.selfRef().release(); throw ex; } return reader; } } }
apache/cassandra
src/java/org/apache/cassandra/io/sstable/format/SSTableReader.java
2,385
/* ***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * 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.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2001 Chad Fowler <[email protected]> * Copyright (C) 2001 Alan Moore <[email protected]> * Copyright (C) 2001-2002 Benoit Cerrina <[email protected]> * Copyright (C) 2001-2004 Jan Arne Petersen <[email protected]> * Copyright (C) 2002-2006 Thomas E Enebo <[email protected]> * Copyright (C) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2004-2005 Charles O Nutter <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2005 Kiel Hodges <[email protected]> * Copyright (C) 2006 Evan Buswell <[email protected]> * Copyright (C) 2006 Ola Bini <[email protected]> * Copyright (C) 2006 Michael Studman <[email protected]> * Copyright (C) 2006 Miguel Covarrubias <[email protected]> * Copyright (C) 2007 Nick Sieger <[email protected]> * Copyright (C) 2008 Joseph LaFata <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import jnr.constants.platform.Errno; import jnr.posix.POSIX; import org.jcodings.specific.USASCIIEncoding; import org.jruby.anno.FrameField; import org.jruby.anno.JRubyMethod; import org.jruby.anno.JRubyModule; import org.jruby.ast.util.ArgsUtil; import org.jruby.common.IRubyWarnings.ID; import org.jruby.common.RubyWarnings; import org.jruby.exceptions.CatchThrow; import org.jruby.exceptions.MainExitException; import org.jruby.exceptions.RaiseException; import org.jruby.internal.runtime.methods.DynamicMethod; import org.jruby.internal.runtime.methods.JavaMethod.JavaMethodNBlock; import org.jruby.ir.interpreter.Interpreter; import org.jruby.ir.runtime.IRRuntimeHelpers; import org.jruby.java.proxies.ConcreteJavaProxy; import org.jruby.platform.Platform; import org.jruby.runtime.Arity; import org.jruby.runtime.Binding; import org.jruby.runtime.Block; import org.jruby.runtime.CallType; import org.jruby.runtime.Helpers; import org.jruby.runtime.JavaSites.KernelSites; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.backtrace.RubyStackTraceElement; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.callsite.CacheEntry; import org.jruby.runtime.callsite.CachingCallSite; import org.jruby.runtime.load.LoadService; import org.jruby.util.ArraySupport; import org.jruby.util.ByteList; import org.jruby.util.ConvertBytes; import org.jruby.util.ShellLauncher; import org.jruby.util.StringSupport; import org.jruby.util.TypeConverter; import org.jruby.util.cli.Options; import org.jruby.util.func.ObjectIntIntFunction; import org.jruby.util.io.OpenFile; import org.jruby.util.io.PopenExecutor; import static org.jruby.RubyEnumerator.SizeFn; import static org.jruby.RubyEnumerator.enumeratorizeWithSize; import static org.jruby.RubyFile.fileResource; import static org.jruby.anno.FrameField.BACKREF; import static org.jruby.RubyIO.checkUnsupportedOptions; import static org.jruby.RubyIO.checkValidSpawnOptions; import static org.jruby.RubyIO.UNSUPPORTED_SPAWN_OPTIONS; import static org.jruby.anno.FrameField.BLOCK; import static org.jruby.anno.FrameField.CLASS; import static org.jruby.anno.FrameField.FILENAME; import static org.jruby.anno.FrameField.LASTLINE; import static org.jruby.anno.FrameField.LINE; import static org.jruby.anno.FrameField.METHODNAME; import static org.jruby.anno.FrameField.SCOPE; import static org.jruby.anno.FrameField.SELF; import static org.jruby.anno.FrameField.VISIBILITY; import static org.jruby.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite; import static org.jruby.runtime.ThreadContext.hasKeywords; import static org.jruby.runtime.Visibility.PRIVATE; import static org.jruby.runtime.Visibility.PROTECTED; import static org.jruby.runtime.Visibility.PUBLIC; import static org.jruby.util.RubyStringBuilder.str; /** * Note: For CVS history, see KernelModule.java. */ @JRubyModule(name="Kernel") public class RubyKernel { public static class MethodMissingMethod extends JavaMethodNBlock { private final Visibility visibility; private final CallType callType; MethodMissingMethod(RubyModule implementationClass, Visibility visibility, CallType callType) { super(implementationClass, Visibility.PRIVATE, "method_missing"); this.callType = callType; this.visibility = visibility; } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { return RubyKernel.methodMissing(context, self, name, visibility, callType, args); } } public static RubyModule createKernelModule(Ruby runtime) { RubyModule module = runtime.defineModule("Kernel"); module.defineAnnotatedMethods(RubyKernel.class); module.setFlag(RubyModule.NEEDSIMPL_F, false); //Kernel is the only normal Module that doesn't need an implementor runtime.setPrivateMethodMissing(new MethodMissingMethod(module, PRIVATE, CallType.NORMAL)); runtime.setProtectedMethodMissing(new MethodMissingMethod(module, PROTECTED, CallType.NORMAL)); runtime.setVariableMethodMissing(new MethodMissingMethod(module, PUBLIC, CallType.VARIABLE)); runtime.setSuperMethodMissing(new MethodMissingMethod(module, PUBLIC, CallType.SUPER)); runtime.setNormalMethodMissing(new MethodMissingMethod(module, PUBLIC, CallType.NORMAL)); if (runtime.getInstanceConfig().isAssumeLoop()) { module.defineAnnotatedMethods(LoopMethods.class); } recacheBuiltinMethods(runtime, module); return module; } /** * Cache built-in versions of several core methods, to improve performance by using identity comparison (==) rather * than going ahead with dynamic dispatch. * * @param runtime */ static void recacheBuiltinMethods(Ruby runtime, RubyModule kernelModule) { runtime.setRespondToMethod(kernelModule.searchMethod("respond_to?")); runtime.setRespondToMissingMethod(kernelModule.searchMethod("respond_to_missing?")); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject at_exit(ThreadContext context, IRubyObject recv, Block block) { if (!block.isGiven()) throw context.runtime.newArgumentError("called without a block"); return context.runtime.pushExitBlock(context.runtime.newProc(Block.Type.PROC, block)); } @JRubyMethod(name = "autoload?", required = 1, module = true, visibility = PRIVATE, reads = {SCOPE}) public static IRubyObject autoload_p(ThreadContext context, final IRubyObject recv, IRubyObject symbol) { RubyModule module = IRRuntimeHelpers.getCurrentClassBase(context, recv); if (module == null || module.isNil()) { return context.nil; } return module.autoload_p(context, symbol); } @JRubyMethod(required = 2, module = true, visibility = PRIVATE, reads = {SCOPE}) public static IRubyObject autoload(ThreadContext context, final IRubyObject recv, IRubyObject symbol, IRubyObject file) { RubyModule module = IRRuntimeHelpers.getCurrentClassBase(context, recv); module = module.getRealModule(); if (module == null || module.isNil()) throw context.runtime.newTypeError("Can not set autoload on singleton class"); return module.autoload(context, symbol, file); } public static IRubyObject method_missing(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { Visibility lastVis = context.getLastVisibility(); CallType lastCallType = context.getLastCallType(); if (args.length == 0 || !(args[0] instanceof RubySymbol)) { throw context.runtime.newArgumentError("no id given"); } return methodMissingDirect(context, recv, (RubySymbol) args[0], lastVis, lastCallType, args); } protected static IRubyObject methodMissingDirect(ThreadContext context, IRubyObject recv, RubySymbol symbol, Visibility lastVis, CallType lastCallType, IRubyObject[] args) { return methodMissing(context, recv, symbol.idString(), lastVis, lastCallType, args, true); } public static IRubyObject methodMissing(ThreadContext context, IRubyObject recv, String name, Visibility lastVis, CallType lastCallType, IRubyObject[] args) { return methodMissing(context, recv, name, lastVis, lastCallType, args, false); } public static IRubyObject methodMissing(ThreadContext context, IRubyObject recv, String name, Visibility lastVis, CallType lastCallType, IRubyObject[] args, boolean dropFirst) { Ruby runtime = context.runtime; boolean privateCall = false; if (lastCallType == CallType.VARIABLE || lastCallType == CallType.FUNCTIONAL) { privateCall = true; } else if (lastVis == PUBLIC) { privateCall = true; } if (lastCallType == CallType.VARIABLE) { throw runtime.newNameError(getMethodMissingFormat(lastVis, lastCallType), recv, name, privateCall); } throw runtime.newNoMethodError(getMethodMissingFormat(lastVis, lastCallType), recv, name, RubyArray.newArrayMayCopy(runtime, args, dropFirst ? 1 : 0), privateCall); } private static String getMethodMissingFormat(Visibility visibility, CallType callType) { String format = "undefined method `%s' for %s%s%s"; if (visibility == PRIVATE) { format = "private method `%s' called for %s%s%s"; } else if (visibility == PROTECTED) { format = "protected method `%s' called for %s%s%s"; } else if (callType == CallType.VARIABLE) { format = "undefined local variable or method `%s' for %s%s%s"; } else if (callType == CallType.SUPER) { format = "super: no superclass method `%s' for %s%s%s"; } return format; } @Deprecated public static IRubyObject open19(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { return open(context, recv, args, block); } @JRubyMethod(name = "open", required = 1, optional = 3, checkArity = false, module = true, visibility = PRIVATE, keywords = true) public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { Ruby runtime = context.runtime; boolean redirect = false; int callInfo = ThreadContext.resetCallInfo(context); boolean keywords = hasKeywords(callInfo); if (args.length >= 1) { // CONST_ID(to_open, "to_open"); if (args[0].respondsTo("to_open")) { redirect = true; } else { IRubyObject tmp = args[0]; tmp = RubyFile.get_path(context, tmp); if (tmp == context.nil) { redirect = true; } else { IRubyObject cmd = PopenExecutor.checkPipeCommand(context, tmp); if (cmd != context.nil) { if (PopenExecutor.nativePopenAvailable(runtime)) { args[0] = cmd; return PopenExecutor.popen(context, args, runtime.getIO(), block); } else { throw runtime.newArgumentError("pipe open is not supported without native subprocess logic"); } } } } } // Mild hack. We want to arity-mismatch if extra arg is not really a kwarg but not if it is one. int maxArgs = keywords ? 5 : 4; Arity.checkArgumentCount(context, args, 1, maxArgs); // symbol to_open = 0; if (redirect) { if (keywords) context.callInfo = ThreadContext.CALL_KEYWORD; IRubyObject io = args[0].callMethod(context, "to_open", Arrays.copyOfRange(args, 1, args.length)); RubyIO.ensureYieldClose(context, io, block); return io; } // We had to save callInfo from original call because kwargs needs to still pass through to IO#open context.callInfo = callInfo; return RubyIO.open(context, runtime.getFile(), args, block); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject getc(ThreadContext context, IRubyObject recv) { context.runtime.getWarnings().warn(ID.DEPRECATED_METHOD, "getc is obsolete; use STDIN.getc instead"); IRubyObject defin = context.runtime.getGlobalVariables().get("$stdin"); return sites(context).getc.call(context, defin, defin); } // MRI: rb_f_gets @JRubyMethod(optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject gets(ThreadContext context, IRubyObject recv, IRubyObject[] args) { Ruby runtime = context.runtime; IRubyObject argsFile = runtime.getArgsFile(); if (recv == argsFile) { return RubyArgsFile.gets(context, argsFile, args); } return sites(context).gets.call(context, argsFile, argsFile, args); } @JRubyMethod(optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject abort(ThreadContext context, IRubyObject recv, IRubyObject[] args) { int argc = Arity.checkArgumentCount(context, args, 0, 1); Ruby runtime = context.runtime; RubyString message = null; if(argc == 1) { message = args[0].convertToString(); IRubyObject stderr = runtime.getGlobalVariables().get("$stderr"); sites(context).puts.call(context, stderr, stderr, message); } exit(runtime, new IRubyObject[] { runtime.getFalse(), message }, false); return runtime.getNil(); // not reached } // MRI: rb_f_array @JRubyMethod(name = "Array", required = 1, module = true, visibility = PRIVATE) public static IRubyObject new_array(ThreadContext context, IRubyObject recv, IRubyObject object) { return TypeConverter.rb_Array(context, object); } @JRubyMethod(name = "Complex", module = true, visibility = PRIVATE) public static IRubyObject new_complex(ThreadContext context, IRubyObject recv) { RubyClass complex = context.runtime.getComplex(); return sites(context).convert_complex.call(context, complex, complex); } @JRubyMethod(name = "Complex", module = true, visibility = PRIVATE) public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0) { RubyClass complex = context.runtime.getComplex(); return sites(context).convert_complex.call(context, complex, complex, arg0); } @JRubyMethod(name = "Complex", module = true, visibility = PRIVATE) public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) { RubyClass complex = context.runtime.getComplex(); return sites(context).convert_complex.call(context, complex, complex, arg0, arg1); } @JRubyMethod(name = "Complex", module = true, visibility = PRIVATE) public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { RubyClass complex = context.runtime.getComplex(); return sites(context).convert_complex.call(context, complex, complex, arg0, arg1, arg2); } @JRubyMethod(name = "Rational", module = true, visibility = PRIVATE) public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0) { RubyClass rational = context.runtime.getRational(); return sites(context).convert_rational.call(context, rational, rational, arg0); } @JRubyMethod(name = "Rational", module = true, visibility = PRIVATE) public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) { RubyClass rational = context.runtime.getRational(); return sites(context).convert_rational.call(context, rational, rational, arg0, arg1); } @JRubyMethod(name = "Rational", module = true, visibility = PRIVATE) public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { RubyClass rational = context.runtime.getRational(); return sites(context).convert_rational.call(context, rational, rational, arg0, arg1, arg2); } @JRubyMethod(name = "Float", module = true, visibility = PRIVATE) public static IRubyObject new_float(ThreadContext context, IRubyObject recv, IRubyObject object) { return new_float(context, object, true); } @JRubyMethod(name = "Float", module = true, visibility = PRIVATE) public static IRubyObject new_float(ThreadContext context, IRubyObject recv, IRubyObject object, IRubyObject opts) { boolean exception = checkExceptionOpt(context, context.runtime.getFloat(), opts); return new_float(context, object, exception); } private static boolean checkExceptionOpt(ThreadContext context, RubyClass rubyClass, IRubyObject opts) { boolean exception = true; IRubyObject maybeOpts = ArgsUtil.getOptionsArg(context.runtime, opts, false); if (!maybeOpts.isNil()) { IRubyObject exObj = ArgsUtil.extractKeywordArg(context, opts, "exception"); if (exObj != context.tru && exObj != context.fals) { throw context.runtime.newArgumentError("`" + rubyClass.getName() + "': expected true or false as exception: " + exObj); } exception = exObj.isTrue(); } return exception; } public static RubyFloat new_float(IRubyObject recv, IRubyObject object) { return (RubyFloat) new_float(recv.getRuntime().getCurrentContext(), object, true); } private static final ByteList ZEROx = new ByteList(new byte[] { '0','x' }, false); public static RubyFloat new_float(final Ruby runtime, IRubyObject object) { return (RubyFloat) new_float(runtime.getCurrentContext(), object, true); } private static BigInteger SIXTEEN = BigInteger.valueOf(16L); private static BigInteger MINUS_ONE = BigInteger.valueOf(-1L); private static RaiseException floatError(Ruby runtime, ByteList string) { throw runtime.newArgumentError(str(runtime, "invalid value for Float(): ", runtime.newString(string))); } /** * Parse hexidecimal exponential notation: * <a href="https://en.wikipedia.org/wiki/Hexadecimal#Hexadecimal_exponential_notation">...</a> * <p/> * This method assumes the string is a valid-formatted string. * * @param str the bytelist to be parsed * @return the result. */ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str) { byte[] bytes = str.unsafeBytes(); int length = str.length(); if (length <= 2) throw floatError(runtime, str); int sign = 1; int letter; int i = str.begin(); letter = bytes[i]; if (letter == '+') { i++; } else if (letter == '-') { sign = -1; i++; } // Skip '0x' letter = bytes[i++]; if (letter != '0') throw floatError(runtime, str); letter = bytes[i++]; if (letter != 'x') throw floatError(runtime, str); int exponent = 0; int explicitExponent = 0; int explicitExponentSign = 1; boolean periodFound = false; boolean explicitExponentFound = false; BigInteger value = BigInteger.valueOf(0L); if (i == length || bytes[i] == '_' || bytes[i] == 'p' || bytes[i] == 'P') throw floatError(runtime, str); for(; i < length && !explicitExponentFound; i++) { letter = bytes[i]; switch (letter) { case '.': // Fractional part of floating point value "1(.)23" periodFound = true; continue; case 'p': // Explicit exponent "1.23(p)1a" case 'P': if (bytes[i-1] == '_' || i == length - 1) throw floatError(runtime, str); explicitExponentFound = true; continue; case '_': continue; } // base 16 value representing main pieces of number int digit = Character.digit(letter, 16); if (Character.forDigit(digit, 16) == 0) throw floatError(runtime, str); value = value.multiply(SIXTEEN).add(BigInteger.valueOf(digit)); if (periodFound) exponent++; } if (explicitExponentFound) { if (bytes[i] == '-') { explicitExponentSign = -1; i++; } else if (bytes[i] == '+') { i++; } else if (bytes[i] == '_') { throw floatError(runtime, str); } for (; i < length; i++) { // base 10 value representing base 2 exponent letter = bytes[i]; if (letter == '_') { if (i == length - 1) throw floatError(runtime, str); continue; } int digit = Character.digit(letter, 10); if (Character.forDigit(digit, 10) == 0) throw floatError(runtime, str); explicitExponent = explicitExponent * 10 + digit; } } // each exponent in main number is 4 bits and the value after 'p' represents a power of 2. Wacky. int scaleFactor = 4 * exponent - explicitExponent * explicitExponentSign; return sign * Math.scalb(value.doubleValue(), -scaleFactor); } public static IRubyObject new_float(ThreadContext context, IRubyObject object, boolean exception) { Ruby runtime = context.runtime; if (object instanceof RubyInteger){ return new_float(runtime, (RubyInteger) object); } if (object instanceof RubyFloat) { return object; } if (object instanceof RubyString) { RubyString str = (RubyString) object; ByteList bytes = str.getByteList(); if (bytes.getRealSize() == 0){ // rb_cstr_to_dbl case if (!exception) return runtime.getNil(); throw runtime.newArgumentError("invalid value for Float(): " + object.inspect()); } if (bytes.startsWith(ZEROx)) { // startsWith("0x") if (bytes.indexOf('p') != -1 || bytes.indexOf('P') != -1) { return runtime.newFloat(parseHexidecimalExponentString2(runtime, bytes)); } IRubyObject inum = ConvertBytes.byteListToInum(runtime, bytes, 16, true, exception); if (!exception && inum.isNil()) return inum; return ((RubyInteger) inum).toFloat(); } return RubyNumeric.str2fnum(runtime, str, true, exception); } if (object.isNil()){ if (!exception) return object; throw runtime.newTypeError("can't convert nil into Float"); } try { IRubyObject flote = TypeConverter.convertToType(context, object, runtime.getFloat(), sites(context).to_f_checked, false); if (flote instanceof RubyFloat) return flote; } catch (RaiseException re) { if (exception) throw re; } if (!exception) return runtime.getNil(); return TypeConverter.handleUncoercibleObject(runtime, object, runtime.getFloat(), true); } static RubyFloat new_float(final Ruby runtime, RubyInteger num) { if (num instanceof RubyBignum) { return RubyFloat.newFloat(runtime, RubyBignum.big2dbl((RubyBignum) num)); } return RubyFloat.newFloat(runtime, num.getDoubleValue()); } @JRubyMethod(name = "Hash", required = 1, module = true, visibility = PRIVATE) public static IRubyObject new_hash(ThreadContext context, IRubyObject recv, IRubyObject arg) { IRubyObject tmp; Ruby runtime = context.runtime; if (arg == context.nil) return RubyHash.newHash(runtime); tmp = TypeConverter.checkHashType(context, sites(context).to_hash_checked, arg); if (tmp == context.nil) { if (arg instanceof RubyArray && ((RubyArray) arg).isEmpty()) { return RubyHash.newHash(runtime); } throw runtime.newTypeError("can't convert " + arg.getMetaClass() + " into Hash"); } return tmp; } @JRubyMethod(name = "Integer", module = true, visibility = PRIVATE) public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object) { return TypeConverter.convertToInteger(context, object, 0, true); } @JRubyMethod(name = "Integer", module = true, visibility = PRIVATE) public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object, IRubyObject baseOrOpts) { IRubyObject maybeOpts = ArgsUtil.getOptionsArg(context.runtime, baseOrOpts, false); if (maybeOpts.isNil()) { return TypeConverter.convertToInteger(context, object, baseOrOpts.convertToInteger().getIntValue(), true); } boolean exception = checkExceptionOpt(context, context.runtime.getInteger(), maybeOpts); return TypeConverter.convertToInteger( context, object, 0, exception); } @JRubyMethod(name = "Integer", module = true, visibility = PRIVATE) public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object, IRubyObject base, IRubyObject opts) { boolean exception = checkExceptionOpt(context, context.runtime.getInteger(), opts); IRubyObject baseInteger = TypeConverter.convertToInteger(context, base, 0, exception); if (baseInteger.isNil()) return baseInteger; return TypeConverter.convertToInteger( context, object, ((RubyInteger) baseInteger).getIntValue(), exception); } @JRubyMethod(name = "String", required = 1, module = true, visibility = PRIVATE) public static IRubyObject new_string(ThreadContext context, IRubyObject recv, IRubyObject object) { Ruby runtime = context.runtime; KernelSites sites = sites(context); IRubyObject tmp = TypeConverter.checkStringType(context, sites.to_str_checked, object, runtime.getString()); if (tmp == context.nil) { tmp = TypeConverter.convertToType(context, object, runtime.getString(), sites(context).to_s_checked); } return tmp; } @Deprecated public static IRubyObject new_string19(ThreadContext context, IRubyObject recv, IRubyObject object) { return new_string(context, recv, object); } // MRI: rb_f_p @JRubyMethod(rest = true, module = true, visibility = PRIVATE) public static IRubyObject p(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return RubyThread.uninterruptible(context, args, RubyKernel::pBody); } private static IRubyObject pBody(ThreadContext context, IRubyObject[] args) { Ruby runtime = context.runtime; int argc = args.length; int i; IRubyObject ret = context.nil; IRubyObject defout = runtime.getGlobalVariables().get("$>"); IRubyObject defaultRS = context.runtime.getGlobalVariables().getDefaultSeparator(); boolean defoutWriteBuiltin = defout instanceof RubyIO && defout.getMetaClass().isMethodBuiltin("write"); for (i=0; i<argc; i++) { // pulled out as rb_p in MRI // rb_p(argv[i]); IRubyObject obj = args[i]; IRubyObject str = RubyBasicObject.rbInspect(context, obj); if (defoutWriteBuiltin) { ((RubyIO)defout).write(context, str, true); ((RubyIO)defout).write(context, defaultRS, true); } else { RubyIO.write(context, defout, str); RubyIO.write(context, defout, defaultRS); } } if (argc == 1) { ret = args[0]; } else if (argc > 1) { ret = RubyArray.newArray(runtime, args); } if (defout instanceof RubyIO) { ((RubyIO)defout).flush(context); } return ret; } @JRubyMethod(module = true) public static IRubyObject public_method(ThreadContext context, IRubyObject recv, IRubyObject symbol) { return recv.getMetaClass().newMethod(recv, symbol.asJavaString(), true, PUBLIC, true, false); } /** rb_f_putc */ @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject putc(ThreadContext context, IRubyObject recv, IRubyObject ch) { IRubyObject defout = context.runtime.getGlobalVariables().get("$>"); if (recv == defout) { return RubyIO.putc(context, recv, ch); } return sites(context).putc.call(context, defout, defout, ch); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject puts(ThreadContext context, IRubyObject recv) { IRubyObject defout = context.runtime.getGlobalVariables().get("$>"); if (recv == defout) { return RubyIO.puts0(context, recv); } return sites(context).puts.call(context, defout, defout); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject arg0) { IRubyObject defout = context.runtime.getGlobalVariables().get("$>"); if (recv == defout) { return RubyIO.puts1(context, recv, arg0); } return sites(context).puts.call(context, defout, defout, arg0); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) { IRubyObject defout = context.runtime.getGlobalVariables().get("$>"); if (recv == defout) { return RubyIO.puts2(context, recv, arg0, arg1); } return sites(context).puts.call(context, defout, defout, arg0, arg1); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { IRubyObject defout = context.runtime.getGlobalVariables().get("$>"); if (recv == defout) { return RubyIO.puts3(context, recv, arg0, arg1, arg2); } return sites(context).puts.call(context, defout, defout, arg0, arg1, arg2); } @JRubyMethod(rest = true, module = true, visibility = PRIVATE) public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject[] args) { IRubyObject defout = context.runtime.getGlobalVariables().get("$>"); if (recv == defout) { return RubyIO.puts(context, recv, args); } return sites(context).puts.call(context, defout, defout, args); } // rb_f_print @JRubyMethod(rest = true, module = true, visibility = PRIVATE, reads = LASTLINE) public static IRubyObject print(ThreadContext context, IRubyObject recv, IRubyObject[] args) { RubyIO.print(context, context.runtime.getGlobalVariables().get("$>"), args); return context.nil; } // rb_f_printf @JRubyMethod(rest = true, module = true, visibility = PRIVATE) public static IRubyObject printf(ThreadContext context, IRubyObject recv, IRubyObject[] args) { if (args.length == 0) return context.nil; final IRubyObject out; if (args[0] instanceof RubyString) { out = context.runtime.getGlobalVariables().get("$>"); } else { out = args[0]; args = Arrays.copyOfRange(args, 1, args.length); } RubyIO.write(context, out, sprintf(context, recv, args)); return context.nil; } @JRubyMethod(optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject readline(ThreadContext context, IRubyObject recv, IRubyObject[] args) { IRubyObject line = gets(context, recv, args); if (line.isNil()) { throw context.runtime.newEOFError(); } return line; } @JRubyMethod(optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject readlines(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return RubyArgsFile.readlines(context, context.runtime.getArgsFile(), args); } @JRubyMethod(name = "respond_to_missing?", visibility = PRIVATE) public static IRubyObject respond_to_missing_p(ThreadContext context, IRubyObject recv, IRubyObject symbol) { return context.fals; } @JRubyMethod(name = "respond_to_missing?", visibility = PRIVATE) public static IRubyObject respond_to_missing_p(ThreadContext context, IRubyObject recv, IRubyObject symbol, IRubyObject isPrivate) { return context.fals; } /** Returns value of $_. * * @throws RaiseException TypeError if $_ is not a String or nil. * @return value of $_ as String. */ private static RubyString getLastlineString(ThreadContext context, Ruby runtime) { IRubyObject line = context.getLastLine(); if (line.isNil()) { throw runtime.newTypeError("$_ value need to be String (nil given)."); } else if (!(line instanceof RubyString)) { throw runtime.newTypeError("$_ value need to be String (" + line.getMetaClass().getName() + " given)."); } else { return (RubyString) line; } } @JRubyMethod(required = 1, optional = 3, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject select(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return RubyIO.select(context, recv, args); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject sleep(ThreadContext context, IRubyObject recv) { // Zero sleeps forever return sleepCommon(context, 0); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject sleep(ThreadContext context, IRubyObject recv, IRubyObject timeout) { long milliseconds = (long) (RubyTime.convertTimeInterval(context, timeout) * 1000); // Explicit zero in MRI returns immediately if (milliseconds == 0) return RubyFixnum.zero(context.runtime); return sleepCommon(context, milliseconds); } private static RubyFixnum sleepCommon(ThreadContext context, long milliseconds) { final long startTime = System.currentTimeMillis(); final RubyThread rubyThread = context.getThread(); boolean interrupted = false; try { // Spurious wakeup-loop do { long loopStartTime = System.currentTimeMillis(); if (!rubyThread.sleep(milliseconds)) break; milliseconds -= (System.currentTimeMillis() - loopStartTime); } while (milliseconds > 0); } catch (InterruptedException ie) { // ignore; sleep gets interrupted interrupted = true; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return context.runtime.newFixnum(Math.round((System.currentTimeMillis() - startTime) / 1000.0)); } // FIXME: Add at_exit and finalizers to exit, then make exit_bang not call those. @JRubyMethod(optional = 1, module = true, visibility = PRIVATE) public static IRubyObject exit(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 0, 1); exit(runtime, args, false); return runtime.getNil(); // not reached } @JRubyMethod(name = "exit!", optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject exit_bang(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 0, 1); exit(runtime, args, true); return runtime.getNil(); // not reached } private static void exit(Ruby runtime, IRubyObject[] args, boolean hard) { int status = hard ? 1 : 0; String message = null; if (args.length > 0) { RubyObject argument = (RubyObject) args[0]; if (argument instanceof RubyBoolean) { status = argument.isFalse() ? 1 : 0; } else { status = RubyNumeric.fix2int(argument); } } if (args.length == 2) { if (args[1] instanceof RubyString) { message = ((RubyString) args[1]).toString(); } } if (hard) { if (runtime.getInstanceConfig().isHardExit()) { System.exit(status); } else { throw new MainExitException(status, true); } } else { if (message == null) { throw runtime.newSystemExit(status); } else { throw runtime.newSystemExit(status, message); } } } /** * @param context * @param recv * @return an Array with the names of all global variables. */ @JRubyMethod(name = "global_variables", module = true, visibility = PRIVATE) public static RubyArray global_variables(ThreadContext context, IRubyObject recv) { Ruby runtime = context.runtime; RubyArray globalVariables = runtime.newArray(); for (String globalVariableName : runtime.getGlobalVariables().getNames()) { globalVariables.append(runtime.newSymbol(globalVariableName)); } return globalVariables; } @Deprecated public static RubyArray global_variables19(ThreadContext context, IRubyObject recv) { return global_variables(context, recv); } /** * @param context * @param recv * @return an Array with the names of all local variables. */ @JRubyMethod(name = "local_variables", module = true, visibility = PRIVATE, reads = SCOPE) public static RubyArray local_variables(ThreadContext context, IRubyObject recv) { return context.getCurrentStaticScope().getLocalVariables(context.runtime); } @Deprecated public static RubyArray local_variables19(ThreadContext context, IRubyObject recv) { return local_variables(context, recv); } @JRubyMethod(name = "binding", module = true, visibility = PRIVATE, reads = {LASTLINE, BACKREF, VISIBILITY, BLOCK, SELF, METHODNAME, LINE, CLASS, FILENAME, SCOPE}, writes = {LASTLINE, BACKREF, VISIBILITY, BLOCK, SELF, METHODNAME, LINE, CLASS, FILENAME, SCOPE}) public static RubyBinding binding(ThreadContext context, IRubyObject recv, Block block) { return RubyBinding.newBinding(context.runtime, context.currentBinding()); } @Deprecated public static RubyBinding binding19(ThreadContext context, IRubyObject recv, Block block) { return binding(context, recv, block); } @JRubyMethod(name = {"block_given?", "iterator?"}, module = true, visibility = PRIVATE, reads = BLOCK) public static RubyBoolean block_given_p(ThreadContext context, IRubyObject recv) { return RubyBoolean.newBoolean(context, context.getCurrentFrame().getBlock().isGiven()); } @JRubyMethod(name = {"sprintf", "format"}, required = 1, rest = true, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject sprintf(ThreadContext context, IRubyObject recv, IRubyObject[] args) { if (args.length == 0) { throw context.runtime.newArgumentError("sprintf must have at least one argument"); } RubyString str = RubyString.stringValue(args[0]); IRubyObject arg; if (args.length == 2 && args[1] instanceof RubyHash) { arg = args[1]; } else { RubyArray newArgs = RubyArray.newArrayMayCopy(context.runtime, args); newArgs.shift(context); arg = newArgs; } return str.op_format(context, arg); } @Deprecated public static IRubyObject sprintf(IRubyObject recv, IRubyObject[] args) { return sprintf(recv.getRuntime().getCurrentContext(), recv, args); } public static IRubyObject raise(ThreadContext context, IRubyObject self, IRubyObject arg0) { final Ruby runtime = context.runtime; // semi extract_raise_opts : IRubyObject cause; if (arg0 instanceof RubyHash) { RubyHash opt = (RubyHash) arg0; RubySymbol key; if (!opt.isEmpty() && (opt.has_key_p(context, runtime.newSymbol("cause")) == runtime.getTrue())) { throw runtime.newArgumentError("only cause is given with no arguments"); } } cause = context.getErrorInfo(); // returns nil for no error-info maybeRaiseJavaException(runtime, arg0); RaiseException raise; if (arg0 instanceof RubyString) { raise = ((RubyException) runtime.getRuntimeError().newInstance(context, arg0)).toThrowable(); } else { raise = convertToException(context, arg0, null).toThrowable(); } if (runtime.isDebug()) { printExceptionSummary(runtime, raise.getException()); } if (raise.getException().getCause() == null && cause != raise.getException()) { raise.getException().setCause(cause); } throw raise; } @JRubyMethod(name = {"raise", "fail"}, optional = 3, checkArity = false, module = true, visibility = PRIVATE, omit = true) public static IRubyObject raise(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { int argc = Arity.checkArgumentCount(context, args, 0, 3); final Ruby runtime = context.runtime; boolean forceCause = false; // semi extract_raise_opts : IRubyObject cause = null; if (argc > 0) { IRubyObject last = args[argc - 1]; if (last instanceof RubyHash) { RubyHash opt = (RubyHash) last; RubySymbol key; if (!opt.isEmpty() && (opt.has_key_p(context, key = runtime.newSymbol("cause")) == runtime.getTrue())) { cause = opt.delete(context, key, Block.NULL_BLOCK); forceCause = true; if (opt.isEmpty() && --argc == 0) { // more opts will be passed along throw runtime.newArgumentError("only cause is given with no arguments"); } } } } if ( argc > 0 ) { // for argc == 0 we will be raising $! // NOTE: getErrorInfo needs to happen before new RaiseException(...) if ( cause == null ) cause = context.getErrorInfo(); // returns nil for no error-info } maybeRaiseJavaException(runtime, args, argc); RaiseException raise; switch (argc) { case 0: IRubyObject lastException = runtime.getGlobalVariables().get("$!"); if (lastException.isNil()) { raise = RaiseException.from(runtime, runtime.getRuntimeError(), ""); } else { // non RubyException value is allowed to be assigned as $!. raise = ((RubyException) lastException).toThrowable(); } break; case 1: if (args[0] instanceof RubyString) { raise = ((RubyException) runtime.getRuntimeError().newInstance(context, args, block)).toThrowable(); } else { raise = convertToException(context, args[0], null).toThrowable(); } break; case 2: raise = convertToException(context, args[0], args[1]).toThrowable(); break; default: RubyException exception = convertToException(context, args[0], args[1]); exception.setBacktrace(args[2]); raise = exception.toThrowable(); break; } if (runtime.isDebug()) { printExceptionSummary(runtime, raise.getException()); } if (forceCause || argc > 0 && raise.getException().getCause() == null && cause != raise.getException()) { raise.getException().setCause(cause); } throw raise; } private static void maybeRaiseJavaException(final Ruby runtime, final IRubyObject[] args, final int argc) { // Check for a Java exception IRubyObject maybeException = null; switch (argc) { case 0: maybeException = runtime.getGlobalVariables().get("$!"); break; case 1: if (args.length == 1) maybeException = args[0]; break; } maybeRaiseJavaException(runtime, maybeException); } private static void maybeRaiseJavaException( final Ruby runtime, final IRubyObject arg0) { // Check for a Java exception if (arg0 instanceof ConcreteJavaProxy) { // looks like someone's trying to raise a Java exception. Let them. Object maybeThrowable = ((ConcreteJavaProxy) arg0).getObject(); if (!(maybeThrowable instanceof Throwable)) { throw runtime.newTypeError("can't raise a non-Throwable Java object"); } final Throwable ex = (Throwable) maybeThrowable; Helpers.throwException(ex); return; // not reached } } private static RubyException convertToException(ThreadContext context, IRubyObject obj, IRubyObject optionalMessage) { if (!obj.respondsTo("exception")) { throw context.runtime.newTypeError("exception class/object expected"); } IRubyObject exception; if (optionalMessage == null) { exception = obj.callMethod(context, "exception"); } else { exception = obj.callMethod(context, "exception", optionalMessage); } try { return (RubyException) exception; } catch (ClassCastException cce) { throw context.runtime.newTypeError("exception object expected"); } } private static void printExceptionSummary(Ruby runtime, RubyException rEx) { RubyStackTraceElement[] elements = rEx.getBacktraceElements(); RubyStackTraceElement firstElement = elements.length > 0 ? elements[0] : new RubyStackTraceElement("", "", "(empty)", 0, false); String msg = String.format("Exception `%s' at %s:%s - %s\n", rEx.getMetaClass(), firstElement.getFileName(), firstElement.getLineNumber(), TypeConverter.convertToType(rEx, runtime.getString(), "to_s")); runtime.getErrorStream().print(msg); } /** * Require. * MRI allows to require ever .rb files or ruby extension dll (.so or .dll depending on system). * we allow requiring either .rb files or jars. * @param recv ruby object used to call require (any object will do and it won't be used anyway). * @param name the name of the file to require **/ @JRubyMethod(name = "require", module = true, visibility = PRIVATE) public static IRubyObject require(ThreadContext context, IRubyObject recv, IRubyObject name, Block block) { IRubyObject tmp = name.checkStringType(); if (tmp != context.nil) return requireCommon(context.runtime, (RubyString) tmp, block); return requireCommon(context.runtime, RubyFile.get_path(context, name), block); } private static IRubyObject requireCommon(Ruby runtime, RubyString name, Block block) { RubyString path = StringSupport.checkEmbeddedNulls(runtime, name); return runtime.newBoolean(runtime.getLoadService().require(path.toString())); } @JRubyMethod(name = "require_relative", module = true, visibility = PRIVATE, reads = SCOPE) public static IRubyObject require_relative(ThreadContext context, IRubyObject recv, IRubyObject name){ Ruby runtime = context.runtime; RubyString relativePath = RubyFile.get_path(context, name); String file = context.getCurrentStaticScope().getFile(); if (file == null || file.equals("-") || file.equals("-e") || file.matches("\\A\\((.*)\\)")) { throw runtime.newLoadError("cannot infer basepath"); } file = runtime.getLoadService().getPathForLocation(file); RubyClass fileClass = runtime.getFile(); IRubyObject realpath = RubyFile.realpath(context, fileClass, runtime.newString(file)); IRubyObject dirname = RubyFile.dirname(context, fileClass, realpath); IRubyObject absoluteFeature = RubyFile.expand_path(context, fileClass, relativePath, dirname); return RubyKernel.require(context, runtime.getKernel(), absoluteFeature, Block.NULL_BLOCK); } @JRubyMethod(name = "load", module = true, visibility = PRIVATE) public static IRubyObject load(ThreadContext context, IRubyObject recv, IRubyObject path, Block block) { Ruby runtime = context.runtime; RubyString pathStr = StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, path)); return loadCommon(runtime, pathStr, false); } @JRubyMethod(name = "load", module = true, visibility = PRIVATE) public static IRubyObject load(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject wrap, Block block) { Ruby runtime = context.runtime; RubyString pathStr = StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, path)); return loadCommon(runtime, pathStr, wrap); } public static IRubyObject load(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { switch (args.length) { case 1: return load(context, recv, args[0], block); case 2: return load(context, recv, args[0], args[1], block); } Arity.raiseArgumentError(context.runtime, args.length, 1, 2); return null; // not reached } @Deprecated public static IRubyObject load(IRubyObject recv, IRubyObject[] args, Block block) { return load19(recv.getRuntime().getCurrentContext(), recv, args, block); } @Deprecated public static IRubyObject load19(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { return load(context, recv, args, block); } private static IRubyObject loadCommon(Ruby runtime, RubyString path, boolean wrap) { runtime.getLoadService().load(path.toString(), wrap); return runtime.getTrue(); } private static IRubyObject loadCommon(Ruby runtime, RubyString path, IRubyObject wrap) { String file = path.toString(); LoadService loadService = runtime.getLoadService(); if (wrap.isNil() || wrap instanceof RubyBoolean) { loadService.load(file, wrap.isTrue()); } else { loadService.load(file, wrap); } return runtime.getTrue(); } @JRubyMethod(name = "eval", required = 1, optional = 3, checkArity = false, module = true, visibility = PRIVATE, reads = {LASTLINE, BACKREF, VISIBILITY, BLOCK, SELF, METHODNAME, LINE, CLASS, FILENAME, SCOPE}, writes = {LASTLINE, BACKREF, VISIBILITY, BLOCK, SELF, METHODNAME, LINE, CLASS, FILENAME, SCOPE}) public static IRubyObject eval(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { int argc = Arity.checkArgumentCount(context, args, 1, 4); return evalCommon(context, recv, args); } @Deprecated public static IRubyObject eval19(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { return eval(context, recv, args, block); } private static IRubyObject evalCommon(ThreadContext context, IRubyObject recv, IRubyObject[] args) { // string to eval RubyString src = args[0].convertToString(); boolean bindingGiven = args.length > 1 && args[1] != context.nil; Binding binding = bindingGiven ? getBindingForEval(context, args[1]) : context.currentBinding(); if (args.length > 2) { // file given, use it and force it into binding binding.setFile(args[2].convertToString().toString()); if (args.length > 3) { // line given, use it and force it into binding // -1 because parser uses zero offsets and other code compensates binding.setLine(((int) args[3].convertToInteger().getLongValue()) - 1); } else { // filename given, but no line, start from the beginning. binding.setLine(0); } } else { // no explicit file/line argument given binding.setFile("(eval)"); binding.setLine(0); } // set method to current frame's, which should be caller's String frameName = context.getCompositeName(); if (frameName != null) binding.setMethod(frameName); if (bindingGiven) recv = binding.getSelf(); return Interpreter.evalWithBinding(context, recv, src, binding, bindingGiven); } private static Binding getBindingForEval(ThreadContext context, IRubyObject scope) { if (scope instanceof RubyBinding) { return ((RubyBinding) scope).getBinding().cloneForEval(); } throw context.runtime.newTypeError("wrong argument type " + scope.getMetaClass() + " (expected binding)"); } @JRubyMethod(name = "caller", module = true, visibility = PRIVATE, omit = true) public static IRubyObject caller(ThreadContext context, IRubyObject recv) { return callerInternal(context, recv, null, null); } @JRubyMethod(name = "caller", module = true, visibility = PRIVATE, omit = true) public static IRubyObject caller(ThreadContext context, IRubyObject recv, IRubyObject level) { return callerInternal(context, recv, level, null); } @JRubyMethod(name = "caller", module = true, visibility = PRIVATE, omit = true) public static IRubyObject caller(ThreadContext context, IRubyObject recv, IRubyObject level, IRubyObject length) { return callerInternal(context, recv, level, length); } private static IRubyObject callerInternal(ThreadContext context, IRubyObject recv, IRubyObject level, IRubyObject length) { if (length != null && length.isNil()) length = null; // caller(0, nil) should act like caller(0) if (length == null) { // use Java 8 version of walker to reduce overhead (GH-5857) return withLevelAndLength(context, level, length, 1, (ctx, lev, len) -> ThreadContext.WALKER8.walk(stream -> ctx.createCallerBacktrace(lev, len, stream))); } return withLevelAndLength(context, level, length, 1, (ctx, lev, len) -> ThreadContext.WALKER.walk(stream -> ctx.createCallerBacktrace(lev, len, stream))); } @JRubyMethod(module = true, visibility = PRIVATE, omit = true) public static IRubyObject caller_locations(ThreadContext context, IRubyObject recv) { return callerLocationsInternal(context, null, null); } @JRubyMethod(module = true, visibility = PRIVATE, omit = true) public static IRubyObject caller_locations(ThreadContext context, IRubyObject recv, IRubyObject level) { return callerLocationsInternal(context, level, null); } @JRubyMethod(module = true, visibility = PRIVATE, omit = true) public static IRubyObject caller_locations(ThreadContext context, IRubyObject recv, IRubyObject level, IRubyObject length) { return callerLocationsInternal(context, level, length); } private static IRubyObject callerLocationsInternal(ThreadContext context, IRubyObject level, IRubyObject length) { if (length == null) { // use Java 8 version of walker to reduce overhead (GH-5857) return withLevelAndLength( context, level, length, 1, (ctx, lev, len) -> ThreadContext.WALKER8.walk(stream -> ctx.createCallerLocations(lev, len, stream))); } return withLevelAndLength( context, level, length, 1, (ctx, lev, len) -> ThreadContext.WALKER.walk(stream -> ctx.createCallerLocations(lev, len, stream))); } /** * Retrieve the level and length from given args, if non-null. */ static <R> R withLevelAndLength(ThreadContext context, IRubyObject level, IRubyObject length, int defaultLevel, ObjectIntIntFunction<ThreadContext, R> func) { int lev; // Suitably large but no chance to overflow int when combined with level int len = 1 << 24; if (length != null) { lev = RubyNumeric.fix2int(level); len = RubyNumeric.fix2int(length); } else if (level instanceof RubyRange) { RubyRange range = (RubyRange) level; IRubyObject first = range.begin(context); lev = first.isNil() ? 0 : RubyNumeric.fix2int(first); IRubyObject last = range.end(context); if (last.isNil()) { len = 1 << 24; } else { len = RubyNumeric.fix2int(last) - lev; } if (!range.isExcludeEnd()) len++; len = len < 0 ? 0 : len; } else if (level != null) { lev = RubyNumeric.fix2int(level); } else { lev = defaultLevel; } if (lev < 0) { throw context.runtime.newArgumentError("negative level (" + lev + ')'); } if (len < 0) { throw context.runtime.newArgumentError("negative size (" + len + ')'); } return func.apply(context, lev, len); } @JRubyMethod(name = "catch", module = true, visibility = PRIVATE) public static IRubyObject rbCatch(ThreadContext context, IRubyObject recv, Block block) { return rbCatch(context, recv, new RubyObject(context.runtime.getObject()), block); } @JRubyMethod(name = "catch", module = true, visibility = PRIVATE) public static IRubyObject rbCatch(ThreadContext context, IRubyObject recv, IRubyObject tag, Block block) { return new CatchThrow(tag).enter(context, tag, block); } @Deprecated public static IRubyObject rbCatch19(ThreadContext context, IRubyObject recv, Block block) { return rbCatch(context, recv, block); } @Deprecated public static IRubyObject rbCatch19(ThreadContext context, IRubyObject recv, IRubyObject tag, Block block) { return rbCatch(context, recv, tag, block); } @JRubyMethod(name = "throw", module = true, visibility = PRIVATE) public static IRubyObject rbThrow(ThreadContext context, IRubyObject recv, IRubyObject tag, Block block) { return rbThrowInternal(context, tag, null); } @JRubyMethod(name = "throw", module = true, visibility = PRIVATE) public static IRubyObject rbThrow(ThreadContext context, IRubyObject recv, IRubyObject tag, IRubyObject value, Block block) { return rbThrowInternal(context, tag, value); } @Deprecated public static IRubyObject rbThrow19(ThreadContext context, IRubyObject recv, IRubyObject tag, Block block) { return rbThrowInternal(context, tag, null); } @Deprecated public static IRubyObject rbThrow19(ThreadContext context, IRubyObject recv, IRubyObject tag, IRubyObject value, Block block) { return rbThrowInternal(context, tag, value); } private static final byte[] uncaught_throw_p = { 'u','n','c','a','u','g','h','t',' ','t','h','r','o','w',' ','%','p' }; private static IRubyObject rbThrowInternal(ThreadContext context, IRubyObject tag, IRubyObject arg) { final Ruby runtime = context.runtime; runtime.getGlobalVariables().set("$!", context.nil); CatchThrow continuation = context.getActiveCatch(tag); if (continuation != null) { continuation.args = arg == null ? IRubyObject.NULL_ARRAY : new IRubyObject[] { arg }; throw continuation; } // No catch active for this throw IRubyObject value = arg == null ? context.nil : arg; throw uncaughtThrow(runtime, tag, value, RubyString.newStringShared(runtime, uncaught_throw_p)); } private static RaiseException uncaughtThrow(Ruby runtime, IRubyObject tag, IRubyObject value, RubyString message) { return RubyUncaughtThrowError.newUncaughtThrowError(runtime, tag, value, message).toThrowable(); } @JRubyMethod(module = true, visibility = PRIVATE, omit = true) public static IRubyObject warn(ThreadContext context, IRubyObject recv, IRubyObject arg) { if (arg instanceof RubyHash) { // warn({}) - treat as kwarg return warn(context, recv, new IRubyObject[] { arg }); } if (!context.runtime.getVerbose().isNil()) { warnObj(context, recv, arg, context.nil); } return context.nil; } private static void warnObj(ThreadContext context, IRubyObject recv, IRubyObject arg, IRubyObject category) { if (arg instanceof RubyArray) { final RubyArray argAry = arg.convertToArray(); for (int i = 0; i < argAry.size(); i++) warnObj(context, recv, argAry.eltOk(i), category); return; } warnStr(context, recv, arg.asString(), category); } static void warnStr(ThreadContext context, IRubyObject recv, RubyString message, IRubyObject category) { final Ruby runtime = context.runtime; if (!message.endsWithAsciiChar('\n')) { message = message.strDup(runtime).cat('\n', USASCIIEncoding.INSTANCE); } if (recv == runtime.getWarning()) { RubyWarnings.warn(context, message); return; } // FIXME: This seems "fragile". Not sure if other transitional Ruby methods need this sort of thing or not (e.g. perhaps we need a helper on callsite for this). DynamicMethod method = ((CachingCallSite) sites(context).warn).retrieveCache(runtime.getWarning()).method; if (method.getSignature().isOneArgument()) { sites(context).warn.call(context, recv, runtime.getWarning(), message); } else { RubyHash keywords = RubyHash.newHash(runtime, runtime.newSymbol("category"), category); context.callInfo = ThreadContext.CALL_KEYWORD; sites(context).warn.call(context, recv, runtime.getWarning(), message, keywords); } } @JRubyMethod(module = true, rest = true, visibility = PRIVATE, omit = true) public static IRubyObject warn(ThreadContext context, IRubyObject recv, IRubyObject[] args) { boolean explicitUplevel = false; int uplevel = 0; IRubyObject category = context.nil; int argMessagesLen = args.length; if (argMessagesLen > 0) { IRubyObject opts = TypeConverter.checkHashType(context.runtime, args[argMessagesLen - 1]); if (opts != context.nil) { argMessagesLen--; IRubyObject[] ret = ArgsUtil.extractKeywordArgs(context, (RubyHash) opts, "uplevel", "category"); if (ret[0] != null) { explicitUplevel = true; if ((uplevel = RubyNumeric.num2int(ret[0])) < 0) { throw context.runtime.newArgumentError("negative level (" + uplevel + ")"); } } if (ret[1] != null) { if (ret[1].isNil()) { category = ret[1]; } else { category = TypeConverter.convertToType(ret[1], context.runtime.getSymbol(), "to_sym"); } } } } int i = 0; if (!context.runtime.getVerbose().isNil() && argMessagesLen > 0) { if (explicitUplevel && argMessagesLen > 0) { // warn(uplevel: X) does nothing warnStr(context, recv, buildWarnMessage(context, uplevel, args[0]), category); i = 1; } for (; i < argMessagesLen; i++) { warnObj(context, recv, args[i], category); } } return context.nil; } private static RubyString buildWarnMessage(ThreadContext context, final int uplevel, final IRubyObject arg) { RubyStackTraceElement element = context.getSingleBacktraceExact(uplevel); RubyString message = RubyString.newStringLight(context.runtime, 32); if (element != null) { message.catString(element.getFileName()).cat(':').catString(Integer.toString(element.getLineNumber())) .catString(": warning: "); } else { message.catString("warning: "); } return (RubyString) message.op_plus19(context, arg.asString()); } @JRubyMethod(module = true, alias = "then") public static IRubyObject yield_self(ThreadContext context, IRubyObject recv, Block block) { if (block.isGiven()) { return block.yield(context, recv); } else { return RubyEnumerator.enumeratorizeWithSize(context, recv, "yield_self", RubyKernel::objectSize); } } /** * An exactly-one size method suitable for lambda method reference implementation of {@link SizeFn#size(ThreadContext, IRubyObject, IRubyObject[])} * * @see SizeFn#size(ThreadContext, IRubyObject, IRubyObject[]) */ private static IRubyObject objectSize(ThreadContext context, IRubyObject self, IRubyObject[] args) { // always 1 return RubyFixnum.one(context.runtime); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject set_trace_func(ThreadContext context, IRubyObject recv, IRubyObject trace_func, Block block) { if (trace_func.isNil()) { context.traceEvents.setTraceFunction(null); } else if (!(trace_func instanceof RubyProc)) { throw context.runtime.newTypeError("trace_func needs to be Proc."); } else { context.traceEvents.setTraceFunction((RubyProc) trace_func); } return trace_func; } @JRubyMethod(required = 1, optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject trace_var(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { int argc = Arity.checkArgumentCount(context, args, 1, 2); RubyProc proc = null; String var = args[0].toString(); // ignore if it's not a global var if (var.charAt(0) != '$') { return context.nil; } if (argc == 1) { proc = RubyProc.newProc(context.runtime, block, Block.Type.PROC); } else if (argc == 2) { if (args[1] instanceof RubyString) { RubyString rubyString = context.runtime.newString("proc {"); RubyString s = rubyString.catWithCodeRange(((RubyString) args[1])).cat('}'); proc = (RubyProc) evalCommon(context, recv, new IRubyObject[] { s }); } else { proc = (RubyProc) TypeConverter.convertToType(args[1], context.runtime.getProc(), "to_proc", true); } } context.runtime.getGlobalVariables().setTraceVar(var, proc); return context.nil; } @JRubyMethod(required = 1, optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject untrace_var(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { int argc = Arity.checkArgumentCount(context, args, 1, 2); String var = args[0].toString(); // ignore if it's not a global var if (var.charAt(0) != '$') { return context.nil; } if (argc > 1) { ArrayList<IRubyObject> success = new ArrayList<>(argc); for (int i = 1; i < argc; i++) { if (context.runtime.getGlobalVariables().untraceVar(var, args[i])) { success.add(args[i]); } } return RubyArray.newArray(context.runtime, success); } else { context.runtime.getGlobalVariables().untraceVar(var); } return context.nil; } @JRubyMethod(required = 1, optional = 1, checkArity = false) public static IRubyObject define_singleton_method(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { int argc = Arity.checkArgumentCount(context, args, 1, 2); RubyClass singleton_class = recv.getSingletonClass(); if (argc > 1) { IRubyObject arg1 = args[1]; if (context.runtime.getUnboundMethod().isInstance(arg1)) { RubyUnboundMethod method = (RubyUnboundMethod) arg1; RubyModule owner = (RubyModule) method.owner(context); if (owner.isSingleton() && !(recv.getMetaClass().isSingleton() && recv.getMetaClass().isKindOfModule(owner))) { throw context.runtime.newTypeError("can't bind singleton method to a different class"); } } return singleton_class.defineMethodFromCallable(context, args[0], args[1], PUBLIC); } else { return singleton_class.defineMethodFromBlock(context, args[0], block, PUBLIC); } } @JRubyMethod(name = "proc", module = true, visibility = PRIVATE) public static RubyProc proc(ThreadContext context, IRubyObject recv, Block block) { return context.runtime.newProc(Block.Type.PROC, block); } @JRubyMethod(module = true, visibility = PRIVATE) public static RubyProc lambda(ThreadContext context, IRubyObject recv, Block block) { // existing procs remain procs vs becoming lambdas. Block.Type type = block.type; if (type == Block.Type.PROC) { context.runtime.getWarnings().warnDeprecated(ID.MISCELLANEOUS, "lambda without a literal block is deprecated; use the proc without lambda instead"); } else { type = Block.Type.LAMBDA; } return context.runtime.newProc(type, block); } @Deprecated public static RubyProc proc_1_9(ThreadContext context, IRubyObject recv, Block block) { return proc(context, recv, block); } @JRubyMethod(name = "loop", module = true, visibility = PRIVATE) public static IRubyObject loop(ThreadContext context, IRubyObject recv, Block block) { if ( ! block.isGiven() ) { return enumeratorizeWithSize(context, recv, "loop", RubyKernel::loopSize); } final Ruby runtime = context.runtime; IRubyObject oldExc = runtime.getGlobalVariables().get("$!"); // Save $! try { while (true) { block.yieldSpecific(context); context.pollThreadEvents(); } } catch (RaiseException ex) { final RubyClass StopIteration = runtime.getStopIteration(); if ( StopIteration.isInstance(ex.getException()) ) { runtime.getGlobalVariables().set("$!", oldExc); // Restore $! return ex.getException().callMethod("result"); } else { throw ex; } } } /** * A loop size method suitable for lambda method reference implementation of {@link SizeFn#size(ThreadContext, IRubyObject, IRubyObject[])} * * @see SizeFn#size(ThreadContext, IRubyObject, IRubyObject[]) */ private static IRubyObject loopSize(ThreadContext context, IRubyObject self, IRubyObject[] args) { return RubyFloat.newFloat(context.runtime, RubyFloat.INFINITY); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject test(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) { return testCommon(context, recv, getTestCommand(context, arg0), arg1, null); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject test(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { return testCommon(context, recv, getTestCommand(context, arg0), arg1, arg2); } private static IRubyObject testCommon(ThreadContext context, IRubyObject recv, int cmd, IRubyObject arg1, IRubyObject arg2) { // MRI behavior: now check arg count switch (cmd) { case '-': case '=': case '<': case '>': if (arg2 == null) { throw context.runtime.newArgumentError(2, 3); } break; default: if (arg1 == null) { throw context.runtime.newArgumentError(1, 2); } break; } switch (cmd) { case 'A': // ?A | Time | Last access time for file1 return context.runtime.newFileStat(fileResource(arg1).path(), false).atime(); case 'b': // ?b | boolean | True if file1 is a block device return RubyFileTest.blockdev_p(recv, arg1); case 'c': // ?c | boolean | True if file1 is a character device return RubyFileTest.chardev_p(recv, arg1); case 'C': // ?C | Time | Last change time for file1 return context.runtime.newFileStat(fileResource(arg1).path(), false).ctime(); case 'd': // ?d | boolean | True if file1 exists and is a directory return RubyFileTest.directory_p(context, recv, arg1); case 'e': // ?e | boolean | True if file1 exists return RubyFileTest.exist_p(context, recv, arg1); case 'f': // ?f | boolean | True if file1 exists and is a regular file return RubyFileTest.file_p(context, recv, arg1); case 'g': // ?g | boolean | True if file1 has the \CF{setgid} bit return RubyFileTest.setgid_p(recv, arg1); case 'G': // ?G | boolean | True if file1 exists and has a group ownership equal to the caller's group return RubyFileTest.grpowned_p(recv, arg1); case 'k': // ?k | boolean | True if file1 exists and has the sticky bit set return RubyFileTest.sticky_p(recv, arg1); case 'M': // ?M | Time | Last modification time for file1 return context.runtime.newFileStat(fileResource(arg1).path(), false).mtime(); case 'l': // ?l | boolean | True if file1 exists and is a symbolic link return RubyFileTest.symlink_p(recv, arg1); case 'o': // ?o | boolean | True if file1 exists and is owned by the caller's effective uid return RubyFileTest.owned_p(recv, arg1); case 'O': // ?O | boolean | True if file1 exists and is owned by the caller's real uid return RubyFileTest.rowned_p(recv, arg1); case 'p': // ?p | boolean | True if file1 exists and is a fifo return RubyFileTest.pipe_p(recv, arg1); case 'r': // ?r | boolean | True if file1 is readable by the effective uid/gid of the caller return RubyFileTest.readable_p(context, recv, arg1); case 'R': // ?R | boolean | True if file is readable by the real uid/gid of the caller return RubyFileTest.readable_p(context, recv, arg1); case 's': // ?s | int/nil | If file1 has nonzero size, return the size, otherwise nil return RubyFileTest.size_p(context, recv, arg1); case 'S': // ?S | boolean | True if file1 exists and is a socket return RubyFileTest.socket_p(recv, arg1); case 'u': // ?u | boolean | True if file1 has the setuid bit set return RubyFileTest.setuid_p(recv, arg1); case 'w': // ?w | boolean | True if file1 exists and is writable by effective uid/gid return RubyFileTest.writable_p(recv, arg1); case 'W': // ?W | boolean | True if file1 exists and is writable by the real uid/gid // FIXME: Need to implement an writable_real_p in FileTest return RubyFileTest.writable_p(recv, arg1); case 'x': // ?x | boolean | True if file1 exists and is executable by the effective uid/gid return RubyFileTest.executable_p(recv, arg1); case 'X': // ?X | boolean | True if file1 exists and is executable by the real uid/gid return RubyFileTest.executable_real_p(recv, arg1); case 'z': // ?z | boolean | True if file1 exists and has a zero length return RubyFileTest.zero_p(context, recv, arg1); case '=': // ?= | boolean | True if the modification times of file1 and file2 are equal return context.runtime.newFileStat(arg1.convertToString().toString(), false).mtimeEquals(arg2); case '<': // ?< | boolean | True if the modification time of file1 is prior to that of file2 return context.runtime.newFileStat(arg1.convertToString().toString(), false).mtimeLessThan(arg2); case '>': // ?> | boolean | True if the modification time of file1 is after that of file2 return context.runtime.newFileStat(arg1.convertToString().toString(), false).mtimeGreaterThan(arg2); case '-': // ?- | boolean | True if file1 and file2 are identical return RubyFileTest.identical_p(context, recv, arg1, arg2); default: throw new InternalError("unreachable code reached!"); } } private static int getTestCommand(ThreadContext context, IRubyObject arg0) { int cmd; if (arg0 instanceof RubyFixnum) { cmd = (int)((RubyFixnum) arg0).getLongValue(); } else if (arg0 instanceof RubyString && ((RubyString) arg0).getByteList().length() > 0) { // MRI behavior: use first byte of string value if len > 0 cmd = ((RubyString) arg0).getByteList().charAt(0); } else { cmd = (int) arg0.convertToInteger().getLongValue(); } // MRI behavior: raise ArgumentError for 'unknown command' before checking number of args switch(cmd) { case 'A': case 'b': case 'c': case 'C': case 'd': case 'e': case 'f': case 'g': case 'G': case 'k': case 'M': case 'l': case 'o': case 'O': case 'p': case 'r': case 'R': case 's': case 'S': case 'u': case 'w': case 'W': case 'x': case 'X': case 'z': case '=': case '<': case '>': case '-': break; default: throw context.runtime.newArgumentError("unknown command ?" + (char) cmd); } return cmd; } @JRubyMethod(name = "`", module = true, visibility = PRIVATE) public static IRubyObject backquote(ThreadContext context, IRubyObject recv, IRubyObject str) { Ruby runtime = context.runtime; if (PopenExecutor.nativePopenAvailable(runtime)) { IRubyObject port; IRubyObject result; OpenFile fptr; str = str.convertToString(); context.setLastExitStatus(context.nil); port = PopenExecutor.pipeOpen(context, str, "r", OpenFile.READABLE|OpenFile.TEXTMODE, null); if (port.isNil()) return RubyString.newEmptyString(runtime); fptr = ((RubyIO)port).getOpenFileChecked(); result = fptr.readAll(context, fptr.remainSize(), context.nil); ((RubyIO)port).rbIoClose(context); return result; } IRubyObject[] args = new IRubyObject[] { str.convertToString() }; ByteArrayOutputStream output = new ByteArrayOutputStream(); long[] tuple; try { // NOTE: not searching executable path before invoking args tuple = ShellLauncher.runAndWaitPid(runtime, args, output, false); } catch (Exception e) { tuple = new long[] {127, -1}; } // RubyStatus uses real native status now, so we unshift Java's shifted exit status context.setLastExitStatus(RubyProcess.RubyStatus.newProcessStatus(runtime, tuple[0] << 8, tuple[1])); byte[] out = output.toByteArray(); int length = out.length; if (Platform.IS_WINDOWS) { // MRI behavior, replace '\r\n' by '\n' int newPos = 0; byte curr, next; for (int pos = 0; pos < length; pos++) { curr = out[pos]; if (pos == length - 1) { out[newPos++] = curr; break; } next = out[pos + 1]; if (curr != '\r' || next != '\n') { out[newPos++] = curr; } } // trim the length length = newPos; } ByteList buf = new ByteList(out, 0, length, runtime.getDefaultExternalEncoding(), false); return RubyString.newString(runtime, buf); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject srand(ThreadContext context, IRubyObject recv) { return RubyRandom.srandCommon(context, recv); } @JRubyMethod(module = true, visibility = PRIVATE) public static IRubyObject srand(ThreadContext context, IRubyObject recv, IRubyObject arg) { return RubyRandom.srandCommon(context, recv, arg); } @JRubyMethod(name = "rand", module = true, visibility = PRIVATE) public static IRubyObject rand(ThreadContext context, IRubyObject recv) { return RubyRandom.randFloat(context); } @JRubyMethod(name = "rand", module = true, visibility = PRIVATE) public static IRubyObject rand(ThreadContext context, IRubyObject recv, IRubyObject arg) { return RubyRandom.randKernel(context, recv, arg); } @JRubyMethod(rest = true, module = true, visibility = PRIVATE) public static RubyFixnum spawn(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return RubyProcess.spawn(context, recv, args); } @JRubyMethod(required = 1, optional = 9, checkArity = false, module = true, notImplemented = true, visibility = PRIVATE) public static IRubyObject syscall(ThreadContext context, IRubyObject recv, IRubyObject[] args) { throw context.runtime.newNotImplementedError("Kernel#syscall is not implemented in JRuby"); } @JRubyMethod(name = "system", required = 1, rest = true, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject system(ThreadContext context, IRubyObject recv, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 1, -1); final Ruby runtime = context.runtime; boolean needChdir = !runtime.getCurrentDirectory().equals(runtime.getPosix().getcwd()); if (PopenExecutor.nativePopenAvailable(runtime)) { // MRI: rb_f_system long pid; int status; // #if defined(SIGCLD) && !defined(SIGCHLD) // # define SIGCHLD SIGCLD // #endif // // #ifdef SIGCHLD // RETSIGTYPE (*chfunc)(int); context.setLastExitStatus(context.nil); // chfunc = signal(SIGCHLD, SIG_DFL); // #endif PopenExecutor executor = new PopenExecutor(); return executor.systemInternal(context, args, null); } int resultCode = systemCommon(context, recv, args); switch (resultCode) { case 0: return runtime.getTrue(); case 127: return runtime.getNil(); default: return runtime.getFalse(); } } @Deprecated public static IRubyObject system19(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return system(context, recv, args); } private static int systemCommon(ThreadContext context, IRubyObject recv, IRubyObject[] args) { Ruby runtime = context.runtime; long[] tuple; try { args = dropLastArgIfOptions(runtime, args); if (! Platform.IS_WINDOWS && args[args.length -1].asJavaString().matches(".*[^&]&\\s*")) { // looks like we need to send process to the background ShellLauncher.runWithoutWait(runtime, args); return 0; } tuple = ShellLauncher.runAndWaitPid(runtime, args); } catch (Exception e) { tuple = new long[] {127, -1}; } // RubyStatus uses real native status now, so we unshift Java's shifted exit status context.setLastExitStatus(RubyProcess.RubyStatus.newProcessStatus(runtime, tuple[0] << 8, tuple[1])); return (int) tuple[0]; } private static IRubyObject[] dropLastArgIfOptions(final Ruby runtime, final IRubyObject[] args) { IRubyObject lastArg = args[args.length - 1]; if (lastArg instanceof RubyHash) { if (!((RubyHash) lastArg).isEmpty()) { runtime.getWarnings().warn(ID.UNSUPPORTED_SUBPROCESS_OPTION, "system does not support options in JRuby yet: " + lastArg); } return Arrays.copyOf(args, args.length - 1); } return args; } public static IRubyObject exec(ThreadContext context, IRubyObject recv, IRubyObject[] args) { return execCommon(context, null, args[0], null, args); } /* Actual exec definition which calls this internal version is specified * in /core/src/main/ruby/jruby/kernel/kernel.rb. */ @JRubyMethod(required = 4, visibility = PRIVATE) public static IRubyObject _exec_internal(ThreadContext context, IRubyObject recv, IRubyObject[] args) { IRubyObject env = args[0]; IRubyObject prog = args[1]; IRubyObject options = args[2]; RubyArray cmdArgs = (RubyArray) args[3]; if (options instanceof RubyHash) checkExecOptions(context, (RubyHash) options); return execCommon(context, env, prog, options, cmdArgs.toJavaArray()); } static void checkExecOptions(ThreadContext context, RubyHash opts) { checkValidSpawnOptions(context, opts); checkUnsupportedOptions(context, opts, UNSUPPORTED_SPAWN_OPTIONS, "unsupported exec option"); } private static IRubyObject execCommon(ThreadContext context, IRubyObject env, IRubyObject prog, IRubyObject options, IRubyObject[] args) { final Ruby runtime = context.runtime; // This is a fairly specific hack for empty string, but it does the job if (args.length == 1) { RubyString command = args[0].convertToString(); if (command.isEmpty()) { throw runtime.newErrnoENOENTError(command.toString()); } else { for(byte b : command.getBytes()) { if (b == 0x00) { throw runtime.newArgumentError("string contains null byte"); } } } } if (env != null && env != context.nil) { RubyHash envMap = env.convertToHash(); if (envMap != null) { runtime.getENV().merge_bang(context, new IRubyObject[]{envMap}, Block.NULL_BLOCK); } } boolean nativeFailed = false; boolean nativeExec = Options.NATIVE_EXEC.load(); boolean jmxStopped = false; System.setProperty("user.dir", runtime.getCurrentDirectory()); if (nativeExec) { IRubyObject oldExc = runtime.getGlobalVariables().get("$!"); // Save $! try { ShellLauncher.LaunchConfig cfg = new ShellLauncher.LaunchConfig(runtime, args, true); // Duplicated in part from ShellLauncher.runExternalAndWait if (cfg.shouldRunInShell()) { // execute command with sh -c // this does shell expansion of wildcards cfg.verifyExecutableForShell(); } else { cfg.verifyExecutableForDirect(); } String progStr = cfg.getExecArgs()[0]; String[] argv = cfg.getExecArgs(); // attempt to shut down the JMX server jmxStopped = runtime.getBeanManager().tryShutdownAgent(); final POSIX posix = runtime.getPosix(); posix.chdir(System.getProperty("user.dir")); if (Platform.IS_WINDOWS) { // Windows exec logic is much more elaborate; exec() in jnr-posix attempts to duplicate it posix.exec(progStr, argv); } else { // TODO: other logic surrounding this call? In jnr-posix? @SuppressWarnings("unchecked") final Map<String, String> ENV = (Map<String, String>) runtime.getENV(); ArrayList<String> envStrings = new ArrayList<>(ENV.size() + 1); for ( Map.Entry<String, String> envEntry : ENV.entrySet() ) { envStrings.add( envEntry.getKey() + '=' + envEntry.getValue() ); } envStrings.add(null); int status = posix.execve(progStr, argv, envStrings.toArray(new String[envStrings.size()])); if (Platform.IS_WSL && status == -1) { // work-around a bug in Windows Subsystem for Linux if (posix.errno() == Errno.ENOMEM.intValue()) { posix.exec(progStr, argv); } } } // Only here because native exec could not exec (always -1) nativeFailed = true; } catch (RaiseException e) { runtime.getGlobalVariables().set("$!", oldExc); // Restore $! } catch (Exception e) { throw runtime.newErrnoENOENTError("cannot execute: " + e.getLocalizedMessage()); } } // if we get here, either native exec failed or we should try an in-process exec if (nativeFailed) { if (jmxStopped && runtime.getBeanManager().tryRestartAgent()) { runtime.registerMBeans(); } throw runtime.newErrnoFromLastPOSIXErrno(); } // Fall back onto our existing code if native not available // FIXME: Make jnr-posix Pure-Java backend do this as well int resultCode = ShellLauncher.execAndWait(runtime, args); exit(runtime, new IRubyObject[] {runtime.newFixnum(resultCode)}, true); // not reached return runtime.getNil(); } @JRubyMethod(name = "fork", module = true, visibility = PRIVATE, notImplemented = true) public static IRubyObject fork(ThreadContext context, IRubyObject recv, Block block) { Ruby runtime = context.runtime; throw runtime.newNotImplementedError("fork is not available on this platform"); } @Deprecated public static IRubyObject fork19(ThreadContext context, IRubyObject recv, Block block) { return fork(context, recv, block); } @JRubyMethod(name = {"to_enum", "enum_for"}, rest = true, keywords = true) public static IRubyObject obj_to_enum(final ThreadContext context, IRubyObject self, IRubyObject[] args, final Block block) { // to_enum is a bit strange in that it will propagate the arguments it passes to each element it calls. We are determining // whether we have received keywords so we can propagate this info. int callInfo = context.callInfo; String method = "each"; SizeFn sizeFn = null; if (args.length > 0) { method = RubySymbol.retrieveIDSymbol(args[0]).asJavaString(); args = Arrays.copyOfRange(args, 1, args.length); } if (block.isGiven()) { sizeFn = (ctx, recv, args1) -> { ctx.callInfo = callInfo; return block.yieldValues(ctx, args1); }; } boolean keywords = (callInfo & ThreadContext.CALL_KEYWORD) != 0 && (callInfo & ThreadContext.CALL_KEYWORD_EMPTY) == 0; ThreadContext.resetCallInfo(context); return enumeratorizeWithSize(context, self, method, args, sizeFn, keywords); } @JRubyMethod(name = { "__method__" }, module = true, visibility = PRIVATE, reads = METHODNAME, omit = true) public static IRubyObject __method__(ThreadContext context, IRubyObject recv) { String frameName = context.getFrameName(); if (frameName == null || frameName == Ruby.ROOT_FRAME_NAME) { return context.nil; } return context.runtime.newSymbol(frameName); } @JRubyMethod(name = { "__callee__" }, module = true, visibility = PRIVATE, reads = METHODNAME, omit = true) public static IRubyObject __callee__(ThreadContext context, IRubyObject recv) { String frameName = context.getCalleeName(); if (frameName == null || frameName == Ruby.ROOT_FRAME_NAME) { return context.nil; } return context.runtime.newSymbol(frameName); } @JRubyMethod(name = "__dir__", module = true, visibility = PRIVATE, reads = FILENAME) public static IRubyObject __dir__(ThreadContext context, IRubyObject recv) { Ruby runtime = context.runtime; // NOTE: not using __FILE__ = context.getFile() since it won't work with JIT String __FILE__ = context.getSingleBacktrace().getFileName(); __FILE__ = runtime.getLoadService().getPathForLocation(__FILE__); RubyString path = RubyFile.expandPathInternal(context, RubyString.newString(runtime, __FILE__), null, false, true); return RubyString.newString(runtime, RubyFile.dirname(context, path.asJavaString())); } @JRubyMethod(module = true) public static IRubyObject singleton_class(IRubyObject recv) { return recv.getSingletonClass(); } @JRubyMethod(rest = true, keywords = true, reads = SCOPE) public static IRubyObject public_send(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { if (args.length == 0) { throw context.runtime.newArgumentError("no method name given"); } String name = RubySymbol.checkID(args[0]); if (args.length > 1) { args[args.length - 1] = dupIfKeywordRestAtCallsite(context, args[args.length - 1]); } final int length = args.length - 1; args = ( length == 0 ) ? IRubyObject.NULL_ARRAY : ArraySupport.newCopy(args, 1, length); final RubyClass klass = RubyBasicObject.getMetaClass(recv); CacheEntry entry = klass.searchWithRefinements(name, context.getCurrentStaticScope()); DynamicMethod method = entry.method; if (method.isUndefined() || method.getVisibility() != PUBLIC) { return Helpers.callMethodMissing(context, recv, klass, method.getVisibility(), name, CallType.NORMAL, args, block); } return method.call(context, recv, entry.sourceModule, name, args, block); } /* * Moved binding of these methods here, since Kernel can be included into * BasicObject subclasses, and these methods must still work. * See JRUBY-4871 (because of RubyObject instead of RubyBasicObject cast) * BEGIN delegated bindings: */ @JRubyMethod(name = "eql?") public static IRubyObject eql_p(IRubyObject self, IRubyObject obj) { return ((RubyBasicObject)self).eql_p(obj); } @JRubyMethod(name = "===") public static IRubyObject op_eqq(ThreadContext context, IRubyObject self, IRubyObject other) { return ((RubyBasicObject) self).op_eqq(context, other); } @JRubyMethod(name = "<=>") public static IRubyObject op_cmp(ThreadContext context, IRubyObject self, IRubyObject other) { return ((RubyBasicObject) self).op_cmp(context, other); } @JRubyMethod(name = "initialize_copy", required = 1, visibility = PRIVATE) public static IRubyObject initialize_copy(IRubyObject self, IRubyObject original) { return ((RubyBasicObject) self).initialize_copy(original); } // Replaced in jruby/kernel/kernel.rb with Ruby for better caching @JRubyMethod(name = "initialize_clone", required = 1, visibility = Visibility.PRIVATE) public static IRubyObject initialize_clone(ThreadContext context, IRubyObject self, IRubyObject original) { return sites(context).initialize_copy.call(context, self, self, original); } // Replaced in jruby/kernel/kernel.rb with Ruby for better caching @JRubyMethod(name = "initialize_dup", required = 1, visibility = Visibility.PRIVATE) public static IRubyObject initialize_dup(ThreadContext context, IRubyObject self, IRubyObject original) { return sites(context).initialize_copy.call(context, self, self, original); } @Deprecated public static RubyBoolean respond_to_p(IRubyObject self, IRubyObject mname) { return ((RubyBasicObject) self).respond_to_p(mname); } @Deprecated public static IRubyObject respond_to_p19(IRubyObject self, IRubyObject mname) { return ((RubyBasicObject) self).respond_to_p19(mname); } @Deprecated public static RubyBoolean respond_to_p(IRubyObject self, IRubyObject mname, IRubyObject includePrivate) { return ((RubyBasicObject) self).respond_to_p(mname, includePrivate); } @Deprecated public static IRubyObject respond_to_p19(IRubyObject self, IRubyObject mname, IRubyObject includePrivate) { return ((RubyBasicObject) self).respond_to_p19(mname, includePrivate); } @JRubyMethod(name = "respond_to?") public static IRubyObject respond_to_p(ThreadContext context, IRubyObject self, IRubyObject name) { return ((RubyBasicObject) self).respond_to_p(context, name, false); } @JRubyMethod(name = "respond_to?") public static IRubyObject respond_to_p(ThreadContext context, IRubyObject self, IRubyObject name, IRubyObject includePrivate) { return ((RubyBasicObject) self).respond_to_p(context, name, includePrivate.isTrue()); } @JRubyMethod public static RubyFixnum hash(IRubyObject self) { return ((RubyBasicObject)self).hash(); } @JRubyMethod(name = "class") public static RubyClass type(IRubyObject self) { return ((RubyBasicObject)self).type(); } @JRubyMethod(name = "clone") public static IRubyObject rbClone(ThreadContext context, IRubyObject self) { return self.rbClone(); } @JRubyMethod(name = "clone") public static IRubyObject rbClone(ThreadContext context, IRubyObject self, IRubyObject opts) { return ((RubyBasicObject) self).rbClone(context, opts); } @JRubyMethod public static IRubyObject dup(IRubyObject self) { return ((RubyBasicObject)self).dup(); } @JRubyMethod(optional = 1, checkArity = false) public static IRubyObject display(ThreadContext context, IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); return ((RubyBasicObject)self).display(context, args); } @JRubyMethod public static IRubyObject freeze(ThreadContext context, IRubyObject self) { return ((RubyBasicObject)self).freeze(context); } @JRubyMethod(name = "frozen?") public static RubyBoolean frozen_p(ThreadContext context, IRubyObject self) { return ((RubyBasicObject)self).frozen_p(context); } @JRubyMethod(name = "inspect") public static IRubyObject inspect(IRubyObject self) { return ((RubyBasicObject)self).inspect(); } @JRubyMethod(name = "instance_of?") public static RubyBoolean instance_of_p(ThreadContext context, IRubyObject self, IRubyObject type) { return ((RubyBasicObject)self).instance_of_p(context, type); } @JRubyMethod(name = "itself") public static IRubyObject itself(IRubyObject self) { return self; } @JRubyMethod(name = {"kind_of?", "is_a?"}) public static RubyBoolean kind_of_p(ThreadContext context, IRubyObject self, IRubyObject type) { return ((RubyBasicObject)self).kind_of_p(context, type); } @JRubyMethod(name = "methods", optional = 1, checkArity = false) public static IRubyObject methods(ThreadContext context, IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); return ((RubyBasicObject)self).methods(context, args); } @Deprecated public static IRubyObject methods19(ThreadContext context, IRubyObject self, IRubyObject[] args) { return ((RubyBasicObject)self).methods(context, args); } @JRubyMethod(name = "object_id") public static IRubyObject object_id(IRubyObject self) { return self.id(); } @JRubyMethod(name = "public_methods", optional = 1, checkArity = false) public static IRubyObject public_methods(ThreadContext context, IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); return ((RubyBasicObject)self).public_methods(context, args); } @Deprecated public static IRubyObject public_methods19(ThreadContext context, IRubyObject self, IRubyObject[] args) { return ((RubyBasicObject)self).public_methods(context, args); } @JRubyMethod(name = "protected_methods", optional = 1, checkArity = false) public static IRubyObject protected_methods(ThreadContext context, IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); return ((RubyBasicObject)self).protected_methods(context, args); } @Deprecated public static IRubyObject protected_methods19(ThreadContext context, IRubyObject self, IRubyObject[] args) { return ((RubyBasicObject)self).protected_methods(context, args); } @JRubyMethod(name = "private_methods", optional = 1, checkArity = false) public static IRubyObject private_methods(ThreadContext context, IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); return ((RubyBasicObject)self).private_methods(context, args); } @Deprecated public static IRubyObject private_methods19(ThreadContext context, IRubyObject self, IRubyObject[] args) { return ((RubyBasicObject)self).private_methods(context, args); } @JRubyMethod(name = "singleton_methods", optional = 1, checkArity = false) public static RubyArray singleton_methods(ThreadContext context, IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); return ((RubyBasicObject)self).singleton_methods(context, args); } @Deprecated public static RubyArray singleton_methods19(ThreadContext context, IRubyObject self, IRubyObject[] args) { return ((RubyBasicObject)self).singleton_methods(context, args); } @JRubyMethod(name = "singleton_method") public static IRubyObject singleton_method(IRubyObject self, IRubyObject symbol) { return ((RubyBasicObject)self).singleton_method(symbol); } @JRubyMethod(name = "method", required = 1, reads = SCOPE) public static IRubyObject method(ThreadContext context, IRubyObject self, IRubyObject symbol) { return ((RubyBasicObject)self).method(symbol, context.getCurrentStaticScope()); } @JRubyMethod(name = "to_s") public static IRubyObject to_s(IRubyObject self) { return ((RubyBasicObject)self).to_s(); } @JRubyMethod(name = "extend", required = 1, rest = true, checkArity = false) public static IRubyObject extend(IRubyObject self, IRubyObject[] args) { Arity.checkArgumentCount(self.getRuntime(), args, 1, -1); return ((RubyBasicObject)self).extend(args); } @JRubyMethod(name = "send", omit = true, keywords = true) public static IRubyObject send(ThreadContext context, IRubyObject self, IRubyObject arg0, Block block) { return ((RubyBasicObject)self).send(context, arg0, block); } @JRubyMethod(name = "send", omit = true, keywords = true) public static IRubyObject send(ThreadContext context, IRubyObject self, IRubyObject arg0, IRubyObject arg1, Block block) { return ((RubyBasicObject)self).send(context, arg0, arg1, block); } @JRubyMethod(name = "send", omit = true, keywords = true) public static IRubyObject send(ThreadContext context, IRubyObject self, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return ((RubyBasicObject)self).send(context, arg0, arg1, arg2, block); } @JRubyMethod(name = "send", required = 1, rest = true, checkArity = false, omit = true, keywords = true) public static IRubyObject send(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) { Arity.checkArgumentCount(context, args, 1, -1); return ((RubyBasicObject)self).send(context, args, block); } @Deprecated public static IRubyObject send19(ThreadContext context, IRubyObject self, IRubyObject arg0, Block block) { return send(context, self, arg0, block); } @Deprecated public static IRubyObject send19(ThreadContext context, IRubyObject self, IRubyObject arg0, IRubyObject arg1, Block block) { return send(context, self, arg0, arg1, block); } @Deprecated public static IRubyObject send19(ThreadContext context, IRubyObject self, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return send(context, self, arg0, arg1, arg2, block); } @Deprecated public static IRubyObject send19(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) { return send(context, self, args, block); } @JRubyMethod(name = "nil?") public static IRubyObject nil_p(ThreadContext context, IRubyObject self) { return ((RubyBasicObject) self).nil_p(context); } // Writes backref due to decendant calls ending up in Regexp#=~ @JRubyMethod(name = "=~", writes = FrameField.BACKREF) public static IRubyObject op_match(ThreadContext context, IRubyObject self, IRubyObject arg) { context.runtime.getWarnings().warnDeprecated(ID.DEPRECATED_METHOD, "deprecated Object#=~ is called on " + ((RubyBasicObject) self).type() + "; it always returns nil"); return ((RubyBasicObject) self).op_match(context, arg); } // Writes backref due to decendant calls ending up in Regexp#=~ @JRubyMethod(name = "!~", writes = FrameField.BACKREF) public static IRubyObject op_not_match(ThreadContext context, IRubyObject self, IRubyObject arg) { return ((RubyBasicObject) self).op_not_match(context, arg); } @JRubyMethod(name = "instance_variable_defined?") public static IRubyObject instance_variable_defined_p(ThreadContext context, IRubyObject self, IRubyObject name) { return ((RubyBasicObject)self).instance_variable_defined_p(context, name); } @JRubyMethod(name = "instance_variable_get") public static IRubyObject instance_variable_get(ThreadContext context, IRubyObject self, IRubyObject name) { return ((RubyBasicObject)self).instance_variable_get(context, name); } @JRubyMethod(name = "instance_variable_set") public static IRubyObject instance_variable_set(IRubyObject self, IRubyObject name, IRubyObject value) { return ((RubyBasicObject)self).instance_variable_set(name, value); } @JRubyMethod(name = "remove_instance_variable") public static IRubyObject remove_instance_variable(ThreadContext context, IRubyObject self, IRubyObject name, Block block) { return ((RubyBasicObject) self).remove_instance_variable(context, name, block); } @JRubyMethod(name = "instance_variables") public static RubyArray instance_variables(ThreadContext context, IRubyObject self) { return ((RubyBasicObject) self).instance_variables(context); } @Deprecated public static RubyArray instance_variables19(ThreadContext context, IRubyObject self) { return instance_variables(context, self); } /* end delegated bindings */ public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) { RubyString str = (RubyString) getLastlineString(context, context.runtime).dup(); if (!str.gsub_bang(context, arg0, block).isNil()) { context.setLastLine(str); } return str; } public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) { RubyString str = (RubyString) getLastlineString(context, context.runtime).dup(); if (!str.gsub_bang(context, arg0, arg1, block).isNil()) { context.setLastLine(str); } return str; } public static IRubyObject rbClone(IRubyObject self) { return rbClone(self.getRuntime().getCurrentContext(), self); } public static class LoopMethods { @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) { return context.setLastLine(getLastlineString(context, context.runtime).gsub(context, arg0, block)); } @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) { return context.setLastLine(getLastlineString(context, context.runtime).gsub(context, arg0, arg1, block)); } @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) { return context.setLastLine(getLastlineString(context, context.runtime).sub(context, arg0, block)); } @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) { return context.setLastLine(getLastlineString(context, context.runtime).sub(context, arg0, arg1, block)); } @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject chop(ThreadContext context, IRubyObject recv) { return context.setLastLine(getLastlineString(context, context.runtime).chop(context)); } @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject chomp(ThreadContext context, IRubyObject recv) { return context.setLastLine(getLastlineString(context, context.runtime).chomp(context)); } @JRubyMethod(module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE) public static IRubyObject chomp(ThreadContext context, IRubyObject recv, IRubyObject arg0) { return context.setLastLine(getLastlineString(context, context.runtime).chomp(context, arg0)); } } private static KernelSites sites(ThreadContext context) { return context.sites.Kernel; } @Deprecated public static IRubyObject methodMissing(ThreadContext context, IRubyObject recv, String name, Visibility lastVis, CallType lastCallType, IRubyObject[] args, Block block) { return methodMissing(context, recv, name, lastVis, lastCallType, args); } @Deprecated public static IRubyObject caller20(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { return caller(context, recv, args, block); } @Deprecated public static IRubyObject caller19(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { return caller(context, recv, args, block); } @Deprecated private static IRubyObject caller(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { switch (args.length) { case 0: return caller(context, recv); case 1: return caller(context, recv, args[0]); case 2: return caller(context, recv, args[0], args[1]); default: Arity.checkArgumentCount(context.runtime, args, 0, 2); return null; // not reached } } @Deprecated public static IRubyObject caller_locations(ThreadContext context, IRubyObject recv, IRubyObject[] args) { switch (args.length) { case 0: return caller_locations(context, recv); case 1: return caller_locations(context, recv, args[0]); case 2: return caller_locations(context, recv, args[0], args[1]); default: Arity.checkArgumentCount(context.runtime, args, 0, 2); return null; // not reached } } @Deprecated public static IRubyObject require(IRubyObject recv, IRubyObject name, Block block) { return require(recv.getRuntime().getCurrentContext(), recv, name, block); } @Deprecated public static IRubyObject require19(ThreadContext context, IRubyObject recv, IRubyObject name, Block block) { return require(context, recv, name, block); } @Deprecated public static IRubyObject op_match19(ThreadContext context, IRubyObject self, IRubyObject arg) { return op_match(context, self, arg); } @Deprecated public static IRubyObject new_integer19(ThreadContext context, IRubyObject recv, IRubyObject object) { return new_integer(context, recv, object); } @Deprecated public static RubyFloat new_float19(IRubyObject recv, IRubyObject object) { return new_float(recv, object); } @Deprecated public static IRubyObject autoload(final IRubyObject recv, IRubyObject symbol, IRubyObject file) { return autoload(recv.getRuntime().getCurrentContext(), recv, symbol, file); } @Deprecated public static IRubyObject rand18(ThreadContext context, IRubyObject recv, IRubyObject[] arg) { return rand(context, recv, arg); } @Deprecated public static IRubyObject rand19(ThreadContext context, IRubyObject recv, IRubyObject[] arg) { return rand(context, recv, arg); } @Deprecated public static IRubyObject rand(ThreadContext context, IRubyObject recv, IRubyObject[] args) { switch (args.length) { case 0: return RubyRandom.randFloat(context); case 1: return RubyRandom.randKernel(context, recv, args[0]); default: throw context.runtime.newArgumentError(args.length, 0, 1); } } @Deprecated @JRubyMethod(name = "tainted?") public static RubyBoolean tainted_p(ThreadContext context, IRubyObject self) { context.runtime.getWarnings().warnDeprecatedForRemoval("Object#tainted?", "3.2"); return context.fals; } @Deprecated @JRubyMethod(name = "taint") public static IRubyObject taint(ThreadContext context, IRubyObject self) { context.runtime.getWarnings().warnDeprecatedForRemoval("Object#taint", "3.2"); return self; } @Deprecated @JRubyMethod(name = "untaint") public static IRubyObject untaint(ThreadContext context, IRubyObject self) { context.runtime.getWarnings().warnDeprecatedForRemoval("Object#untaint", "3.2"); return self; } @Deprecated @JRubyMethod(name = "untrusted?") public static RubyBoolean untrusted_p(ThreadContext context, IRubyObject self) { context.runtime.getWarnings().warnDeprecatedForRemoval("Object#untrusted?", "3.2"); return context.fals; } @Deprecated @JRubyMethod(name = "untrust") public static IRubyObject untrust(ThreadContext context, IRubyObject self) { context.runtime.getWarnings().warnDeprecatedForRemoval("Object#untrust", "3.2"); return self; } @Deprecated @JRubyMethod(name = "trust") public static IRubyObject trust(ThreadContext context, IRubyObject self) { context.runtime.getWarnings().warnDeprecatedForRemoval("Object#trust", "3.2"); return self; } @Deprecated public static IRubyObject method(IRubyObject self, IRubyObject symbol) { return ((RubyBasicObject)self).method(symbol); } @Deprecated public static IRubyObject method19(IRubyObject self, IRubyObject symbol) { return method(self, symbol); } // defined in Ruby now but left here for backward compat @Deprecated public static IRubyObject tap(ThreadContext context, IRubyObject recv, Block block) { if (block.getProcObject() != null) { block.getProcObject().call(context, recv); } else { block.yield(context, recv); } return recv; } @Deprecated public static IRubyObject sleep(ThreadContext context, IRubyObject recv, IRubyObject[] args) { switch (args.length) { case 0: return sleep(context, recv); case 1: return sleep(context, recv, args[0]); default: throw context.runtime.newArgumentError(args.length, 0, 1); } } @Deprecated public static IRubyObject test(ThreadContext context, IRubyObject recv, IRubyObject[] args) { switch (args.length) { case 2: return test(context, recv, args[0], args[1]); case 3: return test(context, recv, args[0], args[1], args[2]); default: throw context.runtime.newArgumentError(args.length, 2, 3); } } }
jruby/jruby
core/src/main/java/org/jruby/RubyKernel.java
2,386
/* * 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.druid.segment.data; import com.google.common.primitives.Ints; import org.apache.druid.common.utils.ByteUtils; import org.apache.druid.io.Channels; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.io.smoosh.FileSmoosher; import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector; import org.apache.druid.segment.serde.MetaSerdeHelper; import org.apache.druid.segment.writeout.HeapByteBufferWriteOutBytes; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.Iterator; /** */ public class VSizeColumnarMultiInts implements ColumnarMultiInts, WritableSupplier<ColumnarMultiInts> { private static final byte VERSION = 0x1; private static final MetaSerdeHelper<VSizeColumnarMultiInts> META_SERDE_HELPER = MetaSerdeHelper .firstWriteByte((VSizeColumnarMultiInts x) -> VERSION) .writeByte(x -> ByteUtils.checkedCast(x.numBytes)) .writeInt(x -> Ints.checkedCast(x.theBuffer.remaining() + (long) Integer.BYTES)) .writeInt(x -> x.size); public static VSizeColumnarMultiInts fromIterable(Iterable<VSizeColumnarInts> objectsIterable) { Iterator<VSizeColumnarInts> objects = objectsIterable.iterator(); if (!objects.hasNext()) { final ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES).putInt(0, 0); return new VSizeColumnarMultiInts(buffer, Integer.BYTES); } int numBytes = -1; int count = 0; while (objects.hasNext()) { VSizeColumnarInts next = objects.next(); if (numBytes == -1) { numBytes = next.getNumBytes(); } ++count; } HeapByteBufferWriteOutBytes headerBytes = new HeapByteBufferWriteOutBytes(); HeapByteBufferWriteOutBytes valueBytes = new HeapByteBufferWriteOutBytes(); int offset = 0; headerBytes.writeInt(count); for (VSizeColumnarInts object : objectsIterable) { if (object.getNumBytes() != numBytes) { throw new ISE("val.numBytes[%s] != numBytesInValue[%s]", object.getNumBytes(), numBytes); } offset += object.getNumBytesNoPadding(); headerBytes.writeInt(offset); object.writeBytesNoPaddingTo(valueBytes); } valueBytes.write(new byte[Integer.BYTES - numBytes]); ByteBuffer theBuffer = ByteBuffer.allocate(Ints.checkedCast(headerBytes.size() + valueBytes.size())); headerBytes.writeTo(theBuffer); valueBytes.writeTo(theBuffer); theBuffer.flip(); return new VSizeColumnarMultiInts(theBuffer.asReadOnlyBuffer(), numBytes); } private final ByteBuffer theBuffer; private final int numBytes; private final int size; private final int valuesOffset; private final int bufferBytes; VSizeColumnarMultiInts( ByteBuffer buffer, int numBytes ) { this.theBuffer = buffer; this.numBytes = numBytes; size = theBuffer.getInt(); valuesOffset = theBuffer.position() + (size << 2); bufferBytes = 4 - numBytes; } @Override public int size() { return size; } @Override public VSizeColumnarInts get(int index) { if (index >= size) { throw new IAE("Index[%d] >= size[%d]", index, size); } ByteBuffer myBuffer = theBuffer.asReadOnlyBuffer(); int startOffset = 0; int endOffset; if (index == 0) { endOffset = myBuffer.getInt(); } else { myBuffer.position(myBuffer.position() + ((index - 1) * Integer.BYTES)); startOffset = myBuffer.getInt(); endOffset = myBuffer.getInt(); } myBuffer.position(valuesOffset + startOffset); myBuffer.limit(myBuffer.position() + (endOffset - startOffset) + bufferBytes); return myBuffer.hasRemaining() ? new VSizeColumnarInts(myBuffer, numBytes) : null; } @Override public IndexedInts getUnshared(final int index) { return get(index); } @Override public int indexOf(IndexedInts value) { throw new UnsupportedOperationException("Reverse lookup not allowed."); } @Override public long getSerializedSize() { return META_SERDE_HELPER.size(this) + (long) theBuffer.remaining(); } @Override public void writeTo(WritableByteChannel channel, FileSmoosher smoosher) throws IOException { META_SERDE_HELPER.writeTo(channel, this); Channels.writeFully(channel, theBuffer.asReadOnlyBuffer()); } @Override public ColumnarMultiInts get() { return this; } public static VSizeColumnarMultiInts readFromByteBuffer(ByteBuffer buffer) { byte versionFromBuffer = buffer.get(); if (VERSION == versionFromBuffer) { int numBytes = buffer.get(); int size = buffer.getInt(); ByteBuffer bufferToUse = buffer.asReadOnlyBuffer(); bufferToUse.limit(bufferToUse.position() + size); buffer.position(bufferToUse.limit()); return new VSizeColumnarMultiInts(bufferToUse, numBytes); } throw new IAE("Unknown version[%s]", versionFromBuffer); } @Override public Iterator<IndexedInts> iterator() { return IndexedIterable.create(this).iterator(); } @Override public void close() { // no-op } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("theBuffer", theBuffer); } }
apache/druid
processing/src/main/java/org/apache/druid/segment/data/VSizeColumnarMultiInts.java
2,387
/* Copyright 2010, Lawrence Philips All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. 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. */ /* * A request from the author: Please comment and sign any changes you make to * the Metaphone 3 reference implementation. * <br> * Please do NOT reformat this module to Refine's coding standard, * but instead keep the original format so that it can be more easily compared * to any modified fork of the original. */ /** * Metaphone 3<br> * VERSION 2.1.3 * * by Lawrence Philips<br> * * Metaphone 3 is designed to return an *approximate* phonetic key (and an alternate * approximate phonetic key when appropriate) that should be the same for English * words, and most names familiar in the United States, that are pronounced *similarly*. * The key value is *not* intended to be an *exact* phonetic, or even phonemic, * representation of the word. This is because a certain degree of 'fuzziness' has * proven to be useful in compensating for variations in pronunciation, as well as * misheard pronunciations. For example, although americans are not usually aware of it, * the letter 's' is normally pronounced 'z' at the end of words such as "sounds".<br><br> * * The 'approximate' aspect of the encoding is implemented according to the following rules:<br><br> * * (1) All vowels are encoded to the same value - 'A'. If the parameter encodeVowels * is set to false, only *initial* vowels will be encoded at all. If encodeVowels is set * to true, 'A' will be encoded at all places in the word that any vowels are normally * pronounced. 'W' as well as 'Y' are treated as vowels. Although there are differences in * the pronunciation of 'W' and 'Y' in different circumstances that lead to their being * classified as vowels under some circumstances and as consonants in others, for the purposes * of the 'fuzziness' component of the Soundex and Metaphone family of algorithms they will * be always be treated here as vowels.<br><br> * * (2) Voiced and un-voiced consonant pairs are mapped to the same encoded value. This * means that:<br> * 'D' and 'T' -> 'T'<br> * 'B' and 'P' -> 'P'<br> * 'G' and 'K' -> 'K'<br> * 'Z' and 'S' -> 'S'<br> * 'V' and 'F' -> 'F'<br><br> * * - In addition to the above voiced/unvoiced rules, 'CH' and 'SH' -> 'X', where 'X' * represents the "-SH-" and "-CH-" sounds in Metaphone 3 encoding.<br><br> * * - Also, the sound that is spelled as "TH" in English is encoded to '0' (zero symbol). (Although * Americans are not usually aware of it, "TH" is pronounced in a voiced (e.g. "that") as * well as an unvoiced (e.g. "theater") form, which are naturally mapped to the same encoding.)<br><br> * * The encodings in this version of Metaphone 3 are according to pronunciations common in the * United States. This means that they will be inaccurate for consonant pronunciations that * are different in the United Kingdom, for example "tube" -> "CHOOBE" -> XAP rather than american TAP.<br><br> * * Metaphone 3 was preceded by by Soundex, patented in 1919, and Metaphone and Double Metaphone, * developed by Lawrence Philips. All of these algorithms resulted in a significant number of * incorrect encodings. Metaphone3 was tested against a database of about 100 thousand English words, * names common in the United States, and non-English words found in publications in the United States, * with an emphasis on words that are commonly mispronounced, prepared by the Moby Words website, * but with the Moby Words 'phonetic' encodings algorithmically mapped to Double Metaphone encodings. * Metaphone3 increases the accuracy of encoding of english words, common names, and non-English * words found in american publications from the 89% for Double Metaphone, to over 98%.<br><br> * * DISCLAIMER: * Anthropomorphic Software LLC claims only that Metaphone 3 will return correct encodings, * within the 'fuzzy' definition of correct as above, for a very high percentage of correctly * spelled English and commonly recognized non-English words. Anthropomorphic Software LLC * warns the user that a number of words remain incorrectly encoded, that misspellings may not * be encoded 'properly', and that people often have differing ideas about the pronunciation * of a word. Therefore, Metaphone 3 is not guaranteed to return correct results every time, and * so a desired target word may very well be missed. Creators of commercial products should * keep in mind that systems like Metaphone 3 produce a 'best guess' result, and should * condition the expectations of end users accordingly.<br><br> * * METAPHONE3 IS PROVIDED "AS IS" WITHOUT * WARRANTY OF ANY KIND. LAWRENCE PHILIPS AND ANTHROPOMORPHIC SOFTWARE LLC * MAKE NO WARRANTIES, EXPRESS OR IMPLIED, THAT IT IS FREE OF ERROR, * OR ARE CONSISTENT WITH ANY PARTICULAR STANDARD OF MERCHANTABILITY, * OR THAT IT WILL MEET YOUR REQUIREMENTS FOR ANY PARTICULAR APPLICATION. * LAWRENCE PHILIPS AND ANTHROPOMORPHIC SOFTWARE LLC DISCLAIM ALL LIABILITY * FOR DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES RESULTING FROM USE * OF THIS SOFTWARE. * * @author Lawrence Philips * * Metaphone 3 is designed to return an <i>approximate</i> phonetic key (and an alternate * approximate phonetic key when appropriate) that should be the same for English * words, and most names familiar in the United States, that are pronounced "similarly". * The key value is <i>not</i> intended to be an exact phonetic, or even phonemic, * representation of the word. This is because a certain degree of 'fuzziness' has * proven to be useful in compensating for variations in pronunciation, as well as * misheard pronunciations. For example, although americans are not usually aware of it, * the letter 's' is normally pronounced 'z' at the end of words such as "sounds".<br><br> * * The 'approximate' aspect of the encoding is implemented according to the following rules:<br><br> * * (1) All vowels are encoded to the same value - 'A'. If the parameter encodeVowels * is set to false, only *initial* vowels will be encoded at all. If encodeVowels is set * to true, 'A' will be encoded at all places in the word that any vowels are normally * pronounced. 'W' as well as 'Y' are treated as vowels. Although there are differences in * the pronunciation of 'W' and 'Y' in different circumstances that lead to their being * classified as vowels under some circumstances and as consonants in others, for the purposes * of the 'fuzziness' component of the Soundex and Metaphone family of algorithms they will * be always be treated here as vowels.<br><br> * * (2) Voiced and un-voiced consonant pairs are mapped to the same encoded value. This * means that:<br> * 'D' and 'T' -> 'T'<br> * 'B' and 'P' -> 'P'<br> * 'G' and 'K' -> 'K'<br> * 'Z' and 'S' -> 'S'<br> * 'V' and 'F' -> 'F'<br><br> * * - In addition to the above voiced/unvoiced rules, 'CH' and 'SH' -> 'X', where 'X' * represents the "-SH-" and "-CH-" sounds in Metaphone 3 encoding.<br><br> * * - Also, the sound that is spelled as "TH" in English is encoded to '0' (zero symbol). (Although * americans are not usually aware of it, "TH" is pronounced in a voiced (e.g. "that") as * well as an unvoiced (e.g. "theater") form, which are naturally mapped to the same encoding.)<br><br> * * In the "Exact" encoding, voiced/unvoiced pairs are <i>not</i> mapped to the same encoding, except * for the voiced and unvoiced versions of 'TH', sounds such as 'CH' and 'SH', and for 'S' and 'Z', * so that the words whose metaph keys match will in fact be closer in pronunciation that with the * more approximate setting. Keep in mind that encoding settings for search strings should always * be exactly the same as the encoding settings of the stored metaph keys in your database! * Because of the considerably increased accuracy of Metaphone3, it is now possible to use this * setting and have a very good chance of getting a correct encoding. * <br><br> * In the Encode Vowels encoding, all non-initial vowels and diphthongs will be encoded to * 'A', and there will only be one such vowel encoding character between any two consonants. * It turns out that there are some surprising wrinkles to encoding non-initial vowels in * practice, pre-eminently in inversions between spelling and pronunciation such as e.g. * "wrinkle" => 'RANKAL', where the last two sounds are inverted when spelled. * <br><br> * The encodings in this version of Metaphone 3 are according to pronunciations common in the * United States. This means that they will be inaccurate for consonant pronunciations that * are different in the United Kingdom, for example "tube" -> "CHOOBE" -> XAP rather than american TAP. * <br><br> * */ package com.google.refine.clustering.binning; public class Metaphone3 { /** Length of word sent in to be encoded, as * measured at beginning of encoding. */ int m_length; /** Length of encoded key string. */ int m_metaphLength; /** Flag whether or not to encode non-initial vowels. */ boolean m_encodeVowels; /** Flag whether or not to encode consonants as exactly * as possible. */ boolean m_encodeExact; /** Internal copy of word to be encoded, allocated separately * from string pointed to in incoming parameter. */ String m_inWord; /** Running copy of primary key. */ StringBuffer m_primary; /** Running copy of secondary key. */ StringBuffer m_secondary; /** Index of character in m_inWord currently being * encoded. */ int m_current; /** Index of last character in m_inWord. */ int m_last; /** Flag that an AL inversion has already been done. */ boolean flag_AL_inversion; /** Default size of key storage allocation */ int MAX_KEY_ALLOCATION = 32; /** Default maximum length of encoded key. */ int DEFAULT_MAX_KEY_LENGTH = 8; //////////////////////////////////////////////////////////////////////////////// // Metaphone3 class definition //////////////////////////////////////////////////////////////////////////////// /** * Constructor, default. This constructor is most convenient when * encoding more than one word at a time. New words to encode can * be set using SetWord(char *). * */ Metaphone3() { m_primary = new StringBuffer(); m_secondary = new StringBuffer(); m_metaphLength = DEFAULT_MAX_KEY_LENGTH; m_encodeVowels = false; m_encodeExact = false; } /** * Constructor, parameterized. The Metaphone3 object will * be initialized with the incoming string, and can be called * on to encode this string. This constructor is most convenient * when only one word needs to be encoded. * * @param in pointer to char string of word to be encoded. * */ Metaphone3(String in) { this(); SetWord(in); } /** * Sets word to be encoded. * * @param in pointer to EXTERNALLY ALLOCATED char string of * the word to be encoded. * */ void SetWord(String in) { m_inWord = in.toUpperCase();; m_length = m_inWord.length(); } /** * Sets length allocated for output keys. * If incoming number is greater than maximum allowable * length returned by GetMaximumKeyLength(), set key length * to maximum key length and return false; otherwise, set key * length to parameter value and return true. * * @param inKeyLength new length of key. * @return true if able to set key length to requested value. * */ boolean SetKeyLength(int inKeyLength) { if(inKeyLength < 1) { // can't have that - // no room for terminating null inKeyLength = 1; } if(inKeyLength > MAX_KEY_ALLOCATION) { m_metaphLength = MAX_KEY_ALLOCATION; return false; } m_metaphLength = inKeyLength; return true; } /** * Adds an encoding character to the encoded key value string - one parameter version. * * @param main primary encoding character to be added to encoded key string. */ void MetaphAdd(String in) { if(!(in.equals("A") && (m_primary.length() > 0) && (m_primary.charAt(m_primary.length() - 1) == 'A'))) { m_primary.append(in); } if(!(in.equals("A") && (m_secondary.length() > 0) && (m_secondary.charAt(m_secondary.length() - 1) == 'A'))) { m_secondary.append(in); } } /** * Adds an encoding character to the encoded key value string - two parameter version * * @param main primary encoding character to be added to encoded key string * @param alt alternative encoding character to be added to encoded alternative key string * */ void MetaphAdd(String main, String alt) { if(!(main.equals("A") && (m_primary.length() > 0) && (m_primary.charAt(m_primary.length() - 1) == 'A'))) { m_primary.append(main); } if(!(alt.equals("A") && (m_secondary.length() > 0) && (m_secondary.charAt(m_secondary.length() - 1) == 'A'))) { if(!alt.isEmpty()) { m_secondary.append(alt); } } } /** * Adds an encoding character to the encoded key value string - Exact/Approx version * * @param mainExact primary encoding character to be added to encoded key string if * m_encodeExact is set * * @param altExact alternative encoding character to be added to encoded alternative * key string if m_encodeExact is set * * @param main primary encoding character to be added to encoded key string * * @param alt alternative encoding character to be added to encoded alternative key string * */ void MetaphAddExactApprox(String mainExact, String altExact, String main, String alt) { if(m_encodeExact) { MetaphAdd(mainExact, altExact); } else { MetaphAdd(main, alt); } } /** * Adds an encoding character to the encoded key value string - Exact/Approx version * * @param mainExact primary encoding character to be added to encoded key string if * m_encodeExact is set * * @param main primary encoding character to be added to encoded key string * */ void MetaphAddExactApprox(String mainExact, String main) { if(m_encodeExact) { MetaphAdd(mainExact); } else { MetaphAdd(main); } } /** Retrieves maximum number of characters currently allocated for encoded key. * * @return short integer representing the length allowed for the key. */ int GetKeyLength(){return m_metaphLength;} /** Retrieves maximum number of characters allowed for encoded key. * * @return short integer representing the length of allocated storage for the key. */ int GetMaximumKeyLength(){return (int)MAX_KEY_ALLOCATION;} /** Sets flag that causes Metaphone3 to encode non-initial vowels. However, even * if there are more than one vowel sound in a vowel sequence (i.e. * vowel diphthong, etc.), only one 'A' will be encoded before the next consonant or the * end of the word. * * @param inEncodeVowels Non-initial vowels encoded if true, not if false. */ void SetEncodeVowels(boolean inEncodeVowels){m_encodeVowels = inEncodeVowels;} /** Retrieves setting determining whether or not non-initial vowels will be encoded. * * @return true if the Metaphone3 object has been set to encode non-initial vowels, false if not. */ boolean GetEncodeVowels(){return m_encodeVowels;} /** Sets flag that causes Metaphone3 to encode consonants as exactly as possible. * This does not include 'S' vs. 'Z', since americans will pronounce 'S' at the * at the end of many words as 'Z', nor does it include "CH" vs. "SH". It does cause * a distinction to be made between 'B' and 'P', 'D' and 'T', 'G' and 'K', and 'V' * and 'F'. * * @param inEncodeExact consonants to be encoded "exactly" if true, not if false. */ void SetEncodeExact(boolean inEncodeExact){m_encodeExact = inEncodeExact;} /** Retrieves setting determining whether or not consonants will be encoded "exactly". * * @return true if the Metaphone3 object has been set to encode "exactly", false if not. */ boolean GetEncodeExact(){return m_encodeExact;} /** Retrieves primary encoded key. * * @return a character pointer to the primary encoded key */ String GetMetaph() { String primary = new String(m_primary); return primary; } /** Retrieves alternate encoded key, if any. * * @return a character pointer to the alternate encoded key */ String GetAlternateMetaph() { String secondary = new String(m_secondary); return secondary; } /** * Test for close front vowels * * @return true if close front vowel */ boolean Front_Vowel(int at) { if(((CharAt(at) == 'E') || (CharAt(at) == 'I') || (CharAt(at) == 'Y'))) { return true; } return false; } /** * Detect names or words that begin with spellings * typical of german or slavic words, for the purpose * of choosing alternate pronunciations correctly * */ boolean SlavoGermanic() { if(StringAt(0, 3, "SCH", "") || StringAt(0, 2, "SW", "") || (CharAt(0) == 'J') || (CharAt(0) == 'W')) { return true; } return false; } /** * Tests if character is a vowel * * @param inChar character to be tested in string to be encoded * @return true if character is a vowel, false if not * */ boolean IsVowel(char inChar) { if((inChar == 'A') || (inChar == 'E') || (inChar == 'I') || (inChar == 'O') || (inChar == 'U') || (inChar == 'Y') || (inChar == 'À') || (inChar == 'Á') || (inChar == 'Â') || (inChar == 'Ã') || (inChar == 'Ä') || (inChar == 'Å') || (inChar == 'Æ') || (inChar == 'È') || (inChar == 'É') || (inChar == 'Ê') || (inChar == 'Ë') || (inChar == 'Ì') || (inChar == 'Í') || (inChar == 'Î') || (inChar == 'Ï') || (inChar == 'Ò') || (inChar == 'Ó') || (inChar == 'Ô') || (inChar == 'Õ') || (inChar == 'Ö') || (inChar == 'Œ') || (inChar == 'Ø') || (inChar == 'Ù') || (inChar == 'Ú') || (inChar == 'Û') || (inChar == 'Ü') || (inChar == 'Ý') || (inChar == 'Ÿ')) { return true; } return false; } /** * Tests if character in the input string is a vowel * * @param at position of character to be tested in string to be encoded * @return true if character is a vowel, false if not * */ boolean IsVowel(int at) { if((at < 0) || (at >= m_length)) { return false; } char it = CharAt(at); if(IsVowel(it)) { return true; } return false; } /** * Skips over vowels in a string. Has exceptions for skipping consonants that * will not be encoded. * * @param at position, in string to be encoded, of character to start skipping from * * @return position of next consonant in string to be encoded */ int SkipVowels(int at) { if(at < 0) { return 0; } if(at >= m_length) { return m_length; } char it = CharAt(at); while(IsVowel(it) || (it == 'W')) { if(StringAt(at, 4, "WICZ", "WITZ", "WIAK", "") || StringAt((at - 1), 5, "EWSKI", "EWSKY", "OWSKI", "OWSKY", "") || (StringAt(at, 5, "WICKI", "WACKI", "") && ((at + 4) == m_last))) { break; } at++; if(((CharAt(at - 1) == 'W') && (CharAt(at) == 'H')) && !(StringAt(at, 3, "HOP", "") || StringAt(at, 4, "HIDE", "HARD", "HEAD", "HAWK", "HERD", "HOOK", "HAND", "HOLE", "") || StringAt(at, 5, "HEART", "HOUSE", "HOUND", "") || StringAt(at, 6, "HAMMER", ""))) { at++; } if(at > (m_length - 1)) { break; } it = CharAt(at); } return at; } /** * Advanced counter m_current so that it indexes the next character to be encoded * * @param ifNotEncodeVowels number of characters to advance if not encoding internal vowels * @param ifEncodeVowels number of characters to advance if encoding internal vowels * */ void AdvanceCounter(int ifNotEncodeVowels, int ifEncodeVowels) { if(!m_encodeVowels) { m_current += ifNotEncodeVowels; } else { m_current += ifEncodeVowels; } } /** * Subscript safe .charAt() * * @param at index of character to access * @return null if index out of bounds, .charAt() otherwise */ char CharAt(int at) { // check substring bounds if((at < 0) || (at > (m_length - 1))) { return '\0'; } return m_inWord.charAt(at); } /** * Tests whether the word is the root or a regular english inflection * of it, e.g. "ache", "achy", "aches", "ached", "aching", "achingly" * This is for cases where we want to match only the root and corresponding * inflected forms, and not completely different words which may have the * same substring in them. */ boolean RootOrInflections(String inWord, String root) { int len = root.length(); String test; test = root + "S"; if((inWord.equals(root)) || (inWord.equals(test))) { return true; } if(root.charAt(len - 1) != 'E') { test = root + "ES"; } if(inWord.equals(test)) { return true; } if(root.charAt(len - 1) != 'E') { test = root + "ED"; } else { test = root + "D"; } if(inWord.equals(test)) { return true; } if(root.charAt(len - 1) == 'E') { root = root.substring(0, len - 1); } test = root + "ING"; if(inWord.equals(test)) { return true; } test = root + "INGLY"; if(inWord.equals(test)) { return true; } test = root + "Y"; if(inWord.equals(test)) { return true; } return false; } /** * Determines if one of the substrings sent in is the same as * what is at the specified position in the string being encoded. * * @param start * @param length * @param compareStrings * @return */ boolean StringAt(int start, int length, String... compareStrings) { // check substring bounds if((start < 0) || (start > (m_length - 1)) || ((start + length - 1) > (m_length - 1))) { return false; } String target = m_inWord.substring(start, (start + length)); for(String strFragment : compareStrings) { if(target.equals(strFragment)) { return true; } } return false; } /** * Encodes input string to one or two key values according to Metaphone 3 rules. * */ void Encode() { flag_AL_inversion = false; m_current = 0; m_primary.setLength(0); m_secondary.setLength(0); if(m_length < 1) { return; } //zero based index m_last = m_length - 1; ///////////main loop////////////////////////// while(!(m_primary.length() > m_metaphLength) && !(m_secondary.length() > m_metaphLength)) { if(m_current >= m_length) { break; } switch(CharAt(m_current)) { case 'B': Encode_B(); break; case 'ß': case 'Ç': MetaphAdd("S"); m_current++; break; case 'C': Encode_C(); break; case 'D': Encode_D(); break; case 'F': Encode_F(); break; case 'G': Encode_G(); break; case 'H': Encode_H(); break; case 'J': Encode_J(); break; case 'K': Encode_K(); break; case 'L': Encode_L(); break; case 'M': Encode_M(); break; case 'N': Encode_N(); break; case 'Ñ': MetaphAdd("N"); m_current++; break; case 'P': Encode_P(); break; case 'Q': Encode_Q(); break; case 'R': Encode_R(); break; case 'S': Encode_S(); break; case 'T': Encode_T(); break; case 'Ð': // eth case 'Þ': // thorn MetaphAdd("0"); m_current++; break; case 'V': Encode_V(); break; case 'W': Encode_W(); break; case 'X': Encode_X(); break; case 'Š': MetaphAdd("X"); m_current++; break; case 'Ž': MetaphAdd("S"); m_current++; break; case 'Z': Encode_Z(); break; default: if(IsVowel(CharAt(m_current))) { Encode_Vowels(); break; } m_current++; } } //only give back m_metaphLength number of chars in m_metaph if(m_primary.length() > m_metaphLength) { m_primary.setLength(m_metaphLength); } if(m_secondary.length() > m_metaphLength) { m_secondary.setLength(m_metaphLength); } // it is possible for the two metaphs to be the same // after truncation. lose the second one if so if((m_primary.toString()).equals(m_secondary.toString())) { m_secondary.setLength(0); } } /** * Encodes all initial vowels to A. * * Encodes non-initial vowels to A if m_encodeVowels is true * * */ void Encode_Vowels() { if(m_current == 0) { // all init vowels map to 'A' // as of Double Metaphone MetaphAdd("A"); } else if(m_encodeVowels) { if(CharAt(m_current) != 'E') { if(Skip_Silent_UE()) { return; } if (O_Silent()) { m_current++; return; } // encode all vowels and // diphthongs to the same value MetaphAdd("A"); } else { Encode_E_Pronounced(); } } if(!(!IsVowel(m_current - 2) && StringAt((m_current - 1), 4, "LEWA", "LEWO", "LEWI", ""))) { m_current = SkipVowels(m_current); } else { m_current++; } } /** * Encodes cases where non-initial 'e' is pronounced, taking * care to detect unusual cases from the greek. * * Only executed if non initial vowel encoding is turned on * * */ void Encode_E_Pronounced() { // special cases with two pronunciations // 'agape' 'lame' 'resume' if((StringAt(0, 4, "LAME", "SAKE", "PATE", "") && (m_length == 4)) || (StringAt(0, 5, "AGAPE", "") && (m_length == 5)) || ((m_current == 5) && StringAt(0, 6, "RESUME", ""))) { MetaphAdd("", "A"); return; } // special case "inge" => 'INGA', 'INJ' if(StringAt(0, 4, "INGE", "") && (m_length == 4)) { MetaphAdd("A", ""); return; } // special cases with two pronunciations // special handling due to the difference in // the pronunciation of the '-D' if((m_current == 5) && StringAt(0, 7, "BLESSED", "LEARNED", "")) { MetaphAddExactApprox("D", "AD", "T", "AT"); m_current += 2; return; } // encode all vowels and diphthongs to the same value if((!E_Silent() && !flag_AL_inversion && !Silent_Internal_E()) || E_Pronounced_Exceptions()) { MetaphAdd("A"); } // now that we've visited the vowel in question flag_AL_inversion = false; } /** * Tests for cases where non-initial 'o' is not pronounced * Only executed if non initial vowel encoding is turned on * * @return true if encoded as silent - no addition to m_metaph key * */ boolean O_Silent() { // if "iron" at beginning or end of word and not "irony" if ((CharAt(m_current) == 'O') && StringAt((m_current - 2), 4, "IRON", "")) { if ((StringAt(0, 4, "IRON", "") || (StringAt((m_current - 2), 4, "IRON", "") && (m_last == (m_current + 1)))) && !StringAt((m_current - 2), 6, "IRONIC", "")) { return true; } } return false; } /** * Tests and encodes cases where non-initial 'e' is never pronounced * Only executed if non initial vowel encoding is turned on * * @return true if encoded as silent - no addition to m_metaph key * */ boolean E_Silent() { if(E_Pronounced_At_End()) { return false; } // 'e' silent when last letter, altho if((m_current == m_last) // also silent if before plural 's' // or past tense or participle 'd', e.g. // 'grapes' and 'banished' => PNXT || ((StringAt(m_last, 1, "S", "D", "") && (m_current > 1) && ((m_current + 1) == m_last) // and not e.g. "nested", "rises", or "pieces" => RASAS && !(StringAt((m_current - 1), 3, "TED", "SES", "CES", "") || StringAt(0, 9, "ANTIPODES", "ANOPHELES", "") || StringAt(0, 8, "MOHAMMED", "MUHAMMED", "MOUHAMED", "") || StringAt(0, 7, "MOHAMED", "") || StringAt(0, 6, "NORRED", "MEDVED", "MERCED", "ALLRED", "KHALED", "RASHED", "MASJED", "") || StringAt(0, 5, "JARED", "AHMED", "HAMED", "JAVED", "") || StringAt(0, 4, "ABED", "IMED", "")))) // e.g. 'wholeness', 'boneless', 'barely' || (StringAt((m_current + 1), 4, "NESS", "LESS", "") && ((m_current + 4) == m_last)) || (StringAt((m_current + 1), 2, "LY", "") && ((m_current + 2) == m_last) && !StringAt(0, 6, "CICELY", ""))) { return true; } return false; } /** * Tests for words where an 'E' at the end of the word * is pronounced * * special cases, mostly from the greek, spanish, japanese, * italian, and french words normally having an acute accent. * also, pronouns and articles * * Many Thanks to ali, QuentinCompson, JeffCO, ToonScribe, Xan, * Trafalz, and VictorLaszlo, all of them atriots from the Eschaton, * for all their fine contributions! * * @return true if 'E' at end is pronounced * */ boolean E_Pronounced_At_End() { if((m_current == m_last) && (StringAt((m_current - 6), 7, "STROPHE", "") // if a vowel is before the 'E', vowel eater will have eaten it. //otherwise, consonant + 'E' will need 'E' pronounced || (m_length == 2) || ((m_length == 3) && !IsVowel(0)) // these german name endings can be relied on to have the 'e' pronounced || (StringAt((m_last - 2), 3, "BKE", "DKE", "FKE", "KKE", "LKE", "NKE", "MKE", "PKE", "TKE", "VKE", "ZKE", "") && !StringAt(0, 5, "FINKE", "FUNKE", "") && !StringAt(0, 6, "FRANKE", "")) || StringAt((m_last - 4), 5, "SCHKE", "") || (StringAt(0, 4, "ACME", "NIKE", "CAFE", "RENE", "LUPE", "JOSE", "ESME", "") && (m_length == 4)) || (StringAt(0, 5, "LETHE", "CADRE", "TILDE", "SIGNE", "POSSE", "LATTE", "ANIME", "DOLCE", "CROCE", "ADOBE", "OUTRE", "JESSE", "JAIME", "JAFFE", "BENGE", "RUNGE", "CHILE", "DESME", "CONDE", "URIBE", "LIBRE", "ANDRE", "") && (m_length == 5)) || (StringAt(0, 6, "HECATE", "PSYCHE", "DAPHNE", "PENSKE", "CLICHE", "RECIPE", "TAMALE", "SESAME", "SIMILE", "FINALE", "KARATE", "RENATE", "SHANTE", "OBERLE", "COYOTE", "KRESGE", "STONGE", "STANGE", "SWAYZE", "FUENTE", "SALOME", "URRIBE", "") && (m_length == 6)) || (StringAt(0, 7, "ECHIDNE", "ARIADNE", "MEINEKE", "PORSCHE", "ANEMONE", "EPITOME", "SYNCOPE", "SOUFFLE", "ATTACHE", "MACHETE", "KARAOKE", "BUKKAKE", "VICENTE", "ELLERBE", "VERSACE", "") && (m_length == 7)) || (StringAt(0, 8, "PENELOPE", "CALLIOPE", "CHIPOTLE", "ANTIGONE", "KAMIKAZE", "EURIDICE", "YOSEMITE", "FERRANTE", "") && (m_length == 8)) || (StringAt(0, 9, "HYPERBOLE", "GUACAMOLE", "XANTHIPPE", "") && (m_length == 9)) || (StringAt(0, 10, "SYNECDOCHE", "") && (m_length == 10)))) { return true; } return false; } /** * Detect internal silent 'E's e.g. "roseman", * "firestone" * */ boolean Silent_Internal_E() { // 'olesen' but not 'olen' RAKE BLAKE if((StringAt(0, 3, "OLE", "") && E_Silent_Suffix(3) && !E_Pronouncing_Suffix(3)) || (StringAt(0, 4, "BARE", "FIRE", "FORE", "GATE", "HAGE", "HAVE", "HAZE", "HOLE", "CAPE", "HUSE", "LACE", "LINE", "LIVE", "LOVE", "MORE", "MOSE", "MORE", "NICE", "RAKE", "ROBE", "ROSE", "SISE", "SIZE", "WARE", "WAKE", "WISE", "WINE", "") && E_Silent_Suffix(4) && !E_Pronouncing_Suffix(4)) || (StringAt(0, 5, "BLAKE", "BRAKE", "BRINE", "CARLE", "CLEVE", "DUNNE", "HEDGE", "HOUSE", "JEFFE", "LUNCE", "STOKE", "STONE", "THORE", "WEDGE", "WHITE", "") && E_Silent_Suffix(5) && !E_Pronouncing_Suffix(5)) || (StringAt(0, 6, "BRIDGE", "CHEESE", "") && E_Silent_Suffix(6) && !E_Pronouncing_Suffix(6)) || StringAt((m_current - 5), 7, "CHARLES", "")) { return true; } return false; } /** * Detect conditions required * for the 'E' not to be pronounced * */ boolean E_Silent_Suffix(int at) { if((m_current == (at - 1)) && (m_length > (at + 1)) && (IsVowel((at + 1)) || (StringAt(at, 2, "ST", "SL", "") && (m_length > (at + 2))))) { return true; } return false; } /** * Detect endings that will * cause the 'e' to be pronounced * */ boolean E_Pronouncing_Suffix(int at) { // e.g. 'bridgewood' - the other vowels will get eaten // up so we need to put one in here if((m_length == (at + 4)) && StringAt(at, 4, "WOOD", "")) { return true; } // same as above if((m_length == (at + 5)) && StringAt(at, 5, "WATER", "WORTH", "")) { return true; } // e.g. 'bridgette' if((m_length == (at + 3)) && StringAt(at, 3, "TTE", "LIA", "NOW", "ROS", "RAS", "")) { return true; } // e.g. 'olena' if((m_length == (at + 2)) && StringAt(at, 2, "TA", "TT", "NA", "NO", "NE", "RS", "RE", "LA", "AU", "RO", "RA", "")) { return true; } // e.g. 'bridget' if((m_length == (at + 1)) && StringAt(at, 1, "T", "R", "")) { return true; } return false; } /** * Exceptions where 'E' is pronounced where it * usually wouldn't be, and also some cases * where 'LE' transposition rules don't apply * and the vowel needs to be encoded here * * @return true if 'E' pronounced * */ boolean E_Pronounced_Exceptions() { // greek names e.g. "herakles" or hispanic names e.g. "robles", where 'e' is pronounced, other exceptions if((((m_current + 1) == m_last) && (StringAt((m_current - 3), 5, "OCLES", "ACLES", "AKLES", "") || StringAt(0, 4, "INES", "") || StringAt(0, 5, "LOPES", "ESTES", "GOMES", "NUNES", "ALVES", "ICKES", "INNES", "PERES", "WAGES", "NEVES", "BENES", "DONES", "") || StringAt(0, 6, "CORTES", "CHAVES", "VALDES", "ROBLES", "TORRES", "FLORES", "BORGES", "NIEVES", "MONTES", "SOARES", "VALLES", "GEDDES", "ANDRES", "VIAJES", "CALLES", "FONTES", "HERMES", "ACEVES", "BATRES", "MATHES", "") || StringAt(0, 7, "DELORES", "MORALES", "DOLORES", "ANGELES", "ROSALES", "MIRELES", "LINARES", "PERALES", "PAREDES", "BRIONES", "SANCHES", "CAZARES", "REVELES", "ESTEVES", "ALVARES", "MATTHES", "SOLARES", "CASARES", "CACERES", "STURGES", "RAMIRES", "FUNCHES", "BENITES", "FUENTES", "PUENTES", "TABARES", "HENTGES", "VALORES", "") || StringAt(0, 8, "GONZALES", "MERCEDES", "FAGUNDES", "JOHANNES", "GONSALES", "BERMUDES", "CESPEDES", "BETANCES", "TERRONES", "DIOGENES", "CORRALES", "CABRALES", "MARTINES", "GRAJALES", "") || StringAt(0, 9, "CERVANTES", "FERNANDES", "GONCALVES", "BENEVIDES", "CIFUENTES", "SIFUENTES", "SERVANTES", "HERNANDES", "BENAVIDES", "") || StringAt(0, 10, "ARCHIMEDES", "CARRIZALES", "MAGALLANES", ""))) || StringAt(m_current - 2, 4, "FRED", "DGES", "DRED", "GNES", "") || StringAt((m_current - 5), 7, "PROBLEM", "RESPLEN", "") || StringAt((m_current - 4), 6, "REPLEN", "") || StringAt((m_current - 3), 4, "SPLE", "")) { return true; } return false; } /** * Encodes "-UE". * * @return true if encoding handled in this routine, false if not */ boolean Skip_Silent_UE() { // always silent except for cases listed below if((StringAt((m_current - 1), 3, "QUE", "GUE", "") && !StringAt(0, 8, "BARBEQUE", "PALENQUE", "APPLIQUE", "") // '-que' cases usually french but missing the acute accent && !StringAt(0, 6, "RISQUE", "") && !StringAt((m_current - 3), 5, "ARGUE", "SEGUE", "") && !StringAt(0, 7, "PIROGUE", "ENRIQUE", "") && !StringAt(0, 10, "COMMUNIQUE", "")) && (m_current > 1) && (((m_current + 1) == m_last) || StringAt(0, 7, "JACQUES", ""))) { m_current = SkipVowels(m_current); return true; } return false; } /** * Encodes 'B' * * */ void Encode_B() { if(Encode_Silent_B()) { return; } // "-mb", e.g", "dumb", already skipped over under // 'M', altho it should really be handled here... MetaphAddExactApprox("B", "P"); if((CharAt(m_current + 1) == 'B') || ((CharAt(m_current + 1) == 'P') && ((m_current + 1 < m_last) && (CharAt(m_current + 2) != 'H')))) { m_current += 2; } else { m_current++; } } /** * Encodes silent 'B' for cases not covered under "-mb-" * * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_B() { //'debt', 'doubt', 'subtle' if(StringAt((m_current - 2), 4, "DEBT", "") || StringAt((m_current - 2), 5, "SUBTL", "") || StringAt((m_current - 2), 6, "SUBTIL", "") || StringAt((m_current - 3), 5, "DOUBT", "")) { MetaphAdd("T"); m_current += 2; return true; } return false; } /** * Encodes 'C' * */ void Encode_C() { if(Encode_Silent_C_At_Beginning() || Encode_CA_To_S() || Encode_CO_To_S() || Encode_CH() || Encode_CCIA() || Encode_CC() || Encode_CK_CG_CQ() || Encode_C_Front_Vowel() || Encode_Silent_C() || Encode_CZ() || Encode_CS()) { return; } //else if(!StringAt((m_current - 1), 1, "C", "K", "G", "Q", "")) { MetaphAdd("K"); } //name sent in 'mac caffrey', 'mac gregor if(StringAt((m_current + 1), 2, " C", " Q", " G", "")) { m_current += 2; } else { if(StringAt((m_current + 1), 1, "C", "K", "Q", "") && !StringAt((m_current + 1), 2, "CE", "CI", "")) { m_current += 2; // account for combinations such as Ro-ckc-liffe if(StringAt((m_current), 1, "C", "K", "Q", "") && !StringAt((m_current + 1), 2, "CE", "CI", "")) { m_current++; } } else { m_current++; } } } /** * Encodes cases where 'C' is silent at beginning of word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_C_At_Beginning() { //skip these when at start of word if((m_current == 0) && StringAt(m_current, 2, "CT", "CN", "")) { m_current += 1; return true; } return false; } /** * Encodes exceptions where "-CA-" should encode to S * instead of K including cases where the cedilla has not been used * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CA_To_S() { // Special case: 'caesar'. // Also, where cedilla not used, as in "linguica" => LNKS if(((m_current == 0) && StringAt(m_current, 4, "CAES", "CAEC", "CAEM", "")) || StringAt(0, 8, "FRANCAIS", "FRANCAIX", "LINGUICA", "") || StringAt(0, 6, "FACADE", "") || StringAt(0, 9, "GONCALVES", "PROVENCAL", "")) { MetaphAdd("S"); AdvanceCounter(2, 1); return true; } return false; } /** * Encodes exceptions where "-CO-" encodes to S instead of K * including cases where the cedilla has not been used * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CO_To_S() { // e.g. 'coelecanth' => SLKN0 if((StringAt(m_current, 4, "COEL", "") && (IsVowel(m_current + 4) || ((m_current + 3) == m_last))) || StringAt(m_current, 5, "COENA", "COENO", "") || StringAt(0, 8, "FRANCOIS", "MELANCON", "") || StringAt(0, 6, "GARCON", "")) { MetaphAdd("S"); AdvanceCounter(3, 1); return true; } return false; } /** * Encode "-CH-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CH() { if(StringAt(m_current, 2, "CH", "")) { if(Encode_CHAE() || Encode_CH_To_H() || Encode_Silent_CH() || Encode_ARCH() // Encode_CH_To_X() should be // called before the germanic // and greek encoding functions || Encode_CH_To_X() || Encode_English_CH_To_K() || Encode_Germanic_CH_To_K() || Encode_Greek_CH_Initial() || Encode_Greek_CH_Non_Initial()) { return true; } if(m_current > 0) { if(StringAt(0, 2, "MC", "") && (m_current == 1)) { //e.g., "McHugh" MetaphAdd("K"); } else { MetaphAdd("X", "K"); } } else { MetaphAdd("X"); } m_current += 2; return true; } return false; } /** * Encodes "-CHAE-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CHAE() { // e.g. 'michael' if(((m_current > 0) && StringAt((m_current + 2), 2, "AE", ""))) { if(StringAt(0, 7, "RACHAEL", "")) { MetaphAdd("X"); } else if(!StringAt((m_current - 1), 1, "C", "K", "G", "Q", "")) { MetaphAdd("K"); } AdvanceCounter(4, 2); return true; } return false; } /** * Encdoes transliterations from the hebrew where the * sound 'kh' is represented as "-CH-". The normal pronounciation * of this in english is either 'h' or 'kh', and alternate * spellings most often use "-H-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CH_To_H() { // hebrew => 'H', e.g. 'channukah', 'chabad' if(((m_current == 0) && (StringAt((m_current + 2), 3, "AIM", "ETH", "ELM", "") || StringAt((m_current + 2), 4, "ASID", "AZAN", "") || StringAt((m_current + 2), 5, "UPPAH", "UTZPA", "ALLAH", "ALUTZ", "AMETZ", "") || StringAt((m_current + 2), 6, "ESHVAN", "ADARIM", "ANUKAH", "") || StringAt((m_current + 2), 7, "ALLLOTH", "ANNUKAH", "AROSETH", ""))) // and an irish name with the same encoding || StringAt((m_current - 3), 7, "CLACHAN", "")) { MetaphAdd("H"); AdvanceCounter(3, 2); return true; } return false; } /** * Encodes cases where "-CH-" is not pronounced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_CH() { // '-ch-' not pronounced if(StringAt((m_current - 2), 7, "FUCHSIA", "") || StringAt((m_current - 2), 5, "YACHT", "") || StringAt(0, 8, "STRACHAN", "") || StringAt(0, 8, "CRICHTON", "") || (StringAt((m_current - 3), 6, "DRACHM", "")) && !StringAt((m_current - 3), 7, "DRACHMA", "")) { m_current += 2; return true; } return false; } /** * Encodes "-CH-" to X * English language patterns * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CH_To_X() { // e.g. 'approach', 'beach' if((StringAt((m_current - 2), 4, "OACH", "EACH", "EECH", "OUCH", "OOCH", "MUCH", "SUCH", "") && !StringAt((m_current - 3), 5, "JOACH", "")) // e.g. 'dacha', 'macho' || (((m_current + 2) == m_last ) && StringAt((m_current - 1), 4, "ACHA", "ACHO", "")) || (StringAt(m_current, 4, "CHOT", "CHOD", "CHAT", "") && ((m_current + 3) == m_last)) || ((StringAt((m_current - 1), 4, "OCHE", "") && ((m_current + 2) == m_last)) && !StringAt((m_current - 2), 5, "DOCHE", "")) || StringAt((m_current - 4), 6, "ATTACH", "DETACH", "KOVACH", "") || StringAt((m_current - 5), 7, "SPINACH", "") || StringAt(0, 6, "MACHAU", "") || StringAt((m_current - 4), 8, "PARACHUT", "") || StringAt((m_current - 5), 8, "MASSACHU", "") || (StringAt((m_current - 3), 5, "THACH", "") && !StringAt((m_current - 1), 4, "ACHE", "")) || StringAt((m_current - 2), 6, "VACHON", "") ) { MetaphAdd("X"); m_current += 2; return true; } return false; } /** * Encodes "-CH-" to K in contexts of * initial "A" or "E" follwed by "CH" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_English_CH_To_K() { //'ache', 'echo', alternate spelling of 'michael' if(((m_current == 1) && RootOrInflections(m_inWord, "ACHE")) || (((m_current > 3) && RootOrInflections(m_inWord.substring(m_current - 1), "ACHE")) && (StringAt(0, 3, "EAR", "") || StringAt(0, 4, "HEAD", "BACK", "") || StringAt(0, 5, "HEART", "BELLY", "TOOTH", ""))) || StringAt((m_current - 1), 4, "ECHO", "") || StringAt((m_current - 2), 7, "MICHEAL", "") || StringAt((m_current - 4), 7, "JERICHO", "") || StringAt((m_current - 5), 7, "LEPRECH", "")) { MetaphAdd("K", "X"); m_current += 2; return true; } return false; } /** * Encodes "-CH-" to K in mostly germanic context * of internal "-ACH-", with exceptions * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Germanic_CH_To_K() { // various germanic // "<consonant><vowel>CH-"implies a german word where 'ch' => K if(((m_current > 1) && !IsVowel(m_current - 2) && StringAt((m_current - 1), 3, "ACH", "") && !StringAt((m_current - 2), 7, "MACHADO", "MACHUCA", "LACHANC", "LACHAPE", "KACHATU", "") && !StringAt((m_current - 3), 7, "KHACHAT", "") && ((CharAt(m_current + 2) != 'I') && ((CharAt(m_current + 2) != 'E') || StringAt((m_current - 2), 6, "BACHER", "MACHER", "MACHEN", "LACHER", "")) ) // e.g. 'brecht', 'fuchs' || (StringAt((m_current + 2), 1, "T", "S", "") && !(StringAt(0, 11, "WHICHSOEVER", "") || StringAt(0, 9, "LUNCHTIME", "") )) // e.g. 'andromache' || StringAt(0, 4, "SCHR", "") || ((m_current > 2) && StringAt((m_current - 2), 5, "MACHE", "")) || ((m_current == 2) && StringAt((m_current - 2), 4, "ZACH", "")) || StringAt((m_current - 4), 6, "SCHACH", "") || StringAt((m_current - 1), 5, "ACHEN", "") || StringAt((m_current - 3), 5, "SPICH", "ZURCH", "BUECH", "") || (StringAt((m_current - 3), 5, "KIRCH", "JOACH", "BLECH", "MALCH", "") // "kirch" and "blech" both get 'X' && !(StringAt((m_current - 3), 8, "KIRCHNER", "") || ((m_current + 1) == m_last))) || (((m_current + 1) == m_last) && StringAt((m_current - 2), 4, "NICH", "LICH", "BACH", "")) || (((m_current + 1) == m_last) && StringAt((m_current - 3), 5, "URICH", "BRICH", "ERICH", "DRICH", "NRICH", "") && !StringAt((m_current - 5), 7, "ALDRICH", "") && !StringAt((m_current - 6), 8, "GOODRICH", "") && !StringAt((m_current - 7), 9, "GINGERICH", ""))) || (((m_current + 1) == m_last) && StringAt((m_current - 4), 6, "ULRICH", "LFRICH", "LLRICH", "EMRICH", "ZURICH", "EYRICH", "")) // e.g., 'wachtler', 'wechsler', but not 'tichner' || ((StringAt((m_current - 1), 1, "A", "O", "U", "E", "") || (m_current == 0)) && StringAt((m_current + 2), 1, "L", "R", "N", "M", "B", "H", "F", "V", "W", " ", ""))) { // "CHR/L-" e.g. 'chris' do not get // alt pronunciation of 'X' if(StringAt((m_current + 2), 1, "R", "L", "") || SlavoGermanic()) { MetaphAdd("K"); } else { MetaphAdd("K", "X"); } m_current += 2; return true; } return false; } /** * Encode "-ARCH-". Some occurances are from greek roots and therefore encode * to 'K', others are from english words and therefore encode to 'X' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_ARCH() { if(StringAt((m_current - 2), 4, "ARCH", "")) { // "-ARCH-" has many combining forms where "-CH-" => K because of its // derivation from the greek if(((IsVowel(m_current + 2) && StringAt((m_current - 2), 5, "ARCHA", "ARCHI", "ARCHO", "ARCHU", "ARCHY", "")) || StringAt((m_current - 2), 6, "ARCHEA", "ARCHEG", "ARCHEO", "ARCHET", "ARCHEL", "ARCHES", "ARCHEP", "ARCHEM", "ARCHEN", "") || (StringAt((m_current - 2), 4, "ARCH", "") && (((m_current + 1) == m_last))) || StringAt(0, 7, "MENARCH", "")) && (!RootOrInflections(m_inWord, "ARCH") && !StringAt((m_current - 4), 6, "SEARCH", "POARCH", "") && !StringAt(0, 9, "ARCHENEMY", "ARCHIBALD", "ARCHULETA", "ARCHAMBAU", "") && !StringAt(0, 6, "ARCHER", "ARCHIE", "") && !((((StringAt((m_current - 3), 5, "LARCH", "MARCH", "PARCH", "") || StringAt((m_current - 4), 6, "STARCH", "")) && !(StringAt(0, 6, "EPARCH", "") || StringAt(0, 7, "NOMARCH", "") || StringAt(0, 8, "EXILARCH", "HIPPARCH", "MARCHESE", "") || StringAt(0, 9, "ARISTARCH", "") || StringAt(0, 9, "MARCHETTI", "")) ) || RootOrInflections(m_inWord, "STARCH")) && (!StringAt((m_current - 2), 5, "ARCHU", "ARCHY", "") || StringAt(0, 7, "STARCHY", ""))))) { MetaphAdd("K", "X"); } else { MetaphAdd("X"); } m_current += 2; return true; } return false; } /** * Encode "-CH-" to K when from greek roots * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Greek_CH_Initial() { // greek roots e.g. 'chemistry', 'chorus', ch at beginning of root if((StringAt(m_current, 6, "CHAMOM", "CHARAC", "CHARIS", "CHARTO", "CHARTU", "CHARYB", "CHRIST", "CHEMIC", "CHILIA", "") || (StringAt(m_current, 5, "CHEMI", "CHEMO", "CHEMU", "CHEMY", "CHOND", "CHONA", "CHONI", "CHOIR", "CHASM", "CHARO", "CHROM", "CHROI", "CHAMA", "CHALC", "CHALD", "CHAET","CHIRO", "CHILO", "CHELA", "CHOUS", "CHEIL", "CHEIR", "CHEIM", "CHITI", "CHEOP", "") && !(StringAt(m_current, 6, "CHEMIN", "") || StringAt((m_current - 2), 8, "ANCHONDO", ""))) || (StringAt(m_current, 5, "CHISM", "CHELI", "") // exclude spanish "machismo" && !(StringAt(0, 8, "MACHISMO", "") // exclude some french words || StringAt(0, 10, "REVANCHISM", "") || StringAt(0, 9, "RICHELIEU", "") || (StringAt(0, 5, "CHISM", "") && (m_length == 5)) || StringAt(0, 6, "MICHEL", ""))) // include e.g. "chorus", "chyme", "chaos" || (StringAt(m_current, 4, "CHOR", "CHOL", "CHYM", "CHYL", "CHLO", "CHOS", "CHUS", "CHOE", "") && !StringAt(0, 6, "CHOLLO", "CHOLLA", "CHORIZ", "")) // "chaos" => K but not "chao" || (StringAt(m_current, 4, "CHAO", "") && ((m_current + 3) != m_last)) // e.g. "abranchiate" || (StringAt(m_current, 4, "CHIA", "") && !(StringAt(0, 10, "APPALACHIA", "") || StringAt(0, 7, "CHIAPAS", ""))) // e.g. "chimera" || StringAt(m_current, 7, "CHIMERA", "CHIMAER", "CHIMERI", "") // e.g. "chameleon" || ((m_current == 0) && StringAt(m_current, 5, "CHAME", "CHELO", "CHITO", "") ) // e.g. "spirochete" || ((((m_current + 4) == m_last) || ((m_current + 5) == m_last)) && StringAt((m_current - 1), 6, "OCHETE", ""))) // more exceptions where "-CH-" => X e.g. "chortle", "crocheter" && !((StringAt(0, 5, "CHORE", "CHOLO", "CHOLA", "") && (m_length == 5)) || StringAt(m_current, 5, "CHORT", "CHOSE", "") || StringAt((m_current - 3), 7, "CROCHET", "") || StringAt(0, 7, "CHEMISE", "CHARISE", "CHARISS", "CHAROLE", "")) ) { // "CHR/L-" e.g. 'christ', 'chlorine' do not get // alt pronunciation of 'X' if(StringAt((m_current + 2), 1, "R", "L", "")) { MetaphAdd("K"); } else { MetaphAdd("K", "X"); } m_current += 2; return true; } return false; } /** * Encode a variety of greek and some german roots where "-CH-" => K * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Greek_CH_Non_Initial() { //greek & other roots e.g. 'tachometer', 'orchid', ch in middle or end of root if(StringAt((m_current - 2), 6, "ORCHID", "NICHOL", "MECHAN", "LICHEN", "MACHIC", "PACHEL", "RACHIF", "RACHID", "RACHIS", "RACHIC", "MICHAL", "") || StringAt((m_current - 3), 5, "MELCH", "GLOCH", "TRACH", "TROCH", "BRACH", "SYNCH", "PSYCH", "STICH", "PULCH", "EPOCH", "") || (StringAt((m_current - 3), 5, "TRICH", "") && !StringAt((m_current - 5), 7, "OSTRICH", "")) || (StringAt((m_current - 2), 4, "TYCH", "TOCH", "BUCH", "MOCH", "CICH", "DICH", "NUCH", "EICH", "LOCH", "DOCH", "ZECH", "WYCH", "") && !(StringAt((m_current - 4), 9, "INDOCHINA", "") || StringAt((m_current - 2), 6, "BUCHON", ""))) || StringAt((m_current - 2), 5, "LYCHN", "TACHO", "ORCHO", "ORCHI", "LICHO", "") || (StringAt((m_current - 1), 5, "OCHER", "ECHIN", "ECHID", "") && ((m_current == 1) || (m_current == 2))) || StringAt((m_current - 4), 6, "BRONCH", "STOICH", "STRYCH", "TELECH", "PLANCH", "CATECH", "MANICH", "MALACH", "BIANCH", "DIDACH", "") || (StringAt((m_current - 1), 4, "ICHA", "ICHN","") && (m_current == 1)) || StringAt((m_current - 2), 8, "ORCHESTR", "") || StringAt((m_current - 4), 8, "BRANCHIO", "BRANCHIF", "") || (StringAt((m_current - 1), 5, "ACHAB", "ACHAD", "ACHAN", "ACHAZ", "") && !StringAt((m_current - 2), 7, "MACHADO", "LACHANC", "")) || StringAt((m_current - 1), 6, "ACHISH", "ACHILL", "ACHAIA", "ACHENE", "") || StringAt((m_current - 1), 7, "ACHAIAN", "ACHATES", "ACHIRAL", "ACHERON", "") || StringAt((m_current - 1), 8, "ACHILLEA", "ACHIMAAS", "ACHILARY", "ACHELOUS", "ACHENIAL", "ACHERNAR", "") || StringAt((m_current - 1), 9, "ACHALASIA", "ACHILLEAN", "ACHIMENES", "") || StringAt((m_current - 1), 10, "ACHIMELECH", "ACHITOPHEL", "") // e.g. 'inchoate' || (((m_current - 2) == 0) && (StringAt((m_current - 2), 6, "INCHOA", "") // e.g. 'ischemia' || StringAt(0, 4, "ISCH", "")) ) // e.g. 'ablimelech', 'antioch', 'pentateuch' || (((m_current + 1) == m_last) && StringAt((m_current - 1), 1, "A", "O", "U", "E", "") && !(StringAt(0, 7, "DEBAUCH", "") || StringAt((m_current - 2), 4, "MUCH", "SUCH", "KOCH", "") || StringAt((m_current - 5), 7, "OODRICH", "ALDRICH", "")))) { MetaphAdd("K", "X"); m_current += 2; return true; } return false; } /** * Encodes reliably italian "-CCIA-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CCIA() { //e.g., 'focaccia' if(StringAt((m_current + 1), 3, "CIA", "")) { MetaphAdd("X", "S"); m_current += 2; return true; } return false; } /** * Encode "-CC-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CC() { //double 'C', but not if e.g. 'McClellan' if(StringAt(m_current, 2, "CC", "") && !((m_current == 1) && (CharAt(0) == 'M'))) { // exception if (StringAt((m_current - 3), 7, "FLACCID", "")) { MetaphAdd("S"); AdvanceCounter(3, 2); return true; } //'bacci', 'bertucci', other italian if((((m_current + 2) == m_last) && StringAt((m_current + 2), 1, "I", "")) || StringAt((m_current + 2), 2, "IO", "") || (((m_current + 4) == m_last) && StringAt((m_current + 2), 3, "INO", "INI", ""))) { MetaphAdd("X"); AdvanceCounter(3, 2); return true; } //'accident', 'accede' 'succeed' if(StringAt((m_current + 2), 1, "I", "E", "Y", "") //except 'bellocchio','bacchus', 'soccer' get K && !((CharAt(m_current + 2) == 'H') || StringAt((m_current - 2), 6, "SOCCER", ""))) { MetaphAdd("KS"); AdvanceCounter(3, 2); return true; } else { //Pierce's rule MetaphAdd("K"); m_current += 2; return true; } } return false; } /** * Encode cases where the consonant following "C" is redundant * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CK_CG_CQ() { if(StringAt(m_current, 2, "CK", "CG", "CQ", "")) { // eastern european spelling e.g. 'gorecki' == 'goresky' if(StringAt(m_current, 3, "CKI", "CKY", "") && ((m_current + 2) == m_last) && (m_length > 6)) { MetaphAdd("K", "SK"); } else { MetaphAdd("K"); } m_current += 2; if(StringAt(m_current, 1, "K", "G", "Q", "")) { m_current++; } return true; } return false; } /** * Encode cases where "C" preceeds a front vowel such as "E", "I", or "Y". * These cases most likely => S or X * * @return true if encoding handled in this routine, false if not * */ boolean Encode_C_Front_Vowel() { if(StringAt(m_current, 2, "CI", "CE", "CY", "")) { if(Encode_British_Silent_CE() || Encode_CE() || Encode_CI() || Encode_Latinate_Suffixes()) { AdvanceCounter(2, 1); return true; } MetaphAdd("S"); AdvanceCounter(2, 1); return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_British_Silent_CE() { // english place names like e.g.'gloucester' pronounced glo-ster if((StringAt((m_current + 1), 5, "ESTER", "") && ((m_current + 5) == m_last)) || StringAt((m_current + 1), 10, "ESTERSHIRE", "")) { return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CE() { // 'ocean', 'commercial', 'provincial', 'cello', 'fettucini', 'medici' if((StringAt((m_current + 1), 3, "EAN", "") && IsVowel(m_current - 1)) // e.g. 'rosacea' || (StringAt((m_current - 1), 4, "ACEA", "") && ((m_current + 2) == m_last) && !StringAt(0, 7, "PANACEA", "")) // e.g. 'botticelli', 'concerto' || StringAt((m_current + 1), 4, "ELLI", "ERTO", "EORL", "") // some italian names familiar to americans || (StringAt((m_current - 3), 5, "CROCE", "") && ((m_current + 1) == m_last)) || StringAt((m_current - 3), 5, "DOLCE", "") // e.g. 'cello' || (StringAt((m_current + 1), 4, "ELLO", "") && ((m_current + 4) == m_last))) { MetaphAdd("X", "S"); return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CI() { // with consonant before C // e.g. 'fettucini', but exception for the americanized pronunciation of 'mancini' if(((StringAt((m_current + 1), 3, "INI", "") && !StringAt(0, 7, "MANCINI", "")) && ((m_current + 3) == m_last)) // e.g. 'medici' || (StringAt((m_current - 1), 3, "ICI", "") && ((m_current + 1) == m_last)) // e.g. "commercial', 'provincial', 'cistercian' || StringAt((m_current - 1), 5, "RCIAL", "NCIAL", "RCIAN", "UCIUS", "") // special cases || StringAt((m_current - 3), 6, "MARCIA", "") || StringAt((m_current - 2), 7, "ANCIENT", "")) { MetaphAdd("X", "S"); return true; } // with vowel before C (or at beginning?) if(((StringAt(m_current, 3, "CIO", "CIE", "CIA", "") && IsVowel(m_current - 1)) // e.g. "ciao" || StringAt((m_current + 1), 3, "IAO", "")) && !StringAt((m_current - 4), 8, "COERCION", "")) { if((StringAt(m_current, 4, "CIAN", "CIAL", "CIAO", "CIES", "CIOL", "CION", "") // exception - "glacier" => 'X' but "spacier" = > 'S' || StringAt((m_current - 3), 7, "GLACIER", "") || StringAt(m_current, 5, "CIENT", "CIENC", "CIOUS", "CIATE", "CIATI", "CIATO", "CIABL", "CIARY", "") || (((m_current + 2) == m_last) && StringAt(m_current, 3, "CIA", "CIO", "")) || (((m_current + 3) == m_last) && StringAt(m_current, 3, "CIAS", "CIOS", ""))) // exceptions && !(StringAt((m_current - 4), 11, "ASSOCIATION", "") || StringAt(0, 4, "OCIE", "") // exceptions mostly because these names are usually from // the spanish rather than the italian in america || StringAt((m_current - 2), 5, "LUCIO", "") || StringAt((m_current - 2), 6, "MACIAS", "") || StringAt((m_current - 3), 6, "GRACIE", "GRACIA", "") || StringAt((m_current - 2), 7, "LUCIANO", "") || StringAt((m_current - 3), 8, "MARCIANO", "") || StringAt((m_current - 4), 7, "PALACIO", "") || StringAt((m_current - 4), 9, "FELICIANO", "") || StringAt((m_current - 5), 8, "MAURICIO", "") || StringAt((m_current - 7), 11, "ENCARNACION", "") || StringAt((m_current - 4), 8, "POLICIES", "") || StringAt((m_current - 2), 8, "HACIENDA", "") || StringAt((m_current - 6), 9, "ANDALUCIA", "") || StringAt((m_current - 2), 5, "SOCIO", "SOCIE", ""))) { MetaphAdd("X", "S"); } else { MetaphAdd("S", "X"); } return true; } // exception if(StringAt((m_current - 4), 8, "COERCION", "")) { MetaphAdd("J"); return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Latinate_Suffixes() { if(StringAt((m_current + 1), 4, "EOUS", "IOUS", "")) { MetaphAdd("X", "S"); return true; } return false; } /** * Encodes some exceptions where "C" is silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_C() { if(StringAt((m_current + 1), 1, "T", "S", "")) { if (StringAt(0, 11, "CONNECTICUT", "") || StringAt(0, 6, "INDICT", "TUCSON", "")) { m_current++; return true; } } return false; } /** * Encodes slavic spellings or transliterations * written as "-CZ-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CZ() { if(StringAt((m_current + 1), 1, "Z", "") && !StringAt((m_current - 1), 6, "ECZEMA", "")) { if(StringAt(m_current, 4, "CZAR", "")) { MetaphAdd("S"); } // otherwise most likely a czech word... else { MetaphAdd("X"); } m_current += 2; return true; } return false; } /** * "-CS" special cases * * @return true if encoding handled in this routine, false if not * */ boolean Encode_CS() { // give an 'etymological' 2nd // encoding for "kovacs" so // that it matches "kovach" if(StringAt(0, 6, "KOVACS", "")) { MetaphAdd("KS", "X"); m_current += 2; return true; } if(StringAt((m_current - 1), 3, "ACS", "") && ((m_current + 1) == m_last) && !StringAt((m_current - 4), 6, "ISAACS", "")) { MetaphAdd("X"); m_current += 2; return true; } return false; } /** * Encode "-D-" * */ void Encode_D() { if(Encode_DG() || Encode_DJ() || Encode_DT_DD() || Encode_D_To_J() || Encode_DOUS() || Encode_Silent_D()) { return; } if(m_encodeExact) { // "final de-voicing" in this case // e.g. 'missed' == 'mist' if((m_current == m_last) && StringAt((m_current - 3), 4, "SSED", "")) { MetaphAdd("T"); } else { MetaphAdd("D"); } } else { MetaphAdd("T"); } m_current++; } /** * Encode "-DG-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_DG() { if(StringAt(m_current, 2, "DG", "")) { // excludes exceptions e.g. 'edgar', // or cases where 'g' is first letter of combining form // e.g. 'handgun', 'waldglas' if(StringAt((m_current + 2), 1, "A", "O", "") // e.g. "midgut" || StringAt((m_current + 1), 3, "GUN", "GUT", "") // e.g. "handgrip" || StringAt((m_current + 1), 4, "GEAR", "GLAS", "GRIP", "GREN", "GILL", "GRAF", "") // e.g. "mudgard" || StringAt((m_current + 1), 5, "GUARD", "GUILT", "GRAVE", "GRASS", "") // e.g. "woodgrouse" || StringAt((m_current + 1), 6, "GROUSE", "")) { MetaphAddExactApprox("DG", "TK"); } else { //e.g. "edge", "abridgment" MetaphAdd("J"); } m_current += 2; return true; } return false; } /** * Encode "-DJ-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_DJ() { // e.g. "adjacent" if(StringAt(m_current, 2, "DJ", "")) { MetaphAdd("J"); m_current += 2; return true; } return false; } /** * Encode "-DD-" and "-DT-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_DT_DD() { // eat redundant 'T' or 'D' if(StringAt(m_current, 2, "DT", "DD", "")) { if(StringAt(m_current, 3, "DTH", "")) { MetaphAddExactApprox("D0", "T0"); m_current += 3; } else { if(m_encodeExact) { // devoice it if(StringAt(m_current, 2, "DT", "")) { MetaphAdd("T"); } else { MetaphAdd("D"); } } else { MetaphAdd("T"); } m_current += 2; } return true; } return false; } /** * Encode cases where "-DU-" "-DI-", and "-DI-" => J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_D_To_J() { // e.g. "module", "adulate" if((StringAt(m_current, 3, "DUL", "") && (IsVowel(m_current - 1) && IsVowel(m_current + 3))) // e.g. "soldier", "grandeur", "procedure" || (((m_current + 3) == m_last) && StringAt((m_current - 1) , 5, "LDIER", "NDEUR", "EDURE", "RDURE", "")) || StringAt((m_current - 3), 7, "CORDIAL", "") // e.g. "pendulum", "education" || StringAt((m_current - 1), 5, "NDULA", "NDULU", "EDUCA", "") // e.g. "individual", "individual", "residuum" || StringAt((m_current - 1), 4, "ADUA", "IDUA", "IDUU", "")) { MetaphAddExactApprox("J", "D", "J", "T"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode latinate suffix "-DOUS" where 'D' is pronounced as J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_DOUS() { // e.g. "assiduous", "arduous" if(StringAt((m_current + 1), 4, "UOUS", "")) { MetaphAddExactApprox("J", "D", "J", "T"); AdvanceCounter(4, 1); return true; } return false; } /** * Encode silent "-D-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_D() { // silent 'D' e.g. 'wednesday', 'handsome' if(StringAt((m_current - 2), 9, "WEDNESDAY", "") || StringAt((m_current - 3), 7, "HANDKER", "HANDSOM", "WINDSOR", "") // french silent D at end in words or names familiar to americans || StringAt((m_current - 5), 6, "PERNOD", "ARTAUD", "RENAUD", "") || StringAt((m_current - 6), 7, "RIMBAUD", "MICHAUD", "BICHAUD", "")) { m_current++; return true; } return false; } /** * Encode "-F-" * */ void Encode_F() { // Encode cases where "-FT-" => "T" is usually silent // e.g. 'often', 'soften' // This should really be covered under "T"! if(StringAt((m_current - 1), 5, "OFTEN", "")) { MetaphAdd("F", "FT"); m_current += 2; return; } // eat redundant 'F' if(CharAt(m_current + 1) == 'F') { m_current += 2; } else { m_current++; } MetaphAdd("F"); } /** * Encode "-G-" * */ void Encode_G() { if(Encode_Silent_G_At_Beginning() || Encode_GG() || Encode_GK() || Encode_GH() || Encode_Silent_G() || Encode_GN() || Encode_GL() || Encode_Initial_G_Front_Vowel() || Encode_NGER() || Encode_GER() || Encode_GEL() || Encode_Non_Initial_G_Front_Vowel() || Encode_GA_To_J()) { return; } if(!StringAt((m_current - 1), 1, "C", "K", "G", "Q", "")) { MetaphAddExactApprox("G", "K"); } m_current++; } /** * Encode cases where 'G' is silent at beginning of word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_G_At_Beginning() { //skip these when at start of word if((m_current == 0) && StringAt(m_current, 2, "GN", "")) { m_current += 1; return true; } return false; } /** * Encode "-GG-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GG() { if(CharAt(m_current + 1) == 'G') { // italian e.g, 'loggia', 'caraveggio', also 'suggest' and 'exaggerate' if(StringAt((m_current - 1), 5, "AGGIA", "OGGIA", "AGGIO", "EGGIO", "EGGIA", "IGGIO", "") // 'ruggiero' but not 'snuggies' || (StringAt((m_current - 1), 5, "UGGIE", "") && !(((m_current + 3) == m_last) || ((m_current + 4) == m_last))) || (((m_current + 2) == m_last) && StringAt((m_current - 1), 4, "AGGI", "OGGI", "")) || StringAt((m_current - 2), 6, "SUGGES", "XAGGER", "REGGIE", "")) { // expection where "-GG-" => KJ if (StringAt((m_current - 2), 7, "SUGGEST", "")) { MetaphAddExactApprox("G", "K"); } MetaphAdd("J"); AdvanceCounter(3, 2); } else { MetaphAddExactApprox("G", "K"); m_current += 2; } return true; } return false; } /** * Encode "-GK-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GK() { // 'gingko' if(CharAt(m_current + 1) == 'K') { MetaphAdd("K"); m_current += 2; return true; } return false; } /** * Encode "-GH-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH() { if(CharAt(m_current + 1) == 'H') { if(Encode_GH_After_Consonant() || Encode_Initial_GH() || Encode_GH_To_J() || Encode_GH_To_H() || Encode_UGHT() || Encode_GH_H_Part_Of_Other_Word() || Encode_Silent_GH() || Encode_GH_To_F()) { return true; } MetaphAddExactApprox("G", "K"); m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH_After_Consonant() { // e.g. 'burgher', 'bingham' if((m_current > 0) && !IsVowel(m_current - 1) // not e.g. 'greenhalgh' && !(StringAt((m_current - 3), 5, "HALGH", "") && ((m_current + 1) == m_last))) { MetaphAddExactApprox("G", "K"); m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_GH() { if(m_current < 3) { // e.g. "ghislane", "ghiradelli" if(m_current == 0) { if(CharAt(m_current + 2) == 'I') { MetaphAdd("J"); } else { MetaphAddExactApprox("G", "K"); } m_current += 2; return true; } } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH_To_J() { // e.g., 'greenhalgh', 'dunkenhalgh', english names if(StringAt((m_current - 2), 4, "ALGH", "") && ((m_current + 1) == m_last)) { MetaphAdd("J", ""); m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH_To_H() { // special cases // e.g., 'donoghue', 'donaghy' if((StringAt((m_current - 4), 4, "DONO", "DONA", "") && IsVowel(m_current + 2)) || StringAt((m_current - 5), 9, "CALLAGHAN", "")) { MetaphAdd("H"); m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_UGHT() { //e.g. "ought", "aught", "daughter", "slaughter" if(StringAt((m_current - 1), 4, "UGHT", "")) { if ((StringAt((m_current - 3), 5, "LAUGH", "") && !(StringAt((m_current - 4), 7, "SLAUGHT", "") || StringAt((m_current - 3), 7, "LAUGHTO", ""))) || StringAt((m_current - 4), 6, "DRAUGH", "")) { MetaphAdd("FT"); } else { MetaphAdd("T"); } m_current += 3; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH_H_Part_Of_Other_Word() { // if the 'H' is the beginning of another word or syllable if (StringAt((m_current + 1), 4, "HOUS", "HEAD", "HOLE", "HORN", "HARN", "")) { MetaphAddExactApprox("G", "K"); m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_GH() { //Parker's rule (with some further refinements) - e.g., 'hugh' if(((((m_current > 1) && StringAt((m_current - 2), 1, "B", "H", "D", "G", "L", "") ) //e.g., 'bough' || ((m_current > 2) && StringAt((m_current - 3), 1, "B", "H", "D", "K", "W", "N", "P", "V", "") && !StringAt(0, 6, "ENOUGH", "")) //e.g., 'broughton' || ((m_current > 3) && StringAt((m_current - 4), 1, "B", "H", "") ) //'plough', 'slaugh' || ((m_current > 3) && StringAt((m_current - 4), 2, "PL", "SL", "") ) || ((m_current > 0) // 'sigh', 'light' && ((CharAt(m_current - 1) == 'I') || StringAt(0, 4, "PUGH", "") // e.g. 'MCDONAGH', 'MURTAGH', 'CREAGH' || (StringAt((m_current - 1), 3, "AGH", "") && ((m_current + 1) == m_last)) || StringAt((m_current - 4), 6, "GERAGH", "DRAUGH", "") || (StringAt((m_current - 3), 5, "GAUGH", "GEOGH", "MAUGH", "") && !StringAt(0, 9, "MCGAUGHEY", "")) // exceptions to 'tough', 'rough', 'lough' || (StringAt((m_current - 2), 4, "OUGH", "") && (m_current > 3) && !StringAt((m_current - 4), 6, "CCOUGH", "ENOUGH", "TROUGH", "CLOUGH", ""))))) // suffixes starting w/ vowel where "-GH-" is usually silent && (StringAt((m_current - 3), 5, "VAUGH", "FEIGH", "LEIGH", "") || StringAt((m_current - 2), 4, "HIGH", "TIGH", "") || ((m_current + 1) == m_last) || (StringAt((m_current + 2), 2, "IE", "EY", "ES", "ER", "ED", "TY", "") && ((m_current + 3) == m_last) && !StringAt((m_current - 5), 9, "GALLAGHER", "")) || (StringAt((m_current + 2), 1, "Y", "") && ((m_current + 2) == m_last)) || (StringAt((m_current + 2), 3, "ING", "OUT", "") && ((m_current + 4) == m_last)) || (StringAt((m_current + 2), 4, "ERTY", "") && ((m_current + 5) == m_last)) || (!IsVowel(m_current + 2) || StringAt((m_current - 3), 5, "GAUGH", "GEOGH", "MAUGH", "") || StringAt((m_current - 4), 8, "BROUGHAM", "")))) // exceptions where '-g-' pronounced && !(StringAt(0, 6, "BALOGH", "SABAGH", "") || StringAt((m_current - 2), 7, "BAGHDAD", "") || StringAt((m_current - 3), 5, "WHIGH", "") || StringAt((m_current - 5), 7, "SABBAGH", "AKHLAGH", ""))) { // silent - do nothing m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH_Special_Cases() { boolean handled = false; // special case: 'hiccough' == 'hiccup' if(StringAt((m_current - 6), 8, "HICCOUGH", "")) { MetaphAdd("P"); handled = true; } // special case: 'lough' alt spelling for scots 'loch' else if(StringAt(0, 5, "LOUGH", "")) { MetaphAdd("K"); handled = true; } // hungarian else if(StringAt(0, 6, "BALOGH", "")) { MetaphAddExactApprox("G", "", "K", ""); handled = true; } // "maclaughlin" else if(StringAt((m_current - 3), 8, "LAUGHLIN", "COUGHLAN", "LOUGHLIN", "")) { MetaphAdd("K", "F"); handled = true; } else if(StringAt((m_current - 3), 5, "GOUGH", "") || StringAt((m_current - 7), 9, "COLCLOUGH", "")) { MetaphAdd("", "F"); handled = true; } if(handled) { m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GH_To_F() { // the cases covered here would fall under // the GH_To_F rule below otherwise if(Encode_GH_Special_Cases()) { return true; } else { //e.g., 'laugh', 'cough', 'rough', 'tough' if((m_current > 2) && (CharAt(m_current - 1) == 'U') && IsVowel(m_current - 2) && StringAt((m_current - 3), 1, "C", "G", "L", "R", "T", "N", "S", "") && !StringAt((m_current - 4), 8, "BREUGHEL", "FLAUGHER", "")) { MetaphAdd("F"); m_current += 2; return true; } } return false; } /** * Encode some contexts where "g" is silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_G() { // e.g. "phlegm", "apothegm", "voigt" if((((m_current + 1) == m_last) && (StringAt((m_current - 1), 3, "EGM", "IGM", "AGM", "") || StringAt(m_current, 2, "GT", ""))) || (StringAt(0, 5, "HUGES", "") && (m_length == 5))) { m_current++; return true; } // vietnamese names e.g. "Nguyen" but not "Ng" if(StringAt(0, 2, "NG", "") && (m_current != m_last)) { m_current++; return true; } return false; } /** * ENcode "-GN-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GN() { if(CharAt(m_current + 1) == 'N') { // 'align' 'sign', 'resign' but not 'resignation' // also 'impugn', 'impugnable', but not 'repugnant' if(((m_current > 1) && ((StringAt((m_current - 1), 1, "I", "U", "E", "") || StringAt((m_current - 3), 9, "LORGNETTE", "") || StringAt((m_current - 2), 9, "LAGNIAPPE", "") || StringAt((m_current - 2), 6, "COGNAC", "") || StringAt((m_current - 3), 7, "CHAGNON", "") || StringAt((m_current - 5), 9, "COMPAGNIE", "") || StringAt((m_current - 4), 6, "BOLOGN", "")) // Exceptions: following are cases where 'G' is pronounced // in "assign" 'g' is silent, but not in "assignation" && !(StringAt((m_current + 2), 5, "ATION", "") || StringAt((m_current + 2), 4, "ATOR", "") || StringAt((m_current + 2), 3, "ATE", "ITY", "") // exception to exceptions, not pronounced: || (StringAt((m_current + 2), 2, "AN", "AC", "IA", "UM", "") && !(StringAt((m_current - 3), 8, "POIGNANT", "") || StringAt((m_current - 2), 6, "COGNAC", ""))) || StringAt(0, 7, "SPIGNER", "STEGNER", "") || (StringAt(0, 5, "SIGNE", "") && (m_length == 5)) || StringAt((m_current - 2), 5, "LIGNI", "LIGNO", "REGNA", "DIGNI", "WEGNE", "TIGNE", "RIGNE", "REGNE", "TIGNO", "") || StringAt((m_current - 2), 6, "SIGNAL", "SIGNIF", "SIGNAT", "") || StringAt((m_current - 1), 5, "IGNIT", "")) && !StringAt((m_current - 2), 6, "SIGNET", "LIGNEO", "") )) //not e.g. 'cagney', 'magna' || (((m_current + 2) == m_last) && StringAt(m_current, 3, "GNE", "GNA", "") && !StringAt((m_current - 2), 5, "SIGNA", "MAGNA", "SIGNE", ""))) { MetaphAddExactApprox("N", "GN", "N", "KN"); } else { MetaphAddExactApprox("GN", "KN"); } m_current += 2; return true; } return false; } /** * Encode "-GL-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GL() { //'tagliaro', 'puglia' BUT add K in alternative // since americans sometimes do this if(StringAt((m_current + 1), 3, "LIA", "LIO", "LIE", "") && IsVowel(m_current - 1)) { MetaphAddExactApprox("L", "GL", "L", "KL"); m_current += 2; return true; } return false; } /** * * @return true if encoding handled in this routine, false if not * */ boolean Initial_G_Soft() { if(((StringAt((m_current + 1), 2, "EL", "EM", "EN", "EO", "ER", "ES", "IA", "IN", "IO", "IP", "IU", "YM", "YN", "YP", "YR", "EE", "") || StringAt((m_current + 1), 3, "IRA", "IRO", "")) // except for smaller set of cases where => K, e.g. "gerber" && !(StringAt((m_current + 1), 3, "ELD", "ELT", "ERT", "INZ", "ERH", "ITE", "ERD", "ERL", "ERN", "INT", "EES", "EEK", "ELB", "EER", "") || StringAt((m_current + 1), 4, "ERSH", "ERST", "INSB", "INGR", "EROW", "ERKE", "EREN", "") || StringAt((m_current + 1), 5, "ELLER", "ERDIE", "ERBER", "ESUND", "ESNER", "INGKO", "INKGO", "IPPER", "ESELL", "IPSON", "EEZER", "ERSON", "ELMAN", "") || StringAt((m_current + 1), 6, "ESTALT", "ESTAPO", "INGHAM", "ERRITY", "ERRISH", "ESSNER", "ENGLER", "") || StringAt((m_current + 1), 7, "YNAECOL", "YNECOLO", "ENTHNER", "ERAGHTY", "") || StringAt((m_current + 1), 8, "INGERICH", "EOGHEGAN", ""))) ||(IsVowel(m_current + 1) && (StringAt((m_current + 1), 3, "EE ", "EEW", "") || (StringAt((m_current + 1), 3, "IGI", "IRA", "IBE", "AOL", "IDE", "IGL", "") && !StringAt((m_current + 1), 5, "IDEON", "") ) || StringAt((m_current + 1), 4, "ILES", "INGI", "ISEL", "") || (StringAt((m_current + 1), 5, "INGER", "") && !StringAt((m_current + 1), 8, "INGERICH", "")) || StringAt((m_current + 1), 5, "IBBER", "IBBET", "IBLET", "IBRAN", "IGOLO", "IRARD", "IGANT", "") || StringAt((m_current + 1), 6, "IRAFFE", "EEWHIZ","") || StringAt((m_current + 1), 7, "ILLETTE", "IBRALTA", "")))) { return true; } return false; } /** * Encode cases where 'G' is at start of word followed * by a "front" vowel e.g. 'E', 'I', 'Y' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_G_Front_Vowel() { // 'g' followed by vowel at beginning if((m_current == 0) && Front_Vowel(m_current + 1)) { // special case "gila" as in "gila monster" if(StringAt((m_current + 1), 3, "ILA", "") && (m_length == 4)) { MetaphAdd("H"); } else if(Initial_G_Soft()) { MetaphAddExactApprox("J", "G", "J", "K"); } else { // only code alternate 'J' if front vowel if((m_inWord.charAt(m_current + 1) == 'E') || (m_inWord.charAt(m_current + 1) == 'I')) { MetaphAddExactApprox("G", "J", "K", "J"); } else { MetaphAddExactApprox("G", "K"); } } AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-NGER-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_NGER() { if((m_current > 1) && StringAt((m_current - 1), 4, "NGER", "")) { // default 'G' => J such as 'ranger', 'stranger', 'manger', 'messenger', 'orangery', 'granger' // 'boulanger', 'challenger', 'danger', 'changer', 'harbinger', 'lounger', 'ginger', 'passenger' // except for these the following if(!(RootOrInflections(m_inWord, "ANGER") || RootOrInflections(m_inWord, "LINGER") || RootOrInflections(m_inWord, "MALINGER") || RootOrInflections(m_inWord, "FINGER") || (StringAt((m_current - 3), 4, "HUNG", "FING", "BUNG", "WING", "RING", "DING", "ZENG", "ZING", "JUNG", "LONG", "PING", "CONG", "MONG", "BANG", "GANG", "HANG", "LANG", "SANG", "SING", "WANG", "ZANG", "") // exceptions to above where 'G' => J && !(StringAt((m_current - 6), 7, "BOULANG", "SLESING", "KISSING", "DERRING", "") || StringAt((m_current - 8), 9, "SCHLESING", "") || StringAt((m_current - 5), 6, "SALING", "BELANG", "") || StringAt((m_current - 6), 7, "BARRING", "") || StringAt((m_current - 6), 9, "PHALANGER", "") || StringAt((m_current - 4), 5, "CHANG", ""))) || StringAt((m_current - 4), 5, "STING", "YOUNG", "") || StringAt((m_current - 5), 6, "STRONG", "") || StringAt(0, 3, "UNG", "ENG", "ING", "") || StringAt(m_current, 6, "GERICH", "") || StringAt(0, 6, "SENGER", "") || StringAt((m_current - 3), 6, "WENGER", "MUNGER", "SONGER", "KINGER", "") || StringAt((m_current - 4), 7, "FLINGER", "SLINGER", "STANGER", "STENGER", "KLINGER", "CLINGER", "") || StringAt((m_current - 5), 8, "SPRINGER", "SPRENGER", "") || StringAt((m_current - 3), 7, "LINGERF", "") || StringAt((m_current - 2), 7, "ANGERLY", "ANGERBO", "INGERSO", "") )) { MetaphAddExactApprox("J", "G", "J", "K"); } else { MetaphAddExactApprox("G", "J", "K", "J"); } AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-GER-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GER() { if((m_current > 0) && StringAt((m_current + 1), 2, "ER", "")) { // Exceptions to 'GE' where 'G' => K // e.g. "JAGER", "TIGER", "LIGER", "LAGER", "LUGER", "AUGER", "EAGER", "HAGER", "SAGER" if((((m_current == 2) && IsVowel(m_current - 1) && !IsVowel(m_current - 2) && !(StringAt((m_current - 2), 5, "PAGER", "WAGER", "NIGER", "ROGER", "LEGER", "CAGER", "")) || StringAt((m_current - 2), 5, "AUGER", "EAGER", "INGER", "YAGER", "")) || StringAt((m_current - 3), 6, "SEEGER", "JAEGER", "GEIGER", "KRUGER", "SAUGER", "BURGER", "MEAGER", "MARGER", "RIEGER", "YAEGER", "STEGER", "PRAGER", "SWIGER", "YERGER", "TORGER", "FERGER", "HILGER", "ZEIGER", "YARGER", "COWGER", "CREGER", "KROGER", "KREGER", "GRAGER", "STIGER", "BERGER", "") // 'berger' but not 'bergerac' || (StringAt((m_current - 3), 6, "BERGER", "") && ((m_current + 2) == m_last)) || StringAt((m_current - 4), 7, "KREIGER", "KRUEGER", "METZGER", "KRIEGER", "KROEGER", "STEIGER", "DRAEGER", "BUERGER", "BOERGER", "FIBIGER", "") // e.g. 'harshbarger', 'winebarger' || (StringAt((m_current - 3), 6, "BARGER", "") && (m_current > 4)) // e.g. 'weisgerber' || (StringAt(m_current, 6, "GERBER", "") && (m_current > 0)) || StringAt((m_current - 5), 8, "SCHWAGER", "LYBARGER", "SPRENGER", "GALLAGER", "WILLIGER", "") || StringAt(0, 4, "HARGER", "") || (StringAt(0, 4, "AGER", "EGER", "") && (m_length == 4)) || StringAt((m_current - 1), 6, "YGERNE", "") || StringAt((m_current - 6), 9, "SCHWEIGER", "")) && !(StringAt((m_current - 5), 10, "BELLIGEREN", "") || StringAt(0, 7, "MARGERY", "") || StringAt((m_current - 3), 8, "BERGERAC", ""))) { if(SlavoGermanic()) { MetaphAddExactApprox("G", "K"); } else { MetaphAddExactApprox("G", "J", "K", "J"); } } else { MetaphAddExactApprox("J", "G", "J", "K"); } AdvanceCounter(2, 1); return true; } return false; } /** * ENcode "-GEL-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GEL() { // more likely to be "-GEL-" => JL if(StringAt((m_current + 1), 2, "EL", "") && (m_current > 0)) { // except for // "BAGEL", "HEGEL", "HUGEL", "KUGEL", "NAGEL", "VOGEL", "FOGEL", "PAGEL" if(((m_length == 5) && IsVowel(m_current - 1) && !IsVowel(m_current - 2) && !StringAt((m_current - 2), 5, "NIGEL", "RIGEL", "")) // or the following as combining forms || StringAt((m_current - 2), 5, "ENGEL", "HEGEL", "NAGEL", "VOGEL", "") || StringAt((m_current - 3), 6, "MANGEL", "WEIGEL", "FLUGEL", "RANGEL", "HAUGEN", "RIEGEL", "VOEGEL", "") || StringAt((m_current - 4), 7, "SPEIGEL", "STEIGEL", "WRANGEL", "SPIEGEL", "") || StringAt((m_current - 4), 8, "DANEGELD", "")) { if(SlavoGermanic()) { MetaphAddExactApprox("G", "K"); } else { MetaphAddExactApprox("G", "J", "K", "J"); } } else { MetaphAddExactApprox("J", "G", "J", "K"); } AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-G-" followed by a vowel when non-initial leter. * Default for this is a 'J' sound, so check exceptions where * it is pronounced 'G' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Non_Initial_G_Front_Vowel() { // -gy-, gi-, ge- if(StringAt((m_current + 1), 1, "E", "I", "Y", "")) { // '-ge' at end // almost always 'j 'sound if(StringAt(m_current, 2, "GE", "") && (m_current == (m_last - 1))) { if(Hard_GE_At_End()) { if(SlavoGermanic()) { MetaphAddExactApprox("G", "K"); } else { MetaphAddExactApprox("G", "J", "K", "J"); } } else { MetaphAdd("J"); } } else { if(Internal_Hard_G()) { // don't encode KG or KK if e.g. "mcgill" if(!((m_current == 2) && StringAt(0, 2, "MC", "")) || ((m_current == 3) && StringAt(0, 3, "MAC", ""))) { if(SlavoGermanic()) { MetaphAddExactApprox("G", "K"); } else { MetaphAddExactApprox("G", "J", "K", "J"); } } } else { MetaphAddExactApprox("J", "G", "J", "K"); } } AdvanceCounter(2, 1); return true; } return false; } /* * Detect german names and other words that have * a 'hard' 'g' in the context of "-ge" at end * * @return true if encoding handled in this routine, false if not */ boolean Hard_GE_At_End() { if(StringAt(0, 6, "RENEGE", "STONGE", "STANGE", "PRANGE", "KRESGE", "") || StringAt(0, 5, "BYRGE", "BIRGE", "BERGE", "HAUGE", "") || StringAt(0, 4, "HAGE", "") || StringAt(0, 5, "LANGE", "SYNGE", "BENGE", "RUNGE", "HELGE", "") || StringAt(0, 4, "INGE", "LAGE", "")) { return true; } return false; } /** * Exceptions to default encoding to 'J': * encode "-G-" to 'G' in "-g<frontvowel>-" words * where we are not at "-GE" at the end of the word * * @return true if encoding handled in this routine, false if not * */ boolean Internal_Hard_G() { // if not "-GE" at end if(!(((m_current + 1) == m_last) && (CharAt(m_current + 1) == 'E') ) && (Internal_Hard_NG() || Internal_Hard_GEN_GIN_GET_GIT() || Internal_Hard_G_Open_Syllable() || Internal_Hard_G_Other())) { return true; } return false; } /** * Detect words where "-ge-" or "-gi-" get a 'hard' 'g' * even though this is usually a 'soft' 'g' context * * @return true if 'hard' 'g' detected * */ boolean Internal_Hard_G_Other() { if((StringAt(m_current, 4, "GETH", "GEAR", "GEIS", "GIRL", "GIVI", "GIVE", "GIFT", "GIRD", "GIRT", "GILV", "GILD", "GELD", "") && !StringAt((m_current - 3), 6, "GINGIV", "") ) // "gish" but not "largish" || (StringAt((m_current + 1), 3, "ISH", "") && (m_current > 0) && !StringAt(0, 4, "LARG", "")) || (StringAt((m_current - 2), 5, "MAGED", "MEGID", "") && !((m_current + 2) == m_last)) || StringAt(m_current, 3, "GEZ", "") || StringAt(0, 4, "WEGE", "HAGE", "") || (StringAt((m_current - 2), 6, "ONGEST", "UNGEST", "") && ((m_current + 3) == m_last) && !StringAt((m_current - 3), 7, "CONGEST", "")) || StringAt(0, 5, "VOEGE", "BERGE", "HELGE", "") || (StringAt(0, 4, "ENGE", "BOGY", "") && (m_length == 4)) || StringAt(m_current, 6, "GIBBON", "") || StringAt(0, 10, "CORREGIDOR", "") || StringAt(0, 8, "INGEBORG", "") || (StringAt(m_current, 4, "GILL", "") && (((m_current + 3) == m_last) || ((m_current + 4) == m_last)) && !StringAt(0, 8, "STURGILL", ""))) { return true; } return false; } /** * Detect words where "-gy-", "-gie-", "-gee-", * or "-gio-" get a 'hard' 'g' even though this is * usually a 'soft' 'g' context * * @return true if 'hard' 'g' detected * */ boolean Internal_Hard_G_Open_Syllable() { if(StringAt((m_current + 1), 3, "EYE", "") || StringAt((m_current - 2), 4, "FOGY", "POGY", "YOGI", "") || StringAt((m_current - 2), 5, "MAGEE", "MCGEE", "HAGIO", "") || StringAt((m_current - 1), 4, "RGEY", "OGEY", "") || StringAt((m_current - 3), 5, "HOAGY", "STOGY", "PORGY", "") || StringAt((m_current - 5), 8, "CARNEGIE", "") || (StringAt((m_current - 1), 4, "OGEY", "OGIE", "") && ((m_current + 2) == m_last))) { return true; } return false; } /** * Detect a number of contexts, mostly german names, that * take a 'hard' 'g'. * * @return true if 'hard' 'g' detected, false if not * */ boolean Internal_Hard_GEN_GIN_GET_GIT() { if((StringAt((m_current - 3), 6, "FORGET", "TARGET", "MARGIT", "MARGET", "TURGEN", "BERGEN", "MORGEN", "JORGEN", "HAUGEN", "JERGEN", "JURGEN", "LINGEN", "BORGEN", "LANGEN", "KLAGEN", "STIGER", "BERGER", "") && !StringAt(m_current, 7, "GENETIC", "GENESIS", "") && !StringAt((m_current - 4), 8, "PLANGENT", "")) || (StringAt((m_current - 3), 6, "BERGIN", "FEAGIN", "DURGIN", "") && ((m_current + 2) == m_last)) || (StringAt((m_current - 2), 5, "ENGEN", "") && !StringAt((m_current + 3), 3, "DER", "ETI", "ESI", "")) || StringAt((m_current - 4), 7, "JUERGEN", "") || StringAt(0, 5, "NAGIN", "MAGIN", "HAGIN", "") || (StringAt(0, 5, "ENGIN", "DEGEN", "LAGEN", "MAGEN", "NAGIN", "") && (m_length == 5)) || (StringAt((m_current - 2), 5, "BEGET", "BEGIN", "HAGEN", "FAGIN", "BOGEN", "WIGIN", "NTGEN", "EIGEN", "WEGEN", "WAGEN", "") && !StringAt((m_current - 5), 8, "OSPHAGEN", ""))) { return true; } return false; } /** * Detect a number of contexts of '-ng-' that will * take a 'hard' 'g' despite being followed by a * front vowel. * * @return true if 'hard' 'g' detected, false if not * */ boolean Internal_Hard_NG() { if((StringAt((m_current - 3), 4, "DANG", "FANG", "SING", "") // exception to exception && !StringAt((m_current - 5), 8, "DISINGEN", "") ) || StringAt(0, 5, "INGEB", "ENGEB", "") || (StringAt((m_current - 3), 4, "RING", "WING", "HANG", "LONG", "") && !(StringAt((m_current - 4), 5, "CRING", "FRING", "ORANG", "TWING", "CHANG", "PHANG", "") || StringAt((m_current - 5), 6, "SYRING", "") || StringAt((m_current - 3), 7, "RINGENC", "RINGENT", "LONGITU", "LONGEVI", "") // e.g. 'longino', 'mastrangelo' || (StringAt(m_current, 4, "GELO", "GINO", "") && ((m_current + 3) == m_last)))) || (StringAt((m_current - 1), 3, "NGY", "") // exceptions to exception && !(StringAt((m_current - 3), 5, "RANGY", "MANGY", "MINGY", "") || StringAt((m_current - 4), 6, "SPONGY", "STINGY", "")))) { return true; } return false; } /** * Encode special case where "-GA-" => J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_GA_To_J() { // 'margary', 'margarine' if((StringAt((m_current - 3), 7, "MARGARY", "MARGARI", "") // but not in spanish forms such as "margatita" && !StringAt((m_current - 3), 8, "MARGARIT", "")) || StringAt(0, 4, "GAOL", "") || StringAt((m_current - 2), 5, "ALGAE", "")) { MetaphAddExactApprox("J", "G", "J", "K"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode 'H' * * */ void Encode_H() { if(Encode_Initial_Silent_H() || Encode_Initial_HS() || Encode_Initial_HU_HW() || Encode_Non_Initial_Silent_H()) { return; } //only keep if first & before vowel or btw. 2 vowels if(!Encode_H_Pronounced()) { //also takes care of 'HH' m_current++; } } /** * Encode cases where initial 'H' is not pronounced (in American) * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_Silent_H() { //'hour', 'herb', 'heir', 'honor' if(StringAt((m_current + 1), 3, "OUR", "ERB", "EIR", "") || StringAt((m_current + 1), 4, "ONOR", "") || StringAt((m_current + 1), 5, "ONOUR", "ONEST", "")) { // british pronounce H in this word // americans give it 'H' for the name, // no 'H' for the plant if((m_current == 0) && StringAt(m_current, 4, "HERB", "")) { if(m_encodeVowels) { MetaphAdd("HA", "A"); } else { MetaphAdd("H", "A"); } } else if((m_current == 0) || m_encodeVowels) { MetaphAdd("A"); } m_current++; // don't encode vowels twice m_current = SkipVowels(m_current); return true; } return false; } /** * Encode "HS-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_HS() { // old chinese pinyin transliteration // e.g., 'HSIAO' if ((m_current == 0) && StringAt(0, 2, "HS", "")) { MetaphAdd("X"); m_current += 2; return true; } return false; } /** * Encode cases where "HU-" is pronounced as part of a vowel dipthong * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_HU_HW() { // spanish spellings and chinese pinyin transliteration if (StringAt(0, 3, "HUA", "HUE", "HWA", "")) { if(!StringAt(m_current, 4, "HUEY", "")) { MetaphAdd("A"); if(!m_encodeVowels) { m_current += 3; } else { m_current++; // don't encode vowels twice while(IsVowel(m_current) || (CharAt(m_current) == 'W')) { m_current++; } } return true; } } return false; } /** * Encode cases where 'H' is silent between vowels * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Non_Initial_Silent_H() { //exceptions - 'h' not pronounced // "PROHIB" BUT NOT "PROHIBIT" if(StringAt((m_current - 2), 5, "NIHIL", "VEHEM", "LOHEN", "NEHEM", "MAHON", "MAHAN", "COHEN", "GAHAN", "") || StringAt((m_current - 3), 6, "GRAHAM", "PROHIB", "FRAHER", "TOOHEY", "TOUHEY", "") || StringAt((m_current - 3), 5, "TOUHY", "") || StringAt(0, 9, "CHIHUAHUA", "")) { if(!m_encodeVowels) { m_current += 2; } else { m_current++; // don't encode vowels twice m_current = SkipVowels(m_current); } return true; } return false; } /** * Encode cases where 'H' is pronounced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_H_Pronounced() { if((((m_current == 0) || IsVowel(m_current - 1) || ((m_current > 0) && (CharAt(m_current - 1) == 'W'))) && IsVowel(m_current + 1)) // e.g. 'alWahhab' || ((CharAt(m_current + 1) == 'H') && IsVowel(m_current + 2))) { MetaphAdd("H"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode 'J' * */ void Encode_J() { if(Encode_Spanish_J() || Encode_Spanish_OJ_UJ()) { return; } Encode_Other_J(); } /** * Encode cases where initial or medial "j" is in a spanish word or name * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Spanish_J() { //obvious spanish, e.g. "jose", "san jacinto" if((StringAt((m_current + 1), 3, "UAN", "ACI", "ALI", "EFE", "ICA", "IME", "OAQ", "UAR", "") && !StringAt(m_current, 8, "JIMERSON", "JIMERSEN", "")) || (StringAt((m_current + 1), 3, "OSE", "") && ((m_current + 3) == m_last)) || StringAt((m_current + 1), 4, "EREZ", "UNTA", "AIME", "AVIE", "AVIA", "") || StringAt((m_current + 1), 6, "IMINEZ", "ARAMIL", "") || (((m_current + 2) == m_last) && StringAt((m_current - 2), 5, "MEJIA", "")) || StringAt((m_current - 2), 5, "TEJED", "TEJAD", "LUJAN", "FAJAR", "BEJAR", "BOJOR", "CAJIG", "DEJAS", "DUJAR", "DUJAN", "MIJAR", "MEJOR", "NAJAR", "NOJOS", "RAJED", "RIJAL", "REJON", "TEJAN", "UIJAN", "") || StringAt((m_current - 3), 8, "ALEJANDR", "GUAJARDO", "TRUJILLO", "") || (StringAt((m_current - 2), 5, "RAJAS", "") && (m_current > 2)) || (StringAt((m_current - 2), 5, "MEJIA", "") && !StringAt((m_current - 2), 6, "MEJIAN", "")) || StringAt((m_current - 1), 5, "OJEDA", "") || StringAt((m_current - 3), 5, "LEIJA", "MINJA", "") || StringAt((m_current - 3), 6, "VIAJES", "GRAJAL", "") || StringAt(m_current, 8, "JAUREGUI", "") || StringAt((m_current - 4), 8, "HINOJOSA", "") || StringAt(0, 4, "SAN ", "") || (((m_current + 1) == m_last) && (CharAt(m_current + 1) == 'O') // exceptions && !(StringAt(0, 4, "TOJO", "") || StringAt(0, 5, "BANJO", "") || StringAt(0, 6, "MARYJO", "")))) { // americans pronounce "juan" as 'wan' // and "marijuana" and "tijuana" also // do not get the 'H' as in spanish, so // just treat it like a vowel in these cases if(!(StringAt(m_current, 4, "JUAN", "") || StringAt(m_current, 4, "JOAQ", ""))) { MetaphAdd("H"); } else { if(m_current == 0) { MetaphAdd("A"); } } AdvanceCounter(2, 1); return true; } // Jorge gets 2nd HARHA. also JULIO, JESUS if(StringAt((m_current + 1), 4, "ORGE", "ULIO", "ESUS", "") && !StringAt(0, 6, "JORGEN", "")) { // get both consonants for "jorge" if(((m_current + 4) == m_last) && StringAt((m_current + 1), 4, "ORGE", "")) { if(m_encodeVowels) { MetaphAdd("JARJ", "HARHA"); } else { MetaphAdd("JRJ", "HRH"); } AdvanceCounter(5, 5); return true; } MetaphAdd("J", "H"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode cases where 'J' is clearly in a german word or name * that americans pronounce in the german fashion * * @return true if encoding handled in this routine, false if not * */ boolean Encode_German_J() { if(StringAt((m_current + 1), 2, "AH", "") || (StringAt((m_current + 1), 5, "OHANN", "") && ((m_current + 5) == m_last)) || (StringAt((m_current + 1), 3, "UNG", "") && !StringAt((m_current + 1), 4, "UNGL", "")) || StringAt((m_current + 1), 3, "UGO", "")) { MetaphAdd("A"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-JOJ-" and "-JUJ-" as spanish words * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Spanish_OJ_UJ() { if(StringAt((m_current + 1), 5, "OJOBA", "UJUY ", "")) { if(m_encodeVowels) { MetaphAdd("HAH"); } else { MetaphAdd("HH"); } AdvanceCounter(4, 3); return true; } return false; } /** * Encode 'J' => J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_J_To_J() { if(IsVowel(m_current + 1)) { if((m_current == 0) && Names_Beginning_With_J_That_Get_Alt_Y()) { // 'Y' is a vowel so encode // is as 'A' if(m_encodeVowels) { MetaphAdd("JA", "A"); } else { MetaphAdd("J", "A"); } } else { if(m_encodeVowels) { MetaphAdd("JA"); } else { MetaphAdd("J"); } } m_current++; m_current = SkipVowels(m_current); return false; } else { MetaphAdd("J"); m_current++; return true; } // return false; } /** * Encode 'J' toward end in spanish words * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Spanish_J_2() { // spanish forms e.g. "brujo", "badajoz" if((((m_current - 2) == 0) && StringAt((m_current - 2), 4, "BOJA", "BAJA", "BEJA", "BOJO", "MOJA", "MOJI", "MEJI", "")) || (((m_current - 3) == 0) && StringAt((m_current - 3), 5, "FRIJO", "BRUJO", "BRUJA", "GRAJE", "GRIJA", "LEIJA", "QUIJA", "")) || (((m_current + 3) == m_last) && StringAt((m_current - 1), 5, "AJARA", "")) || (((m_current + 2) == m_last) && StringAt((m_current - 1), 4, "AJOS", "EJOS", "OJAS", "OJOS", "UJON", "AJOZ", "AJAL", "UJAR", "EJON", "EJAN", "")) || (((m_current + 1) == m_last) && (StringAt((m_current - 1), 3, "OJA", "EJA", "") && !StringAt(0, 4, "DEJA", "")))) { MetaphAdd("H"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode 'J' as vowel in some exception cases * * @return true if encoding handled in this routine, false if not * */ boolean Encode_J_As_Vowel() { if(StringAt(m_current, 5, "JEWSK", "")) { MetaphAdd("J", ""); return true; } // e.g. "stijl", "sejm" - dutch, scandanavian, and eastern european spellings if((StringAt((m_current + 1), 1, "L", "T", "K", "S", "N", "M", "") // except words from hindi and arabic && !StringAt((m_current + 2), 1, "A", "")) || StringAt(0, 9, "HALLELUJA", "LJUBLJANA", "") || StringAt(0, 4, "LJUB", "BJOR", "") || StringAt(0, 5, "HAJEK", "") || StringAt(0, 3, "WOJ", "") // e.g. 'fjord' || StringAt(0, 2, "FJ", "") // e.g. 'rekjavik', 'blagojevic' || StringAt(m_current, 5, "JAVIK", "JEVIC", "") || (((m_current + 1) == m_last) && StringAt(0, 5, "SONJA", "TANJA", "TONJA", ""))) { return true; } return false; } /** * Call routines to encode 'J', in proper order * */ void Encode_Other_J() { if(m_current == 0) { if(Encode_German_J()) { return; } else { if(Encode_J_To_J()) { return; } } } else { if(Encode_Spanish_J_2()) { return; } else if(!Encode_J_As_Vowel()) { MetaphAdd("J"); } //it could happen! e.g. "hajj" // eat redundant 'J' if(CharAt(m_current + 1) == 'J') { m_current += 2; } else { m_current++; } } } /** * Encode 'K' * * */ void Encode_K() { if(!Encode_Silent_K()) { MetaphAdd("K"); // eat redundant 'K's and 'Q's if((CharAt(m_current + 1) == 'K') || (CharAt(m_current + 1) == 'Q')) { m_current += 2; } else { m_current++; } } } /** * Encode cases where 'K' is not pronounced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_K() { //skip this except for special cases if((m_current == 0) && StringAt(m_current, 2, "KN", "")) { if(!(StringAt((m_current + 2), 5, "ESSET", "IEVEL", "") || StringAt((m_current + 2), 3, "ISH", "") )) { m_current += 1; return true; } } // e.g. "know", "knit", "knob" if((StringAt((m_current + 1), 3, "NOW", "NIT", "NOT", "NOB", "") // exception, "slipknot" => SLPNT but "banknote" => PNKNT && !StringAt(0, 8, "BANKNOTE", "")) || StringAt((m_current + 1), 4, "NOCK", "NUCK", "NIFE", "NACK", "") || StringAt((m_current + 1), 5, "NIGHT", "")) { // N already encoded before // e.g. "penknife" if ((m_current > 0) && CharAt(m_current - 1) == 'N') { m_current += 2; } else { m_current++; } return true; } return false; } /** * Encode 'L' * * Includes special vowel transposition * encoding, where 'LE' => AL * */ void Encode_L() { // logic below needs to know this // after 'm_current' variable changed int save_current = m_current; Interpolate_Vowel_When_Cons_L_At_End(); if(Encode_LELY_To_L() || Encode_COLONEL() || Encode_French_AULT() || Encode_French_EUIL() || Encode_French_OULX() || Encode_Silent_L_In_LM() || Encode_Silent_L_In_LK_LV() || Encode_Silent_L_In_OULD()) { return; } if(Encode_LL_As_Vowel_Cases()) { return; } Encode_LE_Cases(save_current); } /** * Cases where an L follows D, G, or T at the * end have a schwa pronounced before the L * */ void Interpolate_Vowel_When_Cons_L_At_End() { if(m_encodeVowels == true) { // e.g. "ertl", "vogl" if((m_current == m_last) && StringAt((m_current - 1), 1, "D", "G", "T", "")) { MetaphAdd("A"); } } } /** * Catch cases where 'L' spelled twice but pronounced * once, e.g., 'DOCILELY' => TSL * * @return true if encoding handled in this routine, false if not * */ boolean Encode_LELY_To_L() { // e.g. "agilely", "docilely" if(StringAt((m_current - 1), 5, "ILELY", "") && ((m_current + 3) == m_last)) { MetaphAdd("L"); m_current += 3; return true; } return false; } /** * Encode special case "colonel" => KRNL. Can somebody tell * me how this pronounciation came to be? * * @return true if encoding handled in this routine, false if not * */ boolean Encode_COLONEL() { if(StringAt((m_current - 2), 7, "COLONEL", "")) { MetaphAdd("R"); m_current += 2; return true; } return false; } /** * Encode "-AULT-", found in a french names * * @return true if encoding handled in this routine, false if not * */ boolean Encode_French_AULT() { // e.g. "renault" and "foucault", well known to americans, but not "fault" if((m_current > 3) && (StringAt((m_current - 3), 5, "RAULT", "NAULT", "BAULT", "SAULT", "GAULT", "CAULT", "") || StringAt((m_current - 4), 6, "REAULT", "RIAULT", "NEAULT", "BEAULT", "")) && !(RootOrInflections(m_inWord, "ASSAULT") || StringAt((m_current - 8), 10, "SOMERSAULT","") || StringAt((m_current - 9), 11, "SUMMERSAULT", ""))) { m_current += 2; return true; } return false; } /** * Encode "-EUIL-", always found in a french word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_French_EUIL() { // e.g. "auteuil" if(StringAt((m_current - 3), 4, "EUIL", "") && (m_current == m_last)) { m_current++; return true; } return false; } /** * Encode "-OULX", always found in a french word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_French_OULX() { // e.g. "proulx" if(StringAt((m_current - 2), 4, "OULX", "") && ((m_current + 1) == m_last)) { m_current += 2; return true; } return false; } /** * Encodes contexts where 'L' is not pronounced in "-LM-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_L_In_LM() { if(StringAt(m_current, 2, "LM", "LN", "")) { // e.g. "lincoln", "holmes", "psalm", "salmon" if((StringAt((m_current - 2), 4, "COLN", "CALM", "BALM", "MALM", "PALM", "") || (StringAt((m_current - 1), 3, "OLM", "") && ((m_current + 1) == m_last)) || StringAt((m_current - 3), 5, "PSALM", "QUALM", "") || StringAt((m_current - 2), 6, "SALMON", "HOLMES", "") || StringAt((m_current - 1), 6, "ALMOND", "") || ((m_current == 1) && StringAt((m_current - 1), 4, "ALMS", "") )) && (!StringAt((m_current + 2), 1, "A", "") && !StringAt((m_current - 2), 5, "BALMO", "") && !StringAt((m_current - 2), 6, "PALMER", "PALMOR", "BALMER", "") && !StringAt((m_current - 3), 5, "THALM", ""))) { m_current++; return true; } else { MetaphAdd("L"); m_current++; return true; } } return false; } /** * Encodes contexts where '-L-' is silent in 'LK', 'LV' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_L_In_LK_LV() { if((StringAt((m_current - 2), 4, "WALK", "YOLK", "FOLK", "HALF", "TALK", "CALF", "BALK", "CALK", "") || (StringAt((m_current - 2), 4, "POLK", "") && !StringAt((m_current - 2), 5, "POLKA", "WALKO", "")) || (StringAt((m_current - 2), 4, "HALV", "") && !StringAt((m_current - 2), 5, "HALVA", "HALVO", "")) || (StringAt((m_current - 3), 5, "CAULK", "CHALK", "BAULK", "FAULK", "") && !StringAt((m_current - 4), 6, "SCHALK", "")) || (StringAt((m_current - 2), 5, "SALVE", "CALVE", "") || StringAt((m_current - 2), 6, "SOLDER", "")) // exceptions to above cases where 'L' is usually pronounced && !StringAt((m_current - 2), 6, "SALVER", "CALVER", "")) && !StringAt((m_current - 5), 9, "GONSALVES", "GONCALVES", "") && !StringAt((m_current - 2), 6, "BALKAN", "TALKAL", "") && !StringAt((m_current - 3), 5, "PAULK", "CHALF", "")) { m_current++; return true; } return false; } /** * Encode 'L' in contexts of "-OULD-" where it is silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_L_In_OULD() { //'would', 'could' if(StringAt((m_current - 3), 5, "WOULD", "COULD", "") || (StringAt((m_current - 4), 6, "SHOULD", "") && !StringAt((m_current - 4), 8, "SHOULDER", ""))) { MetaphAddExactApprox("D", "T"); m_current += 2; return true; } return false; } /** * Encode "-ILLA-" and "-ILLE-" in spanish and french * contexts were americans know to pronounce it as a 'Y' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_LL_As_Vowel_Special_Cases() { if(StringAt((m_current - 5), 8, "TORTILLA", "") || StringAt((m_current - 8), 11, "RATATOUILLE", "") // e.g. 'guillermo', "veillard" || (StringAt(0, 5, "GUILL", "VEILL", "GAILL", "") // 'guillotine' usually has '-ll-' pronounced as 'L' in english && !(StringAt((m_current - 3), 7, "GUILLOT", "GUILLOR", "GUILLEN", "") || (StringAt(0, 5, "GUILL", "") && (m_length == 5)))) // e.g. "brouillard", "gremillion" || StringAt(0, 7, "BROUILL", "GREMILL", "ROBILL", "") // e.g. 'mireille' || (StringAt((m_current - 2), 5, "EILLE", "") && ((m_current + 2) == m_last) // exception "reveille" usually pronounced as 're-vil-lee' && !StringAt((m_current - 5), 8, "REVEILLE", ""))) { m_current += 2; return true; } return false; } /** * Encode other spanish cases where "-LL-" is pronounced as 'Y' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_LL_As_Vowel() { //spanish e.g. "cabrillo", "gallegos" but also "gorilla", "ballerina" - // give both pronounciations since an american might pronounce "cabrillo" // in the spanish or the american fashion. if((((m_current + 3) == m_length) && StringAt((m_current - 1), 4, "ILLO", "ILLA", "ALLE", "")) || (((StringAt((m_last - 1), 2, "AS", "OS", "") || StringAt(m_last, 2, "AS", "OS", "") || StringAt(m_last, 1, "A", "O", "")) && StringAt((m_current - 1), 2, "AL", "IL", "")) && !StringAt((m_current - 1), 4, "ALLA", "")) || StringAt(0, 5, "VILLE", "VILLA", "") || StringAt(0, 8, "GALLARDO", "VALLADAR", "MAGALLAN", "CAVALLAR", "BALLASTE", "") || StringAt(0, 3, "LLA", "")) { MetaphAdd("L", ""); m_current += 2; return true; } return false; } /** * Call routines to encode "-LL-", in proper order * * @return true if encoding handled in this routine, false if not * */ boolean Encode_LL_As_Vowel_Cases() { if(CharAt(m_current + 1) == 'L') { if(Encode_LL_As_Vowel_Special_Cases()) { return true; } else if(Encode_LL_As_Vowel()) { return true; } m_current += 2; } else { m_current++; } return false; } /** * Encode vowel-encoding cases where "-LE-" is pronounced "-EL-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Vowel_LE_Transposition(int save_current) { // transposition of vowel sound and L occurs in many words, // e.g. "bristle", "dazzle", "goggle" => KAKAL if(m_encodeVowels && (save_current > 1) && !IsVowel(save_current - 1) && (CharAt(save_current + 1) == 'E') && (CharAt(save_current - 1) != 'L') && (CharAt(save_current - 1) != 'R') // lots of exceptions to this: && !IsVowel(save_current + 2) && !StringAt(0, 7, "ECCLESI", "COMPLEC", "COMPLEJ", "ROBLEDO", "") && !StringAt(0, 5, "MCCLE", "MCLEL", "") && !StringAt(0, 6, "EMBLEM", "KADLEC", "") && !(((save_current + 2) == m_last) && StringAt(save_current, 3, "LET", "")) && !StringAt(save_current, 7, "LETTING", "") && !StringAt(save_current, 6, "LETELY", "LETTER", "LETION", "LETIAN", "LETING", "LETORY", "") && !StringAt(save_current, 5, "LETUS", "LETIV", "") && !StringAt(save_current, 4, "LESS", "LESQ", "LECT", "LEDG", "LETE", "LETH", "LETS", "LETT", "") && !StringAt(save_current, 3, "LEG", "LER", "LEX", "") // e.g. "complement" !=> KAMPALMENT && !(StringAt(save_current, 6, "LEMENT", "") && !(StringAt((m_current - 5), 6, "BATTLE", "TANGLE", "PUZZLE", "RABBLE", "BABBLE", "") || StringAt((m_current - 4), 5, "TABLE", ""))) && !(((save_current + 2) == m_last) && StringAt((save_current - 2), 5, "OCLES", "ACLES", "AKLES", "")) && !StringAt((save_current - 3), 5, "LISLE", "AISLE", "") && !StringAt(0, 4, "ISLE", "") && !StringAt(0, 6, "ROBLES", "") && !StringAt((save_current - 4), 7, "PROBLEM", "RESPLEN", "") && !StringAt((save_current - 3), 6, "REPLEN", "") && !StringAt((save_current - 2), 4, "SPLE", "") && (CharAt(save_current - 1) != 'H') && (CharAt(save_current - 1) != 'W')) { MetaphAdd("AL"); flag_AL_inversion = true; // eat redundant 'L' if(CharAt(save_current + 2) == 'L') { m_current = save_current + 3; } return true; } return false; } /** * Encode special vowel-encoding cases where 'E' is not * silent at the end of a word as is the usual case * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Vowel_Preserve_Vowel_After_L(int save_current) { // an example of where the vowel would NOT need to be preserved // would be, say, "hustled", where there is no vowel pronounced // between the 'l' and the 'd' if(m_encodeVowels && !IsVowel(save_current - 1) && (CharAt(save_current + 1) == 'E') && (save_current > 1) && ((save_current + 1) != m_last) && !(StringAt((save_current + 1), 2, "ES", "ED", "") && ((save_current + 2) == m_last)) && !StringAt((save_current - 1), 5, "RLEST", "") ) { MetaphAdd("LA"); m_current = SkipVowels(m_current); return true; } return false; } /** * Call routines to encode "-LE-", in proper order * * @param save_current index of actual current letter * */ void Encode_LE_Cases(int save_current) { if(Encode_Vowel_LE_Transposition(save_current)) { return; } else { if(Encode_Vowel_Preserve_Vowel_After_L(save_current)) { return; } else { MetaphAdd("L"); } } } /** * Encode "-M-" * */ void Encode_M() { if(Encode_Silent_M_At_Beginning() || Encode_MR_And_MRS() || Encode_MAC() || Encode_MPT()) { return; } // Silent 'B' should really be handled // under 'B", not here under 'M'! Encode_MB(); MetaphAdd("M"); } /** * Encode cases where 'M' is silent at beginning of word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_M_At_Beginning() { //skip these when at start of word if((m_current == 0) && StringAt(m_current, 2, "MN", "")) { m_current += 1; return true; } return false; } /** * Encode special cases "Mr." and "Mrs." * * @return true if encoding handled in this routine, false if not * */ boolean Encode_MR_And_MRS() { if((m_current == 0) && StringAt(m_current, 2, "MR", "")) { // exceptions for "mr." and "mrs." if((m_length == 2) && StringAt(m_current, 2, "MR", "")) { if(m_encodeVowels) { MetaphAdd("MASTAR"); } else { MetaphAdd("MSTR"); } m_current += 2; return true; } else if((m_length == 3) && StringAt(m_current, 3, "MRS", "")) { if(m_encodeVowels) { MetaphAdd("MASAS"); } else { MetaphAdd("MSS"); } m_current += 3; return true; } } return false; } /** * Encode "Mac-" and "Mc-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_MAC() { // should only find irish and // scottish names e.g. 'macintosh' if((m_current == 0) && (StringAt(0, 7, "MACIVER", "MACEWEN", "") || StringAt(0, 8, "MACELROY", "MACILROY", "") || StringAt(0, 9, "MACINTOSH", "") || StringAt(0, 2, "MC", "") )) { if(m_encodeVowels) { MetaphAdd("MAK"); } else { MetaphAdd("MK"); } if(StringAt(0, 2, "MC", "")) { if(StringAt((m_current + 2), 1, "K", "G", "Q", "") // watch out for e.g. "McGeorge" && !StringAt((m_current + 2), 4, "GEOR", "")) { m_current += 3; } else { m_current += 2; } } else { m_current += 3; } return true; } return false; } /** * Encode silent 'M' in context of "-MPT-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_MPT() { if(StringAt((m_current - 2), 8, "COMPTROL", "") || StringAt((m_current - 4), 7, "ACCOMPT", "")) { MetaphAdd("N"); m_current += 2; return true; } return false; } /** * Test if 'B' is silent in these contexts * * @return true if 'B' is silent in this context * */ boolean Test_Silent_MB_1() { // e.g. "LAMB", "COMB", "LIMB", "DUMB", "BOMB" // Handle combining roots first if (((m_current == 3) && StringAt((m_current - 3), 5, "THUMB", "")) || ((m_current == 2) && StringAt((m_current - 2), 4, "DUMB", "BOMB", "DAMN", "LAMB", "NUMB", "TOMB", "") )) { return true; } return false; } /** * Test if 'B' is pronounced in this context * * @return true if 'B' is pronounced in this context * */ boolean Test_Pronounced_MB() { if (StringAt((m_current - 2), 6, "NUMBER", "") || (StringAt((m_current + 2), 1, "A", "") && !StringAt((m_current - 2), 7, "DUMBASS", "")) || StringAt((m_current + 2), 1, "O", "") || StringAt((m_current - 2), 6, "LAMBEN", "LAMBER", "LAMBET", "TOMBIG", "LAMBRE", "")) { return true; } return false; } /** * Test whether "-B-" is silent in these contexts * * @return true if 'B' is silent in this context * */ boolean Test_Silent_MB_2() { // 'M' is the current letter if ((CharAt(m_current + 1) == 'B') && (m_current > 1) && (((m_current + 1) == m_last) // other situations where "-MB-" is at end of root // but not at end of word. The tests are for standard // noun suffixes. // e.g. "climbing" => KLMNK || StringAt((m_current + 2), 3, "ING", "ABL", "") || StringAt((m_current + 2), 4, "LIKE", "") || ((CharAt(m_current + 2) == 'S') && ((m_current + 2) == m_last)) || StringAt((m_current - 5), 7, "BUNCOMB", "") // e.g. "bomber", || (StringAt((m_current + 2), 2, "ED", "ER", "") && ((m_current + 3) == m_last) && (StringAt(0, 5, "CLIMB", "PLUMB", "") // e.g. "beachcomber" || !StringAt((m_current - 1), 5, "IMBER", "AMBER", "EMBER", "UMBER", "")) // exceptions && !StringAt((m_current - 2), 6, "CUMBER", "SOMBER", "") ) ) ) { return true; } return false; } /** * Test if 'B' is pronounced in these "-MB-" contexts * * @return true if "-B-" is pronounced in these contexts * */ boolean Test_Pronounced_MB_2() { // e.g. "bombastic", "umbrage", "flamboyant" if (StringAt((m_current - 1), 5, "OMBAS", "OMBAD", "UMBRA", "") || StringAt((m_current - 3), 4, "FLAM", "") ) { return true; } return false; } /** * Tests for contexts where "-N-" is silent when after "-M-" * * @return true if "-N-" is silent in these contexts * */ boolean Test_MN() { if ((CharAt(m_current + 1) == 'N') && (((m_current + 1) == m_last) // or at the end of a word but followed by suffixes || (StringAt((m_current + 2), 3, "ING", "EST", "") && ((m_current + 4) == m_last)) || ((CharAt(m_current + 2) == 'S') && ((m_current + 2) == m_last)) || (StringAt((m_current + 2), 2, "LY", "ER", "ED", "") && ((m_current + 3) == m_last)) || StringAt((m_current - 2), 9, "DAMNEDEST", "") || StringAt((m_current - 5), 9, "GODDAMNIT", "") )) { return true; } return false; } /** * Call routines to encode "-MB-", in proper order * */ void Encode_MB() { if(Test_Silent_MB_1()) { if(Test_Pronounced_MB()) { m_current++; } else { m_current += 2; } } else if(Test_Silent_MB_2()) { if(Test_Pronounced_MB_2()) { m_current++; } else { m_current += 2; } } else if(Test_MN()) { m_current += 2; } else { // eat redundant 'M' if (CharAt(m_current + 1) == 'M') { m_current += 2; } else { m_current++; } } } /** * Encode "-N-" * */ void Encode_N() { if(Encode_NCE()) { return; } // eat redundant 'N' if(CharAt(m_current + 1) == 'N') { m_current += 2; } else { m_current++; } if (!StringAt((m_current - 3), 8, "MONSIEUR", "") // e.g. "aloneness", && !StringAt((m_current - 3), 6, "NENESS", "")) { MetaphAdd("N"); } } /** * Encode "-NCE-" and "-NSE-" * "entrance" is pronounced exactly the same as "entrants" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_NCE() { //'acceptance', 'accountancy' if(StringAt((m_current + 1), 1, "C", "S", "") && StringAt((m_current + 2), 1, "E", "Y", "I", "") && (((m_current + 2) == m_last) || (((m_current + 3) == m_last)) && (CharAt(m_current + 3) == 'S'))) { MetaphAdd("NTS"); m_current += 2; return true; } return false; } /** * Encode "-P-" * */ void Encode_P() { if(Encode_Silent_P_At_Beginning() || Encode_PT() || Encode_PH() || Encode_PPH() || Encode_RPS() || Encode_COUP() || Encode_PNEUM() || Encode_PSYCH() || Encode_PSALM()) { return; } Encode_PB(); MetaphAdd("P"); } /** * Encode cases where "-P-" is silent at the start of a word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_P_At_Beginning() { //skip these when at start of word if((m_current == 0) && StringAt(m_current, 2, "PN", "PF", "PS", "PT", "")) { m_current += 1; return true; } return false; } /** * Encode cases where "-P-" is silent before "-T-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_PT() { // 'pterodactyl', 'receipt', 'asymptote' if((CharAt(m_current + 1) == 'T')) { if (((m_current == 0) && StringAt(m_current, 5, "PTERO", "")) || StringAt((m_current - 5), 7, "RECEIPT", "") || StringAt((m_current - 4), 8, "ASYMPTOT", "")) { MetaphAdd("T"); m_current += 2; return true; } } return false; } /** * Encode "-PH-", usually as F, with exceptions for * cases where it is silent, or where the 'P' and 'T' * are pronounced seperately because they belong to * two different words in a combining form * * @return true if encoding handled in this routine, false if not * */ boolean Encode_PH() { if(CharAt(m_current + 1) == 'H') { // 'PH' silent in these contexts if (StringAt(m_current, 9, "PHTHALEIN", "") || ((m_current == 0) && StringAt(m_current, 4, "PHTH", "")) || StringAt((m_current - 3), 10, "APOPHTHEGM", "")) { MetaphAdd("0"); m_current += 4; } // combining forms //'sheepherd', 'upheaval', 'cupholder' else if((m_current > 0) && (StringAt((m_current + 2), 3, "EAD", "OLE", "ELD", "ILL", "OLD", "EAP", "ERD", "ARD", "ANG", "ORN", "EAV", "ART", "") || StringAt((m_current + 2), 4, "OUSE", "") || (StringAt((m_current + 2), 2, "AM", "") && !StringAt((m_current -1), 5, "LPHAM", "")) || StringAt((m_current + 2), 5, "AMMER", "AZARD", "UGGER", "") || StringAt((m_current + 2), 6, "OLSTER", "")) && !StringAt((m_current - 3), 5, "LYMPH", "NYMPH", "")) { MetaphAdd("P"); AdvanceCounter(3, 2); } else { MetaphAdd("F"); m_current += 2; } return true; } return false; } /** * Encode "-PPH-". I don't know why the greek poet's * name is transliterated this way... * * @return true if encoding handled in this routine, false if not * */ boolean Encode_PPH() { // 'sappho' if((CharAt(m_current + 1) == 'P') && ((m_current + 2) < m_length) && (CharAt(m_current + 2) == 'H')) { MetaphAdd("F"); m_current += 3; return true; } return false; } /** * Encode "-CORPS-" where "-PS-" not pronounced * since the cognate is here from the french * * @return true if encoding handled in this routine, false if not * */ boolean Encode_RPS() { //'-corps-', 'corpsman' if(StringAt((m_current - 3), 5, "CORPS", "") && !StringAt((m_current - 3), 6, "CORPSE", "")) { m_current += 2; return true; } return false; } /** * Encode "-COUP-" where "-P-" is not pronounced * since the word is from the french * * @return true if encoding handled in this routine, false if not * */ boolean Encode_COUP() { //'coup' if((m_current == m_last) && StringAt((m_current - 3), 4, "COUP", "") && !StringAt((m_current - 5), 6, "RECOUP", "")) { m_current++; return true; } return false; } /** * Encode 'P' in non-initial contexts of "-PNEUM-" * where is also silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_PNEUM() { //'-pneum-' if(StringAt((m_current + 1), 4, "NEUM", "")) { MetaphAdd("N"); m_current += 2; return true; } return false; } /** * Encode special case "-PSYCH-" where two encodings need to be * accounted for in one syllable, one for the 'PS' and one for * the 'CH' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_PSYCH() { //'-psych-' if(StringAt((m_current + 1), 4, "SYCH", "")) { if(m_encodeVowels) { MetaphAdd("SAK"); } else { MetaphAdd("SK"); } m_current += 5; return true; } return false; } /** * Encode 'P' in context of "-PSALM-", where it has * become silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_PSALM() { //'-psalm-' if(StringAt((m_current + 1), 4, "SALM", "")) { // go ahead and encode entire word if(m_encodeVowels) { MetaphAdd("SAM"); } else { MetaphAdd("SM"); } m_current += 5; return true; } return false; } /** * Eat redundant 'B' or 'P' * */ void Encode_PB() { // e.g. "campbell", "raspberry" // eat redundant 'P' or 'B' if(StringAt((m_current + 1), 1, "P", "B", "")) { m_current += 2; } else { m_current++; } } /** * Encode "-Q-" * */ void Encode_Q() { // current pinyin if(StringAt(m_current, 3, "QIN", "")) { MetaphAdd("X"); m_current++; return; } // eat redundant 'Q' if(CharAt(m_current + 1) == 'Q') { m_current += 2; } else { m_current++; } MetaphAdd("K"); } /** * Encode "-R-" * */ void Encode_R() { if(Encode_RZ()) { return; } if(!Test_Silent_R()) { if(!Encode_Vowel_RE_Transposition()) { MetaphAdd("R"); } } // eat redundant 'R'; also skip 'S' as well as 'R' in "poitiers" if((CharAt(m_current + 1) == 'R') || StringAt((m_current - 6), 8, "POITIERS", "")) { m_current += 2; } else { m_current++; } } /** * Encode "-RZ-" according * to american and polish pronunciations * * @return true if encoding handled in this routine, false if not * */ boolean Encode_RZ() { if(StringAt((m_current - 2), 4, "GARZ", "KURZ", "MARZ", "MERZ", "HERZ", "PERZ", "WARZ", "") || StringAt(m_current, 5, "RZANO", "RZOLA", "") || StringAt((m_current - 1), 4, "ARZA", "ARZN", "")) { return false; } // 'yastrzemski' usually has 'z' silent in // united states, but should get 'X' in poland if(StringAt((m_current - 4), 11, "YASTRZEMSKI", "")) { MetaphAdd("R", "X"); m_current += 2; return true; } // 'BRZEZINSKI' gets two pronunciations // in the united states, neither of which // are authentically polish if(StringAt((m_current - 1), 10, "BRZEZINSKI", "")) { MetaphAdd("RS", "RJ"); // skip over 2nd 'Z' m_current += 4; return true; } // 'z' in 'rz after voiceless consonant gets 'X' // in alternate polish style pronunciation else if(StringAt((m_current - 1), 3, "TRZ", "PRZ", "KRZ", "") || (StringAt(m_current, 2, "RZ", "") && (IsVowel(m_current - 1) || (m_current == 0)))) { MetaphAdd("RS", "X"); m_current += 2; return true; } // 'z' in 'rz after voiceled consonant, vowel, or at // beginning gets 'J' in alternate polish style pronunciation else if(StringAt((m_current - 1), 3, "BRZ", "DRZ", "GRZ", "")) { MetaphAdd("RS", "J"); m_current += 2; return true; } return false; } /** * Test whether 'R' is silent in this context * * @return true if 'R' is silent in this context * */ boolean Test_Silent_R() { // test cases where 'R' is silent, either because the // word is from the french or because it is no longer pronounced. // e.g. "rogier", "monsieur", "surburban" if(((m_current == m_last) // reliably french word ending && StringAt((m_current - 2), 3, "IER", "") // e.g. "metier" && (StringAt((m_current - 5), 3, "MET", "VIV", "LUC", "") // e.g. "cartier", "bustier" || StringAt((m_current - 6), 4, "CART", "DOSS", "FOUR", "OLIV", "BUST", "DAUM", "ATEL", "SONN", "CORM", "MERC", "PELT", "POIR", "BERN", "FORT", "GREN", "SAUC", "GAGN", "GAUT", "GRAN", "FORC", "MESS", "LUSS", "MEUN", "POTH", "HOLL", "CHEN", "") // e.g. "croupier" || StringAt((m_current - 7), 5, "CROUP", "TORCH", "CLOUT", "FOURN", "GAUTH", "TROTT", "DEROS", "CHART", "") // e.g. "chevalier" || StringAt((m_current - 8), 6, "CHEVAL", "LAVOIS", "PELLET", "SOMMEL", "TREPAN", "LETELL", "COLOMB", "") || StringAt((m_current - 9), 7, "CHARCUT", "") || StringAt((m_current - 10), 8, "CHARPENT", ""))) || StringAt((m_current - 2), 7, "SURBURB", "WORSTED", "") || StringAt((m_current - 2), 9, "WORCESTER", "") || StringAt((m_current - 7), 8, "MONSIEUR", "") || StringAt((m_current - 6), 8, "POITIERS", "") ) { return true; } return false; } /** * Encode '-re-" as 'AR' in contexts * where this is the correct pronunciation * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Vowel_RE_Transposition() { // -re inversion is just like // -le inversion // e.g. "fibre" => FABAR or "centre" => SANTAR if((m_encodeVowels) && (CharAt(m_current + 1) == 'E') && (m_length > 3) && !StringAt(0, 5, "OUTRE", "LIBRE", "ANDRE", "") && !(StringAt(0, 4, "FRED", "TRES", "") && (m_length == 4)) && !StringAt((m_current - 2), 5, "LDRED", "LFRED", "NDRED", "NFRED", "NDRES", "TRES", "IFRED", "") && !IsVowel(m_current - 1) && (((m_current + 1) == m_last) || (((m_current + 2) == m_last) && StringAt((m_current + 2), 1, "D", "S", "")))) { MetaphAdd("AR"); return true; } return false; } /** * Encode "-S-" * */ void Encode_S() { if(Encode_SKJ() || Encode_Special_SW() || Encode_SJ() || Encode_Silent_French_S_Final() || Encode_Silent_French_S_Internal() || Encode_ISL() || Encode_STL() || Encode_Christmas() || Encode_STHM() || Encode_ISTEN() || Encode_Sugar() || Encode_SH() || Encode_SCH() || Encode_SUR() || Encode_SU() || Encode_SSIO() || Encode_SS() || Encode_SIA() || Encode_SIO() || Encode_Anglicisations() || Encode_SC() || Encode_SEA_SUI_SIER() || Encode_SEA()) { return; } MetaphAdd("S"); if(StringAt((m_current + 1), 1, "S", "Z", "") && !StringAt((m_current + 1), 2, "SH", "")) { m_current += 2; } else { m_current++; } } /** * Encode a couple of contexts where scandinavian, slavic * or german names should get an alternate, native * pronunciation of 'SV' or 'XV' * * @return true if handled * */ boolean Encode_Special_SW() { if(m_current == 0) { // if(Names_Beginning_With_SW_That_Get_Alt_SV()) { MetaphAdd("S", "SV"); m_current += 2; return true; } // if(Names_Beginning_With_SW_That_Get_Alt_XV()) { MetaphAdd("S", "XV"); m_current += 2; return true; } } return false; } /** * Encode "-SKJ-" as X ("sh"), since americans pronounce * the name Dag Hammerskjold as "hammer-shold" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SKJ() { // scandinavian if(StringAt(m_current, 4, "SKJO", "SKJU", "") && IsVowel(m_current + 3)) { MetaphAdd("X"); m_current += 3; return true; } return false; } /** * Encode initial swedish "SJ-" as X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SJ() { if(StringAt(0, 2, "SJ", "")) { MetaphAdd("X"); m_current += 2; return true; } return false; } /** * Encode final 'S' in words from the french, where they * are not pronounced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_French_S_Final() { // "louis" is an exception because it gets two pronuncuations if(StringAt(0, 5, "LOUIS", "") && (m_current == m_last)) { MetaphAdd("S", ""); m_current++; return true; } // french words familiar to americans where final s is silent if((m_current == m_last) && (StringAt(0, 4, "YVES", "") || (StringAt(0, 4, "HORS", "") && (m_current == 3)) || StringAt((m_current - 4), 5, "CAMUS", "YPRES", "") || StringAt((m_current - 5), 6, "MESNES", "DEBRIS", "BLANCS", "INGRES", "CANNES", "") || StringAt((m_current - 6), 7, "CHABLIS", "APROPOS", "JACQUES", "ELYSEES", "OEUVRES", "GEORGES", "DESPRES", "") || StringAt(0, 8, "ARKANSAS", "FRANCAIS", "CRUDITES", "BRUYERES", "") || StringAt(0, 9, "DESCARTES", "DESCHUTES", "DESCHAMPS", "DESROCHES", "DESCHENES", "") || StringAt(0, 10, "RENDEZVOUS", "") || StringAt(0, 11, "CONTRETEMPS", "DESLAURIERS", "")) || ((m_current == m_last) && StringAt((m_current - 2), 2, "AI", "OI", "UI", "") && !StringAt(0, 4, "LOIS", "LUIS", ""))) { m_current++; return true; } return false; } /** * Encode non-final 'S' in words from the french where they * are not pronounced. * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_French_S_Internal() { // french words familiar to americans where internal s is silent if(StringAt((m_current - 2), 9, "DESCARTES", "") || StringAt((m_current - 2), 7, "DESCHAM", "DESPRES", "DESROCH", "DESROSI", "DESJARD", "DESMARA", "DESCHEN", "DESHOTE", "DESLAUR", "") || StringAt((m_current - 2), 6, "MESNES", "") || StringAt((m_current - 5), 8, "DUQUESNE", "DUCHESNE", "") || StringAt((m_current - 7), 10, "BEAUCHESNE", "") || StringAt((m_current - 3), 7, "FRESNEL", "") || StringAt((m_current - 3), 9, "GROSVENOR", "") || StringAt((m_current - 4), 10, "LOUISVILLE", "") || StringAt((m_current - 7), 10, "ILLINOISAN", "")) { m_current++; return true; } return false; } /** * Encode silent 'S' in context of "-ISL-" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_ISL() { //special cases 'island', 'isle', 'carlisle', 'carlysle' if((StringAt((m_current - 2), 4, "LISL", "LYSL", "AISL", "") && !StringAt((m_current - 3), 7, "PAISLEY", "BAISLEY", "ALISLAM", "ALISLAH", "ALISLAA", "")) || ((m_current == 1) && ((StringAt((m_current - 1), 4, "ISLE", "") || StringAt((m_current - 1), 5, "ISLAN", "")) && !StringAt((m_current - 1), 5, "ISLEY", "ISLER", "")))) { m_current++; return true; } return false; } /** * Encode "-STL-" in contexts where the 'T' is silent. Also * encode "-USCLE-" in contexts where the 'C' is silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_STL() { //'hustle', 'bustle', 'whistle' if((StringAt(m_current, 4, "STLE", "STLI", "") && !StringAt((m_current + 2), 4, "LESS", "LIKE", "LINE", "")) || StringAt((m_current - 3), 7, "THISTLY", "BRISTLY", "GRISTLY", "") // e.g. "corpuscle" || StringAt((m_current - 1), 5, "USCLE", "")) { // KRISTEN, KRYSTLE, CRYSTLE, KRISTLE all pronounce the 't' // also, exceptions where "-LING" is a nominalizing suffix if(StringAt(0, 7, "KRISTEN", "KRYSTLE", "CRYSTLE", "KRISTLE", "") || StringAt(0, 11, "CHRISTENSEN", "CHRISTENSON", "") || StringAt((m_current - 3), 9, "FIRSTLING", "") || StringAt((m_current - 2), 8, "NESTLING", "WESTLING", "")) { MetaphAdd("ST"); m_current += 2; } else { if(m_encodeVowels && (CharAt(m_current + 3) == 'E') && (CharAt(m_current + 4) != 'R') && !StringAt((m_current + 3), 4, "ETTE", "ETTA", "") && !StringAt((m_current + 3), 2, "EY", "")) { MetaphAdd("SAL"); flag_AL_inversion = true; } else { MetaphAdd("SL"); } m_current += 3; } return true; } return false; } /** * Encode "christmas". Americans always pronounce this as "krissmuss" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Christmas() { //'christmas' if(StringAt((m_current - 4), 8, "CHRISTMA", "")) { MetaphAdd("SM"); m_current += 3; return true; } return false; } /** * Encode "-STHM-" in contexts where the 'TH' * is silent. * * @return true if encoding handled in this routine, false if not * */ boolean Encode_STHM() { //'asthma', 'isthmus' if(StringAt(m_current, 4, "STHM", "")) { MetaphAdd("SM"); m_current += 4; return true; } return false; } /** * Encode "-ISTEN-" and "-STNT-" in contexts * where the 'T' is silent * * @return true if encoding handled in this routine, false if not * */ boolean Encode_ISTEN() { // 't' is silent in verb, pronounced in name if(StringAt(0, 8, "CHRISTEN", "")) { // the word itself if(RootOrInflections(m_inWord, "CHRISTEN") || StringAt(0, 11, "CHRISTENDOM", "")) { MetaphAdd("S", "ST"); } else { // e.g. 'christenson', 'christene' MetaphAdd("ST"); } m_current += 2; return true; } //e.g. 'glisten', 'listen' if(StringAt((m_current - 2), 6, "LISTEN", "RISTEN", "HASTEN", "FASTEN", "MUSTNT", "") || StringAt((m_current - 3), 7, "MOISTEN", "")) { MetaphAdd("S"); m_current += 2; return true; } return false; } /** * Encode special case "sugar" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Sugar() { //special case 'sugar-' if(StringAt(m_current, 5, "SUGAR", "")) { MetaphAdd("X"); m_current++; return true; } return false; } /** * Encode "-SH-" as X ("sh"), except in cases * where the 'S' and 'H' belong to different combining * roots and are therefore pronounced seperately * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SH() { if(StringAt(m_current, 2, "SH", "")) { // exception if(StringAt((m_current - 2), 8, "CASHMERE", "")) { MetaphAdd("J"); m_current += 2; return true; } //combining forms, e.g. 'clotheshorse', 'woodshole' if((m_current > 0) // e.g. "mishap" && ((StringAt((m_current + 1), 3, "HAP", "") && ((m_current + 3) == m_last)) // e.g. "hartsheim", "clothshorse" || StringAt((m_current + 1), 4, "HEIM", "HOEK", "HOLM", "HOLZ", "HOOD", "HEAD", "HEID", "HAAR", "HORS", "HOLE", "HUND", "HELM", "HAWK", "HILL", "") // e.g. "dishonor" || StringAt((m_current + 1), 5, "HEART", "HATCH", "HOUSE", "HOUND", "HONOR", "") // e.g. "mishear" || (StringAt((m_current + 2), 3, "EAR", "") && ((m_current + 4) == m_last)) // e.g. "hartshorn" || (StringAt((m_current + 2), 3, "ORN", "") && !StringAt((m_current - 2), 7, "UNSHORN", "")) // e.g. "newshour" but not "bashour", "manshour" || (StringAt((m_current + 1), 4, "HOUR", "") && !(StringAt(0, 7, "BASHOUR", "") || StringAt(0, 8, "MANSHOUR", "") || StringAt(0, 6, "ASHOUR", "") )) // e.g. "dishonest", "grasshopper" || StringAt((m_current + 2), 5, "ARMON", "ONEST", "ALLOW", "OLDER", "OPPER", "EIMER", "ANDLE", "ONOUR", "") // e.g. "dishabille", "transhumance" || StringAt((m_current + 2), 6, "ABILLE", "UMANCE", "ABITUA", ""))) { if (!StringAt((m_current - 1), 1, "S", "")) MetaphAdd("S"); } else { MetaphAdd("X"); } m_current += 2; return true; } return false; } /** * Encode "-SCH-" in cases where the 'S' is pronounced * seperately from the "CH", in words from the dutch, italian, * and greek where it can be pronounced SK, and german words * where it is pronounced X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SCH() { // these words were combining forms many centuries ago if(StringAt((m_current + 1), 2, "CH", "")) { if((m_current > 0) // e.g. "mischief", "escheat" && (StringAt((m_current + 3), 3, "IEF", "EAT", "") // e.g. "mischance" || StringAt((m_current + 3), 4, "ANCE", "ARGE", "") // e.g. "eschew" || StringAt(0, 6, "ESCHEW", ""))) { MetaphAdd("S"); m_current++; return true; } //Schlesinger's rule //dutch, danish, italian, greek origin, e.g. "school", "schooner", "schiavone", "schiz-" if((StringAt((m_current + 3), 2, "OO", "ER", "EN", "UY", "ED", "EM", "IA", "IZ", "IS", "OL", "") && !StringAt(m_current, 6, "SCHOLT", "SCHISL", "SCHERR", "")) || StringAt((m_current + 3), 3, "ISZ", "") || (StringAt((m_current - 1), 6, "ESCHAT", "ASCHIN", "ASCHAL", "ISCHAE", "ISCHIA", "") && !StringAt((m_current - 2), 8, "FASCHING", "")) || (StringAt((m_current - 1), 5, "ESCHI", "") && ((m_current + 3) == m_last)) || (CharAt(m_current + 3) == 'Y')) { // e.g. "schermerhorn", "schenker", "schistose" if(StringAt((m_current + 3), 2, "ER", "EN", "IS", "") && (((m_current + 4) == m_last) || StringAt((m_current + 3), 3, "ENK", "ENB", "IST", ""))) { MetaphAdd("X", "SK"); } else { MetaphAdd("SK"); } m_current += 3; return true; } else { MetaphAdd("X"); m_current += 3; return true; } } return false; } /** * Encode "-SUR<E,A,Y>-" to J, unless it is at the beginning, * or preceeded by 'N', 'K', or "NO" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SUR() { // 'erasure', 'usury' if(StringAt((m_current + 1), 3, "URE", "URA", "URY", "")) { //'sure', 'ensure' if ((m_current == 0) || StringAt((m_current - 1), 1, "N", "K", "") || StringAt((m_current - 2), 2, "NO", "")) { MetaphAdd("X"); } else { MetaphAdd("J"); } AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-SU<O,A>-" to X ("sh") unless it is preceeded by * an 'R', in which case it is encoded to S, or it is * preceeded by a vowel, in which case it is encoded to J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SU() { //'sensuous', 'consensual' if(StringAt((m_current + 1), 2, "UO", "UA", "") && (m_current != 0)) { // exceptions e.g. "persuade" if(StringAt((m_current - 1), 4, "RSUA", "")) { MetaphAdd("S"); } // exceptions e.g. "casual" else if(IsVowel(m_current - 1)) { MetaphAdd("J", "S"); } else { MetaphAdd("X", "S"); } AdvanceCounter(3, 1); return true; } return false; } /** * Encodes "-SSIO-" in contexts where it is pronounced * either J or X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SSIO() { if(StringAt((m_current + 1), 4, "SION", "")) { //"abcission" if (StringAt((m_current - 2), 2, "CI", "")) { MetaphAdd("J"); } //'mission' else { if (IsVowel(m_current - 1)) { MetaphAdd("X"); } } AdvanceCounter(4, 2); return true; } return false; } /** * Encode "-SS-" in contexts where it is pronounced X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SS() { // e.g. "russian", "pressure" if(StringAt((m_current - 1), 5, "USSIA", "ESSUR", "ISSUR", "ISSUE", "") // e.g. "hessian", "assurance" || StringAt((m_current - 1), 6, "ESSIAN", "ASSURE", "ASSURA", "ISSUAB", "ISSUAN", "ASSIUS", "")) { MetaphAdd("X"); AdvanceCounter(3, 2); return true; } return false; } /** * Encodes "-SIA-" in contexts where it is pronounced * as X ("sh"), J, or S * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SIA() { // e.g. "controversial", also "fuchsia", "ch" is silent if(StringAt((m_current - 2), 5, "CHSIA", "") || StringAt((m_current - 1), 5, "RSIAL", "")) { MetaphAdd("X"); AdvanceCounter(3, 1); return true; } // names generally get 'X' where terms, e.g. "aphasia" get 'J' if((StringAt(0, 6, "ALESIA", "ALYSIA", "ALISIA", "STASIA", "") && (m_current == 3) && !StringAt(0, 9, "ANASTASIA", "")) || StringAt((m_current - 5), 9, "DIONYSIAN", "") || StringAt((m_current - 5), 8, "THERESIA", "")) { MetaphAdd("X", "S"); AdvanceCounter(3, 1); return true; } if((StringAt(m_current, 3, "SIA", "") && ((m_current + 2) == m_last)) || (StringAt(m_current, 4, "SIAN", "") && ((m_current + 3) == m_last)) || StringAt((m_current - 5), 9, "AMBROSIAL", "")) { if ((IsVowel(m_current - 1) || StringAt((m_current - 1), 1, "R", "")) // exclude compounds based on names, or french or greek words && !(StringAt(0, 5, "JAMES", "NICOS", "PEGAS", "PEPYS", "") || StringAt(0, 6, "HOBBES", "HOLMES", "JAQUES", "KEYNES", "") || StringAt(0, 7, "MALTHUS", "HOMOOUS", "") || StringAt(0, 8, "MAGLEMOS", "HOMOIOUS", "") || StringAt(0, 9, "LEVALLOIS", "TARDENOIS", "") || StringAt((m_current - 4), 5, "ALGES", "") )) { MetaphAdd("J"); } else { MetaphAdd("S"); } AdvanceCounter(2, 1); return true; } return false; } /** * Encodes "-SIO-" in contexts where it is pronounced * as J or X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SIO() { // special case, irish name if(StringAt(0, 7, "SIOBHAN", "")) { MetaphAdd("X"); AdvanceCounter(3, 1); return true; } if(StringAt((m_current + 1), 3, "ION", "")) { // e.g. "vision", "version" if (IsVowel(m_current - 1) || StringAt((m_current - 2), 2, "ER", "UR", "")) { MetaphAdd("J"); } else // e.g. "declension" { MetaphAdd("X"); } AdvanceCounter(3, 1); return true; } return false; } /** * Encode cases where "-S-" might well be from a german name * and add encoding of german pronounciation in alternate m_metaph * so that it can be found in a genealogical search * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Anglicisations() { //german & anglicisations, e.g. 'smith' match 'schmidt', 'snider' match 'schneider' //also, -sz- in slavic language altho in hungarian it is pronounced 's' if(((m_current == 0) && StringAt((m_current + 1), 1, "M", "N", "L", "")) || StringAt((m_current + 1), 1, "Z", "")) { MetaphAdd("S", "X"); // eat redundant 'Z' if(StringAt((m_current + 1), 1, "Z", "")) { m_current += 2; } else { m_current++; } return true; } return false; } /** * Encode "-SC<vowel>-" in contexts where it is silent, * or pronounced as X ("sh"), S, or SK * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SC() { if(StringAt(m_current, 2, "SC", "")) { // exception 'viscount' if(StringAt((m_current - 2), 8, "VISCOUNT", "")) { m_current += 1; return true; } // encode "-SC<front vowel>-" if(StringAt((m_current + 2), 1, "I", "E", "Y", "")) { // e.g. "conscious" if(StringAt((m_current + 2), 4, "IOUS", "") // e.g. "prosciutto" || StringAt((m_current + 2), 3, "IUT", "") || StringAt((m_current - 4), 9, "OMNISCIEN", "") // e.g. "conscious" || StringAt((m_current - 3), 8, "CONSCIEN", "CRESCEND", "CONSCION", "") || StringAt((m_current - 2), 6, "FASCIS", "")) { MetaphAdd("X"); } else if(StringAt(m_current, 7, "SCEPTIC", "SCEPSIS", "") || StringAt(m_current, 5, "SCIVV", "SCIRO", "") // commonly pronounced this way in u.s. || StringAt(m_current, 6, "SCIPIO", "") || StringAt((m_current - 2), 10, "PISCITELLI", "")) { MetaphAdd("SK"); } else { MetaphAdd("S"); } m_current += 2; return true; } MetaphAdd("SK"); m_current += 2; return true; } return false; } /** * Encode "-S<EA,UI,IER>-" in contexts where it is pronounced * as J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SEA_SUI_SIER() { // "nausea" by itself has => NJ as a more likely encoding. Other forms // using "nause-" (see Encode_SEA()) have X or S as more familiar pronounciations if((StringAt((m_current - 3), 6, "NAUSEA", "") && ((m_current + 2) == m_last)) // e.g. "casuistry", "frasier", "hoosier" || StringAt((m_current - 2), 5, "CASUI", "") || (StringAt((m_current - 1), 5, "OSIER", "ASIER", "") && !(StringAt(0, 6, "EASIER","") || StringAt(0, 5, "OSIER","") || StringAt((m_current - 2), 6, "ROSIER", "MOSIER", "")))) { MetaphAdd("J", "X"); AdvanceCounter(3, 1); return true; } return false; } /** * Encode cases where "-SE-" is pronounced as X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_SEA() { if((StringAt(0, 4, "SEAN", "") && ((m_current + 3) == m_last)) || (StringAt((m_current - 3), 6, "NAUSEO", "") && !StringAt((m_current - 3), 7, "NAUSEAT", ""))) { MetaphAdd("X"); AdvanceCounter(3, 1); return true; } return false; } /** * Encode "-T-" * */ void Encode_T() { if(Encode_T_Initial() || Encode_TCH() || Encode_Silent_French_T() || Encode_TUN_TUL_TUA_TUO() || Encode_TUE_TEU_TEOU_TUL_TIE() || Encode_TUR_TIU_Suffixes() || Encode_TI() || Encode_TIENT() || Encode_TSCH() || Encode_TZSCH() || Encode_TH_Pronounced_Separately() || Encode_TTH() || Encode_TH()) { return; } // eat redundant 'T' or 'D' if(StringAt((m_current + 1), 1, "T", "D", "")) { m_current += 2; } else { m_current++; } MetaphAdd("T"); } /** * Encode some exceptions for initial 'T' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_T_Initial() { if(m_current == 0) { // americans usually pronounce "tzar" as "zar" if (StringAt((m_current + 1), 3, "SAR", "ZAR", "")) { m_current++; return true; } // old 'École française d'Extrême-Orient' chinese pinyin where 'ts-' => 'X' if (((m_length == 3) && StringAt((m_current + 1), 2, "SO", "SA", "SU", "")) || ((m_length == 4) && StringAt((m_current + 1), 3, "SAO", "SAI", "")) || ((m_length == 5) && StringAt((m_current + 1), 4, "SING", "SANG", ""))) { MetaphAdd("X"); AdvanceCounter(3, 2); return true; } // "TS<vowel>-" at start can be pronounced both with and without 'T' if (StringAt((m_current + 1), 1, "S", "") && IsVowel(m_current + 2)) { MetaphAdd("TS", "S"); AdvanceCounter(3, 2); return true; } // e.g. "Tjaarda" if (StringAt((m_current + 1), 1, "J", "")) { MetaphAdd("X"); AdvanceCounter(3, 2); return true; } // cases where initial "TH-" is pronounced as T and not 0 ("th") if ((StringAt((m_current + 1), 2, "HU", "") && (m_length == 3)) || StringAt((m_current + 1), 3, "HAI", "HUY", "HAO", "") || StringAt((m_current + 1), 4, "HYME", "HYMY", "HANH", "") || StringAt((m_current + 1), 5, "HERES", "")) { MetaphAdd("T"); AdvanceCounter(3, 2); return true; } } return false; } /** * Encode "-TCH-", reliably X ("sh", or in this case, "ch") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TCH() { if(StringAt((m_current + 1), 2, "CH", "")) { MetaphAdd("X"); m_current += 3; return true; } return false; } /** * Encode the many cases where americans are aware that a certain word is * french and know to not pronounce the 'T' * * @return true if encoding handled in this routine, false if not * TOUCHET CHABOT BENOIT */ boolean Encode_Silent_French_T() { // french silent T familiar to americans if(((m_current == m_last) && StringAt((m_current - 4), 5, "MONET", "GENET", "CHAUT", "")) || StringAt((m_current - 2), 9, "POTPOURRI", "") || StringAt((m_current - 3), 9, "BOATSWAIN", "") || StringAt((m_current - 3), 8, "MORTGAGE", "") || (StringAt((m_current - 4), 5, "BERET", "BIDET", "FILET", "DEBUT", "DEPOT", "PINOT", "TAROT", "") || StringAt((m_current - 5), 6, "BALLET", "BUFFET", "CACHET", "CHALET", "ESPRIT", "RAGOUT", "GOULET", "CHABOT", "BENOIT", "") || StringAt((m_current - 6), 7, "GOURMET", "BOUQUET", "CROCHET", "CROQUET", "PARFAIT", "PINCHOT", "CABARET", "PARQUET", "RAPPORT", "TOUCHET", "COURBET", "DIDEROT", "") || StringAt((m_current - 7), 8, "ENTREPOT", "CABERNET", "DUBONNET", "MASSENET", "MUSCADET", "RICOCHET", "ESCARGOT", "") || StringAt((m_current - 8), 9, "SOBRIQUET", "CABRIOLET", "CASSOULET", "OUBRIQUET", "CAMEMBERT", "")) && !StringAt((m_current + 1), 2, "AN", "RY", "IC", "OM", "IN", "")) { m_current++; return true; } return false; } /** * Encode "-TU<N,L,A,O>-" in cases where it is pronounced * X ("sh", or in this case, "ch") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TUN_TUL_TUA_TUO() { // e.g. "fortune", "fortunate" if(StringAt((m_current - 3), 6, "FORTUN", "") // e.g. "capitulate" || (StringAt(m_current, 3, "TUL", "") && (IsVowel(m_current - 1) && IsVowel(m_current + 3))) // e.g. "obituary", "barbituate" || StringAt((m_current - 2), 5, "BITUA", "BITUE", "") // e.g. "actual" || ((m_current > 1) && StringAt(m_current, 3, "TUA", "TUO", ""))) { MetaphAdd("X", "T"); m_current++; return true; } return false; } /** * Encode "-T<vowel>-" forms where 'T' is pronounced as X * ("sh", or in this case "ch") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TUE_TEU_TEOU_TUL_TIE() { // 'constituent', 'pasteur' if(StringAt((m_current + 1), 4, "UENT", "") || StringAt((m_current - 4), 9, "RIGHTEOUS", "") || StringAt((m_current - 3), 7, "STATUTE", "") || StringAt((m_current - 3), 7, "AMATEUR", "") // e.g. "blastula", "pasteur" || (StringAt((m_current - 1), 5, "NTULE", "NTULA", "STULE", "STULA", "STEUR", "")) // e.g. "statue" || (((m_current + 2) == m_last) && StringAt(m_current, 3, "TUE", "")) // e.g. "constituency" || StringAt(m_current, 5, "TUENC", "") // e.g. "statutory" || StringAt((m_current - 3), 8, "STATUTOR", "") // e.g. "patience" || (((m_current + 5) == m_last) && StringAt(m_current, 6, "TIENCE", ""))) { MetaphAdd("X", "T"); AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-TU-" forms in suffixes where it is usually * pronounced as X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TUR_TIU_Suffixes() { // 'adventure', 'musculature' if((m_current > 0) && StringAt((m_current + 1), 3, "URE", "URA", "URI", "URY", "URO", "IUS", "")) { // exceptions e.g. 'tessitura', mostly from romance languages if ((StringAt((m_current + 1), 3, "URA", "URO", "") //&& !StringAt((m_current + 1), 4, "URIA", "") && ((m_current + 3) == m_last)) && !StringAt((m_current - 3), 7, "VENTURA", "") // e.g. "kachaturian", "hematuria" || StringAt((m_current + 1), 4, "URIA", "")) { MetaphAdd("T"); } else { MetaphAdd("X", "T"); } AdvanceCounter(2, 1); return true; } return false; } /** * Encode "-TI<O,A,U>-" as X ("sh"), except * in cases where it is part of a combining form, * or as J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TI() { // '-tio-', '-tia-', '-tiu-' // except combining forms where T already pronounced e.g 'rooseveltian' if((StringAt((m_current + 1), 2, "IO", "") && !StringAt((m_current - 1), 5, "ETIOL", "")) || StringAt((m_current + 1), 3, "IAL", "") || StringAt((m_current - 1), 5, "RTIUM", "ATIUM", "") || ((StringAt((m_current + 1), 3, "IAN", "") && (m_current > 0)) && !(StringAt((m_current - 4), 8, "FAUSTIAN", "") || StringAt((m_current - 5), 9, "PROUSTIAN", "") || StringAt((m_current - 2), 7, "TATIANA", "") ||(StringAt((m_current - 3), 7, "KANTIAN", "GENTIAN", "") || StringAt((m_current - 8), 12, "ROOSEVELTIAN", ""))) || (((m_current + 2) == m_last) && StringAt(m_current, 3, "TIA", "") // exceptions to above rules where the pronounciation is usually X && !(StringAt((m_current - 3), 6, "HESTIA", "MASTIA", "") || StringAt((m_current - 2), 5, "OSTIA", "") || StringAt(0, 3, "TIA", "") || StringAt((m_current - 5), 8, "IZVESTIA", ""))) || StringAt((m_current + 1), 4, "IATE", "IATI", "IABL", "IATO", "IARY", "") || StringAt((m_current - 5), 9, "CHRISTIAN", ""))) { if(((m_current == 2) && StringAt(0, 4, "ANTI", "")) || StringAt(0, 5, "PATIO", "PITIA", "DUTIA", "")) { MetaphAdd("T"); } else if(StringAt((m_current - 4), 8, "EQUATION", "")) { MetaphAdd("J"); } else { if(StringAt(m_current, 4, "TION", "")) { MetaphAdd("X"); } else if(StringAt(0, 5, "KATIA", "LATIA", "")) { MetaphAdd("T", "X"); } else { MetaphAdd("X", "T"); } } AdvanceCounter(3, 1); return true; } return false; } /** * Encode "-TIENT-" where "TI" is pronounced X ("sh") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TIENT() { // e.g. 'patient' if(StringAt((m_current + 1), 4, "IENT", "")) { MetaphAdd("X", "T"); AdvanceCounter(3, 1); return true; } return false; } /** * Encode "-TSCH-" as X ("ch") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TSCH() { //'deutsch' if(StringAt(m_current, 4, "TSCH", "") // combining forms in german where the 'T' is pronounced seperately && !StringAt((m_current - 3), 4, "WELT", "KLAT", "FEST", "")) { // pronounced the same as "ch" in "chit" => X MetaphAdd("X"); m_current += 4; return true; } return false; } /** * Encode "-TZSCH-" as X ("ch") * * "Neitzsche is peachy" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TZSCH() { //'neitzsche' if(StringAt(m_current, 5, "TZSCH", "")) { MetaphAdd("X"); m_current += 5; return true; } return false; } /** * Encodes cases where the 'H' in "-TH-" is the beginning of * another word in a combining form, special cases where it is * usually pronounced as 'T', and a special case where it has * become pronounced as X ("sh", in this case "ch") * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TH_Pronounced_Separately() { //'adulthood', 'bithead', 'apartheid' if(((m_current > 0) && StringAt((m_current + 1), 4, "HOOD", "HEAD", "HEID", "HAND", "HILL", "HOLD", "HAWK", "HEAP", "HERD", "HOLE", "HOOK", "HUNT", "HUMO", "HAUS", "HOFF", "HARD", "") && !StringAt((m_current - 3), 5, "SOUTH", "NORTH", "")) || StringAt((m_current + 1), 5, "HOUSE", "HEART", "HASTE", "HYPNO", "HEQUE", "") // watch out for greek root "-thallic" || (StringAt((m_current + 1), 4, "HALL", "") && ((m_current + 4) == m_last) && !StringAt((m_current - 3), 5, "SOUTH", "NORTH", "")) || (StringAt((m_current + 1), 3, "HAM", "") && ((m_current + 3) == m_last) && !(StringAt(0, 6, "GOTHAM", "WITHAM", "LATHAM", "") || StringAt(0, 7, "BENTHAM", "WALTHAM", "WORTHAM", "") || StringAt(0, 8, "GRANTHAM", ""))) || (StringAt((m_current + 1), 5, "HATCH", "") && !((m_current == 0) || StringAt((m_current - 2), 8, "UNTHATCH", ""))) || StringAt((m_current - 3), 7, "WARTHOG", "") // and some special cases where "-TH-" is usually pronounced 'T' || StringAt((m_current - 2), 6, "ESTHER", "") || StringAt((m_current - 3), 6, "GOETHE", "") || StringAt((m_current - 2), 8, "NATHALIE", "")) { // special case if (StringAt((m_current - 3), 7, "POSTHUM", "")) { MetaphAdd("X"); } else { MetaphAdd("T"); } m_current += 2; return true; } return false; } /** * Encode the "-TTH-" in "matthew", eating the redundant 'T' * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TTH() { // 'matthew' vs. 'outthink' if(StringAt(m_current, 3, "TTH", "")) { if (StringAt((m_current - 2), 5, "MATTH", "")) { MetaphAdd("0"); } else { MetaphAdd("T0"); } m_current += 3; return true; } return false; } /** * Encode "-TH-". 0 (zero) is used in Metaphone to encode this sound * when it is pronounced as a dipthong, either voiced or unvoiced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_TH() { if(StringAt(m_current, 2, "TH", "") ) { //'-clothes-' if(StringAt((m_current - 3), 7, "CLOTHES", "")) { // vowel already encoded so skip right to S m_current += 3; return true; } //special case "thomas", "thames", "beethoven" or germanic words if(StringAt((m_current + 2), 4, "OMAS", "OMPS", "OMPK", "OMSO", "OMSE", "AMES", "OVEN", "OFEN", "ILDA", "ILDE", "") || (StringAt(0, 4, "THOM", "") && (m_length == 4)) || (StringAt(0, 5, "THOMS", "") && (m_length == 5)) || StringAt(0, 4, "VAN ", "VON ", "") || StringAt(0, 3, "SCH", "")) { MetaphAdd("T"); } else { // give an 'etymological' 2nd // encoding for "smith" if(StringAt(0, 2, "SM", "")) { MetaphAdd("0", "T"); } else { MetaphAdd("0"); } } m_current += 2; return true; } return false; } /** * Encode "-V-" * */ void Encode_V() { // eat redundant 'V' if(CharAt(m_current + 1) == 'V') { m_current += 2; } else { m_current++; } MetaphAddExactApprox("V", "F"); } /** * Encode "-W-" * */ void Encode_W() { if(Encode_Silent_W_At_Beginning() || Encode_WITZ_WICZ() || Encode_WR() || Encode_Initial_W_Vowel() || Encode_WH() || Encode_Eastern_European_W()) { return; } // e.g. 'zimbabwe' if(m_encodeVowels && StringAt(m_current, 2, "WE", "") && ((m_current + 1) == m_last)) { MetaphAdd("A"); } //else skip it m_current++; } /** * Encode cases where 'W' is silent at beginning of word * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Silent_W_At_Beginning() { //skip these when at start of word if((m_current == 0) && StringAt(m_current, 2, "WR", "")) { m_current += 1; return true; } return false; } /** * Encode polish patronymic suffix, mapping * alternate spellings to the same encoding, * and including easern european pronounciation * to the american so that both forms can * be found in a genealogy search * * @return true if encoding handled in this routine, false if not * */ boolean Encode_WITZ_WICZ() { //polish e.g. 'filipowicz' if(((m_current + 3) == m_last) && StringAt(m_current, 4, "WICZ", "WITZ", "")) { if(m_encodeVowels) { if((m_primary.length() > 0) && m_primary.charAt(m_primary.length() - 1) == 'A') { MetaphAdd("TS", "FAX"); } else { MetaphAdd("ATS", "FAX"); } } else { MetaphAdd("TS", "FX"); } m_current += 4; return true; } return false; } /** * Encode "-WR-" as R ('W' always effectively silent) * * @return true if encoding handled in this routine, false if not * */ boolean Encode_WR() { //can also be in middle of word if(StringAt(m_current, 2, "WR", "")) { MetaphAdd("R"); m_current += 2; return true; } return false; } /** * Encode "W-", adding central and eastern european * pronounciations so that both forms can be found * in a genealogy search * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_W_Vowel() { if((m_current == 0) && IsVowel(m_current + 1)) { //Witter should match Vitter if(Germanic_Or_Slavic_Name_Beginning_With_W()) { if(m_encodeVowels) { MetaphAddExactApprox("A", "VA", "A", "FA"); } else { MetaphAddExactApprox("A", "V", "A", "F"); } } else { MetaphAdd("A"); } m_current++; // don't encode vowels twice m_current = SkipVowels(m_current); return true; } return false; } /** * Encode "-WH-" either as H, or close enough to 'U' to be * considered a vowel * * @return true if encoding handled in this routine, false if not * */ boolean Encode_WH() { if(StringAt(m_current, 2, "WH", "")) { // cases where it is pronounced as H // e.g. 'who', 'whole' if((CharAt(m_current + 2) == 'O') // exclude cases where it is pronounced like a vowel && !(StringAt((m_current + 2), 4, "OOSH", "") || StringAt((m_current + 2), 3, "OOP", "OMP", "ORL", "ORT", "") || StringAt((m_current + 2), 2, "OA", "OP", ""))) { MetaphAdd("H"); AdvanceCounter(3, 2); return true; } else { // combining forms, e.g. 'hollowhearted', 'rawhide' if(StringAt((m_current + 2), 3, "IDE", "ARD", "EAD", "AWK", "ERD", "OOK", "AND", "OLE", "OOD", "") || StringAt((m_current + 2), 4, "EART", "OUSE", "OUND", "") || StringAt((m_current + 2), 5, "AMMER", "")) { MetaphAdd("H"); m_current += 2; return true; } else if(m_current == 0) { MetaphAdd("A"); m_current += 2; // don't encode vowels twice m_current = SkipVowels(m_current); return true; } } m_current += 2; return true; } return false; } /** * Encode "-W-" when in eastern european names, adding * the eastern european pronounciation to the american so * that both forms can be found in a genealogy search * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Eastern_European_W() { //Arnow should match Arnoff if(((m_current == m_last) && IsVowel(m_current - 1)) || StringAt((m_current - 1), 5, "EWSKI", "EWSKY", "OWSKI", "OWSKY", "") || (StringAt(m_current, 5, "WICKI", "WACKI", "") && ((m_current + 4) == m_last)) || StringAt(m_current, 4, "WIAK", "") && ((m_current + 3) == m_last) || StringAt(0, 3, "SCH", "")) { MetaphAddExactApprox("", "V", "", "F"); m_current++; return true; } return false; } /** * Encode "-X-" * */ void Encode_X() { if(Encode_Initial_X() || Encode_Greek_X() || Encode_X_Special_Cases() || Encode_X_To_H() || Encode_X_Vowel() || Encode_French_X_Final()) { return; } // eat redundant 'X' or other redundant cases if(StringAt((m_current + 1), 1, "X", "Z", "S", "") // e.g. "excite", "exceed" || StringAt((m_current + 1), 2, "CI", "CE", "")) { m_current += 2; } else { m_current++; } } /** * Encode initial X where it is usually pronounced as S * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Initial_X() { // current chinese pinyin spelling if(StringAt(0, 3, "XIA", "XIO", "XIE", "") || StringAt(0, 2, "XU", "")) { MetaphAdd("X"); m_current++; return true; } // else if((m_current == 0)) { MetaphAdd("S"); m_current++; return true; } return false; } /** * Encode X when from greek roots where it is usually pronounced as S * * @return true if encoding handled in this routine, false if not * */ boolean Encode_Greek_X() { // 'xylophone', xylem', 'xanthoma', 'xeno-' if(StringAt((m_current + 1), 3, "YLO", "YLE", "ENO", "") || StringAt((m_current + 1), 4, "ANTH", "")) { MetaphAdd("S"); m_current++; return true; } return false; } /** * Encode special cases, "LUXUR-", "Texeira" * * @return true if encoding handled in this routine, false if not * */ boolean Encode_X_Special_Cases() { // 'luxury' if(StringAt((m_current - 2), 5, "LUXUR", "")) { MetaphAddExactApprox("GJ", "KJ"); m_current++; return true; } // 'texeira' portuguese/galician name if(StringAt(0, 7, "TEXEIRA", "") || StringAt(0, 8, "TEIXEIRA", "")) { MetaphAdd("X"); m_current++; return true; } return false; } /** * Encode special case where americans know the * proper mexican indian pronounciation of this name * * @return true if encoding handled in this routine, false if not * */ boolean Encode_X_To_H() { // TODO: look for other mexican indian words // where 'X' is usually pronounced this way if(StringAt((m_current - 2), 6, "OAXACA", "") || StringAt((m_current - 3), 7, "QUIXOTE", "")) { MetaphAdd("H"); m_current++; return true; } return false; } /** * Encode "-X-" in vowel contexts where it is usually * pronounced KX ("ksh") * account also for BBC pronounciation of => KS * * @return true if encoding handled in this routine, false if not * */ boolean Encode_X_Vowel() { // e.g. "sexual", "connexion" (british), "noxious" if(StringAt((m_current + 1), 3, "UAL", "ION", "IOU", "")) { MetaphAdd("KX", "KS"); AdvanceCounter(3, 1); return true; } return false; } /** * Encode cases of "-X", encoding as silent when part * of a french word where it is not pronounced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_French_X_Final() { //french e.g. "breaux", "paix" if(!((m_current == m_last) && (StringAt((m_current - 3), 3, "IAU", "EAU", "IEU", "") || StringAt((m_current - 2), 2, "AI", "AU", "OU", "OI", "EU", ""))) ) { MetaphAdd("KS"); } return false; } /** * Encode "-Z-" * */ void Encode_Z() { if(Encode_ZZ() || Encode_ZU_ZIER_ZS() || Encode_French_EZ() || Encode_German_Z()) { return; } if(Encode_ZH()) { return; } else { MetaphAdd("S"); } // eat redundant 'Z' if(CharAt(m_current + 1) == 'Z') { m_current += 2; } else { m_current++; } } /** * Encode cases of "-ZZ-" where it is obviously part * of an italian word where "-ZZ-" is pronounced as TS * * @return true if encoding handled in this routine, false if not * */ boolean Encode_ZZ() { // "abruzzi", 'pizza' if((CharAt(m_current + 1) == 'Z') && ((StringAt((m_current + 2), 1, "I", "O", "A", "") && ((m_current + 2) == m_last)) || StringAt((m_current - 2), 9, "MOZZARELL", "PIZZICATO", "PUZZONLAN", ""))) { MetaphAdd("TS", "S"); m_current += 2; return true; } return false; } /** * Encode special cases where "-Z-" is pronounced as J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_ZU_ZIER_ZS() { if(((m_current == 1) && StringAt((m_current - 1), 4, "AZUR", "")) || (StringAt(m_current, 4, "ZIER", "") && !StringAt((m_current - 2), 6, "VIZIER", "")) || StringAt(m_current, 3, "ZSA", "")) { MetaphAdd("J", "S"); if(StringAt(m_current, 3, "ZSA", "")) { m_current += 2; } else { m_current++; } return true; } return false; } /** * Encode cases where americans recognize "-EZ" as part * of a french word where Z not pronounced * * @return true if encoding handled in this routine, false if not * */ boolean Encode_French_EZ() { if(((m_current == 3) && StringAt((m_current - 3), 4, "CHEZ", "")) || StringAt((m_current - 5), 6, "RENDEZ", "")) { m_current++; return true; } return false; } /** * Encode cases where "-Z-" is in a german word * where Z => TS in german * * @return true if encoding handled in this routine, false if not * */ boolean Encode_German_Z() { if(((m_current == 2) && ((m_current + 1) == m_last) && StringAt((m_current - 2), 4, "NAZI", "")) || StringAt((m_current - 2), 6, "NAZIFY", "MOZART", "") || StringAt((m_current - 3), 4, "HOLZ", "HERZ", "MERZ", "FITZ", "") || (StringAt((m_current - 3), 4, "GANZ", "") && !IsVowel(m_current + 1)) || StringAt((m_current - 4), 5, "STOLZ", "PRINZ", "") || StringAt((m_current - 4), 7, "VENEZIA", "") || StringAt((m_current - 3), 6, "HERZOG", "") // german words beginning with "sch-" but not schlimazel, schmooze || (m_inWord.contains("SCH") && !(StringAt((m_last - 2), 3, "IZE", "OZE", "ZEL", ""))) || ((m_current > 0) && StringAt(m_current, 4, "ZEIT", "")) || StringAt((m_current - 3), 4, "WEIZ", "")) { if((m_current > 0) && m_inWord.charAt(m_current - 1) == 'T') { MetaphAdd("S"); } else { MetaphAdd("TS"); } m_current++; return true; } return false; } /** * Encode "-ZH-" as J * * @return true if encoding handled in this routine, false if not * */ boolean Encode_ZH() { //chinese pinyin e.g. 'zhao', also english "phonetic spelling" if(CharAt(m_current + 1) == 'H') { MetaphAdd("J"); m_current += 2; return true; } return false; } /** * Test for names derived from the swedish, * dutch, or slavic that should get an alternate * pronunciation of 'SV' to match the native * version * * @return true if swedish, dutch, or slavic derived name */ boolean Names_Beginning_With_SW_That_Get_Alt_SV() { if(StringAt(0, 7, "SWANSON", "SWENSON", "SWINSON", "SWENSEN", "SWOBODA", "") || StringAt(0, 9, "SWIDERSKI", "SWARTHOUT", "") || StringAt(0, 10, "SWEARENGIN", "")) { return true; } return false; } /** * Test for names derived from the german * that should get an alternate pronunciation * of 'XV' to match the german version spelled * "schw-" * * @return true if german derived name */ boolean Names_Beginning_With_SW_That_Get_Alt_XV() { if(StringAt(0, 5, "SWART", "") || StringAt(0, 6, "SWARTZ", "SWARTS", "SWIGER", "") || StringAt(0, 7, "SWITZER", "SWANGER", "SWIGERT", "SWIGART", "SWIHART", "") || StringAt(0, 8, "SWEITZER", "SWATZELL", "SWINDLER", "") || StringAt(0, 9, "SWINEHART", "") || StringAt(0, 10, "SWEARINGEN", "")) { return true; } return false; } /** * Test whether the word in question * is a name of germanic or slavic origin, for * the purpose of determining whether to add an * alternate encoding of 'V' * * @return true if germanic or slavic name */ boolean Germanic_Or_Slavic_Name_Beginning_With_W() { if(StringAt(0, 3, "WEE", "WIX", "WAX", "") || StringAt(0, 4, "WOLF", "WEIS", "WAHL", "WALZ", "WEIL", "WERT", "WINE", "WILK", "WALT", "WOLL", "WADA", "WULF", "WEHR", "WURM", "WYSE", "WENZ", "WIRT", "WOLK", "WEIN", "WYSS", "WASS", "WANN", "WINT", "WINK", "WILE", "WIKE", "WIER", "WELK", "WISE", "") || StringAt(0, 5, "WIRTH", "WIESE", "WITTE", "WENTZ", "WOLFF", "WENDT", "WERTZ", "WILKE", "WALTZ", "WEISE", "WOOLF", "WERTH", "WEESE", "WURTH", "WINES", "WARGO", "WIMER", "WISER", "WAGER", "WILLE", "WILDS", "WAGAR", "WERTS", "WITTY", "WIENS", "WIEBE", "WIRTZ", "WYMER", "WULFF", "WIBLE", "WINER", "WIEST", "WALKO", "WALLA", "WEBRE", "WEYER", "WYBLE", "WOMAC", "WILTZ", "WURST", "WOLAK", "WELKE", "WEDEL", "WEIST", "WYGAN", "WUEST", "WEISZ", "WALCK", "WEITZ", "WYDRA", "WANDA", "WILMA", "WEBER", "") || StringAt(0, 6, "WETZEL", "WEINER", "WENZEL", "WESTER", "WALLEN", "WENGER", "WALLIN", "WEILER", "WIMMER", "WEIMER", "WYRICK", "WEGNER", "WINNER", "WESSEL", "WILKIE", "WEIGEL", "WOJCIK", "WENDEL", "WITTER", "WIENER", "WEISER", "WEXLER", "WACKER", "WISNER", "WITMER", "WINKLE", "WELTER", "WIDMER", "WITTEN", "WINDLE", "WASHER", "WOLTER", "WILKEY", "WIDNER", "WARMAN", "WEYANT", "WEIBEL", "WANNER", "WILKEN", "WILTSE", "WARNKE", "WALSER", "WEIKEL", "WESNER", "WITZEL", "WROBEL", "WAGNON", "WINANS", "WENNER", "WOLKEN", "WILNER", "WYSONG", "WYCOFF", "WUNDER", "WINKEL", "WIDMAN", "WELSCH", "WEHNER", "WEIGLE", "WETTER", "WUNSCH", "WHITTY", "WAXMAN", "WILKER", "WILHAM", "WITTIG", "WITMAN", "WESTRA", "WEHRLE", "WASSER", "WILLER", "WEGMAN", "WARFEL", "WYNTER", "WERNER", "WAGNER", "WISSER", "") || StringAt(0, 7, "WISEMAN", "WINKLER", "WILHELM", "WELLMAN", "WAMPLER", "WACHTER", "WALTHER", "WYCKOFF", "WEIDNER", "WOZNIAK", "WEILAND", "WILFONG", "WIEGAND", "WILCHER", "WIELAND", "WILDMAN", "WALDMAN", "WORTMAN", "WYSOCKI", "WEIDMAN", "WITTMAN", "WIDENER", "WOLFSON", "WENDELL", "WEITZEL", "WILLMAN", "WALDRUP", "WALTMAN", "WALCZAK", "WEIGAND", "WESSELS", "WIDEMAN", "WOLTERS", "WIREMAN", "WILHOIT", "WEGENER", "WOTRING", "WINGERT", "WIESNER", "WAYMIRE", "WHETZEL", "WENTZEL", "WINEGAR", "WESTMAN", "WYNKOOP", "WALLICK", "WURSTER", "WINBUSH", "WILBERT", "WALLACH", "WYNKOOP", "WALLICK", "WURSTER", "WINBUSH", "WILBERT", "WALLACH", "WEISSER", "WEISNER", "WINDERS", "WILLMON", "WILLEMS", "WIERSMA", "WACHTEL", "WARNICK", "WEIDLER", "WALTRIP", "WHETSEL", "WHELESS", "WELCHER", "WALBORN", "WILLSEY", "WEINMAN", "WAGAMAN", "WOMMACK", "WINGLER", "WINKLES", "WIEDMAN", "WHITNER", "WOLFRAM", "WARLICK", "WEEDMAN", "WHISMAN", "WINLAND", "WEESNER", "WARTHEN", "WETZLER", "WENDLER", "WALLNER", "WOLBERT", "WITTMER", "WISHART", "WILLIAM", "") || StringAt(0, 8, "WESTPHAL", "WICKLUND", "WEISSMAN", "WESTLUND", "WOLFGANG", "WILLHITE", "WEISBERG", "WALRAVEN", "WOLFGRAM", "WILHOITE", "WECHSLER", "WENDLING", "WESTBERG", "WENDLAND", "WININGER", "WHISNANT", "WESTRICK", "WESTLING", "WESTBURY", "WEITZMAN", "WEHMEYER", "WEINMANN", "WISNESKI", "WHELCHEL", "WEISHAAR", "WAGGENER", "WALDROUP", "WESTHOFF", "WIEDEMAN", "WASINGER", "WINBORNE", "") || StringAt(0, 9, "WHISENANT", "WEINSTEIN", "WESTERMAN", "WASSERMAN", "WITKOWSKI", "WEINTRAUB", "WINKELMAN", "WINKFIELD", "WANAMAKER", "WIECZOREK", "WIECHMANN", "WOJTOWICZ", "WALKOWIAK", "WEINSTOCK", "WILLEFORD", "WARKENTIN", "WEISINGER", "WINKLEMAN", "WILHEMINA", "") || StringAt(0, 10, "WISNIEWSKI", "WUNDERLICH", "WHISENHUNT", "WEINBERGER", "WROBLEWSKI", "WAGUESPACK", "WEISGERBER", "WESTERVELT", "WESTERLUND", "WASILEWSKI", "WILDERMUTH", "WESTENDORF", "WESOLOWSKI", "WEINGARTEN", "WINEBARGER", "WESTERBERG", "WANNAMAKER", "WEISSINGER", "") || StringAt(0, 11, "WALDSCHMIDT", "WEINGARTNER", "WINEBRENNER", "") || StringAt(0, 12, "WOLFENBARGER", "") || StringAt(0, 13, "WOJCIECHOWSKI", "")) { return true; } return false; } /** * Test whether the word in question * is a name starting with 'J' that should * match names starting with a 'Y' sound. * All forms of 'John', 'Jane', etc, get * and alt to match e.g. 'Ian', 'Yana'. Joelle * should match 'Yael', 'Joseph' should match * 'Yusef'. German and slavic last names are * also included. * * @return true if name starting with 'J' that * should get an alternate encoding as a vowel */ boolean Names_Beginning_With_J_That_Get_Alt_Y() { if(StringAt(0, 3, "JAN", "JON", "JAN", "JIN", "JEN", "") || StringAt(0, 4, "JUHL", "JULY", "JOEL", "JOHN", "JOSH", "JUDE", "JUNE", "JONI", "JULI", "JENA", "JUNG", "JINA", "JANA", "JENI", "JOEL", "JANN", "JONA", "JENE", "JULE", "JANI", "JONG", "JOHN", "JEAN", "JUNG", "JONE", "JARA", "JUST", "JOST", "JAHN", "JACO", "JANG", "JUDE", "JONE", "") || StringAt(0, 5, "JOANN", "JANEY", "JANAE", "JOANA", "JUTTA", "JULEE", "JANAY", "JANEE", "JETTA", "JOHNA", "JOANE", "JAYNA", "JANES", "JONAS", "JONIE", "JUSTA", "JUNIE", "JUNKO", "JENAE", "JULIO", "JINNY", "JOHNS", "JACOB", "JETER", "JAFFE", "JESKE", "JANKE", "JAGER", "JANIK", "JANDA", "JOSHI", "JULES", "JANTZ", "JEANS", "JUDAH", "JANUS", "JENNY", "JENEE", "JONAH", "JONAS", "JACOB", "JOSUE", "JOSEF", "JULES", "JULIE", "JULIA", "JANIE", "JANIS", "JENNA", "JANNA", "JEANA", "JENNI", "JEANE", "JONNA", "") || StringAt(0, 6, "JORDAN", "JORDON", "JOSEPH", "JOSHUA", "JOSIAH", "JOSPEH", "JUDSON", "JULIAN", "JULIUS", "JUNIOR", "JUDITH", "JOESPH", "JOHNIE", "JOANNE", "JEANNE", "JOANNA", "JOSEFA", "JULIET", "JANNIE", "JANELL", "JASMIN", "JANINE", "JOHNNY", "JEANIE", "JEANNA", "JOHNNA", "JOELLE", "JOVITA", "JOSEPH", "JONNIE", "JANEEN", "JANINA", "JOANIE", "JAZMIN", "JOHNIE", "JANENE", "JOHNNY", "JONELL", "JENELL", "JANETT", "JANETH", "JENINE", "JOELLA", "JOEANN", "JULIAN", "JOHANA", "JENICE", "JANNET", "JANISE", "JULENE", "JOSHUA", "JANEAN", "JAIMEE", "JOETTE", "JANYCE", "JENEVA", "JORDAN", "JACOBS", "JENSEN", "JOSEPH", "JANSEN", "JORDON", "JULIAN", "JAEGER", "JACOBY", "JENSON", "JARMAN", "JOSLIN", "JESSEN", "JAHNKE", "JACOBO", "JULIEN", "JOSHUA", "JEPSON", "JULIUS", "JANSON", "JACOBI", "JUDSON", "JARBOE", "JOHSON", "JANZEN", "JETTON", "JUNKER", "JONSON", "JAROSZ", "JENNER", "JAGGER", "JASMIN", "JEPSEN", "JORDEN", "JANNEY", "JUHASZ", "JERGEN", "JAKOB", "") || StringAt(0, 7, "JOHNSON", "JOHNNIE", "JASMINE", "JEANNIE", "JOHANNA", "JANELLE", "JANETTE", "JULIANA", "JUSTINA", "JOSETTE", "JOELLEN", "JENELLE", "JULIETA", "JULIANN", "JULISSA", "JENETTE", "JANETTA", "JOSELYN", "JONELLE", "JESENIA", "JANESSA", "JAZMINE", "JEANENE", "JOANNIE", "JADWIGA", "JOLANDA", "JULIANE", "JANUARY", "JEANICE", "JANELLA", "JEANETT", "JENNINE", "JOHANNE", "JOHNSIE", "JANIECE", "JOHNSON", "JENNELL", "JAMISON", "JANSSEN", "JOHNSEN", "JARDINE", "JAGGERS", "JURGENS", "JOURDAN", "JULIANO", "JOSEPHS", "JHONSON", "JOZWIAK", "JANICKI", "JELINEK", "JANSSON", "JOACHIM", "JANELLE", "JACOBUS", "JENNING", "JANTZEN", "JOHNNIE", "") || StringAt(0, 8, "JOSEFINA", "JEANNINE", "JULIANNE", "JULIANNA", "JONATHAN", "JONATHON", "JEANETTE", "JANNETTE", "JEANETTA", "JOHNETTA", "JENNEFER", "JULIENNE", "JOSPHINE", "JEANELLE", "JOHNETTE", "JULIEANN", "JOSEFINE", "JULIETTA", "JOHNSTON", "JACOBSON", "JACOBSEN", "JOHANSEN", "JOHANSON", "JAWORSKI", "JENNETTE", "JELLISON", "JOHANNES", "JASINSKI", "JUERGENS", "JARNAGIN", "JEREMIAH", "JEPPESEN", "JARNIGAN", "JANOUSEK", "") || StringAt(0, 9, "JOHNATHAN", "JOHNATHON", "JORGENSEN", "JEANMARIE", "JOSEPHINA", "JEANNETTE", "JOSEPHINE", "JEANNETTA", "JORGENSON", "JANKOWSKI", "JOHNSTONE", "JABLONSKI", "JOSEPHSON", "JOHANNSEN", "JURGENSEN", "JIMMERSON", "JOHANSSON", "") || StringAt(0, 10, "JAKUBOWSKI", "")) { return true; } return false; } // 2024-02-26: Changed the `main` method into a unit test (see Metaphone3Tests.java) }
OpenRefine/OpenRefine
main/src/com/google/refine/clustering/binning/Metaphone3.java
2,388
/* * 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.apache.hadoop.hive.llap; import java.io.EOFException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.ByteBuffer; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PositionedReadable; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hive.common.io.Allocator; import org.apache.hadoop.hive.common.io.CacheTag; import org.apache.hadoop.hive.common.io.DataCache; import org.apache.hadoop.hive.common.io.DiskRange; import org.apache.hadoop.hive.common.io.DiskRangeList; import org.apache.hadoop.hive.common.io.encoded.MemoryBuffer; import org.apache.hadoop.hive.ql.io.orc.encoded.CacheChunk; import org.apache.hadoop.util.Progressable; import org.apache.orc.impl.RecordReaderUtils; /** * This is currently only used by Parquet; however, a generally applicable approach is used - * you pass in a set of offset pairs for a file, and the file is cached with these boundaries. * Don't add anything format specific here. */ public class LlapCacheAwareFs extends FileSystem { public static final String SCHEME = "llapcache"; private static AtomicLong currentSplitId = new AtomicLong(-1); private URI uri; // We store the chunk indices by split file; that way if several callers are reading // the same file they can separately store and remove the relevant parts of the index. private static final ConcurrentHashMap<Long, CacheAwareInputStream> files = new ConcurrentHashMap<>(); public static Path registerFile(DataCache cache, Path path, Object fileKey, TreeMap<Long, Long> index, Configuration conf, CacheTag tag) throws IOException { long splitId = currentSplitId.incrementAndGet(); CacheAwareInputStream stream = new CacheAwareInputStream( cache, conf, index, path, fileKey, -1, tag); if (files.putIfAbsent(splitId, stream) != null) { throw new IOException("Record already exists for " + splitId); } conf.set("fs." + LlapCacheAwareFs.SCHEME + ".impl", LlapCacheAwareFs.class.getCanonicalName()); return new Path(SCHEME + "://" + SCHEME + "/" + splitId); } public static void unregisterFile(Path cachePath) { if (LOG.isDebugEnabled()) { LOG.debug("Unregistering " + cachePath); } files.remove(extractSplitId(cachePath)); } @Override public void initialize(URI uri, Configuration conf) throws IOException { super.initialize(uri, conf); this.uri = URI.create(SCHEME + "://" + SCHEME); } @Override public FSDataInputStream open(Path path, int bufferSize) throws IOException { return new FSDataInputStream(getCtx(path).cloneWithBufferSize(bufferSize)); } private LlapCacheAwareFs.CacheAwareInputStream getCtx(Path path) { return files.get(extractSplitId(path)); } private static long extractSplitId(Path path) { String pathOnly = path.toUri().getPath(); if (pathOnly.startsWith("/")) { pathOnly = pathOnly.substring(1); } return Long.parseLong(pathOnly); } @Override public URI getUri() { return uri; } @Override public Path getWorkingDirectory() { throw new UnsupportedOperationException(); } @Override public void setWorkingDirectory(Path arg0) { throw new UnsupportedOperationException(); } @Override public FSDataOutputStream append(Path arg0, int arg1, Progressable arg2) throws IOException { LlapCacheAwareFs.CacheAwareInputStream ctx = getCtx(arg0); return ctx.getFs().append(ctx.path, arg1, arg2); } @Override public FSDataOutputStream create(Path arg0, FsPermission arg1, boolean arg2, int arg3, short arg4, long arg5, Progressable arg6) throws IOException { LlapCacheAwareFs.CacheAwareInputStream ctx = getCtx(arg0); return ctx.getFs().create(ctx.path, arg1, arg2, arg3, arg4, arg5, arg6); } @Override public boolean delete(Path arg0, boolean arg1) throws IOException { LlapCacheAwareFs.CacheAwareInputStream ctx = getCtx(arg0); return ctx.getFs().delete(ctx.path, arg1); } @Override public FileStatus getFileStatus(Path arg0) throws IOException { LlapCacheAwareFs.CacheAwareInputStream ctx = getCtx(arg0); FileStatus fileStatus = ctx.getFs().getFileStatus(ctx.path); // We replace the path in the file status by the input path as Parquet // may use the path in the file status to open the file fileStatus.setPath(arg0); return fileStatus; } @Override public FileStatus[] listStatus(Path arg0) throws FileNotFoundException, IOException { LlapCacheAwareFs.CacheAwareInputStream ctx = getCtx(arg0); return ctx.getFs().listStatus(ctx.path); } @Override public boolean mkdirs(Path arg0, FsPermission arg1) throws IOException { LlapCacheAwareFs.CacheAwareInputStream ctx = getCtx(arg0); return ctx.getFs().mkdirs(ctx.path, arg1); } @Override public boolean rename(Path arg0, Path arg1) throws IOException { LlapCacheAwareFs.CacheAwareInputStream ctx1 = getCtx(arg0), ctx2 = getCtx(arg1); return ctx1.getFs().rename(ctx1.path, ctx2.path); } private static class CacheAwareInputStream extends InputStream implements Seekable, PositionedReadable { private final TreeMap<Long, Long> chunkIndex; private final Path path; private final Object fileKey; private final CacheTag tag; private final Configuration conf; private final DataCache cache; private final int bufferSize; private long position = 0; public CacheAwareInputStream(DataCache cache, Configuration conf, TreeMap<Long, Long> chunkIndex, Path path, Object fileKey, int bufferSize, CacheTag tag) { this.cache = cache; this.fileKey = fileKey; this.chunkIndex = chunkIndex; this.path = path; this.conf = conf; this.bufferSize = bufferSize; this.tag = tag; } public LlapCacheAwareFs.CacheAwareInputStream cloneWithBufferSize(int bufferSize) { return new CacheAwareInputStream(cache, conf, chunkIndex, path, fileKey, bufferSize, tag); } @Override public int read() throws IOException { // This is not called by ConsecutiveChunk stuff in Parquet. // If this were used, it might make sense to make it faster. byte[] theByte = new byte[1]; int result = read(theByte, 0, 1); if (result != 1) throw new EOFException(); return theByte[0] & 0xFF; } @Override public int read(byte[] array, final int arrayOffset, final int len) throws IOException { long readStartPos = position; DiskRangeList drl = new DiskRangeList(readStartPos, readStartPos + len); DataCache.BooleanRef gotAllData = new DataCache.BooleanRef(); drl = cache.getFileData(fileKey, drl, 0, new DataCache.DiskRangeListFactory() { @Override public DiskRangeList createCacheChunk( MemoryBuffer buffer, long startOffset, long endOffset) { return new CacheChunk(buffer, startOffset, endOffset); } }, gotAllData); if (LOG.isDebugEnabled()) { LOG.debug("Buffers after cache " + RecordReaderUtils.stringifyDiskRanges(drl)); } if (gotAllData.value) { long sizeRead = 0; while (drl != null) { assert drl.hasData(); long from = drl.getOffset(), to = drl.getEnd(); int offsetFromReadStart = (int)(from - readStartPos), candidateSize = (int)(to - from); ByteBuffer data = drl.getData().duplicate(); data.get(array, arrayOffset + offsetFromReadStart, candidateSize); cache.releaseBuffer(((CacheChunk)drl).getBuffer()); sizeRead += candidateSize; drl = drl.next; } validateAndUpdatePosition(len, sizeRead); return len; } int maxAlloc = cache.getAllocator().getMaxAllocation(); // We have some disk data. Separate it by column chunk and put into cache. // We started with a single DRL, so we assume there will be no consecutive missing blocks // after the cache has inserted cache data. We also assume all the missing parts will // represent one or several column chunks, since we always cache on column chunk boundaries. DiskRangeList current = drl; FileSystem fs = path.getFileSystem(conf); try (FSDataInputStream is = fs.open(path, bufferSize)) { Allocator allocator = cache.getAllocator(); long sizeRead = 0; while (current != null) { DiskRangeList candidate = current; current = current.next; long from = candidate.getOffset(), to = candidate.getEnd(); // The offset in the destination array for the beginning of this missing range. int offsetFromReadStart = (int)(from - readStartPos), candidateSize = (int)(to - from); if (candidate.hasData()) { ByteBuffer data = candidate.getData().duplicate(); data.get(array, arrayOffset + offsetFromReadStart, candidateSize); cache.releaseBuffer(((CacheChunk)candidate).getBuffer()); sizeRead += candidateSize; continue; } // The data is not in cache. // Account for potential partial chunks. SortedMap<Long, Long> chunksInThisRead = getAndValidateMissingChunks(maxAlloc, from, to); is.seek(from); is.readFully(array, arrayOffset + offsetFromReadStart, candidateSize); sizeRead += candidateSize; // Now copy missing chunks (and parts of chunks) into cache buffers. if (fileKey == null || cache == null) continue; int extraDiskDataOffset = 0; // TODO: should we try to make a giant array for one cache call to avoid overhead? for (Map.Entry<Long, Long> missingChunk : chunksInThisRead.entrySet()) { long chunkFrom = Math.max(from, missingChunk.getKey()), chunkTo = Math.min(to, missingChunk.getValue()), chunkLength = chunkTo - chunkFrom; // TODO: if we allow partial reads (right now we disable this), we'd have to handle it here. // chunksInThisRead should probably be changed to be a struct array indicating both // partial and full sizes for each chunk; then the partial ones could be merged // with the previous partial ones, and any newly-full chunks put in the cache. MemoryBuffer[] largeBuffers = null, smallBuffer = null, newCacheData = null; try { int largeBufCount = (int) (chunkLength / maxAlloc); int smallSize = (int) (chunkLength % maxAlloc); int chunkPartCount = largeBufCount + ((smallSize > 0) ? 1 : 0); DiskRange[] cacheRanges = new DiskRange[chunkPartCount]; int extraOffsetInChunk = 0; if (maxAlloc < chunkLength) { largeBuffers = new MemoryBuffer[largeBufCount]; // Note: we don't use StoppableAllocator here - this is not on an IO thread. allocator.allocateMultiple(largeBuffers, maxAlloc, cache.getDataBufferFactory()); for (int i = 0; i < largeBuffers.length; ++i) { // By definition here we copy up to the limit of the buffer. ByteBuffer bb = largeBuffers[i].getByteBufferRaw(); int remaining = bb.remaining(); assert remaining == maxAlloc; copyDiskDataToCacheBuffer(array, arrayOffset + offsetFromReadStart + extraDiskDataOffset, remaining, bb, cacheRanges, i, chunkFrom + extraOffsetInChunk); extraDiskDataOffset += remaining; extraOffsetInChunk += remaining; } } newCacheData = largeBuffers; largeBuffers = null; if (smallSize > 0) { smallBuffer = new MemoryBuffer[1]; // Note: we don't use StoppableAllocator here - this is not on an IO thread. allocator.allocateMultiple(smallBuffer, smallSize, cache.getDataBufferFactory()); ByteBuffer bb = smallBuffer[0].getByteBufferRaw(); copyDiskDataToCacheBuffer(array, arrayOffset + offsetFromReadStart + extraDiskDataOffset, smallSize, bb, cacheRanges, largeBufCount, chunkFrom + extraOffsetInChunk); extraDiskDataOffset += smallSize; extraOffsetInChunk += smallSize; // Not strictly necessary, no one will look at it. if (newCacheData == null) { newCacheData = smallBuffer; } else { // TODO: add allocate overload with an offset and length MemoryBuffer[] combinedCacheData = new MemoryBuffer[largeBufCount + 1]; System.arraycopy(newCacheData, 0, combinedCacheData, 0, largeBufCount); newCacheData = combinedCacheData; newCacheData[largeBufCount] = smallBuffer[0]; } smallBuffer = null; } cache.putFileData(fileKey, cacheRanges, newCacheData, 0, tag); } finally { // We do not use the new cache buffers for the actual read, given the way read() API is. // Therefore, we don't need to handle cache collisions - just decref all the buffers. if (newCacheData != null) { for (MemoryBuffer buffer : newCacheData) { if (buffer == null) continue; cache.releaseBuffer(buffer); } } // If we have failed before building newCacheData, deallocate other the allocated. if (largeBuffers != null) { for (MemoryBuffer buffer : largeBuffers) { if (buffer == null) continue; allocator.deallocate(buffer); } } if (smallBuffer != null && smallBuffer[0] != null) { allocator.deallocate(smallBuffer[0]); } } } } validateAndUpdatePosition(len, sizeRead); } return len; } private void validateAndUpdatePosition(int len, long sizeRead) { if (sizeRead != len) { throw new AssertionError("Reading at " + position + " for " + len + ": " + sizeRead + " bytes copied"); } position += len; } private void copyDiskDataToCacheBuffer(byte[] diskData, int offsetInDiskData, int sizeToCopy, ByteBuffer cacheBuffer, DiskRange[] cacheRanges, int cacheRangeIx, long cacheRangeStart) { int bbPos = cacheBuffer.position(); long cacheRangeEnd = cacheRangeStart + sizeToCopy; if (LOG.isTraceEnabled()) { LOG.trace("Caching [" + cacheRangeStart + ", " + cacheRangeEnd + ")"); } cacheRanges[cacheRangeIx] = new DiskRange(cacheRangeStart, cacheRangeEnd); cacheBuffer.put(diskData, offsetInDiskData, sizeToCopy); cacheBuffer.position(bbPos); } private SortedMap<Long, Long> getAndValidateMissingChunks( int maxAlloc, long from, long to) { Map.Entry<Long, Long> firstMissing = chunkIndex.floorEntry(from); if (firstMissing == null) { throw new AssertionError("No lower bound for start offset " + from); } if (firstMissing.getValue() <= from || ((from - firstMissing.getKey()) % maxAlloc) != 0) { // The data does not belong to a recognized chunk, or is split wrong. throw new AssertionError("Lower bound for start offset " + from + " is [" + firstMissing.getKey() + ", " + firstMissing.getValue() + ")"); } SortedMap<Long, Long> missingChunks = chunkIndex.subMap(firstMissing.getKey(), to); if (missingChunks.isEmpty()) { throw new AssertionError("No chunks for [" + from + ", " + to + ")"); } long lastMissingOffset = missingChunks.lastKey(), lastMissingEnd = missingChunks.get(lastMissingOffset); if (lastMissingEnd < to || (to != lastMissingEnd && ((to - lastMissingOffset) % maxAlloc) != 0)) { // The data does not belong to a recognized chunk, or is split wrong. throw new AssertionError("Lower bound for end offset " + to + " is [" + lastMissingOffset + ", " + lastMissingEnd + ")"); } return missingChunks; } public FileSystem getFs() throws IOException { return path.getFileSystem(conf); } @Override public long getPos() throws IOException { return position; } @Override public void seek(long position) throws IOException { this.position = position; } @Override @Private public boolean seekToNewSource(long arg0) throws IOException { throw new UnsupportedOperationException(); } @Override public int read(long arg0, byte[] arg1, int arg2, int arg3) throws IOException { seek(arg0); return read(arg1, arg2, arg3); } @Override public void readFully(long arg0, byte[] arg1) throws IOException { read(arg0, arg1, 0, arg1.length); } @Override public void readFully(long arg0, byte[] arg1, int arg2, int arg3) throws IOException { read(arg0, arg1, 0, arg1.length); } } }
apache/hive
ql/src/java/org/apache/hadoop/hive/llap/LlapCacheAwareFs.java
2,389
/* * DBeaver - Universal Database Manager * Copyright (C) 2016-2016 Karl Griesser ([email protected]) * Copyright (C) 2010-2024 DBeaver Corp and others * * 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.jkiss.dbeaver.ext.exasol.ui; import org.jkiss.dbeaver.model.DBConstants; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Exasol constants * * @author Karl Griesser */ public class ExasolUIConstants { // Display Categories public static final String DRV_ENCRYPT = DBConstants.INTERNAL_PROP_PREFIX + "encrypt"; public static final String DRV_BACKUP_HOST_LIST = DBConstants.INTERNAL_PROP_PREFIX + "backupHostList"; public static final Map<String,String> encoding = new HashMap<String, String>(); public static final ArrayList<String> encodings = new ArrayList<String>(); public static final ArrayList<String> stringSepModes = new ArrayList<String>(); public static final ArrayList<String> rowSeparators = new ArrayList<String>(); static { rowSeparators.add("CRLF"); rowSeparators.add("CR"); rowSeparators.add("LF"); } static { stringSepModes.add("AUTO"); stringSepModes.add("ALWAYS"); stringSepModes.add("NEVER"); } static { encodings.add("UTF-8"); encoding.put("UTF-8", "UTF-8"); encoding.put("UTF8", "UTF-8"); encoding.put("ISO10646/UTF-8", "UTF-8"); encoding.put("ISO10646/UTF8", "UTF-8"); encodings.add("ASCII"); encoding.put("ASCII", "ASCII"); encoding.put("US-ASCII", "ASCII"); encoding.put("US", "ASCII"); encoding.put("ISO-IR-6", "ASCII"); encoding.put("ANSI_X3.4-1968", "ASCII"); encoding.put("ANSI_X3.4-1986", "ASCII"); encoding.put("ISO_646.IRV:1991", "ASCII"); encoding.put("ISO646-US", "ASCII"); encoding.put("IBM367", "ASCII"); encoding.put("IBM-367", "ASCII"); encoding.put("CP367", "ASCII"); encoding.put("CP-367", "ASCII"); encoding.put("367", "ASCII"); encodings.add("ISO-8859-1"); encoding.put("ISO-8859-1", "ISO-8859-1"); encoding.put("ISO8859-1", "ISO-8859-1"); encoding.put("ISO88591", "ISO-8859-1"); encoding.put("LATIN-1", "ISO-8859-1"); encoding.put("LATIN1", "ISO-8859-1"); encoding.put("L1", "ISO-8859-1"); encoding.put("ISO-IR-100", "ISO-8859-1"); encoding.put("ISO_8859-1:1987", "ISO-8859-1"); encoding.put("ISO_8859-1", "ISO-8859-1"); encoding.put("IBM819", "ISO-8859-1"); encoding.put("IBM-819", "ISO-8859-1"); encoding.put("CP819", "ISO-8859-1"); encoding.put("CP-819", "ISO-8859-1"); encoding.put("819", "ISO-8859-1"); encodings.add("ISO-8859-2"); encoding.put("ISO-8859-2", "ISO-8859-2"); encoding.put("ISO8859-2", "ISO-8859-2"); encoding.put("ISO88592", "ISO-8859-2"); encoding.put("LATIN-2", "ISO-8859-2"); encoding.put("LATIN2", "ISO-8859-2"); encoding.put("L2", "ISO-8859-2"); encoding.put("ISO-IR-101", "ISO-8859-2"); encoding.put("ISO_8859-2:1987", "ISO-8859-2"); encoding.put("ISO_8859-2", "ISO-8859-2"); encodings.add("ISO-8859-3"); encoding.put("ISO-8859-3", "ISO-8859-3"); encoding.put("ISO8859-3", "ISO-8859-3"); encoding.put("ISO88593", "ISO-8859-3"); encoding.put("LATIN-3", "ISO-8859-3"); encoding.put("LATIN3", "ISO-8859-3"); encoding.put("L3", "ISO-8859-3"); encoding.put("ISO-IR-109", "ISO-8859-3"); encoding.put("ISO_8859-3:1988", "ISO-8859-3"); encoding.put("ISO_8859-3", "ISO-8859-3"); encodings.add("ISO-8859-4"); encoding.put("ISO-8859-4", "ISO-8859-4"); encoding.put("ISO8859-4", "ISO-8859-4"); encoding.put("ISO88594", "ISO-8859-4"); encoding.put("LATIN-4", "ISO-8859-4"); encoding.put("LATIN4", "ISO-8859-4"); encoding.put("L4", "ISO-8859-4"); encoding.put("ISO-IR-110", "ISO-8859-4"); encoding.put("ISO_8859-4:1988", "ISO-8859-4"); encoding.put("ISO_8859-4", "ISO-8859-4"); encodings.add("ISO-8859-5"); encoding.put("ISO-8859-5", "ISO-8859-5"); encoding.put("ISO8859-5", "ISO-8859-5"); encoding.put("ISO88595", "ISO-8859-5"); encoding.put("CYRILLIC", "ISO-8859-5"); encoding.put("ISO-IR-144", "ISO-8859-5"); encoding.put("ISO_8859-5:1988", "ISO-8859-5"); encoding.put("ISO_8859-5", "ISO-8859-5"); encodings.add("ISO-8859-6"); encoding.put("ISO-8859-6", "ISO-8859-6"); encoding.put("ISO8859-6", "ISO-8859-6"); encoding.put("ISO88596", "ISO-8859-6"); encoding.put("ARABIC", "ISO-8859-6"); encoding.put("ISO-IR-127", "ISO-8859-6"); encoding.put("ISO_8859-6:1987", "ISO-8859-6"); encoding.put("ISO_8859-6", "ISO-8859-6"); encoding.put("ECMA-114", "ISO-8859-6"); encoding.put("ASMO-708", "ISO-8859-6"); encodings.add("ISO-8859-7"); encoding.put("ISO-8859-7", "ISO-8859-7"); encoding.put("ISO8859-7", "ISO-8859-7"); encoding.put("ISO88597", "ISO-8859-7"); encoding.put("GREEK", "ISO-8859-7"); encoding.put("GREEK8", "ISO-8859-7"); encoding.put("ISO-IR-126", "ISO-8859-7"); encoding.put("ISO_8859-7:1987", "ISO-8859-7"); encoding.put("ISO_8859-7", "ISO-8859-7"); encoding.put("ELOT_928", "ISO-8859-7"); encoding.put("ECMA-118", "ISO-8859-7"); encodings.add("ISO-8859-8"); encoding.put("ISO-8859-8", "ISO-8859-8"); encoding.put("ISO8859-8", "ISO-8859-8"); encoding.put("ISO88598", "ISO-8859-8"); encoding.put("HEBREW", "ISO-8859-8"); encoding.put("ISO-IR-138", "ISO-8859-8"); encoding.put("ISO_8859-8:1988", "ISO-8859-8"); encoding.put("ISO_8859-8", "ISO-8859-8"); encodings.add("ISO-8859-9"); encoding.put("ISO-8859-9", "ISO-8859-9"); encoding.put("ISO8859-9", "ISO-8859-9"); encoding.put("ISO88599", "ISO-8859-9"); encoding.put("LATIN-5", "ISO-8859-9"); encoding.put("LATIN5", "ISO-8859-9"); encoding.put("L5", "ISO-8859-9"); encoding.put("ISO-IR-148", "ISO-8859-9"); encoding.put("ISO_8859-9:1989", "ISO-8859-9"); encoding.put("ISO_8859-9", "ISO-8859-9"); encodings.add("ISO-8859-11"); encoding.put("ISO-8859-11", "ISO-8859-11"); encoding.put("ISO8859-11", "ISO-8859-11"); encoding.put("ISO885911", "ISO-8859-11"); encodings.add("ISO-8859-13"); encoding.put("ISO-8859-13", "ISO-8859-13"); encoding.put("ISO8859-13", "ISO-8859-13"); encoding.put("ISO885913", "ISO-8859-13"); encoding.put("LATIN-7", "ISO-8859-13"); encoding.put("LATIN7", "ISO-8859-13"); encoding.put("L7", "ISO-8859-13"); encoding.put("ISO-IR-179", "ISO-8859-13"); encodings.add("ISO-8859-15"); encoding.put("ISO-8859-15", "ISO-8859-15"); encoding.put("ISO8859-15", "ISO-8859-15"); encoding.put("ISO885915", "ISO-8859-15"); encoding.put("LATIN-9", "ISO-8859-15"); encoding.put("LATIN9", "ISO-8859-15"); encoding.put("L9", "ISO-8859-15"); encodings.add("IBM850"); encoding.put("IBM850", "IBM850"); encoding.put("IBM-850", "IBM850"); encoding.put("CP850", "IBM850"); encoding.put("CP-850", "IBM850"); encoding.put("850", "IBM850"); encodings.add("IBM852"); encoding.put("IBM852", "IBM852"); encoding.put("IBM-852", "IBM852"); encoding.put("CP852", "IBM852"); encoding.put("CP-852", "IBM852"); encoding.put("852", "IBM852"); encodings.add("IBM855"); encoding.put("IBM855", "IBM855"); encoding.put("IBM-855", "IBM855"); encoding.put("CP855", "IBM855"); encoding.put("CP-855", "IBM855"); encoding.put("855", "IBM855"); encodings.add("IBM856"); encoding.put("IBM856", "IBM856"); encoding.put("IBM-856", "IBM856"); encoding.put("CP856", "IBM856"); encoding.put("CP-856", "IBM856"); encoding.put("856", "IBM856"); encodings.add("IBM857"); encoding.put("IBM857", "IBM857"); encoding.put("IBM-857", "IBM857"); encoding.put("CP857", "IBM857"); encoding.put("CP-857", "IBM857"); encoding.put("857", "IBM857"); encodings.add("IBM860"); encoding.put("IBM860", "IBM860"); encoding.put("IBM-860", "IBM860"); encoding.put("CP860", "IBM860"); encoding.put("CP-860", "IBM860"); encoding.put("860", "IBM860"); encodings.add("IBM861"); encoding.put("IBM861", "IBM861"); encoding.put("IBM-861", "IBM861"); encoding.put("CP861", "IBM861"); encoding.put("CP-861", "IBM861"); encoding.put("861", "IBM861"); encoding.put("CP-IS", "IBM861"); encodings.add("IBM862"); encoding.put("IBM862", "IBM862"); encoding.put("IBM-862", "IBM862"); encoding.put("CP862", "IBM862"); encoding.put("CP-862", "IBM862"); encoding.put("862", "IBM862"); encodings.add("IBM863"); encoding.put("IBM863", "IBM863"); encoding.put("IBM-863", "IBM863"); encoding.put("CP863", "IBM863"); encoding.put("CP-863", "IBM863"); encoding.put("863", "IBM863"); encodings.add("IBM864"); encoding.put("IBM864", "IBM864"); encoding.put("IBM-864", "IBM864"); encoding.put("CP864", "IBM864"); encoding.put("CP-864", "IBM864"); encoding.put("864", "IBM864"); encodings.add("IBM865"); encoding.put("IBM865", "IBM865"); encoding.put("IBM-865", "IBM865"); encoding.put("CP865", "IBM865"); encoding.put("CP-865", "IBM865"); encoding.put("865", "IBM865"); encodings.add("IBM866"); encoding.put("IBM866", "IBM866"); encoding.put("IBM-866", "IBM866"); encoding.put("CP866", "IBM866"); encoding.put("CP-866", "IBM866"); encoding.put("866", "IBM866"); encodings.add("IBM868"); encoding.put("IBM868", "IBM868"); encoding.put("IBM-868", "IBM868"); encoding.put("CP868", "IBM868"); encoding.put("CP-868", "IBM868"); encoding.put("868", "IBM868"); encoding.put("CP-AR", "IBM868"); encodings.add("IBM869"); encoding.put("IBM869", "IBM869"); encoding.put("IBM-869", "IBM869"); encoding.put("CP869", "IBM869"); encoding.put("CP-869", "IBM869"); encoding.put("869", "IBM869"); encoding.put("CP-GR", "IBM869"); encodings.add("SHIFT-JIS"); encoding.put("SHIFT-JIS", "SHIFT-JIS"); encoding.put("SJIS", "SHIFT-JIS"); encodings.add("WINDOWS-1250"); encoding.put("WINDOWS-1250", "WINDOWS-1250"); encoding.put("CP1250", "WINDOWS-1250"); encoding.put("CP-1250", "WINDOWS-1250"); encoding.put("1250", "WINDOWS-1250"); encoding.put("MS-EE", "WINDOWS-1250"); encodings.add("WINDOWS-1251"); encoding.put("WINDOWS-1251", "WINDOWS-1251"); encoding.put("CP1251", "WINDOWS-1251"); encoding.put("CP-1251", "WINDOWS-1251"); encoding.put("1251", "WINDOWS-1251"); encoding.put("MS-CYRL", "WINDOWS-1251"); encodings.add("WINDOWS-1252"); encoding.put("WINDOWS-1252", "WINDOWS-1252"); encoding.put("CP1252", "WINDOWS-1252"); encoding.put("CP-1252", "WINDOWS-1252"); encoding.put("1252", "WINDOWS-1252"); encoding.put("MS-ANSI", "WINDOWS-1252"); encodings.add("WINDOWS-1253"); encoding.put("WINDOWS-1253", "WINDOWS-1253"); encoding.put("CP1253", "WINDOWS-1253"); encoding.put("CP-1253", "WINDOWS-1253"); encoding.put("1253", "WINDOWS-1253"); encoding.put("MS-GREEK", "WINDOWS-1253"); encodings.add("WINDOWS-1254"); encoding.put("WINDOWS-1254", "WINDOWS-1254"); encoding.put("CP1254", "WINDOWS-1254"); encoding.put("CP-1254", "WINDOWS-1254"); encoding.put("1254", "WINDOWS-1254"); encoding.put("MS-TURK", "WINDOWS-1254"); encodings.add("WINDOWS-1255"); encoding.put("WINDOWS-1255", "WINDOWS-1255"); encoding.put("CP1255", "WINDOWS-1255"); encoding.put("CP-1255", "WINDOWS-1255"); encoding.put("1255", "WINDOWS-1255"); encoding.put("MS-HEBR", "WINDOWS-1255"); encodings.add("WINDOWS-1256"); encoding.put("WINDOWS-1256", "WINDOWS-1256"); encoding.put("CP1256", "WINDOWS-1256"); encoding.put("CP-1256", "WINDOWS-1256"); encoding.put("1256", "WINDOWS-1256"); encoding.put("MS-ARAB", "WINDOWS-1256"); encodings.add("WINDOWS-1257"); encoding.put("WINDOWS-1257", "WINDOWS-1257"); encoding.put("CP1257", "WINDOWS-1257"); encoding.put("CP-1257", "WINDOWS-1257"); encoding.put("1257", "WINDOWS-1257"); encoding.put("WINBALTRIM", "WINDOWS-1257"); encodings.add("WINDOWS-1258"); encoding.put("WINDOWS-1258", "WINDOWS-1258"); encoding.put("CP1258", "WINDOWS-1258"); encoding.put("CP-1258", "WINDOWS-1258"); encoding.put("1258", "WINDOWS-1258"); encodings.add("WINDOWS-874"); encoding.put("WINDOWS-874", "WINDOWS-874"); encoding.put("CP874", "WINDOWS-874"); encoding.put("CP-874", "WINDOWS-874"); encoding.put("874", "WINDOWS-874"); encoding.put("IBM874", "WINDOWS-874"); encoding.put("IBM-874", "WINDOWS-874"); encodings.add("WINDOWS-31J"); encoding.put("WINDOWS-31J", "WINDOWS-31J"); encoding.put("WINDOWS-932", "WINDOWS-31J"); encoding.put("CP932", "WINDOWS-31J"); encoding.put("CP-932", "WINDOWS-31J"); encoding.put("932", "WINDOWS-31J"); encodings.add("WINDOWS-936"); encoding.put("WINDOWS-936", "WINDOWS-936"); encoding.put("CP936", "WINDOWS-936"); encoding.put("CP-936", "WINDOWS-936"); encoding.put("936", "WINDOWS-936"); encoding.put("GBK", "WINDOWS-936"); encoding.put("MS936", "WINDOWS-936"); encoding.put("MS-936", "WINDOWS-936"); encodings.add("CP949"); encoding.put("CP949", "CP949"); encoding.put("WINDOWS-949", "CP949"); encoding.put("CP-949", "CP949"); encoding.put("949", "CP949"); encodings.add("BIG5"); encoding.put("BIG5", "BIG5"); encoding.put("WINDOWS-950", "BIG5"); encoding.put("CP950", "BIG5"); encoding.put("CP-950", "BIG5"); encoding.put("950", "BIG5"); encoding.put("BIG", "BIG5"); encoding.put("BIG-5", "BIG5"); encoding.put("BIG-FIVE", "BIG5"); encoding.put("BIGFIVE", "BIG5"); encoding.put("CN-BIG5", "BIG5"); encoding.put("BIG5-CP950", "BIG5"); } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ext.exasol.ui/src/org/jkiss/dbeaver/ext/exasol/ui/ExasolUIConstants.java
2,390
/* * 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.druid.segment.data; import com.google.common.primitives.Ints; import org.apache.druid.collections.ResourceHolder; import org.apache.druid.common.config.NullHandling; import org.apache.druid.common.utils.SerializerUtils; import org.apache.druid.io.Channels; import org.apache.druid.java.util.common.ByteBufferUtils; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.guava.Comparators; import org.apache.druid.java.util.common.io.Closer; import org.apache.druid.java.util.common.io.smoosh.FileSmoosher; import org.apache.druid.java.util.common.io.smoosh.SmooshedFileMapper; import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector; import org.apache.druid.segment.serde.MetaSerdeHelper; import org.apache.druid.segment.serde.Serializer; import org.apache.druid.segment.writeout.HeapByteBufferWriteOutBytes; import org.apache.druid.utils.CloseableUtils; import javax.annotation.Nullable; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.WritableByteChannel; import java.util.Arrays; import java.util.Iterator; /** * A generic, flat storage mechanism. Use static methods fromArray() or fromIterable() to construct. If input * is sorted, supports binary search index lookups. If input is not sorted, only supports array-like index lookups. * <p> * V1 Storage Format: * <p> * byte 1: version (0x1) * byte 2 == 0x1 =>; allowReverseLookup * bytes 3-6 =>; numBytesUsed * bytes 7-10 =>; numElements * bytes 10-((numElements * 4) + 10): integers representing *end* offsets of byte serialized values * bytes ((numElements * 4) + 10)-(numBytesUsed + 2): 4-byte integer representing length of value, followed by bytes * for value. Length of value stored has no meaning, if next offset is strictly greater than the current offset, * and if they are the same, -1 at this field means null, and 0 at this field means some object * (potentially non-null - e. g. in the string case, that is serialized as an empty sequence of bytes). * <p> * V2 Storage Format * Meta, header and value files are separate and header file stored in native endian byte order. * Meta File: * byte 1: version (0x2) * byte 2 == 0x1 =>; allowReverseLookup * bytes 3-6: numberOfElementsPerValueFile expressed as power of 2. That means all the value files contains same * number of items except last value file and may have fewer elements. * bytes 7-10 =>; numElements * bytes 11-14 =>; columnNameLength * bytes 15-columnNameLength =>; columnName * <p> * Header file name is identified as: StringUtils.format("%s_header", columnName) * value files are identified as: StringUtils.format("%s_value_%d", columnName, fileNumber) * number of value files == numElements/numberOfElementsPerValueFile * * The version {@link EncodedStringDictionaryWriter#VERSION} is reserved and must never be specified as the * {@link GenericIndexed} version byte, else it will interfere with string column deserialization. * * @see GenericIndexedWriter */ public abstract class GenericIndexed<T> implements CloseableIndexed<T>, Serializer { static final byte VERSION_ONE = 0x1; static final byte VERSION_TWO = 0x2; static final byte REVERSE_LOOKUP_ALLOWED = 0x1; static final byte REVERSE_LOOKUP_DISALLOWED = 0x0; static final int NULL_VALUE_SIZE_MARKER = -1; private static final SerializerUtils SERIALIZER_UTILS = new SerializerUtils(); /** * An ObjectStrategy that returns a big-endian ByteBuffer pointing to original data. * * The returned ByteBuffer is a fresh read-only instance, so it is OK for callers to modify its position, limit, etc. * However, it does point to the original data, so callers must take care not to use it if the original data may * have been freed. * * The compare method of this instance uses {@link StringUtils#compareUtf8UsingJavaStringOrdering(byte[], byte[])} * so that behavior is consistent with {@link #STRING_STRATEGY}. */ public static final ObjectStrategy<ByteBuffer> UTF8_STRATEGY = new ObjectStrategy<ByteBuffer>() { @Override public Class<ByteBuffer> getClazz() { return ByteBuffer.class; } @Override public ByteBuffer fromByteBuffer(final ByteBuffer buffer, final int numBytes) { final ByteBuffer dup = buffer.asReadOnlyBuffer(); dup.limit(buffer.position() + numBytes); return dup; } @Override @Nullable public byte[] toBytes(@Nullable ByteBuffer buf) { if (buf == null) { return null; } // This method doesn't have javadocs and I'm not sure if it is OK to modify the "val" argument. Copy defensively. final ByteBuffer dup = buf.duplicate(); final byte[] bytes = new byte[dup.remaining()]; dup.get(bytes); return bytes; } @Override public int compare(@Nullable ByteBuffer o1, @Nullable ByteBuffer o2) { return ByteBufferUtils.utf8Comparator().compare(o1, o2); } }; public static final ObjectStrategy<String> STRING_STRATEGY = new ObjectStrategy<String>() { @Override public Class<String> getClazz() { return String.class; } @Override public String fromByteBuffer(final ByteBuffer buffer, final int numBytes) { return StringUtils.fromUtf8(buffer, numBytes); } @Override @Nullable public byte[] toBytes(@Nullable String val) { return StringUtils.toUtf8Nullable(NullHandling.nullToEmptyIfNeeded(val)); } @Override public int compare(String o1, String o2) { return Comparators.<String>naturalNullsFirst().compare(o1, o2); } }; public static <T> GenericIndexed<T> read(ByteBuffer buffer, ObjectStrategy<T> strategy) { byte versionFromBuffer = buffer.get(); if (VERSION_ONE == versionFromBuffer) { return createGenericIndexedVersionOne(buffer, strategy); } else if (VERSION_TWO == versionFromBuffer) { throw new IAE( "use read(ByteBuffer buffer, ObjectStrategy<T> strategy, SmooshedFileMapper fileMapper)" + " to read version 2 indexed." ); } throw new IAE("Unknown version[%d]", (int) versionFromBuffer); } public static <T> GenericIndexed<T> read(ByteBuffer buffer, ObjectStrategy<T> strategy, SmooshedFileMapper fileMapper) { byte versionFromBuffer = buffer.get(); if (VERSION_ONE == versionFromBuffer) { return createGenericIndexedVersionOne(buffer, strategy); } else if (VERSION_TWO == versionFromBuffer) { return createGenericIndexedVersionTwo(buffer, strategy, fileMapper); } throw new IAE("Unknown version [%s]", versionFromBuffer); } public static <T> GenericIndexed<T> fromArray(T[] objects, ObjectStrategy<T> strategy) { return fromIterable(Arrays.asList(objects), strategy); } public static GenericIndexed<ResourceHolder<ByteBuffer>> ofCompressedByteBuffers( Iterable<ByteBuffer> buffers, CompressionStrategy compression, int bufferSize, ByteOrder order, Closer closer ) { return fromIterableVersionOne( buffers, GenericIndexedWriter.compressedByteBuffersWriteObjectStrategy(compression, bufferSize, closer), false, DecompressingByteBufferObjectStrategy.of(order, compression) ); } public static <T> GenericIndexed<T> fromIterable(Iterable<T> objectsIterable, ObjectStrategy<T> strategy) { return fromIterableVersionOne(objectsIterable, strategy, strategy.canCompare(), strategy); } static int getNumberOfFilesRequired(int bagSize, long numWritten) { int numberOfFilesRequired = (int) (numWritten / bagSize); if ((numWritten % bagSize) != 0) { numberOfFilesRequired += 1; } return numberOfFilesRequired; } protected final ObjectStrategy<T> strategy; protected final boolean allowReverseLookup; protected final int size; public GenericIndexed( final ObjectStrategy<T> strategy, final boolean allowReverseLookup, final int size ) { this.strategy = strategy; this.allowReverseLookup = allowReverseLookup; this.size = size; } public abstract BufferIndexed singleThreaded(); @Override public abstract long getSerializedSize(); private static final class V1<T> extends GenericIndexed<T> { @SuppressWarnings("rawtypes") private static final MetaSerdeHelper<GenericIndexed.V1> META_SERDE_HELPER = MetaSerdeHelper .firstWriteByte((GenericIndexed.V1 x) -> VERSION_ONE) .writeByte(x -> x.allowReverseLookup ? REVERSE_LOOKUP_ALLOWED : REVERSE_LOOKUP_DISALLOWED) .writeInt(x -> Ints.checkedCast(x.theBuffer.remaining() + (long) Integer.BYTES)) .writeInt(x -> x.size); private final ByteBuffer theBuffer; private final int headerOffset; private final int valuesOffset; V1( final ByteBuffer buffer, final ObjectStrategy<T> strategy, final boolean allowReverseLookup ) { super(strategy, allowReverseLookup, buffer.getInt()); this.theBuffer = buffer; this.headerOffset = theBuffer.position(); this.valuesOffset = theBuffer.position() + size * Integer.BYTES; } @Nullable @Override public T get(int index) { checkIndex(index); final int startOffset; final int endOffset; if (index == 0) { startOffset = Integer.BYTES; endOffset = theBuffer.getInt(headerOffset); } else { int headerPosition = (index - 1) * Integer.BYTES; startOffset = theBuffer.getInt(headerOffset + headerPosition) + Integer.BYTES; endOffset = theBuffer.getInt(headerOffset + headerPosition + Integer.BYTES); } return copyBufferAndGet(theBuffer, valuesOffset + startOffset, valuesOffset + endOffset); } @Override public BufferIndexed singleThreaded() { final ByteBuffer copyBuffer = theBuffer.asReadOnlyBuffer(); return new BufferIndexed() { @Nullable @Override protected ByteBuffer getByteBuffer(final int index) { checkIndex(index); final int startOffset; final int endOffset; if (index == 0) { startOffset = Integer.BYTES; endOffset = theBuffer.getInt(headerOffset); } else { int headerPosition = (index - 1) * Integer.BYTES; startOffset = theBuffer.getInt(headerOffset + headerPosition) + Integer.BYTES; endOffset = theBuffer.getInt(headerOffset + headerPosition + Integer.BYTES); } return bufferedIndexedGetByteBuffer(copyBuffer, valuesOffset + startOffset, valuesOffset + endOffset); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("theBuffer", theBuffer); inspector.visit("copyBuffer", copyBuffer); inspector.visit("strategy", strategy); } }; } @Override public long getSerializedSize() { return META_SERDE_HELPER.size(this) + (long) theBuffer.remaining(); } @Override public void writeTo(WritableByteChannel channel, FileSmoosher smoosher) throws IOException { META_SERDE_HELPER.writeTo(channel, this); Channels.writeFully(channel, theBuffer.asReadOnlyBuffer()); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("theBuffer", theBuffer); inspector.visit("strategy", strategy); } } private static final class V2<T> extends GenericIndexed<T> { private final ByteBuffer headerBuffer; private final ByteBuffer[] valueBuffers; private final int logBaseTwoOfElementsPerValueFile; private final int relativeIndexMask; private V2( ByteBuffer[] valueBuffs, ByteBuffer headerBuff, ObjectStrategy<T> strategy, boolean allowReverseLookup, int logBaseTwoOfElementsPerValueFile, int numWritten ) { super(strategy, allowReverseLookup, numWritten); this.valueBuffers = valueBuffs; this.headerBuffer = headerBuff; this.logBaseTwoOfElementsPerValueFile = logBaseTwoOfElementsPerValueFile; this.relativeIndexMask = (1 << logBaseTwoOfElementsPerValueFile) - 1; headerBuffer.order(ByteOrder.nativeOrder()); } @Nullable @Override public T get(int index) { checkIndex(index); final int startOffset; final int endOffset; int relativePositionOfIndex = index & relativeIndexMask; if (relativePositionOfIndex == 0) { int headerPosition = index * Integer.BYTES; startOffset = Integer.BYTES; endOffset = headerBuffer.getInt(headerPosition); } else { int headerPosition = (index - 1) * Integer.BYTES; startOffset = headerBuffer.getInt(headerPosition) + Integer.BYTES; endOffset = headerBuffer.getInt(headerPosition + Integer.BYTES); } int fileNum = index >> logBaseTwoOfElementsPerValueFile; return copyBufferAndGet(valueBuffers[fileNum], startOffset, endOffset); } @Override public BufferIndexed singleThreaded() { final ByteBuffer[] copyValueBuffers = new ByteBuffer[valueBuffers.length]; for (int i = 0; i < valueBuffers.length; i++) { copyValueBuffers[i] = valueBuffers[i].asReadOnlyBuffer(); } return new BufferIndexed() { @Nullable @Override protected ByteBuffer getByteBuffer(int index) { checkIndex(index); final int startOffset; final int endOffset; int relativePositionOfIndex = index & relativeIndexMask; if (relativePositionOfIndex == 0) { int headerPosition = index * Integer.BYTES; startOffset = 4; endOffset = headerBuffer.getInt(headerPosition); } else { int headerPosition = (index - 1) * Integer.BYTES; startOffset = headerBuffer.getInt(headerPosition) + Integer.BYTES; endOffset = headerBuffer.getInt(headerPosition + Integer.BYTES); } int fileNum = index >> logBaseTwoOfElementsPerValueFile; return bufferedIndexedGetByteBuffer(copyValueBuffers[fileNum], startOffset, endOffset); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("headerBuffer", headerBuffer); // Inspecting just one example of copyValueBuffer, not needed to inspect the whole array, because all buffers // in it are the same. inspector.visit("copyValueBuffer", copyValueBuffers.length > 0 ? copyValueBuffers[0] : null); inspector.visit("strategy", strategy); } }; } @Override public long getSerializedSize() { throw new UnsupportedOperationException("Method not supported for version 2 GenericIndexed."); } @Override public void writeTo(WritableByteChannel channel, FileSmoosher smoosher) { throw new UnsupportedOperationException( "GenericIndexed serialization for V2 is unsupported. Use GenericIndexedWriter instead."); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("headerBuffer", headerBuffer); // Inspecting just one example of valueBuffer, not needed to inspect the whole array, because all buffers in it // are the same. inspector.visit("valueBuffer", valueBuffers.length > 0 ? valueBuffers[0] : null); inspector.visit("strategy", strategy); } } /** * Checks if {@code index} a valid `element index` in GenericIndexed. * Similar to Preconditions.checkElementIndex() except this method throws {@link IAE} with custom error message. * <p> * Used here to get existing behavior(same error message and exception) of V1 GenericIndexed. * * @param index index identifying an element of an GenericIndexed. */ protected void checkIndex(int index) { if (index < 0) { throw new IAE("Index[%s] < 0", index); } if (index >= size) { throw new IAE("Index[%d] >= size[%d]", index, size); } } public Class<? extends T> getClazz() { return strategy.getClazz(); } @Override public int size() { return size; } /** * Returns the index of "value" in this GenericIndexed object, or (-(insertion point) - 1) if the value is not * present, in the manner of Arrays.binarySearch. This strengthens the contract of Indexed, which only guarantees * that values-not-found will return some negative number. * * @param value value to search for * * @return index of value, or negative number equal to (-(insertion point) - 1). */ @Override public int indexOf(@Nullable T value) { if (!allowReverseLookup) { throw new UnsupportedOperationException("Reverse lookup not allowed."); } int minIndex = 0; int maxIndex = size - 1; while (minIndex <= maxIndex) { int currIndex = (minIndex + maxIndex) >>> 1; T currValue = get(currIndex); int comparison = strategy.compare(currValue, value); if (comparison == 0) { return currIndex; } if (comparison < 0) { minIndex = currIndex + 1; } else { maxIndex = currIndex - 1; } } return -(minIndex + 1); } @Override public boolean isSorted() { return allowReverseLookup; } @Override public Iterator<T> iterator() { return IndexedIterable.create(this).iterator(); } @Nullable protected T copyBufferAndGet(ByteBuffer valueBuffer, int startOffset, int endOffset) { ByteBuffer copyValueBuffer = valueBuffer.asReadOnlyBuffer(); int size = endOffset - startOffset; // When size is 0 and SQL compatibility is enabled also check for null marker before returning null. // When SQL compatibility is not enabled return null for both null as well as empty string case. if (size == 0 && (NullHandling.replaceWithDefault() || copyValueBuffer.get(startOffset - Integer.BYTES) == NULL_VALUE_SIZE_MARKER)) { return null; } copyValueBuffer.position(startOffset); // fromByteBuffer must not modify the buffer limit return strategy.fromByteBuffer(copyValueBuffer, size); } /** * Single-threaded view. */ public abstract class BufferIndexed implements Indexed<T> { @Override public int size() { return size; } @Override public T get(final int index) { final ByteBuffer buf = getByteBuffer(index); if (buf == null) { return null; } // Traditionally, ObjectStrategy.fromByteBuffer() is given a buffer with limit set to capacity, and the // actual limit is passed along as an extra parameter. final int len = buf.remaining(); buf.limit(buf.capacity()); return strategy.fromByteBuffer(buf, len); } @Nullable ByteBuffer bufferedIndexedGetByteBuffer(ByteBuffer copyValueBuffer, int startOffset, int endOffset) { int size = endOffset - startOffset; // When size is 0 and SQL compatibility is enabled also check for null marker before returning null. // When SQL compatibility is not enabled return null for both null as well as empty string case. if (size == 0 && (NullHandling.replaceWithDefault() || copyValueBuffer.get(startOffset - Integer.BYTES) == NULL_VALUE_SIZE_MARKER)) { return null; } // ObjectStrategy.fromByteBuffer() is allowed to reset the limit of the buffer. So if the limit is changed, // position() call could throw an exception, if the position is set beyond the new limit. Calling limit() // followed by position() is safe, because limit() resets position if needed. copyValueBuffer.limit(endOffset); copyValueBuffer.position(startOffset); return copyValueBuffer; } /** * Like {@link #get(int)}, but returns a {@link ByteBuffer} instead of using the {@link ObjectStrategy}. * * The returned ByteBuffer is reused by future calls. Callers must discard it before calling another method * on this BufferedIndexed object that may want to reuse the buffer. */ @Nullable protected abstract ByteBuffer getByteBuffer(int index); @Override public int indexOf(@Nullable T value) { if (!allowReverseLookup) { throw new UnsupportedOperationException("Reverse lookup not allowed."); } //noinspection ObjectEquality final boolean isByteBufferStrategy = strategy == UTF8_STRATEGY; int minIndex = 0; int maxIndex = size - 1; while (minIndex <= maxIndex) { int currIndex = (minIndex + maxIndex) >>> 1; int comparison; if (isByteBufferStrategy) { // Specialization avoids ByteBuffer allocation in strategy.fromByteBuffer. ByteBuffer currValue = getByteBuffer(currIndex); comparison = ByteBufferUtils.compareUtf8ByteBuffers(currValue, (ByteBuffer) value); } else { T currValue = get(currIndex); comparison = strategy.compare(currValue, value); } if (comparison == 0) { return currIndex; } if (comparison < 0) { minIndex = currIndex + 1; } else { maxIndex = currIndex - 1; } } return -(minIndex + 1); } @Override public boolean isSorted() { return allowReverseLookup; } @Override public Iterator<T> iterator() { return GenericIndexed.this.iterator(); } } @Override public void close() { // nothing to close } private static <T> GenericIndexed<T> createGenericIndexedVersionOne(ByteBuffer byteBuffer, ObjectStrategy<T> strategy) { boolean allowReverseLookup = byteBuffer.get() == REVERSE_LOOKUP_ALLOWED; int size = byteBuffer.getInt(); ByteBuffer bufferToUse = byteBuffer.asReadOnlyBuffer(); bufferToUse.limit(bufferToUse.position() + size); byteBuffer.position(bufferToUse.limit()); return new GenericIndexed.V1<>( bufferToUse, strategy, allowReverseLookup ); } private static <T, U> GenericIndexed<U> fromIterableVersionOne( Iterable<T> objectsIterable, ObjectStrategy<T> strategy, boolean allowReverseLookup, ObjectStrategy<U> resultObjectStrategy ) { Iterator<T> objects = objectsIterable.iterator(); if (!objects.hasNext()) { final ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES).putInt(0); buffer.flip(); return new GenericIndexed.V1<>(buffer, resultObjectStrategy, allowReverseLookup); } int count = 0; HeapByteBufferWriteOutBytes headerOut = new HeapByteBufferWriteOutBytes(); HeapByteBufferWriteOutBytes valuesOut = new HeapByteBufferWriteOutBytes(); try { T prevVal = null; do { count++; T next = objects.next(); if (allowReverseLookup && prevVal != null && !(strategy.compare(prevVal, next) < 0)) { allowReverseLookup = false; } if (next != null) { valuesOut.writeInt(0); strategy.writeTo(next, valuesOut); } else { valuesOut.writeInt(NULL_VALUE_SIZE_MARKER); } headerOut.writeInt(Ints.checkedCast(valuesOut.size())); if (prevVal instanceof Closeable) { CloseableUtils.closeAndWrapExceptions((Closeable) prevVal); } prevVal = next; } while (objects.hasNext()); if (prevVal instanceof Closeable) { CloseableUtils.closeAndWrapExceptions((Closeable) prevVal); } } catch (IOException e) { throw new RuntimeException(e); } ByteBuffer theBuffer = ByteBuffer.allocate(Ints.checkedCast(Integer.BYTES + headerOut.size() + valuesOut.size())); theBuffer.putInt(count); headerOut.writeTo(theBuffer); valuesOut.writeTo(theBuffer); theBuffer.flip(); return new GenericIndexed.V1<>(theBuffer.asReadOnlyBuffer(), resultObjectStrategy, allowReverseLookup); } private static <T> GenericIndexed<T> createGenericIndexedVersionTwo( ByteBuffer byteBuffer, ObjectStrategy<T> strategy, SmooshedFileMapper fileMapper ) { if (fileMapper == null) { throw new IAE("SmooshedFileMapper can not be null for version 2."); } boolean allowReverseLookup = byteBuffer.get() == REVERSE_LOOKUP_ALLOWED; int logBaseTwoOfElementsPerValueFile = byteBuffer.getInt(); int numElements = byteBuffer.getInt(); try { String columnName = SERIALIZER_UTILS.readString(byteBuffer); int elementsPerValueFile = 1 << logBaseTwoOfElementsPerValueFile; int numberOfFilesRequired = getNumberOfFilesRequired(elementsPerValueFile, numElements); ByteBuffer[] valueBuffersToUse = new ByteBuffer[numberOfFilesRequired]; for (int i = 0; i < numberOfFilesRequired; i++) { // SmooshedFileMapper.mapFile() contract guarantees that the valueBuffer's limit equals to capacity. ByteBuffer valueBuffer = fileMapper.mapFile(GenericIndexedWriter.generateValueFileName(columnName, i)); valueBuffersToUse[i] = valueBuffer.asReadOnlyBuffer(); } ByteBuffer headerBuffer = fileMapper.mapFile(GenericIndexedWriter.generateHeaderFileName(columnName)); return new GenericIndexed.V2<>( valueBuffersToUse, headerBuffer, strategy, allowReverseLookup, logBaseTwoOfElementsPerValueFile, numElements ); } catch (IOException e) { throw new RuntimeException("File mapping failed.", e); } } }
apache/druid
processing/src/main/java/org/apache/druid/segment/data/GenericIndexed.java
2,391
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.locale; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class LocaleUtil { public static List<Locale> getAllLocales() { // Data from https://restcountries.eu/rest/v2/all?fields=name;region;subregion;alpha2Code;languages List<Locale> allLocales = new ArrayList<>(); allLocales.add(new Locale("ps", "AF")); // Afghanistan / lang=Pashto allLocales.add(new Locale("sv", "AX")); // Åland Islands / lang=Swedish allLocales.add(new Locale("sq", "AL")); // Albania / lang=Albanian allLocales.add(new Locale("ar", "DZ")); // Algeria / lang=Arabic allLocales.add(new Locale("en", "AS")); // American Samoa / lang=English allLocales.add(new Locale("ca", "AD")); // Andorra / lang=Catalan allLocales.add(new Locale("pt", "AO")); // Angola / lang=Portuguese allLocales.add(new Locale("en", "AI")); // Anguilla / lang=English allLocales.add(new Locale("en", "AG")); // Antigua and Barbuda / lang=English allLocales.add(new Locale("es", "AR")); // Argentina / lang=Spanish allLocales.add(new Locale("hy", "AM")); // Armenia / lang=Armenian allLocales.add(new Locale("nl", "AW")); // Aruba / lang=Dutch allLocales.add(new Locale("en", "AU")); // Australia / lang=English allLocales.add(new Locale("de", "AT")); // Austria / lang=German allLocales.add(new Locale("az", "AZ")); // Azerbaijan / lang=Azerbaijani allLocales.add(new Locale("en", "BS")); // Bahamas / lang=English allLocales.add(new Locale("ar", "BH")); // Bahrain / lang=Arabic allLocales.add(new Locale("bn", "BD")); // Bangladesh / lang=Bengali allLocales.add(new Locale("en", "BB")); // Barbados / lang=English allLocales.add(new Locale("be", "BY")); // Belarus / lang=Belarusian allLocales.add(new Locale("nl", "BE")); // Belgium / lang=Dutch allLocales.add(new Locale("en", "BZ")); // Belize / lang=English allLocales.add(new Locale("fr", "BJ")); // Benin / lang=French allLocales.add(new Locale("en", "BM")); // Bermuda / lang=English allLocales.add(new Locale("dz", "BT")); // Bhutan / lang=Dzongkha allLocales.add(new Locale("es", "BO")); // Bolivia (Plurinational State of) / lang=Spanish allLocales.add(new Locale("nl", "BQ")); // Bonaire, Sint Eustatius and Saba / lang=Dutch allLocales.add(new Locale("bs", "BA")); // Bosnia and Herzegovina / lang=Bosnian allLocales.add(new Locale("en", "BW")); // Botswana / lang=English allLocales.add(new Locale("pt", "BR")); // Brazil / lang=Portuguese allLocales.add(new Locale("en", "IO")); // British Indian Ocean Territory / lang=English allLocales.add(new Locale("en", "UM")); // United States Minor Outlying Islands / lang=English allLocales.add(new Locale("en", "VG")); // Virgin Islands (British) / lang=English allLocales.add(new Locale("en", "VI")); // Virgin Islands (U.S.) / lang=English allLocales.add(new Locale("ms", "BN")); // Brunei Darussalam / lang=Malay allLocales.add(new Locale("bg", "BG")); // Bulgaria / lang=Bulgarian allLocales.add(new Locale("fr", "BF")); // Burkina Faso / lang=French allLocales.add(new Locale("fr", "BI")); // Burundi / lang=French allLocales.add(new Locale("km", "KH")); // Cambodia / lang=Khmer allLocales.add(new Locale("en", "CM")); // Cameroon / lang=English allLocales.add(new Locale("en", "CA")); // Canada / lang=English allLocales.add(new Locale("pt", "CV")); // Cabo Verde / lang=Portuguese allLocales.add(new Locale("en", "KY")); // Cayman Islands / lang=English allLocales.add(new Locale("fr", "CF")); // Central African Republic / lang=French allLocales.add(new Locale("fr", "TD")); // Chad / lang=French allLocales.add(new Locale("es", "CL")); // Chile / lang=Spanish allLocales.add(new Locale("zh", "CN")); // China / lang=Chinese allLocales.add(new Locale("en", "CX")); // Christmas Island / lang=English allLocales.add(new Locale("en", "CC")); // Cocos (Keeling) Islands / lang=English allLocales.add(new Locale("es", "CO")); // Colombia / lang=Spanish allLocales.add(new Locale("ar", "KM")); // Comoros / lang=Arabic allLocales.add(new Locale("fr", "CG")); // Congo / lang=French allLocales.add(new Locale("fr", "CD")); // Congo (Democratic Republic of the) / lang=French allLocales.add(new Locale("en", "CK")); // Cook Islands / lang=English allLocales.add(new Locale("es", "CR")); // Costa Rica / lang=Spanish allLocales.add(new Locale("hr", "HR")); // Croatia / lang=Croatian allLocales.add(new Locale("es", "CU")); // Cuba / lang=Spanish allLocales.add(new Locale("nl", "CW")); // Curaçao / lang=Dutch allLocales.add(new Locale("el", "CY")); // Cyprus / lang=Greek (modern) allLocales.add(new Locale("cs", "CZ")); // Czech Republic / lang=Czech allLocales.add(new Locale("da", "DK")); // Denmark / lang=Danish allLocales.add(new Locale("fr", "DJ")); // Djibouti / lang=French allLocales.add(new Locale("en", "DM")); // Dominica / lang=English allLocales.add(new Locale("es", "DO")); // Dominican Republic / lang=Spanish allLocales.add(new Locale("es", "EC")); // Ecuador / lang=Spanish allLocales.add(new Locale("ar", "EG")); // Egypt / lang=Arabic allLocales.add(new Locale("es", "SV")); // El Salvador / lang=Spanish allLocales.add(new Locale("es", "GQ")); // Equatorial Guinea / lang=Spanish allLocales.add(new Locale("ti", "ER")); // Eritrea / lang=Tigrinya allLocales.add(new Locale("et", "EE")); // Estonia / lang=Estonian allLocales.add(new Locale("am", "ET")); // Ethiopia / lang=Amharic allLocales.add(new Locale("en", "FK")); // Falkland Islands (Malvinas) / lang=English allLocales.add(new Locale("fo", "FO")); // Faroe Islands / lang=Faroese allLocales.add(new Locale("en", "FJ")); // Fiji / lang=English allLocales.add(new Locale("fi", "FI")); // Finland / lang=Finnish allLocales.add(new Locale("fr", "FR")); // France / lang=French allLocales.add(new Locale("fr", "GF")); // French Guiana / lang=French allLocales.add(new Locale("fr", "PF")); // French Polynesia / lang=French allLocales.add(new Locale("fr", "TF")); // French Southern Territories / lang=French allLocales.add(new Locale("fr", "GA")); // Gabon / lang=French allLocales.add(new Locale("en", "GM")); // Gambia / lang=English allLocales.add(new Locale("ka", "GE")); // Georgia / lang=Georgian allLocales.add(new Locale("de", "DE")); // Germany / lang=German allLocales.add(new Locale("en", "GH")); // Ghana / lang=English allLocales.add(new Locale("en", "GI")); // Gibraltar / lang=English allLocales.add(new Locale("el", "GR")); // Greece / lang=Greek (modern) allLocales.add(new Locale("kl", "GL")); // Greenland / lang=Kalaallisut allLocales.add(new Locale("en", "GD")); // Grenada / lang=English allLocales.add(new Locale("fr", "GP")); // Guadeloupe / lang=French allLocales.add(new Locale("en", "GU")); // Guam / lang=English allLocales.add(new Locale("es", "GT")); // Guatemala / lang=Spanish allLocales.add(new Locale("en", "GG")); // Guernsey / lang=English allLocales.add(new Locale("fr", "GN")); // Guinea / lang=French allLocales.add(new Locale("pt", "GW")); // Guinea-Bissau / lang=Portuguese allLocales.add(new Locale("en", "GY")); // Guyana / lang=English allLocales.add(new Locale("fr", "HT")); // Haiti / lang=French allLocales.add(new Locale("la", "VA")); // Holy See / lang=Latin allLocales.add(new Locale("es", "HN")); // Honduras / lang=Spanish allLocales.add(new Locale("en", "HK")); // Hong Kong / lang=English allLocales.add(new Locale("hu", "HU")); // Hungary / lang=Hungarian allLocales.add(new Locale("is", "IS")); // Iceland / lang=Icelandic allLocales.add(new Locale("hi", "IN")); // India / lang=Hindi allLocales.add(new Locale("id", "ID")); // Indonesia / lang=Indonesian allLocales.add(new Locale("fr", "CI")); // Côte d'Ivoire / lang=French allLocales.add(new Locale("fa", "IR")); // Iran (Islamic Republic of) / lang=Persian (Farsi) allLocales.add(new Locale("ar", "IQ")); // Iraq / lang=Arabic allLocales.add(new Locale("ga", "IE")); // Ireland / lang=Irish allLocales.add(new Locale("en", "IM")); // Isle of Man / lang=English allLocales.add(new Locale("he", "IL")); // Israel / lang=Hebrew (modern) allLocales.add(new Locale("it", "IT")); // Italy / lang=Italian allLocales.add(new Locale("en", "JM")); // Jamaica / lang=English allLocales.add(new Locale("ja", "JP")); // Japan / lang=Japanese allLocales.add(new Locale("en", "JE")); // Jersey / lang=English allLocales.add(new Locale("ar", "JO")); // Jordan / lang=Arabic allLocales.add(new Locale("kk", "KZ")); // Kazakhstan / lang=Kazakh allLocales.add(new Locale("en", "KE")); // Kenya / lang=English allLocales.add(new Locale("en", "KI")); // Kiribati / lang=English allLocales.add(new Locale("ar", "KW")); // Kuwait / lang=Arabic allLocales.add(new Locale("ky", "KG")); // Kyrgyzstan / lang=Kyrgyz allLocales.add(new Locale("lo", "LA")); // Lao People's Democratic Republic / lang=Lao allLocales.add(new Locale("lv", "LV")); // Latvia / lang=Latvian allLocales.add(new Locale("ar", "LB")); // Lebanon / lang=Arabic allLocales.add(new Locale("en", "LS")); // Lesotho / lang=English allLocales.add(new Locale("en", "LR")); // Liberia / lang=English allLocales.add(new Locale("ar", "LY")); // Libya / lang=Arabic allLocales.add(new Locale("de", "LI")); // Liechtenstein / lang=German allLocales.add(new Locale("lt", "LT")); // Lithuania / lang=Lithuanian allLocales.add(new Locale("fr", "LU")); // Luxembourg / lang=French allLocales.add(new Locale("zh", "MO")); // Macao / lang=Chinese allLocales.add(new Locale("mk", "MK")); // Macedonia (the former Yugoslav Republic of) / lang=Macedonian allLocales.add(new Locale("fr", "MG")); // Madagascar / lang=French allLocales.add(new Locale("en", "MW")); // Malawi / lang=English allLocales.add(new Locale("en", "MY")); // Malaysia / lang=Malaysian allLocales.add(new Locale("dv", "MV")); // Maldives / lang=Divehi allLocales.add(new Locale("fr", "ML")); // Mali / lang=French allLocales.add(new Locale("mt", "MT")); // Malta / lang=Maltese allLocales.add(new Locale("en", "MH")); // Marshall Islands / lang=English allLocales.add(new Locale("fr", "MQ")); // Martinique / lang=French allLocales.add(new Locale("ar", "MR")); // Mauritania / lang=Arabic allLocales.add(new Locale("en", "MU")); // Mauritius / lang=English allLocales.add(new Locale("fr", "YT")); // Mayotte / lang=French allLocales.add(new Locale("es", "MX")); // Mexico / lang=Spanish allLocales.add(new Locale("en", "FM")); // Micronesia (Federated States of) / lang=English allLocales.add(new Locale("ro", "MD")); // Moldova (Republic of) / lang=Romanian allLocales.add(new Locale("fr", "MC")); // Monaco / lang=French allLocales.add(new Locale("mn", "MN")); // Mongolia / lang=Mongolian allLocales.add(new Locale("sr", "ME")); // Montenegro / lang=Serbian allLocales.add(new Locale("en", "MS")); // Montserrat / lang=English allLocales.add(new Locale("ar", "MA")); // Morocco / lang=Arabic allLocales.add(new Locale("pt", "MZ")); // Mozambique / lang=Portuguese allLocales.add(new Locale("my", "MM")); // Myanmar / lang=Burmese allLocales.add(new Locale("en", "NA")); // Namibia / lang=English allLocales.add(new Locale("en", "NR")); // Nauru / lang=English allLocales.add(new Locale("ne", "NP")); // Nepal / lang=Nepali allLocales.add(new Locale("nl", "NL")); // Netherlands / lang=Dutch allLocales.add(new Locale("fr", "NC")); // New Caledonia / lang=French allLocales.add(new Locale("en", "NZ")); // New Zealand / lang=English allLocales.add(new Locale("es", "NI")); // Nicaragua / lang=Spanish allLocales.add(new Locale("fr", "NE")); // Niger / lang=French allLocales.add(new Locale("en", "NG")); // Nigeria / lang=English allLocales.add(new Locale("en", "NU")); // Niue / lang=English allLocales.add(new Locale("en", "NF")); // Norfolk Island / lang=English allLocales.add(new Locale("ko", "KP")); // Korea (Democratic People's Republic of) / lang=Korean allLocales.add(new Locale("en", "MP")); // Northern Mariana Islands / lang=English allLocales.add(new Locale("no", "NO")); // Norway / lang=Norwegian allLocales.add(new Locale("ar", "OM")); // Oman / lang=Arabic allLocales.add(new Locale("en", "PK")); // Pakistan / lang=English allLocales.add(new Locale("en", "PW")); // Palau / lang=English allLocales.add(new Locale("ar", "PS")); // Palestine, State of / lang=Arabic allLocales.add(new Locale("es", "PA")); // Panama / lang=Spanish allLocales.add(new Locale("en", "PG")); // Papua New Guinea / lang=English allLocales.add(new Locale("es", "PY")); // Paraguay / lang=Spanish allLocales.add(new Locale("es", "PE")); // Peru / lang=Spanish allLocales.add(new Locale("en", "PH")); // Philippines / lang=English allLocales.add(new Locale("en", "PN")); // Pitcairn / lang=English allLocales.add(new Locale("pl", "PL")); // Poland / lang=Polish allLocales.add(new Locale("pt", "PT")); // Portugal / lang=Portuguese allLocales.add(new Locale("es", "PR")); // Puerto Rico / lang=Spanish allLocales.add(new Locale("ar", "QA")); // Qatar / lang=Arabic allLocales.add(new Locale("sq", "XK")); // Republic of Kosovo / lang=Albanian allLocales.add(new Locale("fr", "RE")); // Réunion / lang=French allLocales.add(new Locale("ro", "RO")); // Romania / lang=Romanian allLocales.add(new Locale("ru", "RU")); // Russian Federation / lang=Russian allLocales.add(new Locale("rw", "RW")); // Rwanda / lang=Kinyarwanda allLocales.add(new Locale("fr", "BL")); // Saint Barthélemy / lang=French allLocales.add(new Locale("en", "SH")); // Saint Helena, Ascension and Tristan da Cunha / lang=English allLocales.add(new Locale("en", "KN")); // Saint Kitts and Nevis / lang=English allLocales.add(new Locale("en", "LC")); // Saint Lucia / lang=English allLocales.add(new Locale("en", "MF")); // Saint Martin (French part) / lang=English allLocales.add(new Locale("fr", "PM")); // Saint Pierre and Miquelon / lang=French allLocales.add(new Locale("en", "VC")); // Saint Vincent and the Grenadines / lang=English allLocales.add(new Locale("sm", "WS")); // Samoa / lang=Samoan allLocales.add(new Locale("it", "SM")); // San Marino / lang=Italian allLocales.add(new Locale("pt", "ST")); // Sao Tome and Principe / lang=Portuguese allLocales.add(new Locale("ar", "SA")); // Saudi Arabia / lang=Arabic allLocales.add(new Locale("fr", "SN")); // Senegal / lang=French allLocales.add(new Locale("sr", "RS")); // Serbia / lang=Serbian allLocales.add(new Locale("fr", "SC")); // Seychelles / lang=French allLocales.add(new Locale("en", "SL")); // Sierra Leone / lang=English allLocales.add(new Locale("en", "SG")); // Singapore / lang=English allLocales.add(new Locale("nl", "SX")); // Sint Maarten (Dutch part) / lang=Dutch allLocales.add(new Locale("sk", "SK")); // Slovakia / lang=Slovak allLocales.add(new Locale("sl", "SI")); // Slovenia / lang=Slovene allLocales.add(new Locale("en", "SB")); // Solomon Islands / lang=English allLocales.add(new Locale("so", "SO")); // Somalia / lang=Somali allLocales.add(new Locale("af", "ZA")); // South Africa / lang=Afrikaans allLocales.add(new Locale("en", "GS")); // South Georgia and the South Sandwich Islands / lang=English allLocales.add(new Locale("ko", "KR")); // Korea (Republic of) / lang=Korean allLocales.add(new Locale("en", "SS")); // South Sudan / lang=English allLocales.add(new Locale("es", "ES")); // Spain / lang=Spanish allLocales.add(new Locale("si", "LK")); // Sri Lanka / lang=Sinhalese allLocales.add(new Locale("ar", "SD")); // Sudan / lang=Arabic allLocales.add(new Locale("nl", "SR")); // Suriname / lang=Dutch allLocales.add(new Locale("no", "SJ")); // Svalbard and Jan Mayen / lang=Norwegian allLocales.add(new Locale("en", "SZ")); // Swaziland / lang=English allLocales.add(new Locale("sv", "SE")); // Sweden / lang=Swedish allLocales.add(new Locale("de", "CH")); // Switzerland / lang=German allLocales.add(new Locale("ar", "SY")); // Syrian Arab Republic / lang=Arabic allLocales.add(new Locale("zh", "TW")); // Taiwan / lang=Chinese allLocales.add(new Locale("tg", "TJ")); // Tajikistan / lang=Tajik allLocales.add(new Locale("sw", "TZ")); // Tanzania, United Republic of / lang=Swahili allLocales.add(new Locale("th", "TH")); // Thailand / lang=Thai allLocales.add(new Locale("pt", "TL")); // Timor-Leste / lang=Portuguese allLocales.add(new Locale("fr", "TG")); // Togo / lang=French allLocales.add(new Locale("en", "TK")); // Tokelau / lang=English allLocales.add(new Locale("en", "TO")); // Tonga / lang=English allLocales.add(new Locale("en", "TT")); // Trinidad and Tobago / lang=English allLocales.add(new Locale("ar", "TN")); // Tunisia / lang=Arabic allLocales.add(new Locale("tr", "TR")); // Turkey / lang=Turkish allLocales.add(new Locale("tk", "TM")); // Turkmenistan / lang=Turkmen allLocales.add(new Locale("en", "TC")); // Turks and Caicos Islands / lang=English allLocales.add(new Locale("en", "TV")); // Tuvalu / lang=English allLocales.add(new Locale("en", "UG")); // Uganda / lang=English allLocales.add(new Locale("uk", "UA")); // Ukraine / lang=Ukrainian allLocales.add(new Locale("ar", "AE")); // United Arab Emirates / lang=Arabic allLocales.add(new Locale("en", "GB")); // United Kingdom of Great Britain and Northern Ireland / lang=English allLocales.add(new Locale("en", "US")); // United States of America / lang=English allLocales.add(new Locale("es", "UY")); // Uruguay / lang=Spanish allLocales.add(new Locale("uz", "UZ")); // Uzbekistan / lang=Uzbek allLocales.add(new Locale("bi", "VU")); // Vanuatu / lang=Bislama allLocales.add(new Locale("es", "VE")); // Venezuela (Bolivarian Republic of) / lang=Spanish allLocales.add(new Locale("vi", "VN")); // Viet Nam / lang=Vietnamese allLocales.add(new Locale("fr", "WF")); // Wallis and Futuna / lang=French allLocales.add(new Locale("es", "EH")); // Western Sahara / lang=Spanish allLocales.add(new Locale("ar", "YE")); // Yemen / lang=Arabic allLocales.add(new Locale("en", "ZM")); // Zambia / lang=English allLocales.add(new Locale("en", "ZW")); // Zimbabwe / lang=English return allLocales; } }
bisq-network/bisq
core/src/main/java/bisq/core/locale/LocaleUtil.java
2,392
// 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.qe.cache; import org.apache.doris.analysis.SelectStmt; import org.apache.doris.common.Status; import org.apache.doris.common.util.DebugUtil; import org.apache.doris.metric.MetricRepo; import org.apache.doris.proto.InternalService; import org.apache.doris.proto.Types.PUniqueId; import org.apache.doris.qe.RowBatch; import org.apache.doris.system.Backend; import org.apache.doris.thrift.TUniqueId; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SqlCache extends Cache { private static final Logger LOG = LogManager.getLogger(SqlCache.class); private String originSql; private PUniqueId cacheMd5; public SqlCache(TUniqueId queryId, SelectStmt selectStmt) { super(queryId, selectStmt); } // For SetOperationStmt and Nereids public SqlCache(TUniqueId queryId, String originSql) { super(queryId); this.originSql = originSql; } public void setCacheInfo(CacheAnalyzer.CacheTable latestTable, String allViewExpandStmtListStr) { this.latestTable = latestTable; this.allViewExpandStmtListStr = allViewExpandStmtListStr; this.cacheMd5 = null; } public PUniqueId getOrComputeCacheMd5() { if (cacheMd5 == null) { cacheMd5 = CacheProxy.getMd5(getSqlWithViewStmt()); } return cacheMd5; } public void setCacheMd5(PUniqueId cacheMd5) { this.cacheMd5 = cacheMd5; } public String getSqlWithViewStmt() { String originSql = selectStmt != null ? selectStmt.toSql() : this.originSql; String cacheKey = originSql + "|" + allViewExpandStmtListStr; if (LOG.isDebugEnabled()) { LOG.debug("Cache key: {}", cacheKey); } return cacheKey; } public long getLatestId() { return latestTable.latestPartitionId; } public long getLatestTime() { return latestTable.latestPartitionTime; } public long getLatestVersion() { return latestTable.latestPartitionVersion; } public long getSumOfPartitionNum() { return latestTable.sumOfPartitionNum; } public static Backend findCacheBe(PUniqueId cacheMd5) { return CacheCoordinator.getInstance().findBackend(cacheMd5); } public static InternalService.PFetchCacheResult getCacheData(CacheProxy proxy, PUniqueId cacheKeyMd5, long latestPartitionId, long latestPartitionVersion, long latestPartitionTime, long sumOfPartitionNum, Status status) { InternalService.PFetchCacheRequest request = InternalService.PFetchCacheRequest.newBuilder() .setSqlKey(cacheKeyMd5) .addParams(InternalService.PCacheParam.newBuilder() .setPartitionKey(latestPartitionId) .setLastVersion(latestPartitionVersion) .setLastVersionTime(latestPartitionTime) .setPartitionNum(sumOfPartitionNum)) .build(); InternalService.PFetchCacheResult cacheResult = proxy.fetchCache(request, 10000, status); if (status.ok() && cacheResult != null && cacheResult.getStatus() == InternalService.PCacheStatus.CACHE_OK) { cacheResult = cacheResult.toBuilder().setAllCount(1).build(); } return cacheResult; } public InternalService.PFetchCacheResult getCacheData(Status status) { InternalService.PFetchCacheResult cacheResult = getCacheData(proxy, getOrComputeCacheMd5(), latestTable.latestPartitionId, latestTable.latestPartitionVersion, latestTable.latestPartitionTime, latestTable.sumOfPartitionNum, status); if (status.ok() && cacheResult != null && cacheResult.getStatus() == InternalService.PCacheStatus.CACHE_OK) { MetricRepo.COUNTER_CACHE_HIT_SQL.increase(1L); hitRange = HitRange.Full; } return cacheResult; } public SelectStmt getRewriteStmt() { return null; } public void copyRowBatch(RowBatch rowBatch) { if (rowBatchBuilder == null) { rowBatchBuilder = new RowBatchBuilder(CacheAnalyzer.CacheMode.Sql); } if (!super.checkRowLimit()) { return; } rowBatchBuilder.copyRowData(rowBatch); } public void updateCache() { if (!super.checkRowLimit()) { return; } PUniqueId cacheKeyMd5 = getOrComputeCacheMd5(); InternalService.PUpdateCacheRequest updateRequest = rowBatchBuilder.buildSqlUpdateRequest(cacheKeyMd5, latestTable.latestPartitionId, latestTable.latestPartitionVersion, latestTable.latestPartitionTime, latestTable.sumOfPartitionNum ); if (updateRequest.getValuesCount() > 0) { CacheBeProxy proxy = new CacheBeProxy(); Status status = new Status(); proxy.updateCache(updateRequest, CacheProxy.UPDATE_TIMEOUT, status); int rowCount = 0; int dataSize = 0; for (InternalService.PCacheValue value : updateRequest.getValuesList()) { rowCount += value.getRowsCount(); dataSize += value.getDataSize(); } LOG.info("update cache model {}, queryid {}, sqlkey {}, value count {}, row count {}, data size {}", CacheAnalyzer.CacheMode.Sql, DebugUtil.printId(queryId), DebugUtil.printId(updateRequest.getSqlKey()), updateRequest.getValuesCount(), rowCount, dataSize); } } }
apache/doris
fe/fe-core/src/main/java/org/apache/doris/qe/cache/SqlCache.java
2,393
/* * 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.kafka.streams.state.internals; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.common.utils.CircularIterator; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl; import org.slf4j.Logger; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicLong; /** * An in-memory LRU cache store similar to {@link MemoryLRUCache} but byte-based, not * record based */ public class ThreadCache { private final Logger log; private volatile long maxCacheSizeBytes; private final StreamsMetricsImpl metrics; private final Map<String, NamedCache> caches = new HashMap<>(); // Invariant: equal to sum of sizeInBytes of caches private final AtomicLong sizeInBytes = new AtomicLong(); // internal stats private long numPuts = 0; private long numGets = 0; private long numEvicts = 0; private long numFlushes = 0; public interface DirtyEntryFlushListener { void apply(final List<DirtyEntry> dirty); } public ThreadCache(final LogContext logContext, final long maxCacheSizeBytes, final StreamsMetricsImpl metrics) { this.maxCacheSizeBytes = maxCacheSizeBytes; this.metrics = metrics; this.log = logContext.logger(getClass()); } public long puts() { return numPuts; } public long gets() { return numGets; } public long evicts() { return numEvicts; } public long flushes() { return numFlushes; } public synchronized void resize(final long newCacheSizeBytes) { final boolean shrink = newCacheSizeBytes < maxCacheSizeBytes; maxCacheSizeBytes = newCacheSizeBytes; if (shrink) { log.debug("Cache size was shrunk to {}", newCacheSizeBytes); if (caches.values().isEmpty()) { return; } final CircularIterator<NamedCache> circularIterator = new CircularIterator<>(caches.values()); while (sizeInBytes.get() > maxCacheSizeBytes) { final NamedCache cache = circularIterator.next(); synchronized (cache) { final long oldSize = cache.sizeInBytes(); cache.evict(); sizeInBytes.getAndAdd(cache.sizeInBytes() - oldSize); } numEvicts++; } } else { log.debug("Cache size was expanded to {}", newCacheSizeBytes); } } /** * The thread cache maintains a set of {@link NamedCache}s whose names are a concatenation of the task ID and the * underlying store name. This method creates those names. * @param taskIDString Task ID * @param underlyingStoreName Underlying store name */ public static String nameSpaceFromTaskIdAndStore(final String taskIDString, final String underlyingStoreName) { return taskIDString + "-" + underlyingStoreName; } /** * Given a cache name of the form taskid-storename, return the task ID. */ public static String taskIDfromCacheName(final String cacheName) { final String[] tokens = cacheName.split("-", 2); return tokens[0]; } /** * Given a cache name of the form taskid-storename, return the store name. */ public static String underlyingStoreNamefromCacheName(final String cacheName) { final String[] tokens = cacheName.split("-", 2); return tokens[1]; } /** * Add a listener that is called each time an entry is evicted from the cache or an explicit flush is called */ public void addDirtyEntryFlushListener(final String namespace, final DirtyEntryFlushListener listener) { final NamedCache cache = getOrCreateCache(namespace); cache.setListener(listener); } public void flush(final String namespace) { numFlushes++; final NamedCache cache = getCache(namespace); if (cache == null) { return; } synchronized (cache) { final long oldSize = cache.sizeInBytes(); cache.flush(); sizeInBytes.getAndAdd(cache.sizeInBytes() - oldSize); } if (log.isTraceEnabled()) { log.trace("Cache stats on flush: #puts={}, #gets={}, #evicts={}, #flushes={}", puts(), gets(), evicts(), flushes()); } } public LRUCacheEntry get(final String namespace, final Bytes key) { numGets++; if (key == null) { return null; } final NamedCache cache = getCache(namespace); if (cache == null) { return null; } return cache.get(key); } public void put(final String namespace, final Bytes key, final LRUCacheEntry value) { numPuts++; final NamedCache cache = getOrCreateCache(namespace); synchronized (cache) { final long oldSize = cache.sizeInBytes(); cache.put(key, value); sizeInBytes.getAndAdd(cache.sizeInBytes() - oldSize); maybeEvict(namespace, cache); } } public LRUCacheEntry putIfAbsent(final String namespace, final Bytes key, final LRUCacheEntry value) { final NamedCache cache = getOrCreateCache(namespace); final LRUCacheEntry result; synchronized (cache) { final long oldSize = cache.sizeInBytes(); result = cache.putIfAbsent(key, value); sizeInBytes.getAndAdd(cache.sizeInBytes() - oldSize); maybeEvict(namespace, cache); } if (result == null) { numPuts++; } return result; } public void putAll(final String namespace, final List<KeyValue<Bytes, LRUCacheEntry>> entries) { for (final KeyValue<Bytes, LRUCacheEntry> entry : entries) { put(namespace, entry.key, entry.value); } } public LRUCacheEntry delete(final String namespace, final Bytes key) { final NamedCache cache = getCache(namespace); if (cache == null) { return null; } final LRUCacheEntry entry; synchronized (cache) { final long oldSize = cache.sizeInBytes(); entry = cache.delete(key); sizeInBytes.getAndAdd(cache.sizeInBytes() - oldSize); } return entry; } public MemoryLRUCacheBytesIterator range(final String namespace, final Bytes from, final Bytes to) { return range(namespace, from, to, true); } public MemoryLRUCacheBytesIterator range(final String namespace, final Bytes from, final Bytes to, final boolean toInclusive) { final NamedCache cache = getCache(namespace); if (cache == null) { return new MemoryLRUCacheBytesIterator(Collections.emptyIterator(), new NamedCache(namespace, this.metrics)); } return new MemoryLRUCacheBytesIterator(cache.keyRange(from, to, toInclusive), cache); } public MemoryLRUCacheBytesIterator reverseRange(final String namespace, final Bytes from, final Bytes to) { final NamedCache cache = getCache(namespace); if (cache == null) { return new MemoryLRUCacheBytesIterator(Collections.emptyIterator(), new NamedCache(namespace, this.metrics)); } return new MemoryLRUCacheBytesIterator(cache.reverseKeyRange(from, to), cache); } public MemoryLRUCacheBytesIterator all(final String namespace) { final NamedCache cache = getCache(namespace); if (cache == null) { return new MemoryLRUCacheBytesIterator(Collections.emptyIterator(), new NamedCache(namespace, this.metrics)); } return new MemoryLRUCacheBytesIterator(cache.allKeys(), cache); } public MemoryLRUCacheBytesIterator reverseAll(final String namespace) { final NamedCache cache = getCache(namespace); if (cache == null) { return new MemoryLRUCacheBytesIterator(Collections.emptyIterator(), new NamedCache(namespace, this.metrics)); } return new MemoryLRUCacheBytesIterator(cache.reverseAllKeys(), cache); } public long size() { long size = 0; for (final NamedCache cache : caches.values()) { size += cache.size(); if (isOverflowing(size)) { return Long.MAX_VALUE; } } return size; } private boolean isOverflowing(final long size) { return size < 0; } long sizeBytes() { return sizeInBytes.get(); } synchronized void close(final String namespace) { final NamedCache removed = caches.remove(namespace); if (removed != null) { sizeInBytes.getAndAdd(-removed.sizeInBytes()); removed.close(); } } synchronized void clear(final String namespace) { final NamedCache cleared = caches.get(namespace); if (cleared != null) { sizeInBytes.getAndAdd(-cleared.sizeInBytes()); cleared.clear(); } } private void maybeEvict(final String namespace, final NamedCache cache) { int numEvicted = 0; while (sizeInBytes.get() > maxCacheSizeBytes) { // we abort here as the put on this cache may have triggered // a put on another cache. So even though the sizeInBytes() is // still > maxCacheSizeBytes there is nothing to evict from this // namespaced cache. if (cache.isEmpty()) { return; } final long oldSize = cache.sizeInBytes(); cache.evict(); sizeInBytes.getAndAdd(cache.sizeInBytes() - oldSize); numEvicts++; numEvicted++; } if (log.isTraceEnabled()) { log.trace("Evicted {} entries from cache {}", numEvicted, namespace); } } private synchronized NamedCache getCache(final String namespace) { return caches.get(namespace); } private synchronized NamedCache getOrCreateCache(final String name) { NamedCache cache = caches.get(name); if (cache == null) { cache = new NamedCache(name, this.metrics); caches.put(name, cache); } return cache; } static class MemoryLRUCacheBytesIterator implements PeekingKeyValueIterator<Bytes, LRUCacheEntry> { private final Iterator<Bytes> keys; private final NamedCache cache; private KeyValue<Bytes, LRUCacheEntry> nextEntry; MemoryLRUCacheBytesIterator(final Iterator<Bytes> keys, final NamedCache cache) { this.keys = keys; this.cache = cache; } public Bytes peekNextKey() { if (!hasNext()) { throw new NoSuchElementException(); } return nextEntry.key; } public KeyValue<Bytes, LRUCacheEntry> peekNext() { if (!hasNext()) { throw new NoSuchElementException(); } return nextEntry; } @Override public boolean hasNext() { if (nextEntry != null) { return true; } while (keys.hasNext() && nextEntry == null) { internalNext(); } return nextEntry != null; } @Override public KeyValue<Bytes, LRUCacheEntry> next() { if (!hasNext()) { throw new NoSuchElementException(); } final KeyValue<Bytes, LRUCacheEntry> result = nextEntry; nextEntry = null; return result; } private void internalNext() { final Bytes cacheKey = keys.next(); final LRUCacheEntry entry = cache.get(cacheKey); if (entry == null) { return; } nextEntry = new KeyValue<>(cacheKey, entry); } @Override public void close() { // do nothing } } static class DirtyEntry { private final Bytes key; private final byte[] newValue; private final LRUCacheEntry recordContext; DirtyEntry(final Bytes key, final byte[] newValue, final LRUCacheEntry recordContext) { this.key = key; this.newValue = newValue; this.recordContext = recordContext; } public Bytes key() { return key; } public byte[] newValue() { return newValue; } public LRUCacheEntry entry() { return recordContext; } } }
apache/kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/ThreadCache.java
2,394
/* * 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.buildpack.platform.build; import java.io.Closeable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import com.sun.jna.Platform; import org.springframework.boot.buildpack.platform.docker.DockerApi; import org.springframework.boot.buildpack.platform.docker.LogUpdateEvent; import org.springframework.boot.buildpack.platform.docker.configuration.ResolvedDockerHost; import org.springframework.boot.buildpack.platform.docker.type.Binding; import org.springframework.boot.buildpack.platform.docker.type.ContainerConfig; import org.springframework.boot.buildpack.platform.docker.type.ContainerContent; import org.springframework.boot.buildpack.platform.docker.type.ContainerReference; import org.springframework.boot.buildpack.platform.docker.type.ContainerStatus; import org.springframework.boot.buildpack.platform.docker.type.ImageReference; import org.springframework.boot.buildpack.platform.docker.type.VolumeName; import org.springframework.boot.buildpack.platform.io.TarArchive; import org.springframework.util.Assert; import org.springframework.util.FileSystemUtils; /** * A buildpack lifecycle used to run the build {@link Phase phases} needed to package an * application. * * @author Phillip Webb * @author Scott Frederick * @author Jeroen Meijer * @author Julian Liebig */ class Lifecycle implements Closeable { private static final LifecycleVersion LOGGING_MINIMUM_VERSION = LifecycleVersion.parse("0.0.5"); private static final String PLATFORM_API_VERSION_KEY = "CNB_PLATFORM_API"; private static final String SOURCE_DATE_EPOCH_KEY = "SOURCE_DATE_EPOCH"; private static final String DOMAIN_SOCKET_PATH = "/var/run/docker.sock"; private static final List<String> DEFAULT_SECURITY_OPTIONS = List.of("label=disable"); private final BuildLog log; private final DockerApi docker; private final ResolvedDockerHost dockerHost; private final BuildRequest request; private final EphemeralBuilder builder; private final LifecycleVersion lifecycleVersion; private final ApiVersion platformVersion; private final Cache layers; private final Cache application; private final Cache buildCache; private final Cache launchCache; private final String applicationDirectory; private final List<String> securityOptions; private boolean executed; private boolean applicationVolumePopulated; /** * Create a new {@link Lifecycle} instance. * @param log build output log * @param docker the Docker API * @param dockerHost the Docker host information * @param request the request to process * @param builder the ephemeral builder used to run the phases */ Lifecycle(BuildLog log, DockerApi docker, ResolvedDockerHost dockerHost, BuildRequest request, EphemeralBuilder builder) { this.log = log; this.docker = docker; this.dockerHost = dockerHost; this.request = request; this.builder = builder; this.lifecycleVersion = LifecycleVersion.parse(builder.getBuilderMetadata().getLifecycle().getVersion()); this.platformVersion = getPlatformVersion(builder.getBuilderMetadata().getLifecycle()); this.layers = getLayersBindingSource(request); this.application = getApplicationBindingSource(request); this.buildCache = getBuildCache(request); this.launchCache = getLaunchCache(request); this.applicationDirectory = getApplicationDirectory(request); this.securityOptions = getSecurityOptions(request); } private Cache getBuildCache(BuildRequest request) { if (request.getBuildCache() != null) { return request.getBuildCache(); } return createVolumeCache(request, "build"); } private Cache getLaunchCache(BuildRequest request) { if (request.getLaunchCache() != null) { return request.getLaunchCache(); } return createVolumeCache(request, "launch"); } private String getApplicationDirectory(BuildRequest request) { return (request.getApplicationDirectory() != null) ? request.getApplicationDirectory() : Directory.APPLICATION; } private List<String> getSecurityOptions(BuildRequest request) { if (request.getSecurityOptions() != null) { return request.getSecurityOptions(); } return (Platform.isWindows()) ? Collections.emptyList() : DEFAULT_SECURITY_OPTIONS; } private ApiVersion getPlatformVersion(BuilderMetadata.Lifecycle lifecycle) { if (lifecycle.getApis().getPlatform() != null) { String[] supportedVersions = lifecycle.getApis().getPlatform(); return ApiVersions.SUPPORTED_PLATFORMS.findLatestSupported(supportedVersions); } String version = lifecycle.getApi().getPlatform(); return ApiVersions.SUPPORTED_PLATFORMS.findLatestSupported(version); } /** * Execute this lifecycle by running each phase in turn. * @throws IOException on IO error */ void execute() throws IOException { Assert.state(!this.executed, "Lifecycle has already been executed"); this.executed = true; this.log.executingLifecycle(this.request, this.lifecycleVersion, this.buildCache); if (this.request.isCleanCache()) { deleteCache(this.buildCache); } run(createPhase()); this.log.executedLifecycle(this.request); } private Phase createPhase() { Phase phase = new Phase("creator", isVerboseLogging()); phase.withDaemonAccess(); configureDaemonAccess(phase); phase.withLogLevelArg(); phase.withArgs("-app", this.applicationDirectory); phase.withArgs("-platform", Directory.PLATFORM); phase.withArgs("-run-image", this.request.getRunImage()); phase.withArgs("-layers", Directory.LAYERS); phase.withArgs("-cache-dir", Directory.CACHE); phase.withArgs("-launch-cache", Directory.LAUNCH_CACHE); phase.withArgs("-daemon"); if (this.request.isCleanCache()) { phase.withArgs("-skip-restore"); } if (requiresProcessTypeDefault()) { phase.withArgs("-process-type=web"); } phase.withArgs(this.request.getName()); phase.withBinding(Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS)); phase.withBinding(Binding.from(getCacheBindingSource(this.application), this.applicationDirectory)); phase.withBinding(Binding.from(getCacheBindingSource(this.buildCache), Directory.CACHE)); phase.withBinding(Binding.from(getCacheBindingSource(this.launchCache), Directory.LAUNCH_CACHE)); if (this.request.getBindings() != null) { this.request.getBindings().forEach(phase::withBinding); } phase.withEnv(PLATFORM_API_VERSION_KEY, this.platformVersion.toString()); if (this.request.getNetwork() != null) { phase.withNetworkMode(this.request.getNetwork()); } if (this.request.getCreatedDate() != null) { phase.withEnv(SOURCE_DATE_EPOCH_KEY, Long.toString(this.request.getCreatedDate().getEpochSecond())); } return phase; } private Cache getLayersBindingSource(BuildRequest request) { if (request.getBuildWorkspace() != null) { return getBuildWorkspaceBindingSource(request.getBuildWorkspace(), "layers"); } return createVolumeCache("pack-layers-"); } private Cache getApplicationBindingSource(BuildRequest request) { if (request.getBuildWorkspace() != null) { return getBuildWorkspaceBindingSource(request.getBuildWorkspace(), "app"); } return createVolumeCache("pack-app-"); } private Cache getBuildWorkspaceBindingSource(Cache buildWorkspace, String suffix) { return (buildWorkspace.getVolume() != null) ? Cache.volume(buildWorkspace.getVolume().getName() + "-" + suffix) : Cache.bind(buildWorkspace.getBind().getSource() + "-" + suffix); } private String getCacheBindingSource(Cache cache) { return (cache.getVolume() != null) ? cache.getVolume().getName() : cache.getBind().getSource(); } private Cache createVolumeCache(String prefix) { return Cache.volume(createRandomVolumeName(prefix)); } private Cache createVolumeCache(BuildRequest request, String suffix) { return Cache.volume( VolumeName.basedOn(request.getName(), ImageReference::toLegacyString, "pack-cache-", "." + suffix, 6)); } protected VolumeName createRandomVolumeName(String prefix) { return VolumeName.random(prefix); } private void configureDaemonAccess(Phase phase) { if (this.dockerHost != null) { if (this.dockerHost.isRemote()) { phase.withEnv("DOCKER_HOST", this.dockerHost.getAddress()); if (this.dockerHost.isSecure()) { phase.withEnv("DOCKER_TLS_VERIFY", "1"); phase.withEnv("DOCKER_CERT_PATH", this.dockerHost.getCertificatePath()); } } else { phase.withBinding(Binding.from(this.dockerHost.getAddress(), DOMAIN_SOCKET_PATH)); } } else { phase.withBinding(Binding.from(DOMAIN_SOCKET_PATH, DOMAIN_SOCKET_PATH)); } if (this.securityOptions != null) { this.securityOptions.forEach(phase::withSecurityOption); } } private boolean isVerboseLogging() { return this.request.isVerboseLogging() && this.lifecycleVersion.isEqualOrGreaterThan(LOGGING_MINIMUM_VERSION); } private boolean requiresProcessTypeDefault() { return this.platformVersion.supportsAny(ApiVersion.of(0, 4), ApiVersion.of(0, 5)); } private void run(Phase phase) throws IOException { Consumer<LogUpdateEvent> logConsumer = this.log.runningPhase(this.request, phase.getName()); ContainerConfig containerConfig = ContainerConfig.of(this.builder.getName(), phase::apply); ContainerReference reference = createContainer(containerConfig); try { this.docker.container().start(reference); this.docker.container().logs(reference, logConsumer::accept); ContainerStatus status = this.docker.container().wait(reference); if (status.getStatusCode() != 0) { throw new BuilderException(phase.getName(), status.getStatusCode()); } } finally { this.docker.container().remove(reference, true); } } private ContainerReference createContainer(ContainerConfig config) throws IOException { if (this.applicationVolumePopulated) { return this.docker.container().create(config); } try { if (this.application.getBind() != null) { Files.createDirectories(Path.of(this.application.getBind().getSource())); } TarArchive applicationContent = this.request.getApplicationContent(this.builder.getBuildOwner()); return this.docker.container() .create(config, ContainerContent.of(applicationContent, this.applicationDirectory)); } finally { this.applicationVolumePopulated = true; } } @Override public void close() throws IOException { deleteCache(this.layers); deleteCache(this.application); } private void deleteCache(Cache cache) throws IOException { if (cache.getVolume() != null) { deleteVolume(cache.getVolume().getVolumeName()); } if (cache.getBind() != null) { deleteBind(cache.getBind()); } } private void deleteVolume(VolumeName name) throws IOException { this.docker.volume().delete(name, true); } private void deleteBind(Cache.Bind bind) { try { FileSystemUtils.deleteRecursively(Path.of(bind.getSource())); } catch (Exception ex) { this.log.failedCleaningWorkDir(bind, ex); } } /** * Common directories used by the various phases. */ private static final class Directory { /** * The directory used by buildpacks to write their layer contributions. A new * layer directory is created for each lifecycle execution. * <p> * Maps to the {@code <layers...>} concept in the * <a href="https://github.com/buildpacks/spec/blob/master/buildpack.md">buildpack * specification</a> and the {@code -layers} argument from the reference lifecycle * implementation. */ static final String LAYERS = "/layers"; /** * The directory containing the original contributed application. A new * application directory is created for each lifecycle execution. * <p> * Maps to the {@code <app...>} concept in the * <a href="https://github.com/buildpacks/spec/blob/master/buildpack.md">buildpack * specification</a> and the {@code -app} argument from the reference lifecycle * implementation. The reference lifecycle follows the Kubernetes/Docker * convention of using {@code '/workspace'}. * <p> * Note that application content is uploaded to the container with the first phase * that runs and saved in a volume that is passed to subsequent phases. The * directory is mutable and buildpacks may modify the content. */ static final String APPLICATION = "/workspace"; /** * The directory used by buildpacks to obtain environment variables and platform * specific concerns. The platform directory is read-only and is created/populated * by the {@link EphemeralBuilder}. * <p> * Maps to the {@code <platform>/env} and {@code <platform>/#} concepts in the * <a href="https://github.com/buildpacks/spec/blob/master/buildpack.md">buildpack * specification</a> and the {@code -platform} argument from the reference * lifecycle implementation. */ static final String PLATFORM = "/platform"; /** * The directory used by buildpacks for caching. The volume name is based on the * image {@link BuildRequest#getName() name} being built, and is persistent across * invocations even if the application content has changed. * <p> * Maps to the {@code -path} argument from the reference lifecycle implementation * cache and restore phases */ static final String CACHE = "/cache"; /** * The directory used by buildpacks for launch related caching. The volume name is * based on the image {@link BuildRequest#getName() name} being built, and is * persistent across invocations even if the application content has changed. * <p> * Maps to the {@code -launch-cache} argument from the reference lifecycle * implementation export phase */ static final String LAUNCH_CACHE = "/launch-cache"; } }
spring-projects/spring-boot
spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java
2,395
/* * 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.tomcat.util.buf; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class CharsetCache { /* Note: Package private to enable testing without reflection */ static final String[] INITIAL_CHARSETS = new String[] { "iso-8859-1", "utf-8" }; /* * Note: Package private to enable testing without reflection */ static final String[] LAZY_CHARSETS = new String[] { // Initial set from Oracle JDK 8 u192 "037", "1006", "1025", "1026", "1046", "1047", "1089", "1097", "1098", "1112", "1122", "1123", "1124", "1140", "1141", "1142", "1143", "1144", "1145", "1146", "1147", "1148", "1149", "1166", "1364", "1381", "1383", "273", "277", "278", "280", "284", "285", "290", "297", "300", "33722", "420", "424", "437", "500", "5601", "646", "737", "775", "813", "834", "838", "850", "852", "855", "856", "857", "858", "860", "861", "862", "863", "864", "865", "866", "868", "869", "870", "871", "874", "875", "8859_13", "8859_15", "8859_2", "8859_3", "8859_4", "8859_5", "8859_6", "8859_7", "8859_8", "8859_9", "912", "913", "914", "915", "916", "918", "920", "921", "922", "923", "930", "933", "935", "937", "939", "942", "942c", "943", "943c", "948", "949", "949c", "950", "964", "970", "ansi-1251", "ansi_x3.4-1968", "ansi_x3.4-1986", "arabic", "ascii", "ascii7", "asmo-708", "big5", "big5-hkscs", "big5-hkscs", "big5-hkscs-2001", "big5-hkscs:unicode3.0", "big5_hkscs", "big5_hkscs_2001", "big5_solaris", "big5hk", "big5hk-2001", "big5hkscs", "big5hkscs-2001", "ccsid00858", "ccsid01140", "ccsid01141", "ccsid01142", "ccsid01143", "ccsid01144", "ccsid01145", "ccsid01146", "ccsid01147", "ccsid01148", "ccsid01149", "cesu-8", "cesu8", "cns11643", "compound_text", "cp-ar", "cp-gr", "cp-is", "cp00858", "cp01140", "cp01141", "cp01142", "cp01143", "cp01144", "cp01145", "cp01146", "cp01147", "cp01148", "cp01149", "cp037", "cp1006", "cp1025", "cp1026", "cp1046", "cp1047", "cp1089", "cp1097", "cp1098", "cp1112", "cp1122", "cp1123", "cp1124", "cp1140", "cp1141", "cp1142", "cp1143", "cp1144", "cp1145", "cp1146", "cp1147", "cp1148", "cp1149", "cp1166", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "cp1364", "cp1381", "cp1383", "cp273", "cp277", "cp278", "cp280", "cp284", "cp285", "cp290", "cp297", "cp300", "cp33722", "cp367", "cp420", "cp424", "cp437", "cp500", "cp50220", "cp50221", "cp5346", "cp5347", "cp5348", "cp5349", "cp5350", "cp5353", "cp737", "cp775", "cp813", "cp833", "cp834", "cp838", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp868", "cp869", "cp870", "cp871", "cp874", "cp875", "cp912", "cp913", "cp914", "cp915", "cp916", "cp918", "cp920", "cp921", "cp922", "cp923", "cp930", "cp933", "cp935", "cp936", "cp937", "cp939", "cp942", "cp942c", "cp943", "cp943c", "cp948", "cp949", "cp949c", "cp950", "cp964", "cp970", "cpibm284", "cpibm285", "cpibm297", "cpibm37", "cs-ebcdic-cp-ca", "cs-ebcdic-cp-nl", "cs-ebcdic-cp-us", "cs-ebcdic-cp-wt", "csascii", "csbig5", "cscesu-8", "cseuckr", "cseucpkdfmtjapanese", "cshalfwidthkatakana", "csibm037", "csibm278", "csibm284", "csibm285", "csibm290", "csibm297", "csibm420", "csibm424", "csibm500", "csibm857", "csibm860", "csibm861", "csibm862", "csibm863", "csibm864", "csibm865", "csibm866", "csibm868", "csibm869", "csibm870", "csibm871", "csiso153gost1976874", "csiso159jisx02121990", "csiso2022cn", "csiso2022jp", "csiso2022jp2", "csiso2022kr", "csiso87jisx0208", "csisolatin0", "csisolatin2", "csisolatin3", "csisolatin4", "csisolatin5", "csisolatin9", "csisolatinarabic", "csisolatincyrillic", "csisolatingreek", "csisolatinhebrew", "csjisencoding", "cskoi8r", "cspc850multilingual", "cspc862latinhebrew", "cspc8codepage437", "cspcp852", "cspcp855", "csshiftjis", "cswindows31j", "cyrillic", "default", "ebcdic-cp-ar1", "ebcdic-cp-ar2", "ebcdic-cp-bh", "ebcdic-cp-ca", "ebcdic-cp-ch", "ebcdic-cp-fr", "ebcdic-cp-gb", "ebcdic-cp-he", "ebcdic-cp-is", "ebcdic-cp-nl", "ebcdic-cp-roece", "ebcdic-cp-se", "ebcdic-cp-us", "ebcdic-cp-wt", "ebcdic-cp-yu", "ebcdic-de-273+euro", "ebcdic-dk-277+euro", "ebcdic-es-284+euro", "ebcdic-fi-278+euro", "ebcdic-fr-277+euro", "ebcdic-gb", "ebcdic-gb-285+euro", "ebcdic-international-500+euro", "ebcdic-it-280+euro", "ebcdic-jp-kana", "ebcdic-no-277+euro", "ebcdic-s-871+euro", "ebcdic-se-278+euro", "ebcdic-sv", "ebcdic-us-037+euro", "ecma-114", "ecma-118", "elot_928", "euc-cn", "euc-jp", "euc-jp-linux", "euc-kr", "euc-tw", "euc_cn", "euc_jp", "euc_jp_linux", "euc_jp_solaris", "euc_kr", "euc_tw", "euccn", "eucjis", "eucjp", "eucjp-open", "euckr", "euctw", "extended_unix_code_packed_format_for_japanese", "gb18030", "gb18030-2000", "gb2312", "gb2312", "gb2312-1980", "gb2312-80", "gbk", "greek", "greek8", "hebrew", "ibm-037", "ibm-1006", "ibm-1025", "ibm-1026", "ibm-1046", "ibm-1047", "ibm-1089", "ibm-1097", "ibm-1098", "ibm-1112", "ibm-1122", "ibm-1123", "ibm-1124", "ibm-1166", "ibm-1364", "ibm-1381", "ibm-1383", "ibm-273", "ibm-277", "ibm-278", "ibm-280", "ibm-284", "ibm-285", "ibm-290", "ibm-297", "ibm-300", "ibm-33722", "ibm-33722_vascii_vpua", "ibm-37", "ibm-420", "ibm-424", "ibm-437", "ibm-500", "ibm-5050", "ibm-737", "ibm-775", "ibm-813", "ibm-833", "ibm-834", "ibm-838", "ibm-850", "ibm-852", "ibm-855", "ibm-856", "ibm-857", "ibm-860", "ibm-861", "ibm-862", "ibm-863", "ibm-864", "ibm-865", "ibm-866", "ibm-868", "ibm-869", "ibm-870", "ibm-871", "ibm-874", "ibm-875", "ibm-912", "ibm-913", "ibm-914", "ibm-915", "ibm-916", "ibm-918", "ibm-920", "ibm-921", "ibm-922", "ibm-923", "ibm-930", "ibm-933", "ibm-935", "ibm-937", "ibm-939", "ibm-942", "ibm-942c", "ibm-943", "ibm-943c", "ibm-948", "ibm-949", "ibm-949c", "ibm-950", "ibm-964", "ibm-970", "ibm-euckr", "ibm-thai", "ibm00858", "ibm01140", "ibm01141", "ibm01142", "ibm01143", "ibm01144", "ibm01145", "ibm01146", "ibm01147", "ibm01148", "ibm01149", "ibm037", "ibm037", "ibm1006", "ibm1025", "ibm1026", "ibm1026", "ibm1046", "ibm1047", "ibm1089", "ibm1097", "ibm1098", "ibm1112", "ibm1122", "ibm1123", "ibm1124", "ibm1166", "ibm1364", "ibm1381", "ibm1383", "ibm273", "ibm273", "ibm277", "ibm277", "ibm278", "ibm278", "ibm280", "ibm280", "ibm284", "ibm284", "ibm285", "ibm285", "ibm290", "ibm290", "ibm297", "ibm297", "ibm300", "ibm33722", "ibm367", "ibm420", "ibm420", "ibm424", "ibm424", "ibm437", "ibm437", "ibm500", "ibm500", "ibm737", "ibm775", "ibm775", "ibm813", "ibm833", "ibm834", "ibm838", "ibm850", "ibm850", "ibm852", "ibm852", "ibm855", "ibm855", "ibm856", "ibm857", "ibm857", "ibm860", "ibm860", "ibm861", "ibm861", "ibm862", "ibm862", "ibm863", "ibm863", "ibm864", "ibm864", "ibm865", "ibm865", "ibm866", "ibm866", "ibm868", "ibm868", "ibm869", "ibm869", "ibm870", "ibm870", "ibm871", "ibm871", "ibm874", "ibm875", "ibm912", "ibm913", "ibm914", "ibm915", "ibm916", "ibm918", "ibm920", "ibm921", "ibm922", "ibm923", "ibm930", "ibm933", "ibm935", "ibm937", "ibm939", "ibm942", "ibm942c", "ibm943", "ibm943c", "ibm948", "ibm949", "ibm949c", "ibm950", "ibm964", "ibm970", "iscii", "iscii91", "iso-10646-ucs-2", "iso-2022-cn", "iso-2022-cn-cns", "iso-2022-cn-gb", "iso-2022-jp", "iso-2022-jp-2", "iso-2022-kr", "iso-8859-11", "iso-8859-13", "iso-8859-15", "iso-8859-15", "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5", "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-ir-101", "iso-ir-109", "iso-ir-110", "iso-ir-126", "iso-ir-127", "iso-ir-138", "iso-ir-144", "iso-ir-148", "iso-ir-153", "iso-ir-159", "iso-ir-6", "iso-ir-87", "iso2022cn", "iso2022cn_cns", "iso2022cn_gb", "iso2022jp", "iso2022jp2", "iso2022kr", "iso646-us", "iso8859-13", "iso8859-15", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5", "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859_11", "iso8859_13", "iso8859_15", "iso8859_15_fdis", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6", "iso8859_7", "iso8859_8", "iso8859_9", "iso_646.irv:1983", "iso_646.irv:1991", "iso_8859-13", "iso_8859-15", "iso_8859-2", "iso_8859-2:1987", "iso_8859-3", "iso_8859-3:1988", "iso_8859-4", "iso_8859-4:1988", "iso_8859-5", "iso_8859-5:1988", "iso_8859-6", "iso_8859-6:1987", "iso_8859-7", "iso_8859-7:1987", "iso_8859-8", "iso_8859-8:1988", "iso_8859-9", "iso_8859-9:1989", "jis", "jis0201", "jis0208", "jis0212", "jis_c6226-1983", "jis_encoding", "jis_x0201", "jis_x0201", "jis_x0208-1983", "jis_x0212-1990", "jis_x0212-1990", "jisautodetect", "johab", "koi8", "koi8-r", "koi8-u", "koi8_r", "koi8_u", "ks_c_5601-1987", "ksc5601", "ksc5601-1987", "ksc5601-1992", "ksc5601_1987", "ksc5601_1992", "ksc_5601", "l2", "l3", "l4", "l5", "l9", "latin0", "latin2", "latin3", "latin4", "latin5", "latin9", "macarabic", "maccentraleurope", "maccroatian", "maccyrillic", "macdingbat", "macgreek", "machebrew", "maciceland", "macroman", "macromania", "macsymbol", "macthai", "macturkish", "macukraine", "ms-874", "ms1361", "ms50220", "ms50221", "ms874", "ms932", "ms936", "ms949", "ms950", "ms950_hkscs", "ms950_hkscs_xp", "ms_936", "ms_949", "ms_kanji", "pc-multilingual-850+euro", "pck", "shift-jis", "shift_jis", "shift_jis", "sjis", "st_sev_358-88", "sun_eu_greek", "tis-620", "tis620", "tis620.2533", "unicode", "unicodebig", "unicodebigunmarked", "unicodelittle", "unicodelittleunmarked", "us", "us-ascii", "utf-16", "utf-16be", "utf-16le", "utf-32", "utf-32be", "utf-32be-bom", "utf-32le", "utf-32le-bom", "utf16", "utf32", "utf_16", "utf_16be", "utf_16le", "utf_32", "utf_32be", "utf_32be_bom", "utf_32le", "utf_32le_bom", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "windows-31j", "windows-437", "windows-874", "windows-932", "windows-936", "windows-949", "windows-950", "windows-iso2022jp", "windows949", "x-big5-hkscs-2001", "x-big5-solaris", "x-compound-text", "x-compound_text", "x-euc-cn", "x-euc-jp", "x-euc-jp-linux", "x-euc-tw", "x-eucjp", "x-eucjp-open", "x-ibm1006", "x-ibm1025", "x-ibm1046", "x-ibm1097", "x-ibm1098", "x-ibm1112", "x-ibm1122", "x-ibm1123", "x-ibm1124", "x-ibm1166", "x-ibm1364", "x-ibm1381", "x-ibm1383", "x-ibm300", "x-ibm33722", "x-ibm737", "x-ibm833", "x-ibm834", "x-ibm856", "x-ibm874", "x-ibm875", "x-ibm921", "x-ibm922", "x-ibm930", "x-ibm933", "x-ibm935", "x-ibm937", "x-ibm939", "x-ibm942", "x-ibm942c", "x-ibm943", "x-ibm943c", "x-ibm948", "x-ibm949", "x-ibm949c", "x-ibm950", "x-ibm964", "x-ibm970", "x-iscii91", "x-iso-2022-cn-cns", "x-iso-2022-cn-gb", "x-iso-8859-11", "x-jis0208", "x-jisautodetect", "x-johab", "x-macarabic", "x-maccentraleurope", "x-maccroatian", "x-maccyrillic", "x-macdingbat", "x-macgreek", "x-machebrew", "x-maciceland", "x-macroman", "x-macromania", "x-macsymbol", "x-macthai", "x-macturkish", "x-macukraine", "x-ms932_0213", "x-ms950-hkscs", "x-ms950-hkscs-xp", "x-mswin-936", "x-pck", "x-sjis", "x-sjis_0213", "x-utf-16be", "x-utf-16le", "x-utf-16le-bom", "x-utf-32be", "x-utf-32be-bom", "x-utf-32le", "x-utf-32le-bom", "x-windows-50220", "x-windows-50221", "x-windows-874", "x-windows-949", "x-windows-950", "x-windows-iso2022jp", "x0201", "x0208", "x0212", "x11-compound_text", // Added from Oracle JDK 10.0.2 "csiso885915", "csiso885916", "iso-8859-16", "iso-ir-226", "iso_8859-16", "iso_8859-16:2001", "l10", "latin-9", "latin10", "ms932-0213", "ms932:2004", "ms932_0213", "shift_jis:2004", "shift_jis_0213:2004", "sjis-0213", "sjis:2004", "sjis_0213", "sjis_0213:2004", "windows-932-0213", "windows-932:2004", // Added from OpenJDK 11.0.1 "932", "cp932", "cpeuccn", "ibm-1252", "ibm-932", "ibm-euccn", "ibm1252", "ibm932", "ibmeuccn", "x-ibm932", // Added from OpenJDK 12 ea28 "1129", "cp1129", "ibm-1129", "ibm-euctw", "ibm1129", "x-ibm1129", // Added from OpenJDK 13 ea15 "29626c", "833", "cp29626c", "ibm-1140", "ibm-1141", "ibm-1142", "ibm-1143", "ibm-1144", "ibm-1145", "ibm-1146", "ibm-1147", "ibm-1148", "ibm-1149", "ibm-29626c", "ibm-858", "ibm-eucjp", "ibm1140", "ibm1141", "ibm1142", "ibm1143", "ibm1144", "ibm1145", "ibm1146", "ibm1147", "ibm1148", "ibm1149", "ibm29626c", "ibm858", "x-ibm29626c", // Added from OpenJDK 15 ea24 "iso8859_16", // Added from HPE JVM 1.8.0.17-hp-ux "cp1051", "cp1386", "cshproman8", "hp-roman8", "ibm-1051", "r8", "roman8", "roman9", // Added from OpenJDK 21 ea18 "gb18030-2022" // If you add and entry to this list, ensure you run // TestCharsetUtil#testIsAcsiiSupersetAll() }; private static final Charset DUMMY_CHARSET = new DummyCharset("Dummy", null); private ConcurrentMap<String,Charset> cache = new ConcurrentHashMap<>(); public CharsetCache() { // Pre-populate the cache for (String charsetName : INITIAL_CHARSETS) { Charset charset = Charset.forName(charsetName); addToCache(charsetName, charset); } for (String charsetName : LAZY_CHARSETS) { addToCache(charsetName, DUMMY_CHARSET); } } private void addToCache(String name, Charset charset) { cache.put(name, charset); for (String alias : charset.aliases()) { cache.put(alias.toLowerCase(Locale.ENGLISH), charset); } } public Charset getCharset(String charsetName) { String lcCharsetName = charsetName.toLowerCase(Locale.ENGLISH); Charset result = cache.get(lcCharsetName); if (result == DUMMY_CHARSET) { // Name is known but the Charset is not in the cache Charset charset = Charset.forName(lcCharsetName); if (charset == null) { // Charset not available in this JVM - remove cache entry cache.remove(lcCharsetName); result = null; } else { // Charset is available - populate cache entry addToCache(lcCharsetName, charset); result = charset; } } return result; } /* * Placeholder Charset implementation for entries that will be loaded lazily into the cache. */ private static class DummyCharset extends Charset { protected DummyCharset(String canonicalName, String[] aliases) { super(canonicalName, aliases); } @Override public boolean contains(Charset cs) { return false; } @Override public CharsetDecoder newDecoder() { return null; } @Override public CharsetEncoder newEncoder() { return null; } } }
apache/tomcat
java/org/apache/tomcat/util/buf/CharsetCache.java
2,396
/* * Copyright (C) 2014 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.internal.codegen.validation; import static androidx.room.compiler.processing.XElementKt.isTypeElement; import static androidx.room.compiler.processing.compat.XConverters.toKS; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static dagger.internal.codegen.base.Keys.isValidImplicitProvisionKey; import static dagger.internal.codegen.base.Keys.isValidMembersInjectionKey; import static dagger.internal.codegen.binding.AssistedInjectionAnnotations.assistedInjectedConstructors; import static dagger.internal.codegen.binding.InjectionAnnotations.injectedConstructors; import static dagger.internal.codegen.binding.SourceFiles.generatedClassNameForBinding; import static dagger.internal.codegen.extension.DaggerCollectors.toOptional; import static dagger.internal.codegen.xprocessing.XElements.asTypeElement; import static dagger.internal.codegen.xprocessing.XElements.closestEnclosingTypeElement; import static dagger.internal.codegen.xprocessing.XTypes.erasedTypeName; import static dagger.internal.codegen.xprocessing.XTypes.isDeclared; import static dagger.internal.codegen.xprocessing.XTypes.nonObjectSuperclass; import static dagger.internal.codegen.xprocessing.XTypes.unwrapType; import androidx.room.compiler.processing.XConstructorElement; import androidx.room.compiler.processing.XFieldElement; import androidx.room.compiler.processing.XMessager; import androidx.room.compiler.processing.XMethodElement; import androidx.room.compiler.processing.XProcessingEnv; import androidx.room.compiler.processing.XType; import androidx.room.compiler.processing.XTypeElement; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.devtools.ksp.symbol.Origin; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.squareup.javapoet.ClassName; import dagger.Component; import dagger.Provides; import dagger.internal.codegen.base.SourceFileGenerationException; import dagger.internal.codegen.base.SourceFileGenerator; import dagger.internal.codegen.binding.Binding; import dagger.internal.codegen.binding.BindingFactory; import dagger.internal.codegen.binding.InjectBindingRegistry; import dagger.internal.codegen.binding.KeyFactory; import dagger.internal.codegen.binding.MembersInjectionBinding; import dagger.internal.codegen.binding.ProvisionBinding; import dagger.internal.codegen.compileroption.CompilerOptions; import dagger.internal.codegen.javapoet.TypeNames; import dagger.internal.codegen.model.Key; import java.util.ArrayDeque; import java.util.Deque; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import javax.inject.Inject; import javax.inject.Singleton; import javax.tools.Diagnostic.Kind; /** * Maintains the collection of provision bindings from {@link Inject} constructors and members * injection bindings from {@link Inject} fields and methods known to the annotation processor. Note * that this registry <b>does not</b> handle any explicit bindings (those from {@link Provides} * methods, {@link Component} dependencies, etc.). */ @Singleton final class InjectBindingRegistryImpl implements InjectBindingRegistry { private final XProcessingEnv processingEnv; private final XMessager messager; private final InjectValidator injectValidator; private final InjectValidator injectValidatorWhenGeneratingCode; private final KeyFactory keyFactory; private final BindingFactory bindingFactory; private final CompilerOptions compilerOptions; private final class BindingsCollection<B extends Binding> { private final ClassName factoryClass; private final Map<Key, B> bindingsByKey = Maps.newLinkedHashMap(); private final Deque<B> bindingsRequiringGeneration = new ArrayDeque<>(); private final Set<Key> materializedBindingKeys = Sets.newLinkedHashSet(); BindingsCollection(ClassName factoryClass) { this.factoryClass = factoryClass; } void generateBindings(SourceFileGenerator<B> generator) throws SourceFileGenerationException { for (B binding = bindingsRequiringGeneration.poll(); binding != null; binding = bindingsRequiringGeneration.poll()) { checkState(!binding.unresolved().isPresent()); XType type = binding.key().type().xprocessing(); if (!isDeclared(type) || injectValidatorWhenGeneratingCode.validate(type.getTypeElement()).isClean()) { generator.generate(binding); } materializedBindingKeys.add(binding.key()); } // Because Elements instantiated across processing rounds are not guaranteed to be equals() to // the logically same element, clear the cache after generating bindingsByKey.clear(); } /** Returns a previously cached binding. */ B getBinding(Key key) { return bindingsByKey.get(key); } /** Caches the binding and generates it if it needs generation. */ void tryRegisterBinding(B binding, boolean isCalledFromInjectProcessor) { if (processingEnv.getBackend() == XProcessingEnv.Backend.KSP) { Origin origin = toKS(closestEnclosingTypeElement(binding.bindingElement().get())).getOrigin(); // If the origin of the element is from a source file in the current compilation unit then // we're guaranteed that the InjectProcessor should run over the element so only generate // the Factory/MembersInjector if we're being called from the InjectProcessor. // // TODO(bcorso): generally, this isn't something we would need to keep track of manually. // However, KSP incremental processing has a bug that will overwrite the cache for the // element if we generate files for it, which can lead to missing generated files from // other processors. See https://github.com/google/dagger/issues/4063 and // https://github.com/google/dagger/issues/4054. Remove this once that bug is fixed. if (!isCalledFromInjectProcessor && (origin == Origin.JAVA || origin == Origin.KOTLIN)) { return; } } tryToCacheBinding(binding); @SuppressWarnings("unchecked") B maybeUnresolved = binding.unresolved().isPresent() ? (B) binding.unresolved().get() : binding; tryToGenerateBinding(maybeUnresolved, isCalledFromInjectProcessor); } /** * Tries to generate a binding, not generating if it already is generated. For resolved * bindings, this will try to generate the unresolved version of the binding. */ void tryToGenerateBinding(B binding, boolean isCalledFromInjectProcessor) { if (shouldGenerateBinding(binding)) { bindingsRequiringGeneration.offer(binding); if (compilerOptions.warnIfInjectionFactoryNotGeneratedUpstream() && !isCalledFromInjectProcessor) { messager.printMessage( Kind.NOTE, String.format( "Generating a %s for %s. " + "Prefer to run the dagger processor over that class instead.", factoryClass.simpleName(), // erasure to strip <T> from msgs. erasedTypeName(binding.key().type().xprocessing()))); } } } /** Returns true if the binding needs to be generated. */ private boolean shouldGenerateBinding(B binding) { if (binding instanceof MembersInjectionBinding) { MembersInjectionBinding membersInjectionBinding = (MembersInjectionBinding) binding; // Empty members injection bindings are special and don't need source files. if (membersInjectionBinding.injectionSites().isEmpty()) { return false; } // Members injectors for classes with no local injection sites and no @Inject // constructor are unused. boolean hasInjectConstructor = !(injectedConstructors(membersInjectionBinding.membersInjectedType()).isEmpty() && assistedInjectedConstructors( membersInjectionBinding.membersInjectedType()).isEmpty()); if (!membersInjectionBinding.hasLocalInjectionSites() && !hasInjectConstructor) { return false; } } return !binding.unresolved().isPresent() && !materializedBindingKeys.contains(binding.key()) && !bindingsRequiringGeneration.contains(binding) && processingEnv.findTypeElement(generatedClassNameForBinding(binding)) == null; } /** Caches the binding for future lookups by key. */ private void tryToCacheBinding(B binding) { // We only cache resolved bindings or unresolved bindings w/o type arguments. // Unresolved bindings w/ type arguments aren't valid for the object graph. if (binding.unresolved().isPresent() || binding.bindingTypeElement().get().getType().getTypeArguments().isEmpty()) { Key key = binding.key(); Binding previousValue = bindingsByKey.put(key, binding); checkState(previousValue == null || binding.equals(previousValue), "couldn't register %s. %s was already registered for %s", binding, previousValue, key); } } } private final BindingsCollection<ProvisionBinding> provisionBindings = new BindingsCollection<>(TypeNames.PROVIDER); private final BindingsCollection<MembersInjectionBinding> membersInjectionBindings = new BindingsCollection<>(TypeNames.MEMBERS_INJECTOR); @Inject InjectBindingRegistryImpl( XProcessingEnv processingEnv, XMessager messager, InjectValidator injectValidator, KeyFactory keyFactory, BindingFactory bindingFactory, CompilerOptions compilerOptions) { this.processingEnv = processingEnv; this.messager = messager; this.injectValidator = injectValidator; this.injectValidatorWhenGeneratingCode = injectValidator.whenGeneratingCode(); this.keyFactory = keyFactory; this.bindingFactory = bindingFactory; this.compilerOptions = compilerOptions; } // TODO(dpb): make the SourceFileGenerators fields so they don't have to be passed in @Override public void generateSourcesForRequiredBindings( SourceFileGenerator<ProvisionBinding> factoryGenerator, SourceFileGenerator<MembersInjectionBinding> membersInjectorGenerator) throws SourceFileGenerationException { provisionBindings.generateBindings(factoryGenerator); membersInjectionBindings.generateBindings(membersInjectorGenerator); } @Override public Optional<ProvisionBinding> tryRegisterInjectConstructor( XConstructorElement constructorElement) { return tryRegisterConstructor( constructorElement, Optional.empty(), /* isCalledFromInjectProcessor= */ true); } @CanIgnoreReturnValue private Optional<ProvisionBinding> tryRegisterConstructor( XConstructorElement constructorElement, Optional<XType> resolvedType, boolean isCalledFromInjectProcessor) { XTypeElement typeElement = constructorElement.getEnclosingElement(); // Validating here shouldn't have a performance penalty because the validator caches its reports ValidationReport report = injectValidator.validate(typeElement); report.printMessagesTo(messager); if (!report.isClean()) { return Optional.empty(); } XType type = typeElement.getType(); Key key = keyFactory.forInjectConstructorWithResolvedType(type); ProvisionBinding cachedBinding = provisionBindings.getBinding(key); if (cachedBinding != null) { return Optional.of(cachedBinding); } ProvisionBinding binding = bindingFactory.injectionBinding(constructorElement, resolvedType); provisionBindings.tryRegisterBinding(binding, isCalledFromInjectProcessor); if (!binding.injectionSites().isEmpty()) { tryRegisterMembersInjectedType(typeElement, resolvedType, isCalledFromInjectProcessor); } return Optional.of(binding); } @Override public Optional<MembersInjectionBinding> tryRegisterInjectField(XFieldElement fieldElement) { // TODO(b/204116636): Add a test for this once we're able to test kotlin sources. // TODO(b/204208307): Add validation for KAPT to test if this came from a top-level field. if (!isTypeElement(fieldElement.getEnclosingElement())) { messager.printMessage( Kind.ERROR, "@Inject fields must be enclosed in a type.", fieldElement); } return tryRegisterMembersInjectedType( asTypeElement(fieldElement.getEnclosingElement()), Optional.empty(), /* isCalledFromInjectProcessor= */ true); } @Override public Optional<MembersInjectionBinding> tryRegisterInjectMethod(XMethodElement methodElement) { // TODO(b/204116636): Add a test for this once we're able to test kotlin sources. // TODO(b/204208307): Add validation for KAPT to test if this came from a top-level method. if (!isTypeElement(methodElement.getEnclosingElement())) { messager.printMessage( Kind.ERROR, "@Inject methods must be enclosed in a type.", methodElement); } return tryRegisterMembersInjectedType( asTypeElement(methodElement.getEnclosingElement()), Optional.empty(), /* isCalledFromInjectProcessor= */ true); } @CanIgnoreReturnValue private Optional<MembersInjectionBinding> tryRegisterMembersInjectedType( XTypeElement typeElement, Optional<XType> resolvedType, boolean isCalledFromInjectProcessor) { // Validating here shouldn't have a performance penalty because the validator caches its reports ValidationReport report = injectValidator.validateForMembersInjection(typeElement); report.printMessagesTo(messager); if (!report.isClean()) { return Optional.empty(); } XType type = typeElement.getType(); Key key = keyFactory.forInjectConstructorWithResolvedType(type); MembersInjectionBinding cachedBinding = membersInjectionBindings.getBinding(key); if (cachedBinding != null) { return Optional.of(cachedBinding); } MembersInjectionBinding binding = bindingFactory.membersInjectionBinding(type, resolvedType); membersInjectionBindings.tryRegisterBinding(binding, isCalledFromInjectProcessor); for (Optional<XType> supertype = nonObjectSuperclass(type); supertype.isPresent(); supertype = nonObjectSuperclass(supertype.get())) { getOrFindMembersInjectionBinding(keyFactory.forMembersInjectedType(supertype.get())); } return Optional.of(binding); } @CanIgnoreReturnValue @Override public Optional<ProvisionBinding> getOrFindProvisionBinding(Key key) { checkNotNull(key); if (!isValidImplicitProvisionKey(key)) { return Optional.empty(); } ProvisionBinding binding = provisionBindings.getBinding(key); if (binding != null) { return Optional.of(binding); } XType type = key.type().xprocessing(); XTypeElement element = type.getTypeElement(); ValidationReport report = injectValidator.validate(element); report.printMessagesTo(messager); if (!report.isClean()) { return Optional.empty(); } return Stream.concat( injectedConstructors(element).stream(), assistedInjectedConstructors(element).stream()) // We're guaranteed that there's at most 1 @Inject constructors from above validation. .collect(toOptional()) .flatMap( constructor -> tryRegisterConstructor( constructor, Optional.of(type), /* isCalledFromInjectProcessor= */ false)); } @CanIgnoreReturnValue @Override public Optional<MembersInjectionBinding> getOrFindMembersInjectionBinding(Key key) { checkNotNull(key); // TODO(gak): is checking the kind enough? checkArgument(isValidMembersInjectionKey(key)); MembersInjectionBinding binding = membersInjectionBindings.getBinding(key); if (binding != null) { return Optional.of(binding); } return tryRegisterMembersInjectedType( key.type().xprocessing().getTypeElement(), Optional.of(key.type().xprocessing()), /* isCalledFromInjectProcessor= */ false); } @Override public Optional<ProvisionBinding> getOrFindMembersInjectorProvisionBinding(Key key) { if (!isValidMembersInjectionKey(key)) { return Optional.empty(); } Key membersInjectionKey = keyFactory.forMembersInjectedType(unwrapType(key.type().xprocessing())); return getOrFindMembersInjectionBinding(membersInjectionKey) .map(binding -> bindingFactory.membersInjectorBinding(key, binding)); } }
google/dagger
java/dagger/internal/codegen/validation/InjectBindingRegistryImpl.java
2,397
package com.google.common.collect; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import com.google.common.base.Function; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public class MigrateMap { public static <K, V> ConcurrentMap<K, V> makeComputingMap(CacheBuilder<Object, Object> builder, Function<? super K, ? extends V> computingFunction) { final Function<? super K, ? extends V> function = computingFunction; LoadingCache<K, V> computingCache = builder.build(new CacheLoader<K, V>() { @Override public V load(K key) throws Exception { return function.apply(key); } }); return new MigrateConcurrentMap<>(computingCache); } public static <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computingFunction) { return makeComputingMap(CacheBuilder.newBuilder(), computingFunction); } final static class MigrateConcurrentMap<K, V> implements ConcurrentMap<K, V> { private final LoadingCache<K, V> computingCache; private final ConcurrentMap<K, V> cacheView; MigrateConcurrentMap(LoadingCache<K, V> computingCache){ this.computingCache = computingCache; this.cacheView = computingCache.asMap(); } @Override public int size() { return cacheView.size(); } @Override public boolean isEmpty() { return cacheView.isEmpty(); } @Override public boolean containsKey(Object key) { return cacheView.containsKey(key); } @Override public boolean containsValue(Object value) { return cacheView.containsValue(value); } @Override public V get(Object key) { try { return computingCache.get((K) key); } catch (ExecutionException e) { throw new RuntimeException(e); } } @Override public V put(K key, V value) { return cacheView.put(key, value); } @Override public V remove(Object key) { return cacheView.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { cacheView.putAll(m); } @Override public void clear() { cacheView.clear(); } @Override public Set<K> keySet() { return cacheView.keySet(); } @Override public Collection<V> values() { return cacheView.values(); } @Override public Set<Entry<K, V>> entrySet() { return cacheView.entrySet(); } @Override public V putIfAbsent(K key, V value) { return cacheView.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { return cacheView.remove(key, value); } @Override public boolean replace(K key, V oldValue, V newValue) { return cacheView.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { return cacheView.replace(key, value); } @Override public String toString() { return cacheView.toString(); } } }
alibaba/canal
common/src/main/java/com/google/common/collect/MigrateMap.java
2,398
package cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.junit.Test; import java.util.concurrent.ExecutionException; /** * Guava demo. * * @author skywalker */ public class CacheDemo { @Test public void cacheLoader() throws ExecutionException { LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2) .build(new CacheLoader<String, String>() { @Override public String load(String s) throws Exception { return "Hello: " + s; } }); System.out.println(cache.get("China")); cache.put("US", "US"); System.out.println(cache.get("US")); //放不进去 cache.put("UK", "UK"); } }
seaswalker/spring-analysis
src/main/java/cache/CacheDemo.java
2,399
/* * 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.cassandra.cql3.functions.types; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import com.google.common.cache.*; import com.google.common.reflect.TypeToken; import com.google.common.util.concurrent.UncheckedExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.cql3.functions.types.exceptions.CodecNotFoundException; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.cassandra.cql3.functions.types.DataType.Name.*; /** * A registry for {@link TypeCodec}s. When the driver needs to serialize or deserialize a Java type * to/from CQL, it will lookup in the registry for a suitable codec. The registry is initialized * with default codecs that handle basic conversions (e.g. CQL {@code text} to {@code * java.lang.String}), and users can add their own. Complex codecs can also be generated on-the-fly * from simpler ones (more details below). * * <h3>Creating a registry </h3> * <p> * By default, the driver uses {@code CodecRegistry#DEFAULT_INSTANCE}, a shareable, JVM-wide * instance initialized with built-in codecs for all the base CQL types. The only reason to create * your own instances is if you have multiple {@code Cluster} objects that use different sets of * codecs. In that case, use {@code * Cluster.Builder#withCodecRegistry(CodecRegistry)} to associate the * registry with the cluster: * * <pre>{@code * CodecRegistry myCodecRegistry = new CodecRegistry(); * myCodecRegistry.register(myCodec1, myCodec2, myCodec3); * Cluster cluster = Cluster.builder().withCodecRegistry(myCodecRegistry).build(); * * // To retrieve the registry later: * CodecRegistry registry = cluster.getConfiguration().getCodecRegistry(); * }</pre> * <p> * {@code CodecRegistry} instances are thread-safe. * * <p>It is possible to turn on log messages by setting the {@code * CodecRegistry} logger level to {@code TRACE}. Beware that the registry * can be very verbose at this log level. * * <h3>Registering and using custom codecs </h3> * <p> * To create a custom codec, write a class that extends {@link TypeCodec}, create an instance, and * pass it to one of the {@link #register(TypeCodec) register} methods; for example, one could * create a codec that maps CQL timestamps to JDK8's {@code java.time.LocalDate}: * * <pre>{@code * class LocalDateCodec extends TypeCodec<java.time.LocalDate> { * ... * } * myCodecRegistry.register(new LocalDateCodec()); * }</pre> * <p> * The conversion will be available to: * * <ul> * <li>all driver types that implement {@link GettableByIndexData}, {@link GettableByNameData}, * {@link SettableByIndexData} and/or {@link SettableByNameData}. Namely: {@code Row}, {@code * BoundStatement}, {@link UDTValue} and {@link TupleValue}; * <li>{@code SimpleStatement#SimpleStatement(String, Object...) simple statements}; * <li>statements created with the {@code querybuilder.QueryBuilder Query * builder}. * </ul> * * <p>Example: * * <pre>{@code * Row row = session.executeQuery("select date from some_table where pk = 1").one(); * java.time.LocalDate date = row.get(0, java.time.LocalDate.class); // uses LocalDateCodec registered above * }</pre> * <p> * You can also bypass the codec registry by passing a standalone codec instance to methods such as * {@link GettableByIndexData#get(int, TypeCodec)}. * * <h3>Codec generation </h3> * <p> * When a {@code CodecRegistry} cannot find a suitable codec among existing ones, it will attempt to * create it on-the-fly. It can manage: * * <ul> * <li>collections (lists, sets and maps) of known types. For example, if you registered a codec * for JDK8's {@code java.time.LocalDate} like in the example above, you get {@code * List<LocalDate>>} and {@code Set<LocalDate>>} handled for free, as well as all {@code Map} * types whose keys and/or values are {@code java.time.LocalDate}. This works recursively for * nested collections; * <li>{@link UserType user types}, mapped to {@link UDTValue} objects. Custom codecs are * available recursively to the UDT's fields, so if one of your fields is a {@code timestamp} * you can use your {@code LocalDateCodec} to retrieve it as a {@code java.time.LocalDate}; * <li>{@link TupleType tuple types}, mapped to {@link TupleValue} (with the same rules for nested * fields); * <li>{@link DataType.CustomType custom types}, mapped to {@code * ByteBuffer}. * </ul> * <p> * If the codec registry encounters a mapping that it can't handle automatically, a {@link * CodecNotFoundException} is thrown; you'll need to register a custom codec for it. * * <h3>Performance and caching </h3> * <p> * Whenever possible, the registry will cache the result of a codec lookup for a specific type * mapping, including any generated codec. For example, if you registered {@code LocalDateCodec} and * ask the registry for a codec to convert a CQL {@code list<timestamp>} to a Java {@code * List<LocalDate>}: * * <ol> * <li>the first lookup will generate a {@code TypeCodec<List<LocalDate>>} from {@code * LocalDateCodec}, and put it in the cache; * <li>the second lookup will hit the cache directly, and reuse the previously generated instance. * </ol> * <p> * The javadoc for each {@link #codecFor(DataType) codecFor} variant specifies whether the result * can be cached or not. * * <h3>Codec order </h3> * <p> * When the registry looks up a codec, the rules of precedence are: * * <ul> * <li>if a result was previously cached for that mapping, it is returned; * <li>otherwise, the registry checks the list of built-in codecs – the default ones – and the * ones that were explicitly registered (in the order that they were registered). It calls * each codec's {@code accepts} methods to determine if it can handle the mapping, and if so * returns it; * <li>otherwise, the registry tries to generate a codec, according to the rules outlined above. * </ul> * <p> * It is currently impossible to override an existing codec. If you try to do so, {@link * #register(TypeCodec)} will log a warning and ignore it. */ public final class CodecRegistry { private static final Logger logger = LoggerFactory.getLogger(CodecRegistry.class); private static final Map<DataType.Name, TypeCodec<?>> BUILT_IN_CODECS_MAP = new EnumMap<>(DataType.Name.class); static { BUILT_IN_CODECS_MAP.put(ASCII, TypeCodec.ascii()); BUILT_IN_CODECS_MAP.put(BIGINT, TypeCodec.bigint()); BUILT_IN_CODECS_MAP.put(BLOB, TypeCodec.blob()); BUILT_IN_CODECS_MAP.put(BOOLEAN, TypeCodec.cboolean()); BUILT_IN_CODECS_MAP.put(COUNTER, TypeCodec.counter()); BUILT_IN_CODECS_MAP.put(DECIMAL, TypeCodec.decimal()); BUILT_IN_CODECS_MAP.put(DOUBLE, TypeCodec.cdouble()); BUILT_IN_CODECS_MAP.put(FLOAT, TypeCodec.cfloat()); BUILT_IN_CODECS_MAP.put(INET, TypeCodec.inet()); BUILT_IN_CODECS_MAP.put(INT, TypeCodec.cint()); BUILT_IN_CODECS_MAP.put(TEXT, TypeCodec.varchar()); BUILT_IN_CODECS_MAP.put(TIMESTAMP, TypeCodec.timestamp()); BUILT_IN_CODECS_MAP.put(UUID, TypeCodec.uuid()); BUILT_IN_CODECS_MAP.put(VARCHAR, TypeCodec.varchar()); BUILT_IN_CODECS_MAP.put(VARINT, TypeCodec.varint()); BUILT_IN_CODECS_MAP.put(TIMEUUID, TypeCodec.timeUUID()); BUILT_IN_CODECS_MAP.put(SMALLINT, TypeCodec.smallInt()); BUILT_IN_CODECS_MAP.put(TINYINT, TypeCodec.tinyInt()); BUILT_IN_CODECS_MAP.put(DATE, TypeCodec.date()); BUILT_IN_CODECS_MAP.put(TIME, TypeCodec.time()); BUILT_IN_CODECS_MAP.put(DURATION, TypeCodec.duration()); } // roughly sorted by popularity private static final TypeCodec<?>[] BUILT_IN_CODECS = new TypeCodec<?>[]{ TypeCodec .varchar(), // must be declared before AsciiCodec so it gets chosen when CQL type not // available TypeCodec .uuid(), // must be declared before TimeUUIDCodec so it gets chosen when CQL type not // available TypeCodec.timeUUID(), TypeCodec.timestamp(), TypeCodec.cint(), TypeCodec.bigint(), TypeCodec.blob(), TypeCodec.cdouble(), TypeCodec.cfloat(), TypeCodec.decimal(), TypeCodec.varint(), TypeCodec.inet(), TypeCodec.cboolean(), TypeCodec.smallInt(), TypeCodec.tinyInt(), TypeCodec.date(), TypeCodec.time(), TypeCodec.duration(), TypeCodec.counter(), TypeCodec.ascii() }; /** * Cache key for the codecs cache. */ private static final class CacheKey { private final DataType cqlType; private final TypeToken<?> javaType; CacheKey(DataType cqlType, TypeToken<?> javaType) { this.javaType = javaType; this.cqlType = cqlType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheKey cacheKey = (CacheKey) o; return Objects.equals(cqlType, cacheKey.cqlType) && Objects.equals(javaType, cacheKey.javaType); } @Override public int hashCode() { return Objects.hash(cqlType, javaType); } } /** * Cache loader for the codecs cache. */ private class TypeCodecCacheLoader extends CacheLoader<CacheKey, TypeCodec<?>> { @Override public TypeCodec<?> load(CacheKey cacheKey) { checkNotNull(cacheKey.cqlType, "Parameter cqlType cannot be null"); if (logger.isTraceEnabled()) logger.trace( "Loading codec into cache: [{} <-> {}]", CodecRegistry.toString(cacheKey.cqlType), CodecRegistry.toString(cacheKey.javaType)); for (TypeCodec<?> codec : codecs) { if (codec.accepts(cacheKey.cqlType) && (cacheKey.javaType == null || codec.accepts(cacheKey.javaType))) { logger.trace("Already existing codec found: {}", codec); return codec; } } return createCodec(cacheKey.cqlType, cacheKey.javaType); } } /** * A complexity-based weigher for the codecs cache. Weights are computed mainly according to the * CQL type: * * <ol> * <li>Manually-registered codecs always weigh 0; * <li>Codecs for primitive types weigh 0; * <li>Codecs for collections weigh the total weight of their inner types + the weight of their * level of deepness; * <li>Codecs for UDTs and tuples weigh the total weight of their inner types + the weight of * their level of deepness, but cannot weigh less than 1; * <li>Codecs for custom (non-CQL) types weigh 1. * </ol> * <p> * A consequence of this algorithm is that codecs for primitive types and codecs for all "shallow" * collections thereof are never evicted. */ private class TypeCodecWeigher implements Weigher<CacheKey, TypeCodec<?>> { @Override public int weigh(CacheKey key, TypeCodec<?> value) { return codecs.contains(value) ? 0 : weigh(value.cqlType, 0); } private int weigh(DataType cqlType, int level) { switch (cqlType.getName()) { case LIST: case SET: case MAP: { int weight = level; for (DataType eltType : cqlType.getTypeArguments()) { weight += weigh(eltType, level + 1); } return weight; } case VECTOR: { int weight = level; DataType eltType = cqlType.getTypeArguments().get(0); if (eltType != null) { weight += weigh(eltType, level + 1); } return weight == 0 ? 1 : weight; } case UDT: { int weight = level; for (UserType.Field field : ((UserType) cqlType)) { weight += weigh(field.getType(), level + 1); } return weight == 0 ? 1 : weight; } case TUPLE: { int weight = level; for (DataType componentType : ((TupleType) cqlType).getComponentTypes()) { weight += weigh(componentType, level + 1); } return weight == 0 ? 1 : weight; } case CUSTOM: return 1; default: return 0; } } } /** * Simple removal listener for the codec cache (can be used for debugging purposes by setting the * {@code CodecRegistry} logger level to {@code TRACE}. */ private static class TypeCodecRemovalListener implements RemovalListener<CacheKey, TypeCodec<?>> { @Override public void onRemoval(RemovalNotification<CacheKey, TypeCodec<?>> notification) { logger.trace( "Evicting codec from cache: {} (cause: {})", notification.getValue(), notification.getCause()); } } /** * The list of user-registered codecs. */ private final CopyOnWriteArrayList<TypeCodec<?>> codecs; /** * A LoadingCache to serve requests for codecs whenever possible. The cache can be used as long as * at least the CQL type is known. */ private final LoadingCache<CacheKey, TypeCodec<?>> cache; /** * Creates a new instance initialized with built-in codecs for all the base CQL types. */ public CodecRegistry() { this.codecs = new CopyOnWriteArrayList<>(); this.cache = defaultCacheBuilder().build(new TypeCodecCacheLoader()); } private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // lists, sets and maps of 20 primitive types = 20 + 20 + 20*20 = 440 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100) .maximumWeight(1000) .weigher(new TypeCodecWeigher()); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; } /** * Register the given codec with this registry. * * <p>This method will log a warning and ignore the codec if it collides with a previously * registered one. Note that this check is not done in a completely thread-safe manner; codecs * should typically be registered at application startup, not in a highly concurrent context (if a * race condition occurs, the worst possible outcome is that no warning gets logged, and the codec * gets registered but will never actually be used). * * @param newCodec The codec to add to the registry. * @return this CodecRegistry (for method chaining). */ public CodecRegistry register(TypeCodec<?> newCodec) { for (TypeCodec<?> oldCodec : BUILT_IN_CODECS) { if (oldCodec.accepts(newCodec.getCqlType()) && oldCodec.accepts(newCodec.getJavaType())) { logger.warn( "Ignoring codec {} because it collides with previously registered codec {}", newCodec, oldCodec); return this; } } for (TypeCodec<?> oldCodec : codecs) { if (oldCodec.accepts(newCodec.getCqlType()) && oldCodec.accepts(newCodec.getJavaType())) { logger.warn( "Ignoring codec {} because it collides with previously registered codec {}", newCodec, oldCodec); return this; } } CacheKey key = new CacheKey(newCodec.getCqlType(), newCodec.getJavaType()); TypeCodec<?> existing = cache.getIfPresent(key); if (existing != null) { logger.warn( "Ignoring codec {} because it collides with previously generated codec {}", newCodec, existing); return this; } this.codecs.add(newCodec); return this; } /** * Register the given codecs with this registry. * * @param codecs The codecs to add to the registry. * @return this CodecRegistry (for method chaining). * @see #register(TypeCodec) */ public CodecRegistry register(TypeCodec<?>... codecs) { for (TypeCodec<?> codec : codecs) register(codec); return this; } /** * Register the given codecs with this registry. * * @param codecs The codecs to add to the registry. * @return this CodecRegistry (for method chaining). * @see #register(TypeCodec) */ public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs) { for (TypeCodec<?> codec : codecs) register(codec); return this; } /** * Returns a {@link TypeCodec codec} that accepts the given value. * * <p>This method takes an arbitrary Java object and tries to locate a suitable codec for it. * Codecs must perform a {@link TypeCodec#accepts(Object) runtime inspection} of the object to * determine if they can accept it or not, which, depending on the implementations, can be * expensive; besides, the resulting codec cannot be cached. Therefore there might be a * performance penalty when using this method. * * <p>Furthermore, this method returns the first matching codec, regardless of its accepted CQL * type. It should be reserved for situations where the target CQL type is not available or * unknown. In the Java driver, this happens mainly when serializing a value in a {@code * SimpleStatement#SimpleStatement(String, Object...) SimpleStatement} or in the {@code * querybuilder.QueryBuilder}, where no CQL type information is * available. * * <p>Codecs returned by this method are <em>NOT</em> cached (see the {@link CodecRegistry * top-level documentation} of this class for more explanations about caching). * * @param value The value the codec should accept; must not be {@code null}. * @return A suitable codec. * @throws CodecNotFoundException if a suitable codec cannot be found. */ public <T> TypeCodec<T> codecFor(T value) { return findCodec(null, value); } /** * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}. * * <p>This method returns the first matching codec, regardless of its accepted Java type. It * should be reserved for situations where the Java type is not available or unknown. In the Java * driver, this happens mainly when deserializing a value using the {@link * GettableByIndexData#getObject(int) getObject} method. * * <p>Codecs returned by this method are cached (see the {@link CodecRegistry top-level * documentation} of this class for more explanations about caching). * * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}. * @return A suitable codec. * @throws CodecNotFoundException if a suitable codec cannot be found. */ public <T> TypeCodec<T> codecFor(DataType cqlType) throws CodecNotFoundException { return lookupCodec(cqlType, null); } /** * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type} and the * given Java class. * * <p>This method can only handle raw (non-parameterized) Java types. For parameterized types, use * {@link #codecFor(DataType, TypeToken)} instead. * * <p>Codecs returned by this method are cached (see the {@link CodecRegistry top-level * documentation} of this class for more explanations about caching). * * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}. * @param javaType The Java type the codec should accept; can be {@code null}. * @return A suitable codec. * @throws CodecNotFoundException if a suitable codec cannot be found. */ public <T> TypeCodec<T> codecFor(DataType cqlType, Class<T> javaType) throws CodecNotFoundException { return codecFor(cqlType, TypeToken.of(javaType)); } /** * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type} and the * given Java type. * * <p>This method handles parameterized types thanks to Guava's {@link TypeToken} API. * * <p>Codecs returned by this method are cached (see the {@link CodecRegistry top-level * documentation} of this class for more explanations about caching). * * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}. * @param javaType The {@link TypeToken Java type} the codec should accept; can be {@code null}. * @return A suitable codec. * @throws CodecNotFoundException if a suitable codec cannot be found. */ public <T> TypeCodec<T> codecFor(DataType cqlType, TypeToken<T> javaType) throws CodecNotFoundException { return lookupCodec(cqlType, javaType); } /** * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type} and the * given value. * * <p>This method takes an arbitrary Java object and tries to locate a suitable codec for it. * Codecs must perform a {@link TypeCodec#accepts(Object) runtime inspection} of the object to * determine if they can accept it or not, which, depending on the implementations, can be * expensive; besides, the resulting codec cannot be cached. Therefore there might be a * performance penalty when using this method. * * <p>Codecs returned by this method are <em>NOT</em> cached (see the {@link CodecRegistry * top-level documentation} of this class for more explanations about caching). * * @param cqlType The {@link DataType CQL type} the codec should accept; can be {@code null}. * @param value The value the codec should accept; must not be {@code null}. * @return A suitable codec. * @throws CodecNotFoundException if a suitable codec cannot be found. */ public <T> TypeCodec<T> codecFor(DataType cqlType, T value) { return findCodec(cqlType, value); } @SuppressWarnings("unchecked") private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) { checkNotNull(cqlType, "Parameter cqlType cannot be null"); TypeCodec<?> codec = BUILT_IN_CODECS_MAP.get(cqlType.getName()); if (codec != null && (javaType == null || codec.accepts(javaType))) { logger.trace("Returning built-in codec {}", codec); return (TypeCodec<T>) codec; } if (logger.isTraceEnabled()) logger.trace("Querying cache for codec [{} <-> {}]", toString(cqlType), toString(javaType)); try { CacheKey cacheKey = new CacheKey(cqlType, javaType); codec = cache.get(cacheKey); } catch (UncheckedExecutionException e) { if (e.getCause() instanceof CodecNotFoundException) { throw (CodecNotFoundException) e.getCause(); } throw new CodecNotFoundException(e.getCause()); } catch (RuntimeException | ExecutionException e) { throw new CodecNotFoundException(e.getCause()); } logger.trace("Returning cached codec {}", codec); return (TypeCodec<T>) codec; } @SuppressWarnings("unchecked") private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) { checkNotNull(cqlType, "Parameter cqlType cannot be null"); if (logger.isTraceEnabled()) logger.trace("Looking for codec [{} <-> {}]", toString(cqlType), toString(javaType)); // Look at the built-in codecs first for (TypeCodec<?> codec : BUILT_IN_CODECS) { if (codec.accepts(cqlType) && (javaType == null || codec.accepts(javaType))) { logger.trace("Built-in codec found: {}", codec); return (TypeCodec<T>) codec; } } // Look at the user-registered codecs next for (TypeCodec<?> codec : codecs) { if (codec.accepts(cqlType) && (javaType == null || codec.accepts(javaType))) { logger.trace("Already registered codec found: {}", codec); return (TypeCodec<T>) codec; } } return createCodec(cqlType, javaType); } @SuppressWarnings("unchecked") private <T> TypeCodec<T> findCodec(DataType cqlType, T value) { checkNotNull(value, "Parameter value cannot be null"); if (logger.isTraceEnabled()) logger.trace("Looking for codec [{} <-> {}]", toString(cqlType), value.getClass()); // Look at the built-in codecs first for (TypeCodec<?> codec : BUILT_IN_CODECS) { if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) { logger.trace("Built-in codec found: {}", codec); return (TypeCodec<T>) codec; } } // Look at the user-registered codecs next for (TypeCodec<?> codec : codecs) { if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) { logger.trace("Already registered codec found: {}", codec); return (TypeCodec<T>) codec; } } return createCodec(cqlType, value); } private <T> TypeCodec<T> createCodec(DataType cqlType, TypeToken<T> javaType) { TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType); if (codec == null) throw notFound(cqlType, javaType); // double-check that the created codec satisfies the initial request // this check can fail specially when creating codecs for collections // e.g. if B extends A and there is a codec registered for A and // we request a codec for List<B>, the registry would generate a codec for List<A> if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType))) throw notFound(cqlType, javaType); logger.trace("Codec created: {}", codec); return codec; } private <T> TypeCodec<T> createCodec(DataType cqlType, T value) { TypeCodec<T> codec = maybeCreateCodec(cqlType, value); if (codec == null) throw notFound(cqlType, TypeToken.of(value.getClass())); // double-check that the created codec satisfies the initial request if ((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value)) throw notFound(cqlType, TypeToken.of(value.getClass())); logger.trace("Codec created: {}", codec); return codec; } @SuppressWarnings("unchecked") private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, TypeToken<T> javaType) { checkNotNull(cqlType); if (cqlType.getName() == LIST && (javaType == null || List.class.isAssignableFrom(javaType.getRawType()))) { TypeToken<?> elementType = null; if (javaType != null && javaType.getType() instanceof ParameterizedType) { Type[] typeArguments = ((ParameterizedType) javaType.getType()).getActualTypeArguments(); elementType = TypeToken.of(typeArguments[0]); } TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType); return (TypeCodec<T>) TypeCodec.list(eltCodec); } if (cqlType.getName() == SET && (javaType == null || Set.class.isAssignableFrom(javaType.getRawType()))) { TypeToken<?> elementType = null; if (javaType != null && javaType.getType() instanceof ParameterizedType) { Type[] typeArguments = ((ParameterizedType) javaType.getType()).getActualTypeArguments(); elementType = TypeToken.of(typeArguments[0]); } TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType); return (TypeCodec<T>) TypeCodec.set(eltCodec); } if (cqlType.getName() == MAP && (javaType == null || Map.class.isAssignableFrom(javaType.getRawType()))) { TypeToken<?> keyType = null; TypeToken<?> valueType = null; if (javaType != null && javaType.getType() instanceof ParameterizedType) { Type[] typeArguments = ((ParameterizedType) javaType.getType()).getActualTypeArguments(); keyType = TypeToken.of(typeArguments[0]); valueType = TypeToken.of(typeArguments[1]); } TypeCodec<?> keyCodec = findCodec(cqlType.getTypeArguments().get(0), keyType); TypeCodec<?> valueCodec = findCodec(cqlType.getTypeArguments().get(1), valueType); return (TypeCodec<T>) TypeCodec.map(keyCodec, valueCodec); } if (cqlType instanceof VectorType && (javaType == null || List.class.isAssignableFrom(javaType.getRawType()))) { VectorType type = (VectorType) cqlType; return (TypeCodec<T>) TypeCodec.vector(type, findCodec(type.getSubtype(), null)); } if (cqlType instanceof TupleType && (javaType == null || TupleValue.class.isAssignableFrom(javaType.getRawType()))) { return (TypeCodec<T>) TypeCodec.tuple((TupleType) cqlType); } if (cqlType instanceof UserType && (javaType == null || UDTValue.class.isAssignableFrom(javaType.getRawType()))) { return (TypeCodec<T>) TypeCodec.userType((UserType) cqlType); } if (cqlType instanceof DataType.CustomType && (javaType == null || ByteBuffer.class.isAssignableFrom(javaType.getRawType()))) { return (TypeCodec<T>) TypeCodec.custom((DataType.CustomType) cqlType); } return null; } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, T value) { checkNotNull(value); if ((cqlType == null || cqlType.getName() == LIST) && value instanceof List) { List list = (List) value; if (list.isEmpty()) { DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty()) ? DataType.blob() : cqlType.getTypeArguments().get(0); return (TypeCodec<T>) TypeCodec.list(findCodec(elementType, (TypeToken) null)); } else { DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty()) ? null : cqlType.getTypeArguments().get(0); return (TypeCodec<T>) TypeCodec.list(findCodec(elementType, list.iterator().next())); } } if ((cqlType == null || cqlType.getName() == SET) && value instanceof Set) { Set set = (Set) value; if (set.isEmpty()) { DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty()) ? DataType.blob() : cqlType.getTypeArguments().get(0); return (TypeCodec<T>) TypeCodec.set(findCodec(elementType, (TypeToken) null)); } else { DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty()) ? null : cqlType.getTypeArguments().get(0); return (TypeCodec<T>) TypeCodec.set(findCodec(elementType, set.iterator().next())); } } if ((cqlType == null || cqlType.getName() == MAP) && value instanceof Map) { Map map = (Map) value; if (map.isEmpty()) { DataType keyType = (cqlType == null || cqlType.getTypeArguments().size() < 1) ? DataType.blob() : cqlType.getTypeArguments().get(0); DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2) ? DataType.blob() : cqlType.getTypeArguments().get(1); return (TypeCodec<T>) TypeCodec.map( findCodec(keyType, (TypeToken) null), findCodec(valueType, (TypeToken) null)); } else { DataType keyType = (cqlType == null || cqlType.getTypeArguments().size() < 1) ? null : cqlType.getTypeArguments().get(0); DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2) ? null : cqlType.getTypeArguments().get(1); Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); return (TypeCodec<T>) TypeCodec.map( findCodec(keyType, entry.getKey()), findCodec(valueType, entry.getValue())); } } if ((cqlType == null || cqlType.getName() == VECTOR) && value instanceof List) { VectorType type = (VectorType) cqlType; return (TypeCodec<T>) TypeCodec.vector(type, findCodec(type.getSubtype(), null)); } if ((cqlType == null || cqlType.getName() == TUPLE) && value instanceof TupleValue) { return (TypeCodec<T>) TypeCodec.tuple(cqlType == null ? ((TupleValue) value).getType() : (TupleType) cqlType); } if ((cqlType == null || cqlType.getName() == UDT) && value instanceof UDTValue) { return (TypeCodec<T>) TypeCodec.userType(cqlType == null ? ((UDTValue) value).getType() : (UserType) cqlType); } if ((cqlType instanceof DataType.CustomType) && value instanceof ByteBuffer) { return (TypeCodec<T>) TypeCodec.custom((DataType.CustomType) cqlType); } return null; } private static CodecNotFoundException notFound(DataType cqlType, TypeToken<?> javaType) { String msg = String.format( "Codec not found for requested operation: [%s <-> %s]", toString(cqlType), toString(javaType)); return new CodecNotFoundException(msg); } private static String toString(Object value) { return value == null ? "ANY" : value.toString(); } }
apache/cassandra
src/java/org/apache/cassandra/cql3/functions/types/CodecRegistry.java
2,400
package com.crossoverjie.guava; import com.google.common.cache.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Function: * * @author crossoverJie * Date: 2018/6/12 15:33 * @since JDK 1.8 */ public class CacheLoaderTest { private final static Logger LOGGER = LoggerFactory.getLogger(CacheLoaderTest.class); private LoadingCache<Integer, AtomicLong> loadingCache ; private final static Integer KEY = 1000; private final static LinkedBlockingQueue<Integer> QUEUE = new LinkedBlockingQueue<>(1000); private void init() throws InterruptedException { loadingCache = CacheBuilder.newBuilder() .expireAfterWrite(2, TimeUnit.SECONDS) .removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> notification) { LOGGER.info("删除原因={},删除 key={},删除 value={}",notification.getCause(),notification.getKey(),notification.getValue()); } }) .build(new CacheLoader<Integer, AtomicLong>() { @Override public AtomicLong load(Integer key) throws Exception { return new AtomicLong(0); } }); for (int i = 10; i < 15; i++) { QUEUE.put(i); } } private void checkAlert(Integer integer) { try { //loadingCache.put(integer,new AtomicLong(integer)); TimeUnit.SECONDS.sleep(3); LOGGER.info("当前缓存值={},缓存大小={}", loadingCache.get(KEY),loadingCache.size()); LOGGER.info("缓存的所有内容={}",loadingCache.asMap().toString()); loadingCache.get(KEY).incrementAndGet(); } catch (ExecutionException e ) { LOGGER.error("Exception", e); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { CacheLoaderTest cacheLoaderTest = new CacheLoaderTest() ; cacheLoaderTest.init(); while (true) { try { Integer integer = QUEUE.poll(200, TimeUnit.MILLISECONDS); if (null == integer) { break; } //TimeUnit.SECONDS.sleep(5); cacheLoaderTest.checkAlert(integer); LOGGER.info("job running times={}", integer); } catch (InterruptedException e) { e.printStackTrace(); } } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/guava/CacheLoaderTest.java
2,401
// Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. // For example, // Given [[0, 30],[5, 10],[15, 20]], // return 2. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class MeetingRoomsII { public int minMeetingRooms(Interval[] intervals) { int[] starts = new int[intervals.length]; int[] ends = new int[intervals.length]; for(int i=0; i<intervals.length; i++) { starts[i] = intervals[i].start; ends[i] = intervals[i].end; } Arrays.sort(starts); Arrays.sort(ends); int rooms = 0; int endsItr = 0; for(int i=0; i<starts.length; i++) { if(starts[i]<ends[endsItr]) { rooms++; } else { endsItr++; } } return rooms; } }
kdn251/interviews
leetcode/sort/MeetingRoomsII.java
2,403
package com.thealgorithms.sorts; import static com.thealgorithms.sorts.SortUtils.less; /** * Generic merge sort algorithm. * * @see SortAlgorithm */ class MergeSort implements SortAlgorithm { private Comparable[] aux; /** * Generic merge sort algorithm implements. * * @param unsorted the array which should be sorted. * @param <T> Comparable class. * @return sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] unsorted) { aux = new Comparable[unsorted.length]; doSort(unsorted, 0, unsorted.length - 1); return unsorted; } /** * @param arr the array to be sorted. * @param left the first index of the array. * @param right the last index of the array. */ private <T extends Comparable<T>> void doSort(T[] arr, int left, int right) { if (left < right) { int mid = (left + right) >>> 1; doSort(arr, left, mid); doSort(arr, mid + 1, right); merge(arr, left, mid, right); } } /** * Merges two parts of an array. * * @param arr the array to be merged. * @param left the first index of the array. * @param mid the middle index of the array. * @param right the last index of the array merges two parts of an array in * increasing order. */ @SuppressWarnings("unchecked") private <T extends Comparable<T>> void merge(T[] arr, int left, int mid, int right) { int i = left, j = mid + 1; System.arraycopy(arr, left, aux, left, right + 1 - left); for (int k = left; k <= right; k++) { if (j > right) { arr[k] = (T) aux[i++]; } else if (i > mid) { arr[k] = (T) aux[j++]; } else if (less(aux[j], aux[i])) { arr[k] = (T) aux[j++]; } else { arr[k] = (T) aux[i++]; } } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/MergeSort.java
2,415
// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) { return -1; } else if (o1.val==o2.val) { return 0; } else { return 1; } } }); ListNode dummy = new ListNode(0); ListNode tail=dummy; for (ListNode node:lists) { if (node!=null) { queue.add(node); } } while (!queue.isEmpty()){ tail.next=queue.poll(); tail=tail.next; if (tail.next!=null) { queue.add(tail.next); } } return dummy.next; } }
kdn251/interviews
company/uber/MergeKSortedLists.java
2,430
/* * 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.apache.lucene.search.Explanation; import org.apache.lucene.search.Scorable; import org.elasticsearch.common.logging.DeprecationCategory; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.search.lookup.SearchLookup; import org.elasticsearch.search.lookup.Source; import java.io.IOException; import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; import java.util.function.DoubleSupplier; import java.util.function.Function; import java.util.function.Supplier; /** * A script used for adjusting the score on a per document basis. */ public abstract class ScoreScript extends DocBasedScript { /** A helper to take in an explanation from a script and turn it into an {@link org.apache.lucene.search.Explanation} */ public static class ExplanationHolder { private String description; /** * Explain the current score. * * @param description A textual description of how the score was calculated */ public void set(String description) { this.description = description; } public Explanation get(double score, Explanation subQueryExplanation) { if (description == null) { return null; } if (subQueryExplanation != null) { return Explanation.match(score, description, subQueryExplanation); } return Explanation.match(score, description); } } private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(DynamicMap.class); @SuppressWarnings("unchecked") private static final Map<String, Function<Object, Object>> PARAMS_FUNCTIONS = Map.of("doc", value -> { deprecationLogger.warn( DeprecationCategory.SCRIPTING, "score-script_doc", "Accessing variable [doc] via [params.doc] from within an score-script " + "is deprecated in favor of directly accessing [doc]." ); return value; }, "_doc", value -> { deprecationLogger.warn( DeprecationCategory.SCRIPTING, "score-script__doc", "Accessing variable [doc] via [params._doc] from within an score-script " + "is deprecated in favor of directly accessing [doc]." ); return value; }, "_source", value -> ((Supplier<Source>) value).get().source()); public static final String[] PARAMETERS = new String[] { "explanation" }; /** The generic runtime parameters for the script. */ private final Map<String, Object> params; private DoubleSupplier scoreSupplier = () -> 0.0; private final int docBase; private int docId; private int shardId = -1; private String indexName = null; public ScoreScript(Map<String, Object> params, SearchLookup searchLookup, DocReader docReader) { // searchLookup parameter is ignored but part of the ScriptFactory contract. It is part of that contract because it's required // for expressions. Expressions should eventually be transitioned to using DocReader. super(docReader); // null check needed b/c of expression engine subclass if (docReader == null) { assert params == null; this.params = null; ; this.docBase = 0; } else { params = new HashMap<>(params); params.putAll(docReader.docAsMap()); this.params = new DynamicMap(params, PARAMS_FUNCTIONS); this.docBase = ((DocValuesDocReader) docReader).getLeafReaderContext().docBase; } } public abstract double execute(ExplanationHolder explanation); /** Return the parameters for this script. */ public Map<String, Object> getParams() { return params; } /** Set the current document to run the script on next. */ public void setDocument(int docid) { super.setDocument(docid); this.docId = docid; } public void setScorer(Scorable scorer) { this.scoreSupplier = () -> { try { return scorer.score(); } catch (IOException e) { throw new UncheckedIOException(e); } }; } /** * Accessed as _score in the painless script * @return the score of the inner query */ public double get_score() { return scoreSupplier.getAsDouble(); } /** * Starting a name with underscore, so that the user cannot access this function directly through a script * It is only used within predefined painless functions. * @return the internal document ID */ public int _getDocId() { return docId; } /** * Starting a name with underscore, so that the user cannot access this function directly through a script * It is only used within predefined painless functions. * @return the internal document ID with the base */ public int _getDocBaseId() { return docBase + docId; } /** * Starting a name with underscore, so that the user cannot access this function directly through a script * It is only used within predefined painless functions. * @return shard id or throws an exception if shard is not set up for this script instance */ public int _getShardId() { if (shardId > -1) { return shardId; } else { throw new IllegalArgumentException("shard id can not be looked up!"); } } /** * Starting a name with underscore, so that the user cannot access this function directly through a script * It is only used within predefined painless functions. * @return index name or throws an exception if the index name is not set up for this script instance */ public String _getIndex() { if (indexName != null) { return indexName; } else { throw new IllegalArgumentException("index name can not be looked up!"); } } /** * Starting a name with underscore, so that the user cannot access this function directly through a script */ public void _setShard(int shardId) { this.shardId = shardId; } /** * Starting a name with underscore, so that the user cannot access this function directly through a script */ public void _setIndexName(String indexName) { this.indexName = indexName; } /** A factory to construct {@link ScoreScript} instances. */ public interface LeafFactory { /** * Return {@code true} if the script needs {@code _score} calculated, or {@code false} otherwise. */ boolean needs_score(); ScoreScript newInstance(DocReader reader) throws IOException; } /** A factory to construct stateful {@link ScoreScript} factories for a specific index. */ public interface Factory extends ScriptFactory { // searchLookup is used taken in for compatibility with expressions. See ExpressionScriptEngine.newScoreScript and // ExpressionScriptEngine.getDocValueSource for where it's used. ScoreScript.LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup); } public static final ScriptContext<ScoreScript.Factory> CONTEXT = new ScriptContext<>("score", ScoreScript.Factory.class); }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/script/ScoreScript.java
2,442
package com.thealgorithms.maths; import java.util.stream.StreamSupport; import org.apache.commons.collections4.IterableUtils; /** * https://en.wikipedia.org/wiki/Mean * <p> * by: Punit Patel */ public final class Means { private Means() { } /** * @brief computes the [Arithmetic Mean](https://en.wikipedia.org/wiki/Arithmetic_mean) of the input * @param numbers the input numbers * @throws IllegalArgumentException empty input * @return the arithmetic mean of the input numbers */ public static Double arithmetic(final Iterable<Double> numbers) { checkIfNotEmpty(numbers); return StreamSupport.stream(numbers.spliterator(), false).reduce((x, y) -> x + y).get() / IterableUtils.size(numbers); } /** * @brief computes the [Geometric Mean](https://en.wikipedia.org/wiki/Geometric_mean) of the input * @param numbers the input numbers * @throws IllegalArgumentException empty input * @return the geometric mean of the input numbers */ public static Double geometric(final Iterable<Double> numbers) { checkIfNotEmpty(numbers); return Math.pow(StreamSupport.stream(numbers.spliterator(), false).reduce((x, y) -> x * y).get(), 1d / IterableUtils.size(numbers)); } /** * @brief computes the [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) of the input * @param numbers the input numbers * @throws IllegalArgumentException empty input * @return the harmonic mean of the input numbers */ public static Double harmonic(final Iterable<Double> numbers) { checkIfNotEmpty(numbers); return IterableUtils.size(numbers) / StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + 1d / y); } private static void checkIfNotEmpty(final Iterable<Double> numbers) { if (!numbers.iterator().hasNext()) { throw new IllegalArgumentException("Emtpy list given for Mean computation."); } } }
ramedwararyan/JavaAlgo
src/main/java/com/thealgorithms/maths/Means.java
2,452
/* * 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.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to object arrays. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault @SuppressWarnings("AvoidObjectArrays") public final class ObjectArrays { private ObjectArrays() {} /** * Returns a new array of the given length with the specified component type. * * @param type the component type * @param length the length of the new array */ @GwtIncompatible // Array.newInstance(Class, int) @SuppressWarnings("unchecked") public static <T extends @Nullable Object> T[] newArray(Class<@NonNull T> type, int length) { return (T[]) Array.newInstance(type, length); } /** * Returns a new array of the given length with the same type as a reference array. * * @param reference any array of the desired type * @param length the length of the new array */ public static <T extends @Nullable Object> T[] newArray(T[] reference, int length) { return Platform.newArray(reference, length); } /** * Returns a new array that contains the concatenated contents of two arrays. * * @param first the first array of elements to concatenate * @param second the second array of elements to concatenate * @param type the component type of the returned array */ @GwtIncompatible // Array.newInstance(Class, int) public static <T extends @Nullable Object> T[] concat( T[] first, T[] second, Class<@NonNull T> type) { T[] result = newArray(type, first.length + second.length); System.arraycopy(first, 0, result, 0, first.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } /** * Returns a new array that prepends {@code element} to {@code array}. * * @param element the element to prepend to the front of {@code array} * @param array the array of elements to append * @return an array whose size is one larger than {@code array}, with {@code element} occupying * the first position, and the elements of {@code array} occupying the remaining elements. */ public static <T extends @Nullable Object> T[] concat(@ParametricNullness T element, T[] array) { T[] result = newArray(array, array.length + 1); result[0] = element; System.arraycopy(array, 0, result, 1, array.length); return result; } /** * Returns a new array that appends {@code element} to {@code array}. * * @param array the array of elements to prepend * @param element the element to append to the end * @return an array whose size is one larger than {@code array}, with the same contents as {@code * array}, plus {@code element} occupying the last position. */ public static <T extends @Nullable Object> T[] concat(T[] array, @ParametricNullness T element) { T[] result = Arrays.copyOf(array, array.length + 1); result[array.length] = element; return result; } /** * Returns an array containing all of the elements in the specified collection; the runtime type * of the returned array is that of the specified array. If the collection fits in the specified * array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the * specified array and the size of the specified collection. * * <p>If the collection fits in the specified array with room to spare (i.e., the array has more * elements than the collection), the element in the array immediately following the end of the * collection is set to {@code null}. This is useful in determining the length of the collection * <i>only</i> if the caller knows that the collection does not contain any null elements. * * <p>This method returns the elements in the order they are returned by the collection's * iterator. * * <p>TODO(kevinb): support concurrently modified collections? * * @param c the collection for which to return an array of elements * @param array the array in which to place the collection elements * @throws ArrayStoreException if the runtime type of the specified array is not a supertype of * the runtime type of every element in the specified collection */ static <T extends @Nullable Object> T[] toArrayImpl(Collection<?> c, T[] array) { int size = c.size(); if (array.length < size) { array = newArray(array, size); } fillArray(c, array); if (array.length > size) { @Nullable Object[] unsoundlyCovariantArray = array; unsoundlyCovariantArray[size] = null; } return array; } /** * Implementation of {@link Collection#toArray(Object[])} for collections backed by an object * array. the runtime type of the returned array is that of the specified array. If the collection * fits in the specified array, it is returned therein. Otherwise, a new array is allocated with * the runtime type of the specified array and the size of the specified collection. * * <p>If the collection fits in the specified array with room to spare (i.e., the array has more * elements than the collection), the element in the array immediately following the end of the * collection is set to {@code null}. This is useful in determining the length of the collection * <i>only</i> if the caller knows that the collection does not contain any null elements. */ static <T extends @Nullable Object> T[] toArrayImpl( @Nullable Object[] src, int offset, int len, T[] dst) { checkPositionIndexes(offset, offset + len, src.length); if (dst.length < len) { dst = newArray(dst, len); } else if (dst.length > len) { @Nullable Object[] unsoundlyCovariantArray = dst; unsoundlyCovariantArray[len] = null; } System.arraycopy(src, offset, dst, 0, len); return dst; } /** * Returns an array containing all of the elements in the specified collection. This method * returns the elements in the order they are returned by the collection's iterator. The returned * array is "safe" in that no references to it are maintained by the collection. The caller is * thus free to modify the returned array. * * <p>This method assumes that the collection size doesn't change while the method is running. * * <p>TODO(kevinb): support concurrently modified collections? * * @param c the collection for which to return an array of elements */ static @Nullable Object[] toArrayImpl(Collection<?> c) { return fillArray(c, new Object[c.size()]); } /** * Returns a copy of the specified subrange of the specified array that is literally an Object[], * and not e.g. a {@code String[]}. */ static @Nullable Object[] copyAsObjectArray(@Nullable Object[] elements, int offset, int length) { checkPositionIndexes(offset, offset + length, elements.length); if (length == 0) { return new Object[0]; } @Nullable Object[] result = new Object[length]; System.arraycopy(elements, offset, result, 0, length); return result; } @CanIgnoreReturnValue private static @Nullable Object[] fillArray(Iterable<?> elements, @Nullable Object[] array) { int i = 0; for (Object element : elements) { array[i++] = element; } return array; } /** Swaps {@code array[i]} with {@code array[j]}. */ static void swap(Object[] array, int i, int j) { Object temp = array[i]; array[i] = array[j]; array[j] = temp; } @CanIgnoreReturnValue static Object[] checkElementsNotNull(Object... array) { return checkElementsNotNull(array, array.length); } @CanIgnoreReturnValue static Object[] checkElementsNotNull(Object[] array, int length) { for (int i = 0; i < length; i++) { checkElementNotNull(array[i], i); } return array; } // We do this instead of Preconditions.checkNotNull to save boxing and array // creation cost. @CanIgnoreReturnValue static Object checkElementNotNull(Object element, int index) { if (element == null) { throw new NullPointerException("at index " + index); } return element; } }
google/guava
guava/src/com/google/common/collect/ObjectArrays.java