diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java index 4b652d30df..66b7189524 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java @@ -46,7 +46,7 @@ public class BusRoutesResult { return sites; } - public void setSite(List site) { + public void setSites(List sites) { this.sites = sites; } diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java index 7921c1dd80..d507fab4f1 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java @@ -11,7 +11,6 @@ import androidx.annotation.NonNull; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.RecyclerView; -import androidx.recyclerview.widget.SimpleItemAnimator; import java.util.ArrayList; import java.util.List; @@ -28,10 +27,10 @@ public class OpenItemAnimator extends DefaultItemAnimator { private static TimeInterpolator sDefaultInterpolator; - private ArrayList mPendingRemovals = new ArrayList<>(); - private ArrayList mPendingAdditions = new ArrayList<>(); - private ArrayList mPendingMoves = new ArrayList<>(); - private ArrayList mPendingChanges = new ArrayList<>(); + private final ArrayList mPendingRemovals = new ArrayList<>(); + private final ArrayList mPendingAdditions = new ArrayList<>(); + private final ArrayList mPendingMoves = new ArrayList<>(); + private final ArrayList mPendingChanges = new ArrayList<>(); private ArrayList> mAdditionsList = new ArrayList<>(); private ArrayList> mMovesList = new ArrayList<>(); @@ -102,20 +101,16 @@ public class OpenItemAnimator extends DefaultItemAnimator { mPendingRemovals.clear(); // Next, move stuff if (movesPending) { - final ArrayList moves = new ArrayList<>(); - moves.addAll(mPendingMoves); + final ArrayList moves = new ArrayList<>(mPendingMoves); mMovesList.add(moves); mPendingMoves.clear(); - Runnable mover = new Runnable() { - @Override - public void run() { - for (MoveInfo moveInfo : moves) { - animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, - moveInfo.toX, moveInfo.toY); - } - moves.clear(); - mMovesList.remove(moves); + Runnable mover = () -> { + for (MoveInfo moveInfo : moves) { + animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, + moveInfo.toX, moveInfo.toY); } + moves.clear(); + mMovesList.remove(moves); }; if (removalsPending) { View view = moves.get(0).holder.itemView; @@ -126,19 +121,15 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // Next, change stuff, to run in parallel with move animations if (changesPending) { - final ArrayList changes = new ArrayList<>(); - changes.addAll(mPendingChanges); + final ArrayList changes = new ArrayList<>(mPendingChanges); mChangesList.add(changes); mPendingChanges.clear(); - Runnable changer = new Runnable() { - @Override - public void run() { - for (ChangeInfo change : changes) { - animateChangeImpl(change); - } - changes.clear(); - mChangesList.remove(changes); + Runnable changer = () -> { + for (ChangeInfo change : changes) { + animateChangeImpl(change); } + changes.clear(); + mChangesList.remove(changes); }; if (removalsPending) { RecyclerView.ViewHolder holder = changes.get(0).oldHolder; @@ -149,19 +140,15 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // Next, add stuff if (additionsPending) { - final ArrayList additions = new ArrayList<>(); - additions.addAll(mPendingAdditions); + final ArrayList additions = new ArrayList<>(mPendingAdditions); mAdditionsList.add(additions); mPendingAdditions.clear(); - Runnable adder = new Runnable() { - @Override - public void run() { - for (RecyclerView.ViewHolder holder : additions) { - animateAddImpl(holder); - } - additions.clear(); - mAdditionsList.remove(additions); + Runnable adder = () -> { + for (RecyclerView.ViewHolder holder : additions) { + animateAddImpl(holder); } + additions.clear(); + mAdditionsList.remove(additions); }; if (removalsPending || movesPending || changesPending) { long removeDuration = removalsPending ? getRemoveDuration() : 0; @@ -480,25 +467,25 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // animations should be ended by the cancel above. - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mRemoveAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mRemoveAnimations list"); } - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mAddAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mAddAnimations list"); } - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mChangeAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mChangeAnimations list"); } - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mMoveAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mMoveAnimations list"); diff --git a/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java b/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java index a8ae762168..f4218e1544 100644 --- a/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java +++ b/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java @@ -13,13 +13,17 @@ public class CollectionUtils { OkHttpClient okHttpClient = OkHttpFactory.Companion.getOkHttpClient(); List interceptors = okHttpClient.interceptors(); Field pro = getDeclaredField(interceptors, "list"); - pro.setAccessible(true); - List modifyerList = null; - try { - modifyerList = (List) pro.get(interceptors); - modifyerList.add(new SimpleInterceptor()); - } catch (IllegalAccessException e) { - e.printStackTrace(); + if(pro != null){ + pro.setAccessible(true); + List modifierList; + try { + modifierList = (List) pro.get(interceptors); + if(modifierList != null){ + modifierList.add(new SimpleInterceptor()); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } } } /** @@ -32,7 +36,10 @@ public class CollectionUtils { * @since:2019年2月26日 下午4:06:16 */ public static Field getDeclaredField(Object object, String fieldName){ - Field field = null ; + if(fieldName == null){ + return null; + } + Field field; Class clazz = object.getClass() ; for(; clazz != Object.class ; clazz = clazz.getSuperclass()) { try { diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java index 2a88ec1dd2..4f8e8db05e 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java @@ -14,7 +14,7 @@ public class NumberFormatUtil { * @return */ public static String formatLong(double d) { - BigDecimal bg = new BigDecimal(d).setScale(1, RoundingMode.HALF_UP); + BigDecimal bg = BigDecimal.valueOf(d).setScale(1, RoundingMode.HALF_UP); double num = bg.doubleValue(); if (Math.ceil(num) - num == 0) { return String.valueOf((long) num); diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java index bd549f2888..5a03ce7e90 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java @@ -26,7 +26,7 @@ public class MarqueeTextView extends androidx.appcompat.widget.AppCompatTextView /** * 是否使用自定义 gap */ - private boolean mUseCustomGap; + private final boolean mUseCustomGap; public MarqueeTextView(Context context) { this(context, null); @@ -60,7 +60,6 @@ public class MarqueeTextView extends androidx.appcompat.widget.AppCompatTextView @Override public void onWindowFocusChanged(boolean hasWindowFocus) { - if (hasWindowFocus){} super.onWindowFocusChanged(true); } diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java index 08b77de55c..7b9632b2ae 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java @@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; */ public class FrameSurfaceView extends BaseSurfaceView { public static final int INVALID_INDEX = Integer.MAX_VALUE; - private int bufferSize = 3; + private final int bufferSize = 3; public static final String DECODE_THREAD_NAME = "DecodingThread"; public static final int INFINITE = -1; //-1 means repeat infinitely @@ -45,12 +45,12 @@ public class FrameSurfaceView extends BaseSurfaceView { * decoded bitmaps stores in this queue * consumer is drawing thread, producer is decoding thread. */ - private LinkedBlockingQueue decodedBitmaps = new LinkedBlockingQueue(bufferSize); + private final LinkedBlockingQueue decodedBitmaps = new LinkedBlockingQueue(bufferSize); /** * bitmaps already drawn by canvas stores in this queue * consumer is decoding thread, producer is drawing thread. */ - private LinkedBlockingQueue drawnBitmaps = new LinkedBlockingQueue(bufferSize); + private final LinkedBlockingQueue drawnBitmaps = new LinkedBlockingQueue(bufferSize); /** * the thread for decoding bitmaps */ @@ -64,9 +64,9 @@ public class FrameSurfaceView extends BaseSurfaceView { */ private Handler handler; private BitmapFactory.Options options; - private Paint paint = new Paint(); + private final Paint paint = new Paint(); private Rect srcRect; - private Rect dstRect = new Rect(); + private final Rect dstRect = new Rect(); private int defaultWidth; private int defaultHeight; @@ -138,7 +138,7 @@ public class FrameSurfaceView extends BaseSurfaceView { return; } this.bitmapIds = bitmapIds; - //by default, take the first bitmap's dimension into consideration + //by default, take the first bitMap's dimension into consideration getBitmapDimension(bitmapIds.get(bitmapIdIndex)); preloadFrames(); decodeRunnable = new DecodeRunnable(bitmapIdIndex, bitmapIds, options); @@ -322,8 +322,7 @@ public class FrameSurfaceView extends BaseSurfaceView { * @param linkedBitmap */ private void decodeAndPutBitmap(int resId, BitmapFactory.Options options, LinkedBitmap linkedBitmap) { - Bitmap bitmap = decodeBitmap(resId, options); - linkedBitmap.bitmap = bitmap; + linkedBitmap.bitmap = decodeBitmap(resId, options); try { decodedBitmaps.put(linkedBitmap); } catch (InterruptedException e) { @@ -377,8 +376,8 @@ public class FrameSurfaceView extends BaseSurfaceView { private class DecodeRunnable implements Runnable { private int index; - private List bitmapIds; - private BitmapFactory.Options options; + private final List bitmapIds; + private final BitmapFactory.Options options; public DecodeRunnable(int index, List bitmapIds, BitmapFactory.Options options) { this.index = index; diff --git a/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml b/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml index 4af9cb07d9..6a04f38ead 100644 --- a/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml +++ b/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml @@ -4,8 +4,7 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" - android:background="@drawable/road_video_bg" - tools:context="com.mogo.eagle.core.function.main.VideoAdAtc"> + android:background="@drawable/road_video_bg"> { - ToastUtils.showLong("读取失败=" + err); - }); - } - - @Override - public void onParseFailed(String err) { - ToastUtils.showLong("解析失败=" + err); - } - - @Override - public void onParse(MessagePad.SetAutopilotModeReq bean) { - ToastUtils.showLong("下发命令\n" + TextFormat.printer().escapingNonAscii(false).printToString(bean)); - AutopilotControlParameters parameters = new AutopilotControlParameters(); - MessagePad.RouteInfo routeInfo = bean.getRouteInfo(); - if (routeInfo.getRouteID() > 0) { - parameters.routeID = routeInfo.getRouteID(); - } - parameters.routeName = routeInfo.getRouteName(); - parameters.startName = routeInfo.getStartName();//拼音 - parameters.endName = routeInfo.getEndName();//拼音 - parameters.startLatLon = new AutopilotControlParameters - .AutoPilotLonLat(routeInfo.getStartLocation().getLatitude(), routeInfo.getStartLocation().getLongitude()); - parameters.endLatLon = new AutopilotControlParameters - .AutoPilotLonLat(routeInfo.getEndLocation().getLatitude(), routeInfo.getEndLocation().getLongitude()); - parameters.vehicleType = 10; - MessagePad.Line line = routeInfo.getLine(); - parameters.autoPilotLine = new AutopilotControlParameters.AutoPilotLine( - line.getLineId(), line.getLineName(), - line.getTrajUrl(), line.getTrajMd5(), - line.getStopUrl(), line.getStopMd5(), - line.getTimestamp(), line.getVehicleModel(), - line.getTrajUrlDpqp(), line.getTrajMd5Dpqp(), - line.getStopUrlDpqp(), line.getStopMd5Dpqp(), - line.getTimestampDpqp()); - CallerAutoPilotControlManager.INSTANCE.startAutoPilot(parameters); - } - }).read(); + findViewById(R.id.btnStartAutopilot).setOnClickListener(v -> { + if (!FunctionBuildConfig.isDemoMode && !OCHAdasAbilityManager.getInstance().getAutopilotAbilityStatus()) { + ToastUtils.showLong(OCHAdasAbilityManager.getInstance().getAutopilotUnAbilityReason() + ", 请稍候重试"); + return; } + new AutopilotModeConfigManager(new AutopilotModeConfigManager.OnReadAutopilotModeConfigListener() { + @Override + public void onReadFailed(String err) { + ThreadUtils.runOnUiThread(() -> { + ToastUtils.showLong("读取失败=" + err); + }); + } + + @Override + public void onParseFailed(String err) { + ToastUtils.showLong("解析失败=" + err); + } + + @Override + public void onParse(MessagePad.SetAutopilotModeReq bean) { + ToastUtils.showLong("下发命令\n" + TextFormat.printer().escapingNonAscii(false).printToString(bean)); + AutopilotControlParameters parameters = new AutopilotControlParameters(); + MessagePad.RouteInfo routeInfo = bean.getRouteInfo(); + if (routeInfo.getRouteID() > 0) { + parameters.routeID = routeInfo.getRouteID(); + } + parameters.routeName = routeInfo.getRouteName(); + parameters.startName = routeInfo.getStartName();//拼音 + parameters.endName = routeInfo.getEndName();//拼音 + parameters.startLatLon = new AutopilotControlParameters + .AutoPilotLonLat(routeInfo.getStartLocation().getLatitude(), routeInfo.getStartLocation().getLongitude()); + parameters.endLatLon = new AutopilotControlParameters + .AutoPilotLonLat(routeInfo.getEndLocation().getLatitude(), routeInfo.getEndLocation().getLongitude()); + parameters.vehicleType = 10; + MessagePad.Line line = routeInfo.getLine(); + parameters.autoPilotLine = new AutopilotControlParameters.AutoPilotLine( + line.getLineId(), line.getLineName(), + line.getTrajUrl(), line.getTrajMd5(), + line.getStopUrl(), line.getStopMd5(), + line.getTimestamp(), line.getVehicleModel(), + line.getTrajUrlDpqp(), line.getTrajMd5Dpqp(), + line.getStopUrlDpqp(), line.getStopMd5Dpqp(), + line.getTimestampDpqp()); + CallerAutoPilotControlManager.INSTANCE.startAutoPilot(parameters); + } + }).read(); }); // 模拟 查询当前任务 findViewById(R.id.btnQueryCurrentTask).setOnClickListener(view -> @@ -437,7 +434,6 @@ public abstract class BaseSweeperTabFragment { - // TODO: 2021/12/9 CallerHmiManager.INSTANCE.showToolsView(); }); if (mCardBtn != null) { @@ -458,8 +454,8 @@ public abstract class BaseSweeperTabFragment msgTypeAndReqNo = new HashMap<>(); + private final HashMap msgTypeAndReqNo = new HashMap<>(); public static SweeperTaskModel getInstance() { if (sInstance == null) { @@ -149,38 +148,35 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM //2022.1.28 // 调用Disposable.dispose() 时候会出现InterruptedException 导致出现崩溃 // The exception could not be delivered to the consumer because it has already canceled/disposed - // the flow or the excTeption has nowhere to go to begin with - RxJavaPlugins.setErrorHandler(new Consumer() { - @Override - public void accept(Throwable e) { - if (e instanceof UndeliverableException) { - e = e.getCause(); - CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); - } - if ((e instanceof IOException)) {// - // fine, irrelevant network problem or API that throws on cancellation - CallerLogger.d(M_SWEEPER + TAG, "IOException"); - return; - } - if (e instanceof InterruptedException) { - // fine, some blocking code was interrupted by a dispose call - CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); - return; - } - if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { - // that's likely a bug in the application - CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - if (e instanceof IllegalStateException) { - // that's a bug in RxJava or in a custom operator - CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); + // the flow or the exception has nowhere to go to begin with + RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); } + if ((e instanceof IOException)) {// + // fine, irrelevant network problem or API that throws on cancellation + CallerLogger.d(M_SWEEPER + TAG, "IOException"); + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); }); } @@ -279,11 +275,6 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM OCHAdasAbilityManager.getInstance().setAdasStartFailureCallback(null); } - private Object readResolve() { - // 阻止反序列化,必须实现 Serializable 接口 - return sInstance; - } - private final IMogoStatusChangedListener mMogoStatusChangedListener = new IMogoStatusChangedListener() { // VR mode变更回调 @Override @@ -424,9 +415,6 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM @Override public void onSweeperFutianCleanSystemState(@NonNull ChassisStatesOuterClass.SweeperFuTianTaskSystemStates cleanSystemState) { - if (cleanSystemState == null) { - return; - } long current = System.currentTimeMillis(); if (current - mVehicleStateCurrentTimeMillis <= VEHICLE_STATE_INTERVAL_MILLIS) { return; @@ -506,7 +494,7 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM } private static String format(double value) { - BigDecimal bd = new BigDecimal(value); + BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(2, RoundingMode.HALF_UP); return bd.toString(); } @@ -688,18 +676,18 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM if (mControllerStatusCallback != null) { mControllerStatusCallback.onAutopilotState(state); } - switch (state) { - case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_DISABLE://不可自动驾驶 - break; - case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_ENABLE://人工驾驶 - break; - case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_RUNNING://自动驾驶中 - break; - case IMoGoAutopilotStatusListener.STATUS_PARALLEL_DRIVING://平行驾驶 - break; - default: - break; - } +// switch (state) { +// case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_DISABLE://不可自动驾驶 +// break; +// case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_ENABLE://人工驾驶 +// break; +// case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_RUNNING://自动驾驶中 +// break; +// case IMoGoAutopilotStatusListener.STATUS_PARALLEL_DRIVING://平行驾驶 +// break; +// default: +// break; +// } } @Override diff --git a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java index ac2436d4f6..6f14326a7c 100644 --- a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java +++ b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java @@ -36,14 +36,14 @@ public class SweeperProvider implements IMogoOCH { FragmentManager supportFragmentManager = activity.getSupportFragmentManager(); if (sweeperFragment == null) { CallerLogger.d(TAG, "准备add fragment======"); - Fragment fragmentByTag = supportFragmentManager.findFragmentByTag(sweeperFragment.TAG); + Fragment fragmentByTag = supportFragmentManager.findFragmentByTag(SweeperFragment.TAG); if (fragmentByTag instanceof SweeperFragment) { sweeperFragment = (SweeperFragment) fragmentByTag; } else { sweeperFragment = new SweeperFragment(); } if(!sweeperFragment.isAdded()) { - supportFragmentManager.beginTransaction().add(containerId, sweeperFragment, sweeperFragment.TAG).commitAllowingStateLoss(); + supportFragmentManager.beginTransaction().add(containerId, sweeperFragment, SweeperFragment.TAG).commitAllowingStateLoss(); } return; } diff --git a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java index cb8754febb..e9fc880d3e 100644 --- a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java +++ b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java @@ -408,8 +408,8 @@ public abstract class BaseSweeperTabFragment() { - @Override - public void accept(Throwable e) { - if (e instanceof UndeliverableException) { - e = e.getCause(); - CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); - } - if ((e instanceof IOException)) {// - // fine, irrelevant network problem or API that throws on cancellation - CallerLogger.d(M_SWEEPER + TAG, "IOException"); - return; - } - if (e instanceof InterruptedException) { - // fine, some blocking code was interrupted by a dispose call - CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); - return; - } - if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { - // that's likely a bug in the application - CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - if (e instanceof IllegalStateException) { - // that's a bug in RxJava or in a custom operator - CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); + // the flow or the exception has nowhere to go to begin with + RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); } + if ((e instanceof IOException)) { + // fine, irrelevant network problem or API that throws on cancellation + CallerLogger.d(M_SWEEPER + TAG, "IOException"); + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); }); } @@ -191,7 +188,7 @@ public class SweeperTaskModel { @Override public void onAutopilotRotting(MessagePad.GlobalPathResp routeList) { - if (null != routeList && routeList.getWayPointsList()!=null&&routeList.getWayPointsList().size() > 0) { + if (null != routeList && routeList.getWayPointsList().size() > 0) { if (mCurrentSubTaskDetail.getLineId() != mLineId) {//判断是否同一条路线 mLineId = mCurrentSubTaskDetail.getLineId(); points.addAll(coordinateConverterWgsToGcjList(mContext, routeList.getWayPointsList())); @@ -316,7 +313,6 @@ public class SweeperTaskModel { } if (SubTaskTypeEnum.MANUAL_DRIVING_SUBTYPE.getCode() == mSubTaskType) {//人工驾驶子任务需要手动跳过,不能自动结束 addCoordinates(gnssInfo); - return; } //子任务完成的围栏判断 子任务正在执行中,还未到达子任务终点 //20230504 为了避免自车定位提前结束任务导致的溜车问题,这里删除自车自动触发到站 @@ -365,7 +361,6 @@ public class SweeperTaskModel { isAutopilotSubTaskArriveEndSite = true; //到达子任务终点 结束子任务 subTaskEnd(mIsFirstSubtask, mIsLastSubtask, mSubTaskId); //无自动驾驶到终点信息传null - return; } } @@ -393,10 +388,6 @@ public class SweeperTaskModel { firstStartAutopilot++; triggerStartServiceEvent(isRestart, false); AutopilotControlParameters parameters = initAutopilotControlParameters(); - if (null == parameters) { - CallerLogger.e(M_SWEEPER + TAG, "行程日志-AutopilotControlParameters is empty."); - return; - } CallerAutoPilotControlManager.INSTANCE.startAutoPilot(parameters); CallerLogger.d(M_SWEEPER + TAG, "行程日志-开启自动驾驶====" + GsonUtil.jsonFromObject(parameters) + " startLatLon=" + parameters.startName + ",endLatLon=" + parameters.endName + @@ -496,10 +487,6 @@ public class SweeperTaskModel { private void updateAutopilotControlParameters() { AutopilotControlParameters parameters = initAutopilotControlParameters(); - if (null == parameters) { - CallerLogger.e(M_SWEEPER + TAG, "AutopilotControlParameters is empty."); - return; - } CallerLogger.d(M_SWEEPER + TAG, "AutopilotControlParameters" + GsonUtil.jsonFromObject(parameters)); CallerLogger.d(M_SWEEPER + TAG, "AutopilotControlParameters is update."); CallerAutoPilotStatusListenerManager.INSTANCE.updateAutopilotControlParameters(parameters); diff --git a/codequality/sonar.gradle b/codequality/sonar.gradle index f89383eec0..b075d553c0 100644 --- a/codequality/sonar.gradle +++ b/codequality/sonar.gradle @@ -11,7 +11,7 @@ sonarqube { property "sonar.android.lint.report", false property "sonar.scm.exclusions.disabled", false property "sonar.scm.exclusions.file", "**/.gitignore" - property "sonar.exclusions", "**/AndroidManifest.xml, **/src/test/**, **/*.jar, **/*.aar, **/*.war, **/*.ear, **/*.rar, **/*.tgz, **/*.zip, **/src/test/java/**/*.java, **/src/test/java/**/*.kt, **/test/**/*, **/*Test.java, **/*Tests.java, **/*Test.kt, **/*.xml,*.xml, **/target/**, **/src/main/java/proto/**, **/build/**, build, build/**, **/db/dao/*.java, **/build/intermediates/**/*" + property "sonar.exclusions", "**/AndroidManifest.xml, **/src/test/**, mogo/core/utils/**, **/*.jar, **/*.aar, **/*.war, **/*.ear, **/*.rar, **/*.tgz, **/*.zip, **/src/test/java/**/*.java, **/src/test/java/**/*.kt, **/test/**/*, **/*Test.java, **/*Tests.java, **/*Test.kt, **/*.xml,*.xml, **/target/**, **/src/main/java/proto/**, **/build/**, build, build/**, **/db/dao/*.java, **/build/intermediates/**/*" // property "sonar.java.coveragePlugin", "jacoco" // property("sonar.coverage.jacoco.xmlReportPaths", "../../build/reports/jacocoTestReport.xml,../build/reports/jacocoTestReport.xml") } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml b/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml index b3e12745bc..f3f3138647 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml +++ b/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml @@ -96,21 +96,6 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/AllAllowedHostnameVerifier.java b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/AllAllowedHostnameVerifier.java deleted file mode 100644 index f0c9f355bb..0000000000 --- a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/AllAllowedHostnameVerifier.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.mogo.eagle.core.network; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; - -/** - * @author congtaowang - * @since 2019-08-30 - *

- * 信任所有域名 - */ -public class AllAllowedHostnameVerifier implements HostnameVerifier { - - @Override - public boolean verify( String hostname, SSLSession session ) { - return true; - } -} diff --git a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java index 4a6ea80e02..aa04ee8c2a 100644 --- a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java +++ b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java @@ -3,8 +3,6 @@ package com.mogo.eagle.core.network; import android.app.Application; import android.content.Context; -import com.mogo.cloud.passport.SpStorage; - import androidx.collection.ArraySet; import java.security.SecureRandom; @@ -13,7 +11,6 @@ import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import okhttp3.Interceptor; @@ -34,15 +31,10 @@ public final class NetConfig { private final Set< Interceptor > interceptors = new ArraySet<>(); private final Set< Interceptor > networkInterceptors = new ArraySet<>(); - private final HostnameVerifier allowAllHostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify( String hostname, SSLSession session ) { - return true; - } - }; + private final HostnameVerifier allowAllHostnameVerifier = (hostname, session) -> true; private String signaturePrefix = "com.foundation.network"; - private HostnameVerifier hostnameVerifier = OkHostnameVerifier.INSTANCE; + private final HostnameVerifier hostnameVerifier = OkHostnameVerifier.INSTANCE; private Map< String, Object > publicParams; private boolean isLoggable; private Context appContext; diff --git a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java index 15e17ede03..a59abcf7dd 100644 --- a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java +++ b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java @@ -1,5 +1,7 @@ package com.mogo.eagle.core.network; +import android.annotation.SuppressLint; + import java.security.cert.CertificateException; import java.security.cert.X509Certificate; @@ -13,11 +15,13 @@ import javax.net.ssl.X509TrustManager; */ public class X509TrustManagerImpl implements X509TrustManager { + @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted( X509Certificate[] chain, String authType ) throws CertificateException { } + @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted( X509Certificate[] chain, String authType ) throws CertificateException { diff --git a/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java b/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java index 5dd31a933a..3669e249bb 100644 --- a/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java +++ b/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java @@ -43,7 +43,6 @@ import java.util.Map; * provides various display options such as scaling and tinting. */ public class TextureVideoView extends TextureView implements MediaPlayerControl { - private String TAG = "TextureVideoView"; public static final int STATE_ERROR = -1; public static final int STATE_IDLE = 0; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java index fa97d2b814..1f13b04f59 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java @@ -38,9 +38,9 @@ public class GlideCircleBitmapTransform extends BitmapTransformation { int radius = newSize / 2; Bitmap bitmap = Bitmap.createBitmap( toTransform, x, y, newSize, newSize ); Bitmap result = pool.get( newSize, newSize, toTransform.getConfig() ); - if ( result == null ) { - result = Bitmap.createBitmap( newSize, newSize, toTransform.getConfig() ); - } +// if ( result == null ) { //get() func always return not null +// result = Bitmap.createBitmap( newSize, newSize, toTransform.getConfig() ); +// } Canvas canvas = new Canvas( result ); if ( mBorderWidth > 0 ) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java index fe2a63f1d5..44c13b5133 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java @@ -18,11 +18,11 @@ import java.security.MessageDigest; public class GlideRoundBitmapTransform extends BitmapTransformation { - private int mRadius; - private int mBorderWidth; - private int mBorderColor; - private String mKey; - private Context mContext; + private final int mRadius; + private final int mBorderWidth; + private final int mBorderColor; + private final String mKey; + private final Context mContext; public GlideRoundBitmapTransform( Context context, String key, int radius, int borderWidth, int borderColor ) { this.mContext = context; @@ -41,9 +41,9 @@ public class GlideRoundBitmapTransform extends BitmapTransformation { int height = toTransform.getHeight(); RectF rectF = new RectF( mBorderWidth, mBorderWidth, width - mBorderWidth, height - mBorderWidth ); Bitmap result = pool.get( width, height, toTransform.getConfig() ); - if ( result == null ) { - result = toTransform.copy( toTransform.getConfig(), true ); - } +// if ( result == null ) { //get() func always return not null +// result = toTransform.copy( toTransform.getConfig(), true ); +// } Canvas canvas = new Canvas( result ); Paint paint = new Paint(); paint.setShader( new BitmapShader( toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP ) ); diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java index a16f333132..c1cee04393 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java @@ -22,8 +22,8 @@ import androidx.annotation.NonNull; * @author tongchenfei */ public class GlideRoundedCornersTransform extends CenterCrop { - private float mRadius; - private CornerType mCornerType; + private final float mRadius; + private final CornerType mCornerType; private static final int VERSION = 1; private static final String ID = BuildConfig.LIBRARY_PACKAGE_NAME + "GlideRoundedCornersTransform." + VERSION; private static final byte[] ID_BYTES = ID.getBytes(CHARSET); @@ -62,10 +62,10 @@ public class GlideRoundedCornersTransform extends CenterCrop { int height = source.getHeight(); Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); - if (result == null) { - result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config - .ARGB_8888); - } +// if (result == null) { //get() func always return not null +// result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config +// .ARGB_8888); +// } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader @@ -102,6 +102,7 @@ public class GlideRoundedCornersTransform extends CenterCrop { drawPath(rids, canvas, paint, path, width, height); break; case TOP: + case TOP_LEFT_TOP_RIGHT: rids = new float[]{mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f}; drawPath(rids, canvas, paint, path, width, height); break; @@ -133,10 +134,6 @@ public class GlideRoundedCornersTransform extends CenterCrop { rids = new float[]{0.0f, 0.0f, mRadius, mRadius, mRadius, mRadius, mRadius, mRadius}; drawPath(rids, canvas, paint, path, width, height); break; - case TOP_LEFT_TOP_RIGHT: - rids = new float[]{mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f}; - drawPath(rids, canvas, paint, path, width, height); - break; default: throw new RuntimeException("RoundedCorners type not belong to CornerType"); } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java index d8ce1700e3..1379120eda 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java @@ -107,7 +107,7 @@ final class LoggerPrinter implements Printer { } } - private static final String xmlHtml = "http://xml.apache.org/xslt"; + private static final String xmlHtml = "{http://xml.apache.org/xslt}indent-amount"; public void xml( String tag, String xml) { if ( TextUtils.isEmpty(xml)) { @@ -118,7 +118,7 @@ final class LoggerPrinter implements Printer { StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent", "yes"); - transformer.setOutputProperty("{" + xmlHtml + "}indent-amount", "2"); + transformer.setOutputProperty(xmlHtml, "2"); transformer.transform(e, xmlOutput); this.d(tag, xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); } catch ( TransformerException var5) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ArrayUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ArrayUtils.java deleted file mode 100644 index 8949cd34a9..0000000000 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ArrayUtils.java +++ /dev/null @@ -1,2143 +0,0 @@ -package com.mogo.eagle.core.utilcode.util; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -/** - *

- *     author: blankj
- *     blog  : http://blankj.com
- *     time  : 2019/08/10
- *     desc  : utils about array
- * 
- */ -public class ArrayUtils { - - public static final int INDEX_NOT_FOUND = -1; - - private ArrayUtils() { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - /** - * Returns a new array only of those given elements. - * - * @param array The array. - * @return a new array only of those given elements. - */ - @NonNull - public static T[] newArray(T... array) { - return array; - } - - @NonNull - public static long[] newLongArray(long... array) { - return array; - } - - @NonNull - public static int[] newIntArray(int... array) { - return array; - } - - @NonNull - public static short[] newShortArray(short... array) { - return array; - } - - @NonNull - public static char[] newCharArray(char... array) { - return array; - } - - @NonNull - public static byte[] newByteArray(byte... array) { - return array; - } - - @NonNull - public static double[] newDoubleArray(double... array) { - return array; - } - - @NonNull - public static float[] newFloatArray(float... array) { - return array; - } - - @NonNull - public static boolean[] newBooleanArray(boolean... array) { - return array; - } - - /** - * Return the array is empty. - * - * @param array The array. - * @return {@code true}: yes
{@code false}: no - */ - public static boolean isEmpty(@Nullable Object array) { - return getLength(array) == 0; - } - - /** - * Return the size of array. - * - * @param array The array. - * @return the size of array - */ - public static int getLength(@Nullable Object array) { - if (array == null) return 0; - return Array.getLength(array); - } - - public static boolean isSameLength(@Nullable Object array1, @Nullable Object array2) { - return getLength(array1) == getLength(array2); - } - - /** - * Get the value of the specified index of the array. - * - * @param array The array. - * @param index The index into the array. - * @return the value of the specified index of the array - */ - @Nullable - public static Object get(@Nullable Object array, int index) { - return get(array, index, null); - } - - /** - * Get the value of the specified index of the array. - * - * @param array The array. - * @param index The index into the array. - * @param defaultValue The default value. - * @return the value of the specified index of the array - */ - @Nullable - public static Object get(@Nullable Object array, int index, @Nullable Object defaultValue) { - if (array == null) return defaultValue; - try { - return Array.get(array, index); - } catch (Exception ignore) { - return defaultValue; - } - } - - /** - * Set the value of the specified index of the array. - * - * @param array The array. - * @param index The index into the array. - * @param value The new value of the indexed component. - */ - public static void set(@Nullable Object array, int index, @Nullable Object value) { - if (array == null) return; - Array.set(array, index, value); - } - - /** - * Return whether the two arrays are equals. - * - * @param a One array. - * @param a2 The other array. - * @return {@code true}: yes
{@code false}: no - */ - public static boolean equals(@Nullable Object[] a, @Nullable Object[] a2) { - return Arrays.deepEquals(a, a2); - } - - public static boolean equals(boolean[] a, boolean[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(byte[] a, byte[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(char[] a, char[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(double[] a, double[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(float[] a, float[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(int[] a, int[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(short[] a, short[] a2) { - return Arrays.equals(a, a2); - } - - /////////////////////////////////////////////////////////////////////////// - // reverse - /////////////////////////////////////////////////////////////////////////// - - /** - *

Reverses the order of the given array.

- * - *

There is no special handling for multi-dimensional arrays.

- * - *

This method does nothing for a null input array.

- * - * @param array the array to reverse, may be null - */ - public static void reverse(T[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - T tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(long[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - long tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(int[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - int tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(short[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - short tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(char[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - char tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(byte[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - byte tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(double[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - double tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(float[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - float tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(boolean[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - boolean tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - /////////////////////////////////////////////////////////////////////////// - // copy - /////////////////////////////////////////////////////////////////////////// - - /** - *

Copies the specified array and handling - * null.

- * - *

The objects in the array are not cloned, thus there is no special - * handling for multi-dimensional arrays.

- * - *

This method returns null for a null input array.

- * - * @param array the array to shallow clone, may be null - * @return the cloned array, null if null input - */ - @Nullable - public static T[] copy(@Nullable T[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static long[] copy(@Nullable long[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static int[] copy(@Nullable int[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static short[] copy(@Nullable short[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static char[] copy(@Nullable char[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static byte[] copy(@Nullable byte[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static double[] copy(@Nullable double[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static float[] copy(@Nullable float[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static boolean[] copy(@Nullable boolean[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - private static Object realCopy(@Nullable Object array) { - if (array == null) return null; - return realSubArray(array, 0, getLength(array)); - } - - /////////////////////////////////////////////////////////////////////////// - // subArray - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static T[] subArray(@Nullable T[] array, int startIndexInclusive, int endIndexExclusive) { - //noinspection unchecked - return (T[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static long[] subArray(@Nullable long[] array, int startIndexInclusive, int endIndexExclusive) { - return (long[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static int[] subArray(@Nullable int[] array, int startIndexInclusive, int endIndexExclusive) { - return (int[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static short[] subArray(@Nullable short[] array, int startIndexInclusive, int endIndexExclusive) { - return (short[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static char[] subArray(@Nullable char[] array, int startIndexInclusive, int endIndexExclusive) { - return (char[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static byte[] subArray(@Nullable byte[] array, int startIndexInclusive, int endIndexExclusive) { - return (byte[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static double[] subArray(@Nullable double[] array, int startIndexInclusive, int endIndexExclusive) { - return (double[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static float[] subArray(@Nullable float[] array, int startIndexInclusive, int endIndexExclusive) { - return (float[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static boolean[] subArray(@Nullable boolean[] array, int startIndexInclusive, int endIndexExclusive) { - return (boolean[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - private static Object realSubArray(@Nullable Object array, int startIndexInclusive, int endIndexExclusive) { - if (array == null) { - return null; - } - if (startIndexInclusive < 0) { - startIndexInclusive = 0; - } - int length = getLength(array); - if (endIndexExclusive > length) { - endIndexExclusive = length; - } - int newSize = endIndexExclusive - startIndexInclusive; - Class type = array.getClass().getComponentType(); - if (newSize <= 0) { - return Array.newInstance(type, 0); - } - Object subArray = Array.newInstance(type, newSize); - System.arraycopy(array, startIndexInclusive, subArray, 0, newSize); - return subArray; - } - - /////////////////////////////////////////////////////////////////////////// - // add - /////////////////////////////////////////////////////////////////////////// - - /** - *

Copies the given array and adds the given element at the end of the new array.

- * - *

The new array contains the same elements of the input - * array plus the given element in the last position. The component type of - * the new array is the same as that of the input array.

- * - *

If the input array is null, a new one element array is returned - * whose component type is the same as the element.

- * - *
-     * ArrayUtils.realAdd(null, null)      = [null]
-     * ArrayUtils.realAdd(null, "a")       = ["a"]
-     * ArrayUtils.realAdd(["a"], null)     = ["a", null]
-     * ArrayUtils.realAdd(["a"], "b")      = ["a", "b"]
-     * ArrayUtils.realAdd(["a", "b"], "c") = ["a", "b", "c"]
-     * 
- * - * @param array the array to "realAdd" the element to, may be null - * @param element the object to realAdd - * @return A new array containing the existing elements plus the new element - */ - @NonNull - public static T[] add(@Nullable T[] array, @Nullable T element) { - Class type = array != null ? array.getClass() : (element != null ? element.getClass() : Object.class); - return (T[]) realAddOne(array, element, type); - } - - @NonNull - public static boolean[] add(@Nullable boolean[] array, boolean element) { - return (boolean[]) realAddOne(array, element, Boolean.TYPE); - } - - @NonNull - public static byte[] add(@Nullable byte[] array, byte element) { - return (byte[]) realAddOne(array, element, Byte.TYPE); - } - - @NonNull - public static char[] add(@Nullable char[] array, char element) { - return (char[]) realAddOne(array, element, Character.TYPE); - } - - @NonNull - public static double[] add(@Nullable double[] array, double element) { - return (double[]) realAddOne(array, element, Double.TYPE); - } - - @NonNull - public static float[] add(@Nullable float[] array, float element) { - return (float[]) realAddOne(array, element, Float.TYPE); - } - - @NonNull - public static int[] add(@Nullable int[] array, int element) { - return (int[]) realAddOne(array, element, Integer.TYPE); - } - - @NonNull - public static long[] add(@Nullable long[] array, long element) { - return (long[]) realAddOne(array, element, Long.TYPE); - } - - @NonNull - public static short[] add(@Nullable short[] array, short element) { - return (short[]) realAddOne(array, element, Short.TYPE); - } - - @NonNull - private static Object realAddOne(@Nullable Object array, @Nullable Object element, Class newArrayComponentType) { - Object newArray; - int arrayLength = 0; - if (array != null) { - arrayLength = getLength(array); - newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); - System.arraycopy(array, 0, newArray, 0, arrayLength); - } else { - newArray = Array.newInstance(newArrayComponentType, 1); - } - Array.set(newArray, arrayLength, element); - return newArray; - } - - /** - *

Adds all the elements of the given arrays into a new array.

- *

The new array contains all of the element of array1 followed - * by all of the elements array2. When an array is returned, it is always - * a new array.

- * - *
-     * ArrayUtils.add(null, null)     = null
-     * ArrayUtils.add(array1, null)   = copy of array1
-     * ArrayUtils.add(null, array2)   = copy of array2
-     * ArrayUtils.add([], [])         = []
-     * ArrayUtils.add([null], [null]) = [null, null]
-     * ArrayUtils.add(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
-     * 
- * - * @param array1 the first array whose elements are added to the new array, may be null - * @param array2 the second array whose elements are added to the new array, may be null - * @return The new array, null if null array inputs. - * The type of the new array is the type of the first array. - */ - @Nullable - public static T[] add(@Nullable T[] array1, @Nullable T[] array2) { - return (T[]) realAddArr(array1, array2); - } - - @Nullable - public static boolean[] add(@Nullable boolean[] array1, @Nullable boolean[] array2) { - return (boolean[]) realAddArr(array1, array2); - } - - @Nullable - public static char[] add(@Nullable char[] array1, @Nullable char[] array2) { - return (char[]) realAddArr(array1, array2); - } - - @Nullable - public static byte[] add(@Nullable byte[] array1, @Nullable byte[] array2) { - return (byte[]) realAddArr(array1, array2); - } - - @Nullable - public static short[] add(@Nullable short[] array1, @Nullable short[] array2) { - return (short[]) realAddArr(array1, array2); - } - - @Nullable - public static int[] add(@Nullable int[] array1, @Nullable int[] array2) { - return (int[]) realAddArr(array1, array2); - } - - @Nullable - public static long[] add(@Nullable long[] array1, @Nullable long[] array2) { - return (long[]) realAddArr(array1, array2); - } - - @Nullable - public static float[] add(@Nullable float[] array1, @Nullable float[] array2) { - return (float[]) realAddArr(array1, array2); - } - - @Nullable - public static double[] add(@Nullable double[] array1, @Nullable double[] array2) { - return (double[]) realAddArr(array1, array2); - } - - private static Object realAddArr(@Nullable Object array1, @Nullable Object array2) { - if (array1 == null && array2 == null) return null; - if (array1 == null) { - return realCopy(array2); - } - if (array2 == null) { - return realCopy(array1); - } - int len1 = getLength(array1); - int len2 = getLength(array2); - Object joinedArray = Array.newInstance(array1.getClass().getComponentType(), len1 + len2); - System.arraycopy(array1, 0, joinedArray, 0, len1); - System.arraycopy(array2, 0, joinedArray, len1, len2); - return joinedArray; - } - - /** - *

Inserts the specified element at the specified position in the array. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices).

- * - *

This method returns a new array with the same elements of the input - * array plus the given element on the specified position. The component - * type of the returned array is always the same as that of the input - * array.

- * - *

If the input array is null, a new one element array is returned - * whose component type is the same as the element.

- * - *
-     * ArrayUtils.add(null, 0, null)        = null
-     * ArrayUtils.add(null, 0, ["a"])       = ["a"]
-     * ArrayUtils.add(["a"], 1, null)       = ["a"]
-     * ArrayUtils.add(["a"], 1, ["b"])      = ["a", "b"]
-     * ArrayUtils.add(["a", "b"], 2, ["c"]) = ["a", "b", "c"]
-     * 
- * - * @param array1 the array to realAdd the element to, may be null - * @param index the position of the new object - * @param array2 the array to realAdd - * @return A new array containing the existing elements and the new element - * @throws IndexOutOfBoundsException if the index is out of range - * (index < 0 || index > array.length). - */ - @Nullable - public static T[] add(@Nullable T[] array1, int index, @Nullable T[] array2) { - Class clss; - if (array1 != null) { - clss = array1.getClass().getComponentType(); - } else if (array2 != null) { - clss = array2.getClass().getComponentType(); - } else { - return null; - } - return (T[]) realAddArr(array1, index, array2, clss); - } - - @Nullable - public static boolean[] add(@Nullable boolean[] array1, int index, @Nullable boolean[] array2) { - Object result = realAddArr(array1, index, array2, Boolean.TYPE); - if (result == null) return null; - return (boolean[]) result; - } - - public static char[] add(@Nullable char[] array1, int index, @Nullable char[] array2) { - Object result = realAddArr(array1, index, array2, Character.TYPE); - if (result == null) return null; - return (char[]) result; - } - - @Nullable - public static byte[] add(@Nullable byte[] array1, int index, @Nullable byte[] array2) { - Object result = realAddArr(array1, index, array2, Byte.TYPE); - if (result == null) return null; - return (byte[]) result; - } - - @Nullable - public static short[] add(@Nullable short[] array1, int index, @Nullable short[] array2) { - Object result = realAddArr(array1, index, array2, Short.TYPE); - if (result == null) return null; - return (short[]) result; - } - - @Nullable - public static int[] add(@Nullable int[] array1, int index, @Nullable int[] array2) { - Object result = realAddArr(array1, index, array2, Integer.TYPE); - if (result == null) return null; - return (int[]) result; - } - - @Nullable - public static long[] add(@Nullable long[] array1, int index, @Nullable long[] array2) { - Object result = realAddArr(array1, index, array2, Long.TYPE); - if (result == null) return null; - return (long[]) result; - } - - @Nullable - public static float[] add(@Nullable float[] array1, int index, @Nullable float[] array2) { - Object result = realAddArr(array1, index, array2, Float.TYPE); - if (result == null) return null; - return (float[]) result; - } - - @Nullable - public static double[] add(@Nullable double[] array1, int index, @Nullable double[] array2) { - Object result = realAddArr(array1, index, array2, Double.TYPE); - if (result == null) return null; - return (double[]) result; - } - - @Nullable - private static Object realAddArr(@Nullable Object array1, int index, @Nullable Object array2, Class clss) { - if (array1 == null && array2 == null) return null; - int len1 = getLength(array1); - int len2 = getLength(array2); - if (len1 == 0) { - if (index != 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", array1 Length: 0"); - } - return realCopy(array2); - } - if (len2 == 0) { - return realCopy(array1); - } - if (index > len1 || index < 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", array1 Length: " + len1); - } - Object joinedArray = Array.newInstance(array1.getClass().getComponentType(), len1 + len2); - if (index == len1) { - System.arraycopy(array1, 0, joinedArray, 0, len1); - System.arraycopy(array2, 0, joinedArray, len1, len2); - } else if (index == 0) { - System.arraycopy(array2, 0, joinedArray, 0, len2); - System.arraycopy(array1, 0, joinedArray, len2, len1); - } else { - System.arraycopy(array1, 0, joinedArray, 0, index); - System.arraycopy(array2, 0, joinedArray, index, len2); - System.arraycopy(array1, index, joinedArray, index + len2, len1 - index); - } - return joinedArray; - } - - /** - *

Inserts the specified element at the specified position in the array. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices).

- * - *

This method returns a new array with the same elements of the input - * array plus the given element on the specified position. The component - * type of the returned array is always the same as that of the input - * array.

- * - *

If the input array is null, a new one element array is returned - * whose component type is the same as the element.

- * - *
-     * ArrayUtils.add(null, 0, null)      = [null]
-     * ArrayUtils.add(null, 0, "a")       = ["a"]
-     * ArrayUtils.add(["a"], 1, null)     = ["a", null]
-     * ArrayUtils.add(["a"], 1, "b")      = ["a", "b"]
-     * ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"]
-     * 
- * - * @param array the array to realAdd the element to, may be null - * @param index the position of the new object - * @param element the object to realAdd - * @return A new array containing the existing elements and the new element - * @throws IndexOutOfBoundsException if the index is out of range - * (index < 0 || index > array.length). - */ - @NonNull - public static T[] add(@Nullable T[] array, int index, @Nullable T element) { - Class clss; - if (array != null) { - clss = array.getClass().getComponentType(); - } else if (element != null) { - clss = element.getClass(); - } else { - return (T[]) new Object[]{null}; - } - return (T[]) realAdd(array, index, element, clss); - } - - @NonNull - public static boolean[] add(@Nullable boolean[] array, int index, boolean element) { - return (boolean[]) realAdd(array, index, element, Boolean.TYPE); - } - - @NonNull - public static char[] add(@Nullable char[] array, int index, char element) { - return (char[]) realAdd(array, index, element, Character.TYPE); - } - - @NonNull - public static byte[] add(@Nullable byte[] array, int index, byte element) { - return (byte[]) realAdd(array, index, element, Byte.TYPE); - } - - @NonNull - public static short[] add(@Nullable short[] array, int index, short element) { - return (short[]) realAdd(array, index, element, Short.TYPE); - } - - @NonNull - public static int[] add(@Nullable int[] array, int index, int element) { - return (int[]) realAdd(array, index, element, Integer.TYPE); - } - - @NonNull - public static long[] add(@Nullable long[] array, int index, long element) { - return (long[]) realAdd(array, index, element, Long.TYPE); - } - - @NonNull - public static float[] add(@Nullable float[] array, int index, float element) { - return (float[]) realAdd(array, index, element, Float.TYPE); - } - - @NonNull - public static double[] add(@Nullable double[] array, int index, double element) { - return (double[]) realAdd(array, index, element, Double.TYPE); - } - - @NonNull - private static Object realAdd(@Nullable Object array, int index, @Nullable Object element, Class clss) { - if (array == null) { - if (index != 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0"); - } - Object joinedArray = Array.newInstance(clss, 1); - Array.set(joinedArray, 0, element); - return joinedArray; - } - int length = Array.getLength(array); - if (index > length || index < 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); - } - Object result = Array.newInstance(clss, length + 1); - System.arraycopy(array, 0, result, 0, index); - Array.set(result, index, element); - if (index < length) { - System.arraycopy(array, index, result, index + 1, length - index); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // remove - /////////////////////////////////////////////////////////////////////////// - - /** - *

Removes the element at the specified position from the specified array. - * All subsequent elements are shifted to the left (substracts one from - * their indices).

- * - *

This method returns a new array with the same elements of the input - * array except the element on the specified position. The component - * type of the returned array is always the same as that of the input - * array.

- * - *

If the input array is null, an IndexOutOfBoundsException - * will be thrown, because in that case no valid index can be specified.

- * - *
-     * ArrayUtils.remove(["a"], 0)           = []
-     * ArrayUtils.remove(["a", "b"], 0)      = ["b"]
-     * ArrayUtils.remove(["a", "b"], 1)      = ["a"]
-     * ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"]
-     * 
- * - * @param array the array to remove the element from, may be null - * @param index the position of the element to be removed - * @return A new array containing the existing elements except the element - * at the specified position. - * @throws IndexOutOfBoundsException if the index is out of range - * (index < 0 || index >= array.length) - */ - @Nullable - public static Object[] remove(@Nullable Object[] array, int index) { - if (array == null) return null; - return (Object[]) remove((Object) array, index); - } - - /** - *

Removes the first occurrence of the specified element from the - * specified array. All subsequent elements are shifted to the left - * (substracts one from their indices). If the array doesn't contains - * such an element, no elements are removed from the array.

- * - *

This method returns a new array with the same elements of the input - * array except the first occurrence of the specified element. The component - * type of the returned array is always the same as that of the input - * array.

- * - *
-     * ArrayUtils.removeElement(null, "a")            = null
-     * ArrayUtils.removeElement([], "a")              = []
-     * ArrayUtils.removeElement(["a"], "b")           = ["a"]
-     * ArrayUtils.removeElement(["a", "b"], "a")      = ["b"]
-     * ArrayUtils.removeElement(["a", "b", "a"], "a") = ["b", "a"]
-     * 
- * - * @param array the array to remove the element from, may be null - * @param element the element to be removed - * @return A new array containing the existing elements except the first - * occurrence of the specified element. - */ - @Nullable - public static Object[] removeElement(@Nullable Object[] array, @Nullable Object element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static boolean[] remove(@Nullable boolean[] array, int index) { - if (array == null) return null; - return (boolean[]) remove((Object) array, index); - } - - @Nullable - public static boolean[] removeElement(@Nullable boolean[] array, boolean element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static byte[] remove(@Nullable byte[] array, int index) { - if (array == null) return null; - return (byte[]) remove((Object) array, index); - } - - @Nullable - public static byte[] removeElement(@Nullable byte[] array, byte element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static char[] remove(@Nullable char[] array, int index) { - if (array == null) return null; - return (char[]) remove((Object) array, index); - } - - @Nullable - public static char[] removeElement(@Nullable char[] array, char element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static double[] remove(@Nullable double[] array, int index) { - if (array == null) return null; - return (double[]) remove((Object) array, index); - } - - @Nullable - public static double[] removeElement(@Nullable double[] array, double element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - //noinspection ConstantConditions - return remove(array, index); - } - - @Nullable - public static float[] remove(@Nullable float[] array, int index) { - if (array == null) return null; - return (float[]) remove((Object) array, index); - } - - @Nullable - public static float[] removeElement(@Nullable float[] array, float element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static int[] remove(@Nullable int[] array, int index) { - if (array == null) return null; - return (int[]) remove((Object) array, index); - } - - @Nullable - public static int[] removeElement(@Nullable int[] array, int element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static long[] remove(@Nullable long[] array, int index) { - if (array == null) return null; - return (long[]) remove((Object) array, index); - } - - @Nullable - public static long[] removeElement(@Nullable long[] array, long element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static short[] remove(@Nullable short[] array, int index) { - if (array == null) return null; - return (short[]) remove((Object) array, index); - } - - @Nullable - public static short[] removeElement(@Nullable short[] array, short element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @NonNull - private static Object remove(@NonNull Object array, int index) { - int length = getLength(array); - if (index < 0 || index >= length) { - throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); - } - - Object result = Array.newInstance(array.getClass().getComponentType(), length - 1); - System.arraycopy(array, 0, result, 0, index); - if (index < length - 1) { - System.arraycopy(array, index + 1, result, index, length - index - 1); - } - - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // object indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable Object[] array, @Nullable Object objectToFind) { - return indexOf(array, objectToFind, 0); - } - - public static int indexOf(@Nullable Object[] array, @Nullable final Object objectToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - if (objectToFind == null) { - for (int i = startIndex; i < array.length; i++) { - if (array[i] == null) { - return i; - } - } - } else { - for (int i = startIndex; i < array.length; i++) { - if (objectToFind.equals(array[i])) { - return i; - } - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable Object[] array, @Nullable Object objectToFind) { - return lastIndexOf(array, objectToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable Object[] array, @Nullable Object objectToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - if (objectToFind == null) { - for (int i = startIndex; i >= 0; i--) { - if (array[i] == null) { - return i; - } - } - } else { - for (int i = startIndex; i >= 0; i--) { - if (objectToFind.equals(array[i])) { - return i; - } - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable Object[] array, @Nullable Object objectToFind) { - return indexOf(array, objectToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // long indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable long[] array, long valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable long[] array, long valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable long[] array, long valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable long[] array, long valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable long[] array, long valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // int indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable int[] array, int valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable int[] array, int valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable int[] array, int valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable int[] array, int valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable int[] array, int valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // short indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable short[] array, short valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable short[] array, short valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable short[] array, short valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable short[] array, short valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable short[] array, short valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // char indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable char[] array, char valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable char[] array, char valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable char[] array, char valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable char[] array, char valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable char[] array, char valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // byte indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable byte[] array, byte valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable byte[] array, byte valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable byte[] array, byte valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable byte[] array, byte valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable byte[] array, byte valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // double indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable double[] array, double valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable double[] array, double valueToFind, double tolerance) { - return indexOf(array, valueToFind, 0, tolerance); - } - - public static int indexOf(@Nullable double[] array, double valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int indexOf(@Nullable double[] array, double valueToFind, int startIndex, double tolerance) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - double min = valueToFind - tolerance; - double max = valueToFind + tolerance; - for (int i = startIndex; i < array.length; i++) { - if (array[i] >= min && array[i] <= max) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind, double tolerance) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance); - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind, int startIndex, double tolerance) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - double min = valueToFind - tolerance; - double max = valueToFind + tolerance; - for (int i = startIndex; i >= 0; i--) { - if (array[i] >= min && array[i] <= max) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable double[] array, double valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable double[] array, double valueToFind, double tolerance) { - return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // float indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable float[] array, float valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable float[] array, float valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable float[] array, float valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable float[] array, float valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable float[] array, float valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // bool indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable boolean[] array, boolean valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable boolean[] array, boolean valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable boolean[] array, boolean valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable boolean[] array, boolean valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable boolean[] array, boolean valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // char converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static char[] toPrimitive(@Nullable Character[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new char[0]; - } - final char[] result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].charValue(); - } - return result; - } - - @Nullable - public static char[] toPrimitive(@Nullable Character[] array, char valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new char[0]; - } - final char[] result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - Character b = array[i]; - result[i] = (b == null ? valueForNull : b.charValue()); - } - return result; - } - - @Nullable - public static Character[] toObject(@Nullable char[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Character[0]; - } - final Character[] result = new Character[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Character(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // long converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static long[] toPrimitive(@Nullable Long[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new long[0]; - } - final long[] result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].longValue(); - } - return result; - } - - @Nullable - public static long[] toPrimitive(@Nullable Long[] array, long valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new long[0]; - } - final long[] result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - Long b = array[i]; - result[i] = (b == null ? valueForNull : b.longValue()); - } - return result; - } - - @Nullable - public static Long[] toObject(@Nullable long[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Long[0]; - } - final Long[] result = new Long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Long(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // int converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static int[] toPrimitive(@Nullable Integer[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new int[0]; - } - final int[] result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].intValue(); - } - return result; - } - - @Nullable - public static int[] toPrimitive(@Nullable Integer[] array, int valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new int[0]; - } - final int[] result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - Integer b = array[i]; - result[i] = (b == null ? valueForNull : b.intValue()); - } - return result; - } - - @Nullable - public static Integer[] toObject(@Nullable int[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Integer[0]; - } - final Integer[] result = new Integer[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Integer(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // short converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static short[] toPrimitive(@Nullable Short[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new short[0]; - } - final short[] result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].shortValue(); - } - return result; - } - - @Nullable - public static short[] toPrimitive(@Nullable Short[] array, short valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new short[0]; - } - final short[] result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - Short b = array[i]; - result[i] = (b == null ? valueForNull : b.shortValue()); - } - return result; - } - - @Nullable - public static Short[] toObject(@Nullable short[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Short[0]; - } - final Short[] result = new Short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Short(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // byte converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static byte[] toPrimitive(@Nullable Byte[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new byte[0]; - } - final byte[] result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].byteValue(); - } - return result; - } - - @Nullable - public static byte[] toPrimitive(@Nullable Byte[] array, byte valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new byte[0]; - } - final byte[] result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - Byte b = array[i]; - result[i] = (b == null ? valueForNull : b.byteValue()); - } - return result; - } - - @Nullable - public static Byte[] toObject(@Nullable byte[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Byte[0]; - } - final Byte[] result = new Byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Byte(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // double converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static double[] toPrimitive(@Nullable Double[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new double[0]; - } - final double[] result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].doubleValue(); - } - return result; - } - - @Nullable - public static double[] toPrimitive(@Nullable Double[] array, double valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new double[0]; - } - final double[] result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - Double b = array[i]; - result[i] = (b == null ? valueForNull : b.doubleValue()); - } - return result; - } - - @Nullable - public static Double[] toObject(@Nullable double[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Double[0]; - } - final Double[] result = new Double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Double(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // float converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static float[] toPrimitive(@Nullable Float[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new float[0]; - } - final float[] result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].floatValue(); - } - return result; - } - - @Nullable - public static float[] toPrimitive(@Nullable Float[] array, float valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new float[0]; - } - final float[] result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - Float b = array[i]; - result[i] = (b == null ? valueForNull : b.floatValue()); - } - return result; - } - - @Nullable - public static Float[] toObject(@Nullable float[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Float[0]; - } - final Float[] result = new Float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Float(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // boolean converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static boolean[] toPrimitive(@Nullable Boolean[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new boolean[0]; - } - final boolean[] result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].booleanValue(); - } - return result; - } - - @Nullable - public static boolean[] toPrimitive(@Nullable Boolean[] array, boolean valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new boolean[0]; - } - final boolean[] result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - Boolean b = array[i]; - result[i] = (b == null ? valueForNull : b.booleanValue()); - } - return result; - } - - @Nullable - public static Boolean[] toObject(@Nullable boolean[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Boolean[0]; - } - final Boolean[] result = new Boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE); - } - return result; - } - - @NonNull - public static List asList(@Nullable T... array) { - if (array == null || array.length == 0) { - return Collections.emptyList(); - } - return Arrays.asList(array); - } - - @NonNull - public static List asUnmodifiableList(@Nullable T... array) { - return Collections.unmodifiableList(asList(array)); - } - - @NonNull - public static List asArrayList(@Nullable T... array) { - List list = new ArrayList<>(); - if (array == null || array.length == 0) return list; - list.addAll(Arrays.asList(array)); - return list; - } - - @NonNull - public static List asLinkedList(@Nullable T... array) { - List list = new LinkedList<>(); - if (array == null || array.length == 0) return list; - list.addAll(Arrays.asList(array)); - return list; - } - - public static void sort(@Nullable T[] array, Comparator c) { - if (array == null || array.length < 2) return; - Arrays.sort(array, c); - } - - public static void sort(@Nullable byte[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable char[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable double[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable float[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable int[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable long[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable short[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - /** - * Executes the given closure on each element in the array. - *

- * If the input array or closure is null, there is no change made. - * - * @param array The array. - * @param closure the closure to perform, may be null - */ - public static void forAllDo(@Nullable Object array, @Nullable Closure closure) { - if (array == null || closure == null) return; - if (array instanceof Object[]) { - Object[] objects = (Object[]) array; - for (int i = 0, length = objects.length; i < length; i++) { - Object ele = objects[i]; - closure.execute(i, (E) ele); - } - } else if (array instanceof boolean[]) { - boolean[] booleans = (boolean[]) array; - for (int i = 0, length = booleans.length; i < length; i++) { - boolean ele = booleans[i]; - closure.execute(i, (E) (ele ? Boolean.TRUE : Boolean.FALSE)); - } - } else if (array instanceof byte[]) { - byte[] bytes = (byte[]) array; - for (int i = 0, length = bytes.length; i < length; i++) { - byte ele = bytes[i]; - closure.execute(i, (E) Byte.valueOf(ele)); - } - } else if (array instanceof char[]) { - char[] chars = (char[]) array; - for (int i = 0, length = chars.length; i < length; i++) { - char ele = chars[i]; - closure.execute(i, (E) Character.valueOf(ele)); - } - } else if (array instanceof short[]) { - short[] shorts = (short[]) array; - for (int i = 0, length = shorts.length; i < length; i++) { - short ele = shorts[i]; - closure.execute(i, (E) Short.valueOf(ele)); - } - } else if (array instanceof int[]) { - int[] ints = (int[]) array; - for (int i = 0, length = ints.length; i < length; i++) { - int ele = ints[i]; - closure.execute(i, (E) Integer.valueOf(ele)); - } - } else if (array instanceof long[]) { - long[] longs = (long[]) array; - for (int i = 0, length = longs.length; i < length; i++) { - long ele = longs[i]; - closure.execute(i, (E) Long.valueOf(ele)); - } - } else if (array instanceof float[]) { - float[] floats = (float[]) array; - for (int i = 0, length = floats.length; i < length; i++) { - float ele = floats[i]; - closure.execute(i, (E) Float.valueOf(ele)); - } - } else if (array instanceof double[]) { - double[] doubles = (double[]) array; - for (int i = 0, length = doubles.length; i < length; i++) { - double ele = doubles[i]; - closure.execute(i, (E) Double.valueOf(ele)); - } - } else { - throw new IllegalArgumentException("Not an array: " + array.getClass()); - } - } - - /** - * Return the string of array. - * - * @param array The array. - * @return the string of array - */ - @NonNull - public static String toString(@Nullable Object array) { - if (array == null) return "null"; - if (array instanceof Object[]) { - return Arrays.deepToString((Object[]) array); - } else if (array instanceof boolean[]) { - return Arrays.toString((boolean[]) array); - } else if (array instanceof byte[]) { - return Arrays.toString((byte[]) array); - } else if (array instanceof char[]) { - return Arrays.toString((char[]) array); - } else if (array instanceof double[]) { - return Arrays.toString((double[]) array); - } else if (array instanceof float[]) { - return Arrays.toString((float[]) array); - } else if (array instanceof int[]) { - return Arrays.toString((int[]) array); - } else if (array instanceof long[]) { - return Arrays.toString((long[]) array); - } else if (array instanceof short[]) { - return Arrays.toString((short[]) array); - } - throw new IllegalArgumentException("Array has incompatible type: " + array.getClass()); - } - - public interface Closure { - void execute(int index, E item); - } -} diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java index 3babaa0035..efe9993ad9 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java @@ -61,9 +61,7 @@ public final class CollectionUtils { public static ArrayList newArrayList(E... array) { ArrayList list = new ArrayList<>(); if (array == null || array.length == 0) return list; - for (E e : array) { - list.add(e); - } + list.addAll(Arrays.asList(array)); return list; } @@ -82,9 +80,7 @@ public final class CollectionUtils { public static LinkedList newLinkedList(E... array) { LinkedList list = new LinkedList<>(); if (array == null || array.length == 0) return list; - for (E e : array) { - list.add(e); - } + list.addAll(Arrays.asList(array)); return list; } @@ -103,9 +99,7 @@ public final class CollectionUtils { public static HashSet newHashSet(E... array) { HashSet set = new HashSet<>(); if (array == null || array.length == 0) return set; - for (E e : array) { - set.add(e); - } + set.addAll(Arrays.asList(array)); return set; } @@ -124,9 +118,7 @@ public final class CollectionUtils { public static TreeSet newTreeSet(Comparator comparator, E... array) { TreeSet set = new TreeSet<>(comparator); if (array == null || array.length == 0) return set; - for (E e : array) { - set.add(e); - } + set.addAll(Arrays.asList(array)); return set; } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java index 5b2f3a420a..3bf45775ed 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java @@ -578,7 +578,12 @@ public final class ConvertUtils { */ public static byte[] inputStream2Bytes(final InputStream is) { if (is == null) return null; - return input2OutputStream(is).toByteArray(); + ByteArrayOutputStream byteArrayOutputStream = input2OutputStream(is); + if(byteArrayOutputStream != null){ + return byteArrayOutputStream.toByteArray(); + }else{ + return null; + } } /** diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java index ffe4576d6d..e761fe2a25 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java @@ -3,6 +3,7 @@ package com.mogo.eagle.core.utilcode.util; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; +import java.math.RoundingMode; /** * @author donghongyu @@ -10,10 +11,6 @@ import java.math.BigDecimal; public class CoordinateUtils { /** - * @param lon1 - * @param lat1 - * @param lon2 - * @param lat2 * @return 两坐标的距离 单位:米(M) */ public static float calculateLineDistance( double lon1, double lat1, double lon2, double lat2 ) { @@ -56,11 +53,11 @@ public class CoordinateUtils { private static final double a = 6378245.0D; private static final double ee = 0.006693421622965943D; - public static final boolean outOfChina( double lat, double lng ) { + public static boolean outOfChina(double lat, double lng ) { return lng <= 73.66D || lng >= 135.05D || lat <= 3.86D || lat >= 53.55D; } - private static final double transformLat( double lng, double lat ) { + private static double transformLat(double lng, double lat ) { double ret = -100.0D + 2.0D * lng + 3.0D * lat + 0.2D * lat * lat + 0.1D * lng * lat + 0.2D * Math.sqrt( Math.abs( lng ) ); ret += ( 20.0D * Math.sin( 6.0D * lng * 3.141592653589793D ) + 20.0D * Math.sin( 2.0D * lng * 3.141592653589793D ) ) * 2.0D / 3.0D; ret += ( 20.0D * Math.sin( lat * 3.141592653589793D ) + 40.0D * Math.sin( lat / 3.0D * 3.141592653589793D ) ) * 2.0D / 3.0D; @@ -68,7 +65,7 @@ public class CoordinateUtils { return ret; } - private static final double transformLon( double lng, double lat ) { + private static double transformLon(double lng, double lat ) { double ret = 300.0D + lng + 2.0D * lat + 0.1D * lng * lng + 0.1D * lng * lat + 0.1D * Math.sqrt( Math.abs( lng ) ); ret += ( 20.0D * Math.sin( 6.0D * lng * 3.141592653589793D ) + 20.0D * Math.sin( 2.0D * lng * 3.141592653589793D ) ) * 2.0D / 3.0D; ret += ( 20.0D * Math.sin( lng * 3.141592653589793D ) + 40.0D * Math.sin( lng / 3.0D * 3.141592653589793D ) ) * 2.0D / 3.0D; @@ -78,12 +75,11 @@ public class CoordinateUtils { @NotNull // World Geodetic System ==> Mars Geodetic System - public static final double[] transformWgsToGcj( double wgLat, double wgLon ) { + public static double[] transformWgsToGcj(double wgLat, double wgLon ) { double[] point = new double[2]; if ( outOfChina( wgLat, wgLon ) ) { point[0] = wgLon; point[1] = wgLat; - return point; } else { double dLat = transformLat( wgLon - 105.0D, wgLat - 35.0D ); double dLon = transformLon( wgLon - 105.0D, wgLat - 35.0D ); @@ -97,12 +93,12 @@ public class CoordinateUtils { double mgLon = wgLon + dLon; point[0] = dealRound( mgLon ); point[1] = dealRound( mgLat ); - return point; } + return point; } @NotNull - public static final double[] transformGcj02toWgs84( double lat, double lng ) { + public static double[] transformGcj02toWgs84(double lat, double lng ) { double[] var10000; if ( outOfChina( lat, lng ) ) { var10000 = new double[]{lng, lat}; @@ -123,10 +119,9 @@ public class CoordinateUtils { return var10000; } - private static final double dealRound( double value ) { - BigDecimal bg = new BigDecimal( value ); - double result = bg.setScale( 6, 4 ).doubleValue(); - return result; + private static double dealRound(double value ) { + BigDecimal bg = BigDecimal.valueOf( value ); + return bg.setScale( 6, RoundingMode.HALF_UP).doubleValue(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java index bc27bf1209..9c2f240976 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java @@ -45,6 +45,9 @@ public class DateTimeUtils { public static Calendar cleanCalendarTime( Calendar c) { + if(c == null){ + return null; + } c.set( Calendar.HOUR_OF_DAY, 0); c.set( Calendar.MINUTE, 0); c.set( Calendar.SECOND, 0); @@ -54,10 +57,6 @@ public class DateTimeUtils { /** * 获得指定日期表示格式转换成Calendar的格式 - * - * @param src - * @param fallback 若无法转换,返回一个默认值 - * @return */ public static Calendar getCalendar( T src, Calendar fallback) { if (src != null) { @@ -101,7 +100,7 @@ public class DateTimeUtils { return getCalendarByPatterns(nSrc, PATTERNS); } catch ( Exception e) { try { - calendar.setTimeInMillis( Long.valueOf(nSrc)); + calendar.setTimeInMillis( Long.parseLong(nSrc)); } catch ( NumberFormatException e1) { throw new IllegalArgumentException(e1); } @@ -134,11 +133,6 @@ public class DateTimeUtils { /** * 匹配pattern获得时间,若无法解析抛出异常 - * - * @param dateTimeStr - * @param patternStr - * @return - * @throws IllegalArgumentException */ public static Calendar getCalendarByPattern( String dateTimeStr, String patternStr) { try { @@ -156,11 +150,6 @@ public class DateTimeUtils { /** * 匹配pattern数组中的所有pattern解析时间格式,若没有可以解析的方式则抛出异常 - * - * @param dateTimeStr - * @param patternStr - * @return - * @throws IllegalArgumentException */ public static Calendar getCalendarByPatterns( String dateTimeStr, String[] patternStr) { for ( String string : patternStr) { @@ -208,8 +197,6 @@ public class DateTimeUtils { /** * login时server的日期 - * - * @return */ public static Calendar getLoginServerDate() { return getCalendar(tss); @@ -229,12 +216,8 @@ public class DateTimeUtils { /** * 获得时间间隔 - * - * @param from - * @param to * @param unit 时间间隔单位{@link DateTimeUtils#ONE_SECOND},{@link DateTimeUtils#ONE_MINUTE}, * {@link DateTimeUtils#ONE_HOUR}, {@link DateTimeUtils#ONE_DAY} - * @return */ public static long getIntervalTimes( Calendar from, Calendar to, long unit) { if (from == null || to == null) { @@ -245,12 +228,7 @@ public class DateTimeUtils { /** * 获得日期间隔 忽略小时 - * - * @param startdate - * @param enddate - * @return */ - public static int getIntervalDays( String startdate, String enddate, String pattern) { int betweenDays = 0; if (startdate == null || enddate == null) { @@ -264,15 +242,15 @@ public class DateTimeUtils { } public static int getIntervalDays(T from, T to) { - Calendar startdate = getCalendar(from); - Calendar enddate = getCalendar(to); - cleanCalendarTime(startdate); - cleanCalendarTime(enddate); - return (int) getIntervalTimes(startdate, enddate, ONE_DAY); + Calendar startDate = getCalendar(from); + Calendar endDate = getCalendar(to); + cleanCalendarTime(startDate); + cleanCalendarTime(endDate); + return (int) getIntervalTimes(startDate, endDate, ONE_DAY); } - private static String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六",}; - private static String[] weekdays1 = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",}; + private static final String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六",}; + private static final String[] weekdays1 = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",}; /** * calendar --> 周一~周日 @@ -310,12 +288,12 @@ public class DateTimeUtils { } // 是否到刷新时间 - public static boolean isRefersh(long beforeTime) { - return isRefersh(DATETIME_FIELD_REFERSH * 1000 * 60, beforeTime); + public static boolean isRefresh(long beforeTime) { + return isRefresh(DATETIME_FIELD_REFERSH * 1_000L * 60, beforeTime); } // 是否到刷新时间 - public static boolean isRefersh(long gap, long beforeTime) { + public static boolean isRefresh(long gap, long beforeTime) { return new Date().getTime() - beforeTime >= gap; } @@ -344,13 +322,7 @@ public class DateTimeUtils { } else if (c1.get( Calendar.MONTH) < c2.get( Calendar.MONTH)) { return -1; } else { - if (c1.get( Calendar.DAY_OF_MONTH) > c2.get( Calendar.DAY_OF_MONTH)) { - return 1; - } else if (c1.get( Calendar.DAY_OF_MONTH) < c2.get( Calendar.DAY_OF_MONTH)) { - return -1; - } else { - return 0; - } + return Integer.compare(c1.get(Calendar.DAY_OF_MONTH), c2.get(Calendar.DAY_OF_MONTH)); } } } @@ -359,14 +331,14 @@ public class DateTimeUtils { if ( TextUtils.isEmpty(HH_mm) || null == src) { return; } - String s[] = HH_mm.split(":"); + String[] s = HH_mm.split(":"); if (s.length != 2) { return; } try { cleanCalendarTime(src); - src.set( Calendar.HOUR_OF_DAY, Integer.valueOf(s[0])); - src.set( Calendar.MINUTE, Integer.valueOf(s[1])); + src.set( Calendar.HOUR_OF_DAY, Integer.parseInt(s[0])); + src.set( Calendar.MINUTE, Integer.parseInt(s[1])); } catch ( NumberFormatException e) { } @@ -394,8 +366,7 @@ public class DateTimeUtils { Calendar a = Calendar.getInstance(); a.set( Calendar.DATE, 1); a.roll( Calendar.DATE, -1); - int maxDate = a.get( Calendar.DATE); - return maxDate; + return a.get( Calendar.DATE); } public static String convertToChineseWeekNumber( int number) { @@ -444,22 +415,18 @@ public class DateTimeUtils { /** * 获取 06月07 格式的日期 * @param timestamp 时间戳 - * @return */ public static String getTimeText( long timestamp, String dateFormat) { SimpleDateFormat format = new SimpleDateFormat(dateFormat, Locale.US); - String strStart = format.format(new Date(timestamp)); - return strStart; + return format.format(new Date(timestamp)); } /** * 获取 06月07 格式的日期 - * @return */ public static String getTimeText(String dateFormat) { SimpleDateFormat format = new SimpleDateFormat(dateFormat, Locale.US); - String strStart = format.format(new Date()); - return strStart; + return format.format(new Date()); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java index 3134cc5b38..a2dea6cc72 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java @@ -24,7 +24,6 @@ import android.telephony.gsm.GsmCellLocation; import android.text.TextUtils; import android.util.Log; -import androidx.annotation.RequiresApi; import androidx.annotation.RequiresPermission; import java.io.BufferedReader; @@ -75,7 +74,6 @@ public final class DeviceUtils { * * @return {@code true}: yes
{@code false}: no */ - @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) public static boolean isAdbEnabled() { return Settings.Secure.getInt( Utils.getApp().getContentResolver(), @@ -277,7 +275,7 @@ public final class DeviceUtils { InetAddress inetAddress = addresses.nextElement(); if (!inetAddress.isLoopbackAddress()) { String hostAddress = inetAddress.getHostAddress(); - if (hostAddress.indexOf(':') < 0) return inetAddress; + if (hostAddress != null && hostAddress.indexOf(':') < 0) return inetAddress; } } } @@ -345,14 +343,7 @@ public final class DeviceUtils { * @return an ordered list of ABIs supported by this device */ public static String[] getABIs() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - return Build.SUPPORTED_ABIS; - } else { - if (!TextUtils.isEmpty(Build.CPU_ABI2)) { - return new String[]{Build.CPU_ABI, Build.CPU_ABI2}; - } - return new String[]{Build.CPU_ABI}; - } + return Build.SUPPORTED_ABIS; } /** @@ -391,20 +382,17 @@ public final class DeviceUtils { operatorName = name; } } - boolean checkOperatorName = operatorName.toLowerCase().equals("android"); + boolean checkOperatorName = operatorName.equalsIgnoreCase("android"); if (checkOperatorName) return true; String url = "tel:" + "123456"; Intent intent = new Intent(); intent.setData(Uri.parse(url)); intent.setAction(Intent.ACTION_DIAL); - boolean checkDial = intent.resolveActivity(Utils.getApp().getPackageManager()) == null; - if (checkDial) return true; + return intent.resolveActivity(Utils.getApp().getPackageManager()) == null; // boolean checkDebuggerConnected = Debug.isDebuggerConnected(); // if (checkDebuggerConnected) return true; - - return false; } /** @@ -412,7 +400,6 @@ public final class DeviceUtils { * * @return whether user has enabled development settings. */ - @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) public static boolean isDevelopmentSettingsEnabled() { return Settings.Global.getInt( Utils.getApp().getContentResolver(), @@ -497,8 +484,8 @@ public final class DeviceUtils { if (!TextUtils.isEmpty(androidId)) { return saveUdid(prefix + 2, androidId); } - } catch (Exception ignore) { - ignore.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); } return saveUdid(prefix + 9, ""); } @@ -565,8 +552,8 @@ public final class DeviceUtils { // Gsm网络 , 联通移动的网络属于这一套 if (location instanceof GsmCellLocation) { GsmCellLocation gsmLoc = (GsmCellLocation) location; - int cellid = gsmLoc.getCid(); - return String.valueOf(cellid); + int cellId = gsmLoc.getCid(); + return String.valueOf(cellId); // Cdma网络 , 电信网络属于这一种 } else if (location instanceof CdmaCellLocation) { CdmaCellLocation cdmaLoc = (CdmaCellLocation) location; @@ -584,18 +571,13 @@ public final class DeviceUtils { public static boolean isLocationEnabled() { int locationMode = 0; String locationProviders; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - try { - locationMode = Settings.Secure.getInt(Utils.getApp().getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE); - } catch (Settings.SettingNotFoundException e) { - e.printStackTrace(); - return false; - } - return locationMode != Settings.Secure.LOCATION_MODE_OFF; - } else { - locationProviders = Settings.Secure.getString(Utils.getApp().getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); - return !TextUtils.isEmpty(locationProviders); + try { + locationMode = Settings.Secure.getInt(Utils.getApp().getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE); + } catch (Settings.SettingNotFoundException e) { + e.printStackTrace(); + return false; } + return locationMode != Settings.Secure.LOCATION_MODE_OFF; } @@ -678,8 +660,8 @@ public final class DeviceUtils { } - private static String getSerialnoNumbers() { - final String serialnoStr = "[ro.boot.serialno]"; + private static String getSerialNoNumbers() { + final String serialNoStr = "[ro.boot.serialno]"; try { Process p = Runtime.getRuntime().exec("getprop"); p.waitFor(); @@ -687,20 +669,20 @@ public final class DeviceUtils { p.getInputStream())); String temp = ""; while ((temp = stdInput.readLine()) != null) { - Log.i("getSerialnoNumbers", temp); - if (temp.contains(serialnoStr)) { - temp.replaceAll(" ", ""); - int index = temp.indexOf(serialnoStr); + Log.i("getSerialNoNumbers", temp); + if (temp.contains(serialNoStr)) { + temp = temp.replaceAll(" ", ""); + int index = temp.indexOf(serialNoStr); temp = temp.substring(index + 20); temp = temp.substring(1, temp.length() - 1); - Log.d("getSerialnoNumbers", temp); + Log.d("getSerialNoNumbers", temp); return temp; } } - } catch (IOException | InterruptedException e) { + } catch (InterruptedException | IOException e) { e.printStackTrace(); } - return serialnoStr; + return serialNoStr; } public static final String KEY_DEVICE_ID = "deviceId"; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java index 1bbb89a98c..bb674f1b95 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java @@ -104,7 +104,7 @@ public class MatcherUtils { * @return */ public static boolean isMatches( String regex, String input) { - return input == null ? false : Pattern.compile(regex).matcher(input).find(); + return input != null && Pattern.compile(regex).matcher(input).find(); } /** @@ -115,7 +115,7 @@ public class MatcherUtils { * @return */ public static boolean isMatchesIgnoreCase( String regex, String input) { - return input == null ? false : Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(input).find(); + return input != null && Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(input).find(); } /** @@ -274,15 +274,13 @@ public class MatcherUtils { */ public static boolean isCJK(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); - if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS // CJK统一汉字 \\u4E00-\\u9fAF + // 半形及全形字符 \\uFF00-\\uFFEF + return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS // CJK统一汉字 \\u4E00-\\u9fAF || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A // CJK统一汉字扩展-A \\u3400-\\u4dBF || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS // CJK兼容汉字 \\uF900-\\uFAFF || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION // CJK符号和标点 \\u3000-\\u303F || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION // 广义标点 \\u2000-\\u206F - || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { // 半形及全形字符 \\uFF00-\\uFFEF - return true; - } - return false; + || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS; } /** @@ -358,6 +356,9 @@ public class MatcherUtils { * @return */ public static boolean isFetionPassword( String input) { + if(input == null){ + return false; + } // 密码必须含有字母和数字,符号可选,但是必须符合Punct标准,否则返回false // 首先判断是否含有无效字符,含有,则返回false if (isIncludeInvalidChar(input)) { @@ -374,11 +375,7 @@ public class MatcherUtils { if (isMatches("[0-9]{1,15}", input)) { tmpValue++; } - if (tmpValue >= 2) { - return true; - } else { - return false; - } + return tmpValue >= 2; } /** @@ -390,9 +387,6 @@ public class MatcherUtils { public static boolean isNumeric( String str) { Pattern pattern = Pattern.compile("[0-9]+"); Matcher isNum = pattern.matcher(str); - if (!isNum.matches()) { - return false; - } - return true; + return isNum.matches(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java index eb536d89e1..fb6e446941 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java @@ -20,6 +20,11 @@ public final class NumberUtils { protected DecimalFormat initialValue() { return (DecimalFormat) NumberFormat.getInstance(); } + + @Override + public void remove() { + super.remove(); + } }; public static DecimalFormat getSafeDecimalFormat() { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java index 55649cef72..a4da2a7ba2 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java @@ -120,7 +120,7 @@ public final class PhoneUtils { } else { return getMinOne(tm.getMeid(0), tm.getMeid(1)); } - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + } else { String ids = getSystemPropertyByReflect(isImei ? "ril.gsm.imei" : "ril.cdma.meid"); if (!TextUtils.isEmpty(ids)) { String[] idArr = ids.split(","); @@ -138,11 +138,7 @@ public final class PhoneUtils { id1 = (String) method.invoke(tm, isImei ? TelephonyManager.PHONE_TYPE_GSM : TelephonyManager.PHONE_TYPE_CDMA); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } if (isImei) { @@ -161,19 +157,7 @@ public final class PhoneUtils { } } return getMinOne(id0, id1); - } else { - String deviceId = tm.getDeviceId(); - if (isImei) { - if (deviceId != null && deviceId.length() >= 15) { - return deviceId; - } - } else { - if (deviceId != null && deviceId.length() == 14) { - return deviceId; - } - } } - return ""; } private static String getMinOne(String s0, String s1) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java index edffee1272..47ab01c38e 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java @@ -158,23 +158,20 @@ public final class ReflectUtils { } private void sortConstructors(List> list) { - Collections.sort(list, new Comparator>() { - @Override - public int compare(Constructor o1, Constructor o2) { - Class[] types1 = o1.getParameterTypes(); - Class[] types2 = o2.getParameterTypes(); - int len = types1.length; - for (int i = 0; i < len; i++) { - if (!types1[i].equals(types2[i])) { - if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { - return 1; - } else { - return -1; - } + Collections.sort(list, (o1, o2) -> { + Class[] types1 = o1.getParameterTypes(); + Class[] types2 = o2.getParameterTypes(); + int len = types1.length; + for (int i = 0; i < len; i++) { + if (!types1[i].equals(types2[i])) { + if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { + return 1; + } else { + return -1; } } - return 0; } + return 0; }); } @@ -363,23 +360,20 @@ public final class ReflectUtils { } private void sortMethods(final List methods) { - Collections.sort(methods, new Comparator() { - @Override - public int compare(Method o1, Method o2) { - Class[] types1 = o1.getParameterTypes(); - Class[] types2 = o2.getParameterTypes(); - int len = types1.length; - for (int i = 0; i < len; i++) { - if (!types1[i].equals(types2[i])) { - if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { - return 1; - } else { - return -1; - } + Collections.sort(methods, (o1, o2) -> { + Class[] types1 = o1.getParameterTypes(); + Class[] types2 = o2.getParameterTypes(); + int len = types1.length; + for (int i = 0; i < len; i++) { + if (!types1[i].equals(types2[i])) { + if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { + return 1; + } else { + return -1; } } - return 0; } + return 0; }); } @@ -432,29 +426,25 @@ public final class ReflectUtils { @SuppressWarnings("unchecked") public

P proxy(final Class

proxyType) { final boolean isMap = (object instanceof Map); - final InvocationHandler handler = new InvocationHandler() { - @Override - @SuppressWarnings("null") - public Object invoke(Object proxy, Method method, Object[] args) { - String name = method.getName(); - try { - return reflect(object).method(name, args).get(); - } catch (ReflectException e) { - if (isMap) { - Map map = (Map) object; - int length = (args == null ? 0 : args.length); + final InvocationHandler handler = (proxy, method, args) -> { + String name = method.getName(); + try { + return reflect(object).method(name, args).get(); + } catch (ReflectException e) { + if (isMap) { + Map map = (Map) object; + int length = (args == null ? 0 : args.length); - if (length == 0 && name.startsWith("get")) { - return map.get(property(name.substring(3))); - } else if (length == 0 && name.startsWith("is")) { - return map.get(property(name.substring(2))); - } else if (length == 1 && name.startsWith("set")) { - map.put(property(name.substring(3)), args[0]); - return null; - } + if (length == 0 && name.startsWith("get")) { + return map.get(property(name.substring(3))); + } else if (length == 0 && name.startsWith("is")) { + return map.get(property(name.substring(2))); + } else if (length == 1 && name.startsWith("set")) { + map.put(property(name.substring(3)), args[0]); + return null; } - throw e; } + throw e; } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java index 6bed3d892c..026f8ca7d3 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java @@ -139,7 +139,7 @@ public final class SpanUtils { private int spaceSize; private int spaceColor; - private SerializableSpannableStringBuilder mBuilder; + private final SerializableSpannableStringBuilder mBuilder; private boolean isCreated; private int mType; @@ -1189,7 +1189,7 @@ public final class SpanUtils { final boolean first, final Layout l) { if (((Spanned) text).getSpanStart(this) == start) { Paint.Style style = p.getStyle(); - int oldColor = 0; + int oldColor; oldColor = p.getColor(); p.setColor(color); p.setStyle(Paint.Style.FILL); @@ -1249,9 +1249,6 @@ public final class SpanUtils { if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } - - paint.getShader(); - paint.setTypeface(tf); } } @@ -1311,9 +1308,11 @@ public final class SpanUtils { } else { try { drawable = ContextCompat.getDrawable(Utils.getApp(), mResourceId); - drawable.setBounds( - 0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() - ); + if(drawable != null){ + drawable.setBounds( + 0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() + ); + } } catch (Exception e) { Log.e("sms", "Unable to find resource: " + mResourceId); } @@ -1358,14 +1357,12 @@ public final class SpanUtils { int lineHeight = fm.bottom - fm.top; if (lineHeight < rect.height()) { if (mVerticalAlignment == ALIGN_TOP) { - fm.top = fm.top; fm.bottom = rect.height() + fm.top; } else if (mVerticalAlignment == ALIGN_CENTER) { fm.top = -rect.height() / 2 - lineHeight / 4; fm.bottom = rect.height() / 2 - lineHeight / 4; } else { fm.top = -rect.height() + fm.bottom; - fm.bottom = fm.bottom; } fm.ascent = fm.top; fm.descent = fm.bottom; @@ -1433,9 +1430,10 @@ public final class SpanUtils { } static class ShadowSpan extends CharacterStyle implements UpdateAppearance { - private float radius; - private float dx, dy; - private int shadowColor; + private final float radius; + private final float dx; + private final float dy; + private final int shadowColor; private ShadowSpan(final float radius, final float dx, diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java index 171817dd7d..184d014669 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java @@ -1068,7 +1068,7 @@ public final class ThreadUtils { private final AtomicInteger mSubmittedCount = new AtomicInteger(); - private LinkedBlockingQueue4Util mWorkQueue; + private final LinkedBlockingQueue4Util mWorkQueue; ThreadPoolExecutor4Util(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, @@ -1376,8 +1376,8 @@ public final class ThreadUtils { public static class SyncValue { - private CountDownLatch mLatch = new CountDownLatch(1); - private AtomicBoolean mFlag = new AtomicBoolean(); + private final CountDownLatch mLatch = new CountDownLatch(1); + private final AtomicBoolean mFlag = new AtomicBoolean(); private T mValue; public void setValue(T value) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java index f8fd01abba..2ad587de61 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java @@ -36,6 +36,11 @@ public final class TimeUtils { protected Map initialValue() { return new HashMap<>(); } + + @Override + public void remove() { + super.remove(); + } }; private static SimpleDateFormat getDefaultFormat() { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java index 7ec8d03d0b..37f6a33d56 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java @@ -118,23 +118,13 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC void removeActivityLifecycleCallbacks(final Activity activity) { if (activity == null) return; - UtilsBridge.runOnUiThread(new Runnable() { - @Override - public void run() { - mActivityLifecycleCallbacksMap.remove(activity); - } - }); + UtilsBridge.runOnUiThread(() -> mActivityLifecycleCallbacksMap.remove(activity)); } void removeActivityLifecycleCallbacks(final Activity activity, final Utils.ActivityLifecycleCallbacks callbacks) { if (activity == null || callbacks == null) return; - UtilsBridge.runOnUiThread(new Runnable() { - @Override - public void run() { - removeActivityLifecycleCallbacksInner(activity, callbacks); - } - }); + UtilsBridge.runOnUiThread(() -> removeActivityLifecycleCallbacksInner(activity, callbacks)); } private void removeActivityLifecycleCallbacksInner(final Activity activity, @@ -182,13 +172,7 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC return null; } return (Application) app; - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } return null; @@ -323,16 +307,13 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC } else { final Object tag = activity.getWindow().getDecorView().getTag(-123); if (!(tag instanceof Integer)) return; - UtilsBridge.runOnUiThreadDelayed(new Runnable() { - @Override - public void run() { - try { - Window window = activity.getWindow(); - if (window != null) { - window.setSoftInputMode(((Integer) tag)); - } - } catch (Exception ignore) { + UtilsBridge.runOnUiThreadDelayed(() -> { + try { + Window window = activity.getWindow(); + if (window != null) { + window.setSoftInputMode(((Integer) tag)); } + } catch (Exception ignore) { } }, 100); } @@ -370,6 +351,9 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC Activity topActivity = null; try { Object activityThread = getActivityThread(); + if(activityThread == null){ + return list; + } Field mActivitiesField = activityThread.getClass().getDeclaredField("mActivities"); mActivitiesField.setAccessible(true); Object mActivities = mActivitiesField.get(activityThread); @@ -448,9 +432,7 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC sDurationScaleField.set(null, 1f); Log.i("UtilsActivityLifecycle", "setAnimatorsEnabled: Animators are enabled now!"); } - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { + } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java index bdc6ed5c2f..0d2bd9d0d8 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java @@ -3,7 +3,6 @@ package com.zhidaoauto.map.sdk.inner.byteh; import com.autonavi.nge.map.LonLat; import java.lang.reflect.Field; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; @@ -14,7 +13,7 @@ public class PayloadEncoder { public static byte[] getPayload(T command) { List fieldWrapperList = command.getFieldWrapperList(); ByteBuf buffer = Unpooled.buffer(); - for(FieldWrapper fieldWrapper :fieldWrapperList){ + for (FieldWrapper fieldWrapper : fieldWrapperList) { write2ByteBuf(fieldWrapper, command, buffer); } return buffer.array(); @@ -37,6 +36,9 @@ public class PayloadEncoder { } catch (IllegalAccessException e) { new RuntimeException("反射获取值失败,filed:" + field.getName(), e); } + if (value == null) { + return; + } switch (typeName) { case "com.autonavi.nge.map.LonLat": LonLat lonLat = (LonLat) value; @@ -51,6 +53,8 @@ public class PayloadEncoder { case "java.lang.Character": case "kotlin.Character": case "char": + case "java.lang.String": + case "kotlin.String": buffer.writeCharSequence((CharSequence) value, StandardCharsets.UTF_8); break; case "java.lang.Byte": @@ -83,10 +87,6 @@ public class PayloadEncoder { case "double": buffer.writeDouble((double) value); break; - case "java.lang.String": - case "kotlin.String": - buffer.writeCharSequence((CharSequence) value, StandardCharsets.UTF_8); - break; default: throw new RuntimeException(typeName + "不支持,bug"); } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt index 4b51a128da..9b3facb18b 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt @@ -38,8 +38,8 @@ class Clerk(private val mMapController: IMapController?) { } job?.cancel() job = mMapController?.getDemaningScope()?.launch(Dispatchers.IO) { - var className: String = "" - var methodName: String = "" + var className = "" + var methodName = "" try { className = Thread.currentThread().stackTrace[3].className methodName = Thread.currentThread().stackTrace[3].methodName @@ -56,8 +56,8 @@ class Clerk(private val mMapController: IMapController?) { } job?.cancel() job = mMapController?.getDemaningScope()?.launch(Dispatchers.IO) { - var className: String = "" - var methodName: String = "" + var className = "" + var methodName = "" try { className = Thread.currentThread().stackTrace[3].className methodName = Thread.currentThread().stackTrace[3].methodName @@ -79,7 +79,7 @@ class Clerk(private val mMapController: IMapController?) { if(CompileConfig.DEBUG){ Log.i(TAG, "add: ${System.currentTimeMillis()}-$key") } - var stringBuffer = cacheMap.get(key) + var stringBuffer = cacheMap[key] if(stringBuffer == null){ stringBuffer = StringBuffer() } @@ -155,29 +155,34 @@ class Clerk(private val mMapController: IMapController?) { uploadJob?.cancel() uploadJob = scope?.launch(Dispatchers.IO) { val path = Recorder.getLogDirectory(TAG) - val file = File(path) - if(!file.isDirectory){ - return@launch - } - val firstlist = file.list() - for(p in firstlist){ - val f = File(p) - if(!f.isDirectory){ - break + path?.let { + val file = File(it) + if(!file.isDirectory){ + return@launch } - val secondlist = f.list() - for(child in secondlist){ - val childFile = File(child) - upload(childFile) + val firstList = file.list() + firstList?.let { + for(p in firstList){ + val f = File(p) + if(!f.isDirectory){ + break + } + val secondList = f.list() + secondList?.let { + for(child in secondList){ + val childFile = File(child) + upload(childFile) + } + } + } } } - } } private suspend fun upload(file:File){ - return - val content = file.readText() +// return +// val content = file.readText() // repository.uploadLogInfo(content) }