code,identifier,lang,repository "package com.chad.baserecyclerviewadapterhelper.utils; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; public class Tips { public static void show(String message) { show(message, Toast.LENGTH_SHORT); } public static void show(String message, int duration) { Toast toast = new Toast(AppUtils.INSTANCE.getApp()); toast.setDuration(duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(createTextToastView(message)); toast.show(); } private static View createTextToastView(String message) { float rc = dp2px(6); RoundRectShape [MASK] = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null); ShapeDrawable drawable = new ShapeDrawable([MASK]); drawable.getPaint().setColor(Color.argb(225, 240, 240, 240)); drawable.getPaint().setStyle(Paint.Style.FILL); drawable.getPaint().setAntiAlias(true); drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG); FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp()); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(layoutParams); layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12)); layout.setBackground(drawable); TextView textView = new TextView(AppUtils.INSTANCE.getApp()); textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); textView.setTextSize(15); textView.setText(message); textView.setLineSpacing(dp2px(4), 1f); textView.setTextColor(Color.BLACK); layout.addView(textView); return layout; } private static int dp2px(float dpValue) { final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }",shape,java,BaseRecyclerViewAdapterHelper "package org.greenrobot.eventbus.meta; import org.greenrobot.eventbus.ThreadMode; public class SubscriberMethodInfo { final String [MASK]; final ThreadMode threadMode; final Class eventType; final int priority; final boolean sticky; public SubscriberMethodInfo(String [MASK], Class eventType, ThreadMode threadMode, int priority, boolean sticky) { this.[MASK] = [MASK]; this.threadMode = threadMode; this.eventType = eventType; this.priority = priority; this.sticky = sticky; } public SubscriberMethodInfo(String [MASK], Class eventType) { this([MASK], eventType, ThreadMode.POSTING, 0, false); } public SubscriberMethodInfo(String [MASK], Class eventType, ThreadMode threadMode) { this([MASK], eventType, threadMode, 0, false); } }",methodName,java,EventBus "package com.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Future; import org.junit.Test; import com.netflix.hystrix.HystrixCollapser; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; public class CommandCollapserGetValueForKey extends HystrixCollapser, String, Integer> { private final Integer key; public CommandCollapserGetValueForKey(Integer key) { this.key = key; } @Override public Integer getRequestArgument() { return key; } @Override protected HystrixCommand> createCommand(final Collection> [MASK]) { return new BatchCommand([MASK]); } @Override protected void mapResponseToRequests(List batchResponse, Collection> [MASK]) { int count = 0; for (CollapsedRequest request : [MASK]) { request.setResponse(batchResponse.get(count++)); } } private static final class BatchCommand extends HystrixCommand> { private final Collection> [MASK]; private BatchCommand(Collection> [MASK]) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(""ExampleGroup"")) .andCommandKey(HystrixCommandKey.Factory.asKey(""GetValueForKey""))); this.[MASK] = [MASK]; } @Override protected List run() { ArrayList response = new ArrayList(); for (CollapsedRequest request : [MASK]) { response.add(""ValueForKey: "" + request.getArgument()); } return response; } } public static class UnitTest { @Test public void testCollapser() throws Exception { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { Future f1 = new CommandCollapserGetValueForKey(1).queue(); Future f2 = new CommandCollapserGetValueForKey(2).queue(); Future f3 = new CommandCollapserGetValueForKey(3).queue(); Future f4 = new CommandCollapserGetValueForKey(4).queue(); assertEquals(""ValueForKey: 1"", f1.get()); assertEquals(""ValueForKey: 2"", f2.get()); assertEquals(""ValueForKey: 3"", f3.get()); assertEquals(""ValueForKey: 4"", f4.get()); int numExecuted = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size(); System.err.println(""num executed: "" + numExecuted); if (numExecuted > 2) { fail(""some of the commands should have been collapsed""); } System.err.println(""HystrixRequestLog.getCurrentRequest().getAllExecutedCommands(): "" + HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()); int numLogs = 0; for (HystrixInvokableInfo command : HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()) { numLogs++; assertEquals(""GetValueForKey"", command.getCommandKey().name()); System.err.println(command.getCommandKey().name() + "" => command.getExecutionEvents(): "" + command.getExecutionEvents()); assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED)); assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS)); } assertEquals(numExecuted, numLogs); } finally { context.shutdown(); } } } }",requests,java,Hystrix "package com.alibaba.fastjson.spi; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; public interface Module { ObjectDeserializer createDeserializer(ParserConfig config, Class [MASK]); ObjectSerializer createSerializer(SerializeConfig config, Class [MASK]); }",type,java,fastjson "package com.facebook.imagepipeline.memory; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.facebook.common.internal.ImmutableMap; import com.facebook.common.memory.ByteArrayPool; import com.facebook.common.memory.PooledByteStreams; import com.facebook.imagepipeline.testing.FakeNativeMemoryChunkPool; import java.io.ByteArrayInputStream; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MemoryPooledByteBufferFactoryTest extends TestUsingNativeMemoryChunk { private MemoryPooledByteBufferFactory mNativeFactory; private PoolStats mNativeStats; private byte[] mData; @Before public void setup() { mData = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; NativeMemoryChunkPool mNativePool = new FakeNativeMemoryChunkPool(); mNativeStats = new PoolStats(mNativePool); ByteArrayPool byteArrayPool = mock(ByteArrayPool.class); byte[] pooledByteArray = new byte[8]; when(byteArrayPool.get(8)).thenReturn(pooledByteArray); PooledByteStreams pooledByteStreams = new PooledByteStreams(byteArrayPool, 8); mNativeFactory = new MemoryPooledByteBufferFactory(mNativePool, pooledByteStreams); } @Test public void testNewByteBuf_1() throws Exception { testNewByteBuf_1(mNativeFactory, mNativeStats); } @Test public void testNewByteBuf_2() throws Exception { testNewByteBuf_2(mNativeFactory, mNativeStats); } @Test public void testNewByteBuf_3() throws Exception { testNewByteBuf_3(mNativeFactory, mNativeStats); } @Test public void testNewByteBuf_4() throws Exception { testNewByteBuf_4(mNativeFactory, mNativeStats); } @Test public void testNewByteBuf_5() { testNewByteBuf_5(mNativeFactory, mNativeStats); } private void testNewByteBuf_1( final MemoryPooledByteBufferFactory mFactory, final PoolStats mStats) throws Exception { MemoryPooledByteBuffer sb1 = mFactory.newByteBuffer(new ByteArrayInputStream(mData)); Assert.assertEquals(16, sb1.getCloseableReference().get().getSize()); assertArrayEquals(mData, getBytes(sb1), mData.length); mStats.refresh(); Assert.assertEquals( ImmutableMap.of( 32, new IntPair(0, 0), 16, new IntPair(1, 0), 8, new IntPair(0, 1), 4, new IntPair(0, 1)), mStats.getBucketStats()); } private void testNewByteBuf_2( final MemoryPooledByteBufferFactory mFactory, final PoolStats mStats) throws Exception { MemoryPooledByteBuffer sb2 = mFactory.newByteBuffer(new ByteArrayInputStream(mData), 8); Assert.assertEquals(16, sb2.getCloseableReference().get().getSize()); assertArrayEquals(mData, getBytes(sb2), mData.length); mStats.refresh(); Assert.assertEquals( ImmutableMap.of( 32, new IntPair(0, 0), 16, new IntPair(1, 0), 8, new IntPair(0, 1), 4, new IntPair(0, 0)), mStats.getBucketStats()); } private void testNewByteBuf_3( final MemoryPooledByteBufferFactory mFactory, final PoolStats mStats) throws Exception { MemoryPooledByteBuffer sb3 = mFactory.newByteBuffer(new ByteArrayInputStream(mData), 16); Assert.assertEquals(16, sb3.getCloseableReference().get().getSize()); assertArrayEquals(mData, getBytes(sb3), mData.length); mStats.refresh(); Assert.assertEquals( ImmutableMap.of( 32, new IntPair(0, 0), 16, new IntPair(1, 0), 8, new IntPair(0, 0), 4, new IntPair(0, 0)), mStats.getBucketStats()); } private void testNewByteBuf_4( final MemoryPooledByteBufferFactory mFactory, final PoolStats mStats) throws Exception { MemoryPooledByteBuffer sb4 = mFactory.newByteBuffer(new ByteArrayInputStream(mData), 32); Assert.assertEquals(32, sb4.getCloseableReference().get().getSize()); assertArrayEquals(mData, getBytes(sb4), mData.length); mStats.refresh(); Assert.assertEquals( ImmutableMap.of( 32, new IntPair(1, 0), 16, new IntPair(0, 0), 8, new IntPair(0, 0), 4, new IntPair(0, 0)), mStats.getBucketStats()); } private static void testNewByteBuf_5( final MemoryPooledByteBufferFactory mFactory, final PoolStats mStats) { MemoryPooledByteBuffer sb5 = mFactory.newByteBuffer(5); Assert.assertEquals(8, sb5.getCloseableReference().get().getSize()); Assert.assertEquals( 1, sb5.getCloseableReference().getUnderlyingReferenceTestOnly().getRefCountTestOnly()); mStats.refresh(); Assert.assertEquals( ImmutableMap.of( 32, new IntPair(0, 0), 16, new IntPair(0, 0), 8, new IntPair(1, 0), 4, new IntPair(0, 0)), mStats.getBucketStats()); sb5.close(); mStats.refresh(); Assert.assertEquals( ImmutableMap.of( 32, new IntPair(0, 0), 16, new IntPair(0, 0), 8, new IntPair(0, 1), 4, new IntPair(0, 0)), mStats.getBucketStats()); } private static void assertArrayEquals(byte[] [MASK], byte[] actual, int length) { Assert.assertTrue([MASK].length >= length); Assert.assertTrue(actual.length >= length); for (int i = 0; i < length; i++) { Assert.assertEquals([MASK][i], actual[i], i); } } private static byte[] getBytes(MemoryPooledByteBuffer bb) { byte[] bytes = new byte[bb.size()]; bb.getCloseableReference().get().read(0, bytes, 0, bytes.length); return bytes; } }",expected,java,fresco "package org.apache.dubbo.common.serialize.kryo.optimized; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.kryo.utils.KryoUtils; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Output; import java.io.IOException; import java.io.OutputStream; public class KryoObjectOutput2 implements ObjectOutput, Cleanable { private Output output; private Kryo kryo; public KryoObjectOutput2(OutputStream outputStream) { output = new Output(outputStream); this.kryo = KryoUtils.get(); } @Override public void writeBool(boolean v) throws IOException { output.writeBoolean(v); } @Override public void writeByte(byte v) throws IOException { output.writeByte(v); } @Override public void writeShort(short v) throws IOException { output.writeShort(v); } @Override public void writeInt(int v) throws IOException { output.writeInt(v); } @Override public void writeLong(long v) throws IOException { output.writeLong(v); } @Override public void writeFloat(float v) throws IOException { output.writeFloat(v); } @Override public void writeDouble(double v) throws IOException { output.writeDouble(v); } @Override public void writeBytes(byte[] v) throws IOException { if (v == null) { output.writeInt(-1); } else { writeBytes(v, 0, v.length); } } @Override public void writeBytes(byte[] v, int [MASK], int len) throws IOException { if (v == null) { output.writeInt(-1); } else { output.writeInt(len); output.write(v, [MASK], len); } } @Override public void writeUTF(String v) throws IOException { output.writeString(v); } @Override public void writeObject(Object v) throws IOException { kryo.writeObjectOrNull(output, v, v.getClass()); } @Override public void writeThrowable(Object v) throws IOException { kryo.writeClassAndObject(output, v); } @Override public void flushBuffer() throws IOException { output.flush(); } @Override public void cleanup() { KryoUtils.release(kryo); kryo = null; } }",off,java,incubator-dubbo "package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import org.jetbrains.annotations.NotNull; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.attributes.nodes.LoopInfo; import jadx.core.utils.BlockUtils; import jadx.core.utils.EmptyBitSet; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.Utils.lockList; public final class BlockNode extends AttrNode implements IBlock, Comparable { private final int cid; private int pos; private final int startOffset; private final List instructions = new ArrayList<>(2); private List predecessors = new ArrayList<>(1); private List successors = new ArrayList<>(1); private List cleanSuccessors; private BitSet doms = EmptyBitSet.EMPTY; private BitSet postDoms = EmptyBitSet.EMPTY; private BitSet domFrontier; private BlockNode idom; private BlockNode iPostDom; private List dominatesOn = new ArrayList<>(3); public BlockNode(int cid, int pos, int offset) { this.cid = cid; this.pos = pos; this.startOffset = offset; } public int getCId() { return cid; } void setPos(int id) { this.pos = id; } @Deprecated public int getId() { return pos; } public int getPos() { return pos; } public List getPredecessors() { return predecessors; } public List getSuccessors() { return successors; } public List getCleanSuccessors() { return this.cleanSuccessors; } public void updateCleanSuccessors() { cleanSuccessors = cleanSuccessors(this); } public static void updateBlockPositions(List blocks) { int count = blocks.size(); for (int i = 0; i < count; i++) { blocks.get(i).setPos(i); } } public void lock() { try { List successorsList = successors; successors = lockList(successorsList); cleanSuccessors = successorsList == cleanSuccessors ? this.successors : lockList(cleanSuccessors); predecessors = lockList(predecessors); dominatesOn = lockList(dominatesOn); if (domFrontier == null) { throw new JadxRuntimeException(""Dominance frontier not set for [MASK]: "" + this); } } catch (Exception e) { throw new JadxRuntimeException(""Failed to lock [MASK]: "" + this, e); } } private static List cleanSuccessors(BlockNode [MASK]) { List sucList = [MASK].getSuccessors(); if (sucList.isEmpty()) { return sucList; } List toRemove = new ArrayList<>(sucList.size()); for (BlockNode b : sucList) { if (BlockUtils.isExceptionHandlerPath(b)) { toRemove.add(b); } } if ([MASK].contains(AFlag.LOOP_END)) { List loops = [MASK].getAll(AType.LOOP); for (LoopInfo loop : loops) { toRemove.add(loop.getStart()); } } if (toRemove.isEmpty()) { return sucList; } List result = new ArrayList<>(sucList); result.removeAll(toRemove); return result; } @Override public List getInstructions() { return instructions; } public int getStartOffset() { return startOffset; } public boolean isDominator(BlockNode [MASK]) { return doms.get([MASK].getPos()); } public BitSet getDoms() { return doms; } public void setDoms(BitSet doms) { this.doms = doms; } public BitSet getPostDoms() { return postDoms; } public void setPostDoms(BitSet postDoms) { this.postDoms = postDoms; } public BitSet getDomFrontier() { return domFrontier; } public void setDomFrontier(BitSet domFrontier) { this.domFrontier = domFrontier; } public BlockNode getIDom() { return idom; } public void setIDom(BlockNode idom) { this.idom = idom; } public BlockNode getIPostDom() { return iPostDom; } public void setIPostDom(BlockNode iPostDom) { this.iPostDom = iPostDom; } public List getDominatesOn() { return dominatesOn; } public void addDominatesOn(BlockNode [MASK]) { dominatesOn.add([MASK]); } public boolean isSynthetic() { return contains(AFlag.SYNTHETIC); } public boolean isReturnBlock() { return contains(AFlag.RETURN); } public boolean isMthExitBlock() { return contains(AFlag.MTH_EXIT_BLOCK); } public boolean isEmpty() { return instructions.isEmpty(); } @Override public int hashCode() { return cid; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BlockNode)) { return false; } BlockNode other = (BlockNode) obj; return cid == other.cid; } @Override public int compareTo(@NotNull BlockNode o) { return Integer.compare(cid, o.cid); } @Override public String baseString() { return Integer.toString(cid); } @Override public String toString() { return ""B:"" + cid + ':' + InsnUtils.formatOffset(startOffset); } }",block,java,jadx "package com.badlogic.gdx.graphics.glutils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.TextureData; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.GdxRuntimeException; public class FileTextureData implements TextureData { static public boolean copyToPOT; final FileHandle file; int width = 0; int height = 0; Format format; Pixmap pixmap; boolean useMipMaps; boolean isPrepared = false; public FileTextureData (FileHandle file, Pixmap preloadedPixmap, Format format, boolean useMipMaps) { this.file = file; this.pixmap = preloadedPixmap; this.format = format; this.useMipMaps = useMipMaps; if (pixmap != null) { pixmap = ensurePot(pixmap); width = pixmap.getWidth(); height = pixmap.getHeight(); if (format == null) this.format = pixmap.getFormat(); } } @Override public boolean isPrepared () { return isPrepared; } @Override public void prepare () { if (isPrepared) throw new GdxRuntimeException(""Already prepared""); if (pixmap == null) { pixmap = ensurePot(new Pixmap(file)); width = pixmap.getWidth(); height = pixmap.getHeight(); if (format == null) format = pixmap.getFormat(); } isPrepared = true; } private Pixmap ensurePot (Pixmap pixmap) { if (Gdx.gl20 == null && copyToPOT) { int pixmapWidth = pixmap.getWidth(); int [MASK] = pixmap.getHeight(); int potWidth = MathUtils.nextPowerOfTwo(pixmapWidth); int potHeight = MathUtils.nextPowerOfTwo([MASK]); if (pixmapWidth != potWidth || [MASK] != potHeight) { Pixmap tmp = new Pixmap(potWidth, potHeight, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, 0, 0, pixmapWidth, [MASK]); pixmap.dispose(); return tmp; } } return pixmap; } @Override public Pixmap consumePixmap () { if (!isPrepared) throw new GdxRuntimeException(""Call prepare() before calling getPixmap()""); isPrepared = false; Pixmap pixmap = this.pixmap; this.pixmap = null; return pixmap; } @Override public boolean disposePixmap () { return true; } @Override public int getWidth () { return width; } @Override public int getHeight () { return height; } @Override public Format getFormat () { return format; } @Override public boolean useMipMaps () { return useMipMaps; } @Override public boolean isManaged () { return true; } public FileHandle getFileHandle () { return file; } @Override public TextureDataType getType () { return TextureDataType.Pixmap; } @Override public void consumeCustomData (int target) { throw new GdxRuntimeException(""This TextureData implementation does not upload data itself""); } }",pixmapHeight,java,libgdx "package io.netty5.channel; import io.netty5.util.ReferenceCounted; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; public interface FileRegion extends ReferenceCounted { long position(); long transferred(); long count(); long transferTo(WritableByteChannel target, long position) throws IOException; @Override FileRegion retain(); @Override FileRegion retain(int increment); @Override FileRegion touch(); @Override FileRegion touch(Object [MASK]); }",hint,java,netty "package com.google.zxing.client.android.book; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import com.google.zxing.client.android.Intents; import com.google.zxing.client.android.HttpHelper; import com.google.zxing.client.android.LocaleManager; import com.google.zxing.client.android.R; public final class SearchBookContentsActivity extends Activity { private static final String TAG = SearchBookContentsActivity.class.getSimpleName(); private static final Pattern TAG_PATTERN = Pattern.compile(""<.*?>""); private static final Pattern LT_ENTITY_PATTERN = Pattern.compile(""<""); private static final Pattern GT_ENTITY_PATTERN = Pattern.compile("">""); private static final Pattern QUOTE_ENTITY_PATTERN = Pattern.compile(""'""); private static final Pattern QUOT_ENTITY_PATTERN = Pattern.compile("""""); private String isbn; private EditText queryTextView; private View queryButton; private ListView resultListView; private TextView headerView; private AsyncTask networkTask; private final View.OnClickListener buttonListener = new View.OnClickListener() { @Override public void onClick(View view) { launchSearch(); } }; private final View.OnKeyListener keyListener = new View.OnKeyListener() { @Override public boolean onKey(View view, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) { launchSearch(); return true; } return false; } }; String getISBN() { return isbn; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Intent intent = getIntent(); if (intent == null || !Intents.SearchBookContents.ACTION.equals(intent.getAction())) { finish(); return; } isbn = intent.getStringExtra(Intents.SearchBookContents.ISBN); if (isbn == null) { finish(); return; } if (LocaleManager.isBookSearchUrl(isbn)) { setTitle(getString(R.string.sbc_name)); } else { setTitle(getString(R.string.sbc_name) + "": ISBN "" + isbn); } setContentView(R.layout.search_book_contents); queryTextView = (EditText) findViewById(R.id.query_text_view); String initialQuery = intent.getStringExtra(Intents.SearchBookContents.QUERY); if (initialQuery != null && !initialQuery.isEmpty()) { queryTextView.setText(initialQuery); } queryTextView.setOnKeyListener(keyListener); queryButton = findViewById(R.id.query_button); queryButton.setOnClickListener(buttonListener); resultListView = (ListView) findViewById(R.id.result_list_view); LayoutInflater factory = LayoutInflater.from(this); headerView = (TextView) factory.inflate(R.layout.search_book_contents_header, resultListView, false); resultListView.addHeaderView(headerView); } @Override protected void onResume() { super.onResume(); queryTextView.selectAll(); } @Override protected void onPause() { AsyncTask oldTask = networkTask; if (oldTask != null) { oldTask.cancel(true); networkTask = null; } super.onPause(); } private void launchSearch() { String query = queryTextView.getText().toString(); if (query != null && !query.isEmpty()) { AsyncTask oldTask = networkTask; if (oldTask != null) { oldTask.cancel(true); } networkTask = new NetworkTask(); networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, query, isbn); headerView.setText(R.string.msg_sbc_searching_book); resultListView.setAdapter(null); queryTextView.setEnabled(false); queryButton.setEnabled(false); } } private final class NetworkTask extends AsyncTask { @Override protected JSONObject doInBackground(String... args) { try { String theQuery = args[0]; String theIsbn = args[1]; String uri; if (LocaleManager.isBookSearchUrl(theIsbn)) { int equals = theIsbn.indexOf('='); String volumeId = theIsbn.substring(equals + 1); uri = ""http: } else { uri = ""http: } CharSequence content = HttpHelper.downloadViaHttp(uri, HttpHelper.ContentType.JSON); return new JSONObject(content.toString()); } catch (IOException | JSONException ioe) { Log.w(TAG, ""Error accessing book search"", ioe); return null; } } @Override protected void onPostExecute(JSONObject result) { if (result == null) { headerView.setText(R.string.msg_sbc_failed); } else { handleSearchResults(result); } queryTextView.setEnabled(true); queryTextView.selectAll(); queryButton.setEnabled(true); } private void handleSearchResults(JSONObject json) { try { int count = json.getInt(""number_of_results""); headerView.setText(getString(R.string.msg_sbc_results) + "" : "" + count); if (count > 0) { JSONArray results = json.getJSONArray(""search_results""); SearchBookContentsResult.setQuery(queryTextView.getText().toString()); List items = new ArrayList<>(count); for (int x = 0; x < count; x++) { items.add(parseResult(results.getJSONObject(x))); } resultListView.setOnItemClickListener(new BrowseBookListener(SearchBookContentsActivity.this, items)); resultListView.setAdapter(new SearchBookContentsAdapter(SearchBookContentsActivity.this, items)); } else { String searchable = json.optString(""searchable""); if (""false"".equals(searchable)) { headerView.setText(R.string.msg_sbc_book_not_searchable); } resultListView.setAdapter(null); } } catch (JSONException e) { Log.w(TAG, ""Bad JSON from book search"", e); resultListView.setAdapter(null); headerView.setText(R.string.msg_sbc_failed); } } private SearchBookContentsResult parseResult(JSONObject json) { String pageId; String pageNumber; String snippet; try { pageId = json.getString(""page_id""); pageNumber = json.optString(""page_number""); snippet = json.optString(""snippet_text""); } catch (JSONException e) { Log.w(TAG, e); return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), """", """", false); } if (pageNumber == null || pageNumber.isEmpty()) { pageNumber = """"; } else { pageNumber = getString(R.string.msg_sbc_page) + ' ' + pageNumber; } boolean [MASK] = snippet != null && !snippet.isEmpty(); if ([MASK]) { snippet = TAG_PATTERN.matcher(snippet).replaceAll(""""); snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll(""<""); snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll("">""); snippet = QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll(""'""); snippet = QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll(""\""""); } else { snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')'; } return new SearchBookContentsResult(pageId, pageNumber, snippet, [MASK]); } } }",valid,java,zxing "package jadx.gui.utils; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.Nullable; public class JumpManager { private static final int MAX_JUMPS = 100; private static final int LIST_SHRINK_COUNT = 50; private final List list = new ArrayList<>(MAX_JUMPS); private int currentPos = 0; public void addPosition(@Nullable JumpPosition pos) { if (pos == null || ignoreJump(pos)) { return; } currentPos++; if (currentPos >= list.size()) { list.add(pos); if (list.size() >= MAX_JUMPS) { list.subList(0, LIST_SHRINK_COUNT).clear(); } currentPos = list.size() - 1; } else { list.set(currentPos, pos); list.subList(currentPos + 1, list.size()).clear(); } } public int size() { return list.size(); } private boolean ignoreJump(JumpPosition pos) { JumpPosition current = getCurrent(); if (current == null) { return false; } return pos.equals(current); } public @Nullable JumpPosition getCurrent() { if (currentPos >= 0 && currentPos < list.size()) { return list.get(currentPos); } return null; } @Nullable public JumpPosition getPrev() { if (currentPos == 0) { return null; } currentPos--; return list.get(currentPos); } @Nullable public JumpPosition getNext() { int size = list.size(); if (size == 0) { currentPos = 0; return null; } int [MASK] = currentPos + 1; if ([MASK] >= size) { currentPos = size - 1; return null; } JumpPosition position = list.get([MASK]); if (position == null) { return null; } currentPos = [MASK]; return position; } public void reset() { list.clear(); currentPos = 0; } }",newPos,java,jadx "package org.apache.dubbo.config.spring.context.event; import org.springframework.context.ApplicationEvent; import org.apache.dubbo.config.[MASK].DubboBootstrap; public class DubboBootstrapStopedEvent extends ApplicationEvent { public DubboBootstrapStopedEvent(DubboBootstrap [MASK]) { super([MASK]); } public DubboBootstrap getDubboBootstrap() { return (DubboBootstrap) super.getSource(); } }",bootstrap,java,incubator-dubbo "package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import java.util.List; public class ListenerInvokerWrapper implements Invoker { private static final Logger logger = LoggerFactory.getLogger(ListenerInvokerWrapper.class); private final Invoker [MASK]; private final List listeners; public ListenerInvokerWrapper(Invoker [MASK], List listeners) { if ([MASK] == null) { throw new IllegalArgumentException(""[MASK] == null""); } this.[MASK] = [MASK]; this.listeners = listeners; if (CollectionUtils.isNotEmpty(listeners)) { for (InvokerListener listener : listeners) { if (listener != null) { try { listener.referred([MASK]); } catch (Throwable t) { logger.error(t.getMessage(), t); } } } } } @Override public Class getInterface() { return [MASK].getInterface(); } @Override public URL getUrl() { return [MASK].getUrl(); } @Override public boolean isAvailable() { return [MASK].isAvailable(); } @Override public Result invoke(Invocation invocation) throws RpcException { return [MASK].invoke(invocation); } @Override public String toString() { return getInterface() + "" -> "" + (getUrl() == null ? "" "" : getUrl().toString()); } @Override public void destroy() { try { [MASK].destroy(); } finally { if (CollectionUtils.isNotEmpty(listeners)) { for (InvokerListener listener : listeners) { if (listener != null) { try { listener.destroyed([MASK]); } catch (Throwable t) { logger.error(t.getMessage(), t); } } } } } } }",invoker,java,incubator-dubbo "package com.alibaba.fastjson.util; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Map; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.annotation.JSONField; public class FieldInfo implements Comparable { public final String name; public final Method method; public final Field field; private int ordinal = 0; public final Class fieldClass; public final Type fieldType; public final Class declaringClass; public final boolean getOnly; public final int serialzeFeatures; public final int parserFeatures; public final String label; private final JSONField fieldAnnotation; private final JSONField methodAnnotation; public final boolean fieldAccess; public final boolean fieldTransient; public final char[] name_chars; public final boolean isEnum; public final boolean jsonDirect; public final boolean unwrapped; public final String format; public final String[] alternateNames; public final long nameHashCode; public FieldInfo(String name, Class declaringClass, Class fieldClass, Type fieldType, Field field, int ordinal, int serialzeFeatures, int parserFeatures){ if (ordinal < 0) { ordinal = 0; } this.name = name; this.declaringClass = declaringClass; this.fieldClass = fieldClass; this.fieldType = fieldType; this.method = null; this.field = field; this.ordinal = ordinal; this.serialzeFeatures = serialzeFeatures; this.parserFeatures = parserFeatures; isEnum = fieldClass.isEnum(); if (field != null) { int modifiers = field.getModifiers(); fieldAccess = (modifiers & Modifier.PUBLIC) != 0 || method == null; fieldTransient = Modifier.isTransient(modifiers); } else { fieldTransient = false; fieldAccess = false; } name_chars = genFieldNameChars(); if (field != null) { TypeUtils.setAccessible(field); } this.label = """"; fieldAnnotation = field == null ? null : TypeUtils.getAnnotation(field, JSONField.class); methodAnnotation = null; this.getOnly = false; this.jsonDirect = false; this.unwrapped = false; this.format = null; this.alternateNames = new String[0]; nameHashCode = nameHashCode64(name, fieldAnnotation); } public FieldInfo(String name, Method method, Field field, Class clazz, Type type, int ordinal, int serialzeFeatures, int parserFeatures, JSONField fieldAnnotation, JSONField methodAnnotation, String label){ this(name, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, fieldAnnotation, methodAnnotation, label, null); } public FieldInfo(String name, Method method, Field field, Class clazz, Type type, int ordinal, int serialzeFeatures, int parserFeatures, JSONField fieldAnnotation, JSONField methodAnnotation, String label, Map genericInfo){ if (field != null) { String fieldName = field.getName(); if (fieldName.equals(name)) { name = fieldName; } } if (ordinal < 0) { ordinal = 0; } this.name = name; this.method = method; this.field = field; this.ordinal = ordinal; this.serialzeFeatures = serialzeFeatures; this.parserFeatures = parserFeatures; this.fieldAnnotation = fieldAnnotation; this.methodAnnotation = methodAnnotation; if (field != null) { int modifiers = field.getModifiers(); fieldAccess = ((modifiers & Modifier.PUBLIC) != 0 || method == null); fieldTransient = Modifier.isTransient(modifiers) || TypeUtils.isTransient(method); } else { fieldAccess = false; fieldTransient = TypeUtils.isTransient(method); } if (label != null && label.length() > 0) { this.label = label; } else { this.label = """"; } String format = null; JSONField annotation = getAnnotation(); nameHashCode = nameHashCode64(name, annotation); boolean jsonDirect = false; if (annotation != null) { format = annotation.format(); if (format.trim().length() == 0) { format = null; } jsonDirect = annotation.jsonDirect(); unwrapped = annotation.unwrapped(); alternateNames = annotation.alternateNames(); } else { jsonDirect = false; unwrapped = false; alternateNames = new String[0]; } this.format = format; name_chars = genFieldNameChars(); if (method != null) { TypeUtils.setAccessible(method); } if (field != null) { TypeUtils.setAccessible(field); } boolean getOnly = false; Type fieldType; Class fieldClass; if (method != null) { Class[] types; if ((types = method.getParameterTypes()).length == 1) { fieldClass = types[0]; fieldType = method.getGenericParameterTypes()[0]; } else if (types.length == 2 && types[0] == String.class && types[1] == Object.class) { fieldType = fieldClass = types[0]; } else { fieldClass = method.getReturnType(); fieldType = method.getGenericReturnType(); getOnly = true; } this.declaringClass = method.getDeclaringClass(); } else { fieldClass = field.getType(); fieldType = field.getGenericType(); this.declaringClass = field.getDeclaringClass(); getOnly = Modifier.isFinal(field.getModifiers()); } this.getOnly = getOnly; this.jsonDirect = jsonDirect && fieldClass == String.class; if (clazz != null && fieldClass == Object.class && fieldType instanceof TypeVariable) { TypeVariable tv = (TypeVariable) fieldType; Type genericFieldType = getInheritGenericType(clazz, type, tv); if (genericFieldType != null) { this.fieldClass = TypeUtils.getClass(genericFieldType); this.fieldType = genericFieldType; isEnum = fieldClass.isEnum(); return; } } Type genericFieldType = fieldType; if (!(fieldType instanceof Class)) { genericFieldType = getFieldType(clazz, type != null ? type : clazz, fieldType, genericInfo); if (genericFieldType != fieldType) { if (genericFieldType instanceof ParameterizedType) { fieldClass = TypeUtils.getClass(genericFieldType); } else if (genericFieldType instanceof Class) { fieldClass = TypeUtils.getClass(genericFieldType); } } } this.fieldType = genericFieldType; this.fieldClass = fieldClass; isEnum = fieldClass.isEnum(); } private long nameHashCode64(String name, JSONField annotation) { if (annotation != null && annotation.name().length() != 0) { return TypeUtils.fnv1a_64_lower(name); } return TypeUtils.fnv1a_64_extract(name); } protected char[] genFieldNameChars() { int nameLen = this.name.length(); char[] name_chars = new char[nameLen + 3]; this.name.getChars(0, this.name.length(), name_chars, 1); name_chars[0] = '""'; name_chars[nameLen + 1] = '""'; name_chars[nameLen + 2] = ':'; return name_chars; } @SuppressWarnings(""unchecked"") public T getAnnation(Class annotationClass) { if (annotationClass == JSONField.class) { return (T) getAnnotation(); } T annotatition = null; if (method != null) { annotatition = TypeUtils.getAnnotation(method, annotationClass); } if (annotatition == null && field != null) { annotatition = TypeUtils.getAnnotation(field, annotationClass); } return annotatition; } public static Type getFieldType(final Class clazz, final Type type, Type fieldType){ return getFieldType(clazz, type, fieldType, null); } public static Type getFieldType(final Class clazz, final Type type, Type fieldType, Map genericInfo) { if (clazz == null || type == null) { return fieldType; } if (fieldType instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) fieldType; Type componentType = genericArrayType.getGenericComponentType(); Type componentTypeX = getFieldType(clazz, type, componentType, genericInfo); if (componentType != componentTypeX) { Type fieldTypeX = Array.newInstance(TypeUtils.getClass(componentTypeX), 0).getClass(); return fieldTypeX; } return fieldType; } if (!TypeUtils.isGenericParamType(type)) { return fieldType; } if (fieldType instanceof TypeVariable) { ParameterizedType paramType = (ParameterizedType) TypeUtils.getGenericParamType(type); Class parameterizedClass = TypeUtils.getClass(paramType); final TypeVariable typeVar = (TypeVariable) fieldType; TypeVariable[] typeVariables = parameterizedClass.getTypeParameters(); for (int i = 0; i < typeVariables.length; ++i) { if (typeVariables[i].getName().equals(typeVar.getName())) { fieldType = paramType.getActualTypeArguments()[i]; return fieldType; } } } if (fieldType instanceof ParameterizedType) { ParameterizedType parameterizedFieldType = (ParameterizedType) fieldType; Type[] arguments = parameterizedFieldType.getActualTypeArguments(); TypeVariable[] typeVariables; ParameterizedType paramType; boolean changed = getArgument(arguments, genericInfo); if(!changed){ if (type instanceof ParameterizedType) { paramType = (ParameterizedType) type; typeVariables = clazz.getTypeParameters(); } else if(clazz.getGenericSuperclass() instanceof ParameterizedType) { paramType = (ParameterizedType) clazz.getGenericSuperclass(); typeVariables = clazz.getSuperclass().getTypeParameters(); } else { paramType = parameterizedFieldType; typeVariables = type.getClass().getTypeParameters(); } changed = getArgument(arguments, typeVariables, paramType.getActualTypeArguments()); } if (changed) { fieldType = TypeReference.intern( new ParameterizedTypeImpl(arguments, parameterizedFieldType.getOwnerType(), parameterizedFieldType.getRawType()) ); return fieldType; } } return fieldType; } private static boolean getArgument(Type[] typeArgs, Map genericInfo){ if(genericInfo == null || genericInfo.size() == 0){ return false; } boolean changed = false; for (int i = 0; i < typeArgs.length; ++i) { Type typeArg = typeArgs[i]; if (typeArg instanceof ParameterizedType) { ParameterizedType p_typeArg = (ParameterizedType) typeArg; Type[] p_typeArg_args = p_typeArg.getActualTypeArguments(); boolean p_changed = getArgument(p_typeArg_args, genericInfo); if (p_changed) { typeArgs[i] = TypeReference.intern( new ParameterizedTypeImpl(p_typeArg_args, p_typeArg.getOwnerType(), p_typeArg.getRawType()) ); changed = true; } } else if (typeArg instanceof TypeVariable) { if (genericInfo.containsKey(typeArg)) { typeArgs[i] = genericInfo.get(typeArg); changed = true; } } } return changed; } private static boolean getArgument(Type[] typeArgs, TypeVariable[] typeVariables, Type[] arguments) { if (arguments == null || typeVariables.length == 0) { return false; } boolean changed = false; for (int i = 0; i < typeArgs.length; ++i) { Type typeArg = typeArgs[i]; if (typeArg instanceof ParameterizedType) { ParameterizedType p_typeArg = (ParameterizedType) typeArg; Type[] p_typeArg_args = p_typeArg.getActualTypeArguments(); boolean p_changed = getArgument(p_typeArg_args, typeVariables, arguments); if (p_changed) { typeArgs[i] = TypeReference.intern( new ParameterizedTypeImpl(p_typeArg_args, p_typeArg.getOwnerType(), p_typeArg.getRawType()) ); changed = true; } } else if (typeArg instanceof TypeVariable) { for (int j = 0; j < typeVariables.length; ++j) { if (typeArg.equals(typeVariables[j])) { typeArgs[i] = arguments[j]; changed = true; } } } } return changed; } private static Type getInheritGenericType(Class clazz, Type type, TypeVariable tv) { GenericDeclaration gd = tv.getGenericDeclaration(); Class class_gd = null; if (gd instanceof Class) { class_gd = (Class) tv.getGenericDeclaration(); } Type[] arguments = null; if (class_gd == clazz) { if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; arguments = ptype.getActualTypeArguments(); } } else { for (Class c = clazz; c != null && c != Object.class && c != class_gd; c = c.getSuperclass()) { Type superType = c.getGenericSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType p_superType = (ParameterizedType) superType; Type[] p_superType_args = p_superType.getActualTypeArguments(); getArgument(p_superType_args, c.getTypeParameters(), arguments); arguments = p_superType_args; } } } if (arguments == null || class_gd == null) { return null; } Type actualType = null; TypeVariable[] typeVariables = class_gd.getTypeParameters(); for (int j = 0; j < typeVariables.length; ++j) { if (tv.equals(typeVariables[j])) { actualType = arguments[j]; break; } } return actualType; } public String toString() { return this.name; } public Member getMember() { if (method != null) { return method; } else { return field; } } protected Class getDeclaredClass() { if (this.method != null) { return this.method.getDeclaringClass(); } if (this.field != null) { return this.field.getDeclaringClass(); } return null; } public int compareTo(FieldInfo o) { if (o.method != null && this.method != null && o.method.isBridge() && !this.method.isBridge() && o.method.getName().equals(this.method.getName())) { return 1; } if (this.ordinal < o.ordinal) { return -1; } if (this.ordinal > o.ordinal) { return 1; } int result = this.name.compareTo(o.name); if (result != 0) { return result; } Class thisDeclaringClass = this.getDeclaredClass(); Class otherDeclaringClass = o.getDeclaredClass(); if (thisDeclaringClass != null && otherDeclaringClass != null && thisDeclaringClass != otherDeclaringClass) { if (thisDeclaringClass.isAssignableFrom(otherDeclaringClass)) { return -1; } if (otherDeclaringClass.isAssignableFrom(thisDeclaringClass)) { return 1; } } boolean isSampeType = this.field != null && this.field.getType() == this.fieldClass; boolean [MASK] = o.field != null && o.field.getType() == o.fieldClass; if (isSampeType && ![MASK]) { return 1; } if ([MASK] && !isSampeType) { return -1; } if (o.fieldClass.isPrimitive() && !this.fieldClass.isPrimitive()) { return 1; } if (this.fieldClass.isPrimitive() && !o.fieldClass.isPrimitive()) { return -1; } if (o.fieldClass.getName().startsWith(""java."") && !this.fieldClass.getName().startsWith(""java."")) { return 1; } if (this.fieldClass.getName().startsWith(""java."") && !o.fieldClass.getName().startsWith(""java."")) { return -1; } return this.fieldClass.getName().compareTo(o.fieldClass.getName()); } public JSONField getAnnotation() { if (this.fieldAnnotation != null) { return this.fieldAnnotation; } return this.methodAnnotation; } public String getFormat() { return format; } public Object get(Object javaObject) throws IllegalAccessException, InvocationTargetException { return method != null ? method.invoke(javaObject) : field.get(javaObject); } public void set(Object javaObject, Object value) throws IllegalAccessException, InvocationTargetException { if (method != null) { method.invoke(javaObject, new Object[] { value }); return; } field.set(javaObject, value); } public void setAccessible() throws SecurityException { if (method != null) { TypeUtils.setAccessible(method); return; } TypeUtils.setAccessible(field); } }",oSameType,java,fastjson "package com.alibaba.json.bvt.parser.deser.generic; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class GenericTest4 extends TestCase { public void test_0() throws Exception { String [MASK]; { User user = new User(""Z友群""); user.getAddresses().add(new Address(""滨江"")); [MASK] = JSON.toJSONString(user); } System.out.println([MASK]); User user = JSON.parseObject([MASK], User.class); Assert.assertEquals(""Z友群"", user.getName()); Assert.assertEquals(1, user.getAddresses().size()); Assert.assertEquals(Address.class, user.getAddresses().get(0).getClass()); Assert.assertEquals(""滨江"", user.getAddresses().get(0).getValue()); } public static class User { private String name; public User(){ } public User(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private List
addresses = new ArrayList
(); public List
getAddresses() { return addresses; } public void setAddresses(List
addresses) { this.addresses = addresses; } } public static class Address { private String value; public Address(){ } public Address(String value){ this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }",text,java,fastjson "package com.alibaba.json.bvt.bug.bug2020; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.List; import java.util.Map; import java.util.Set; public class Bug_for_emptyList extends TestCase { public void test_for_issue() throws Exception { String str = ""{\""[MASK]\"":[1,2,3],\""map\"":{\""a\"":1},\""keys\"":[1,2,3],}""; VO vo = JSON.parseObject(str, VO.class); assertEquals(3, vo.[MASK].size()); assertEquals(1, vo.map.size()); assertEquals(3, vo.keys.size()); } public static class VO { private java.util.List [MASK] = kotlin.collections.CollectionsKt.emptyList(); private java.util.Set keys = kotlin.collections.SetsKt.emptySet(); private java.util.Map map = kotlin.collections.MapsKt.emptyMap(); public List getValues() { return [MASK]; } public Map getMap() { return map; } public Set getKeys() { return keys; } } }",values,java,fastjson "package com.alibaba.json.test.entity.case1; public class Int_100_Entity { private int f0; private int f1; private int f2; private int f3; private int f4; private int f5; private int f6; private int f7; private int f8; private int f9; private int f10; private int f11; private int f12; private int f13; private int f14; private int f15; private int f16; private int f17; private int f18; private int f19; private int f20; private int f21; private int f22; private int f23; private int f24; private int f25; private int f26; private int f27; private int f28; private int f29; private int f30; private int f31; private int f32; private int f33; private int f34; private int f35; private int f36; private int f37; private int f38; private int f39; private int f40; private int f41; private int f42; private int f43; private int f44; private int f45; private int f46; private int f47; private int f48; private int f49; private int f50; private int f51; private int f52; private int f53; private int f54; private int f55; private int f56; private int f57; private int f58; private int f59; private int f60; private int f61; private int f62; private int f63; private int f64; private int f65; private int f66; private int f67; private int f68; private int f69; private int f70; private int f71; private int f72; private int f73; private int f74; private int f75; private int f76; private int f77; private int f78; private int f79; private int f80; private int f81; private int f82; private int f83; private int f84; private int f85; private int [MASK]; private int f87; private int f88; private int f89; private int f90; private int f91; private int f92; private int f93; private int f94; private int f95; private int f96; private int f97; private int f98; private int f99; public int getF0() { return f0; } public void setF0(int f0) { this.f0 = f0; } public int getF1() { return f1; } public void setF1(int f1) { this.f1 = f1; } public int getF2() { return f2; } public void setF2(int f2) { this.f2 = f2; } public int getF3() { return f3; } public void setF3(int f3) { this.f3 = f3; } public int getF4() { return f4; } public void setF4(int f4) { this.f4 = f4; } public int getF5() { return f5; } public void setF5(int f5) { this.f5 = f5; } public int getF6() { return f6; } public void setF6(int f6) { this.f6 = f6; } public int getF7() { return f7; } public void setF7(int f7) { this.f7 = f7; } public int getF8() { return f8; } public void setF8(int f8) { this.f8 = f8; } public int getF9() { return f9; } public void setF9(int f9) { this.f9 = f9; } public int getF10() { return f10; } public void setF10(int f10) { this.f10 = f10; } public int getF11() { return f11; } public void setF11(int f11) { this.f11 = f11; } public int getF12() { return f12; } public void setF12(int f12) { this.f12 = f12; } public int getF13() { return f13; } public void setF13(int f13) { this.f13 = f13; } public int getF14() { return f14; } public void setF14(int f14) { this.f14 = f14; } public int getF15() { return f15; } public void setF15(int f15) { this.f15 = f15; } public int getF16() { return f16; } public void setF16(int f16) { this.f16 = f16; } public int getF17() { return f17; } public void setF17(int f17) { this.f17 = f17; } public int getF18() { return f18; } public void setF18(int f18) { this.f18 = f18; } public int getF19() { return f19; } public void setF19(int f19) { this.f19 = f19; } public int getF20() { return f20; } public void setF20(int f20) { this.f20 = f20; } public int getF21() { return f21; } public void setF21(int f21) { this.f21 = f21; } public int getF22() { return f22; } public void setF22(int f22) { this.f22 = f22; } public int getF23() { return f23; } public void setF23(int f23) { this.f23 = f23; } public int getF24() { return f24; } public void setF24(int f24) { this.f24 = f24; } public int getF25() { return f25; } public void setF25(int f25) { this.f25 = f25; } public int getF26() { return f26; } public void setF26(int f26) { this.f26 = f26; } public int getF27() { return f27; } public void setF27(int f27) { this.f27 = f27; } public int getF28() { return f28; } public void setF28(int f28) { this.f28 = f28; } public int getF29() { return f29; } public void setF29(int f29) { this.f29 = f29; } public int getF30() { return f30; } public void setF30(int f30) { this.f30 = f30; } public int getF31() { return f31; } public void setF31(int f31) { this.f31 = f31; } public int getF32() { return f32; } public void setF32(int f32) { this.f32 = f32; } public int getF33() { return f33; } public void setF33(int f33) { this.f33 = f33; } public int getF34() { return f34; } public void setF34(int f34) { this.f34 = f34; } public int getF35() { return f35; } public void setF35(int f35) { this.f35 = f35; } public int getF36() { return f36; } public void setF36(int f36) { this.f36 = f36; } public int getF37() { return f37; } public void setF37(int f37) { this.f37 = f37; } public int getF38() { return f38; } public void setF38(int f38) { this.f38 = f38; } public int getF39() { return f39; } public void setF39(int f39) { this.f39 = f39; } public int getF40() { return f40; } public void setF40(int f40) { this.f40 = f40; } public int getF41() { return f41; } public void setF41(int f41) { this.f41 = f41; } public int getF42() { return f42; } public void setF42(int f42) { this.f42 = f42; } public int getF43() { return f43; } public void setF43(int f43) { this.f43 = f43; } public int getF44() { return f44; } public void setF44(int f44) { this.f44 = f44; } public int getF45() { return f45; } public void setF45(int f45) { this.f45 = f45; } public int getF46() { return f46; } public void setF46(int f46) { this.f46 = f46; } public int getF47() { return f47; } public void setF47(int f47) { this.f47 = f47; } public int getF48() { return f48; } public void setF48(int f48) { this.f48 = f48; } public int getF49() { return f49; } public void setF49(int f49) { this.f49 = f49; } public int getF50() { return f50; } public void setF50(int f50) { this.f50 = f50; } public int getF51() { return f51; } public void setF51(int f51) { this.f51 = f51; } public int getF52() { return f52; } public void setF52(int f52) { this.f52 = f52; } public int getF53() { return f53; } public void setF53(int f53) { this.f53 = f53; } public int getF54() { return f54; } public void setF54(int f54) { this.f54 = f54; } public int getF55() { return f55; } public void setF55(int f55) { this.f55 = f55; } public int getF56() { return f56; } public void setF56(int f56) { this.f56 = f56; } public int getF57() { return f57; } public void setF57(int f57) { this.f57 = f57; } public int getF58() { return f58; } public void setF58(int f58) { this.f58 = f58; } public int getF59() { return f59; } public void setF59(int f59) { this.f59 = f59; } public int getF60() { return f60; } public void setF60(int f60) { this.f60 = f60; } public int getF61() { return f61; } public void setF61(int f61) { this.f61 = f61; } public int getF62() { return f62; } public void setF62(int f62) { this.f62 = f62; } public int getF63() { return f63; } public void setF63(int f63) { this.f63 = f63; } public int getF64() { return f64; } public void setF64(int f64) { this.f64 = f64; } public int getF65() { return f65; } public void setF65(int f65) { this.f65 = f65; } public int getF66() { return f66; } public void setF66(int f66) { this.f66 = f66; } public int getF67() { return f67; } public void setF67(int f67) { this.f67 = f67; } public int getF68() { return f68; } public void setF68(int f68) { this.f68 = f68; } public int getF69() { return f69; } public void setF69(int f69) { this.f69 = f69; } public int getF70() { return f70; } public void setF70(int f70) { this.f70 = f70; } public int getF71() { return f71; } public void setF71(int f71) { this.f71 = f71; } public int getF72() { return f72; } public void setF72(int f72) { this.f72 = f72; } public int getF73() { return f73; } public void setF73(int f73) { this.f73 = f73; } public int getF74() { return f74; } public void setF74(int f74) { this.f74 = f74; } public int getF75() { return f75; } public void setF75(int f75) { this.f75 = f75; } public int getF76() { return f76; } public void setF76(int f76) { this.f76 = f76; } public int getF77() { return f77; } public void setF77(int f77) { this.f77 = f77; } public int getF78() { return f78; } public void setF78(int f78) { this.f78 = f78; } public int getF79() { return f79; } public void setF79(int f79) { this.f79 = f79; } public int getF80() { return f80; } public void setF80(int f80) { this.f80 = f80; } public int getF81() { return f81; } public void setF81(int f81) { this.f81 = f81; } public int getF82() { return f82; } public void setF82(int f82) { this.f82 = f82; } public int getF83() { return f83; } public void setF83(int f83) { this.f83 = f83; } public int getF84() { return f84; } public void setF84(int f84) { this.f84 = f84; } public int getF85() { return f85; } public void setF85(int f85) { this.f85 = f85; } public int getF86() { return [MASK]; } public void setF86(int [MASK]) { this.[MASK] = [MASK]; } public int getF87() { return f87; } public void setF87(int f87) { this.f87 = f87; } public int getF88() { return f88; } public void setF88(int f88) { this.f88 = f88; } public int getF89() { return f89; } public void setF89(int f89) { this.f89 = f89; } public int getF90() { return f90; } public void setF90(int f90) { this.f90 = f90; } public int getF91() { return f91; } public void setF91(int f91) { this.f91 = f91; } public int getF92() { return f92; } public void setF92(int f92) { this.f92 = f92; } public int getF93() { return f93; } public void setF93(int f93) { this.f93 = f93; } public int getF94() { return f94; } public void setF94(int f94) { this.f94 = f94; } public int getF95() { return f95; } public void setF95(int f95) { this.f95 = f95; } public int getF96() { return f96; } public void setF96(int f96) { this.f96 = f96; } public int getF97() { return f97; } public void setF97(int f97) { this.f97 = f97; } public int getF98() { return f98; } public void setF98(int f98) { this.f98 = f98; } public int getF99() { return f99; } public void setF99(int f99) { this.f99 = f99; } }",f86,java,fastjson "package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.LoadBalance; import java.util.List; public class MockLoadBalance implements LoadBalance { @Override public Invoker select(List> [MASK], URL url, Invocation invocation) throws RpcException { return null; } }",invokers,java,incubator-dubbo "package io.netty5.buffer.tests; import io.netty5.buffer.Buffer; import io.netty5.buffer.BufferAllocator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static java.nio.charset.StandardCharsets.UTF_8; public class BufferEqualsTest extends BufferTestSupport { @ParameterizedTest @MethodSource(""allocators"") void emptyBuffersAreEqual(Fixture fixture) { testEqualsCommutative(fixture, """"); } @ParameterizedTest @MethodSource(""allocators"") void equalBuffersAreEqual(Fixture fixture) { testEqualsCommutative(fixture, ""foo""); } @ParameterizedTest @MethodSource(""allocators"") void differentBuffersAreNotEqual(Fixture fixture) { byte[] data1 = ""foo"".getBytes(UTF_8); byte[] [MASK] = ""foo1"".getBytes(UTF_8); try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf1 = allocator.allocate(data1.length); Buffer buf2 = allocator.allocate([MASK].length)) { buf1.writeBytes(data1); buf2.writeBytes([MASK]); Assertions.assertNotEquals(buf1, buf2); Assertions.assertNotEquals(buf2, buf1); } } @ParameterizedTest @MethodSource(""allocators"") void sameReadableContentBuffersAreEqual(Fixture fixture) { byte[] data1 = ""foo"".getBytes(UTF_8); byte[] [MASK] = ""notfoomaybe"".getBytes(UTF_8); try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf1 = allocator.allocate(data1.length); Buffer buf2 = allocator.allocate([MASK].length)) { buf1.writeBytes(data1); buf2.writeBytes([MASK]); buf2.skipReadableBytes(3); buf2.writerOffset(buf2.writerOffset() - 5); Assertions.assertEquals(buf1, buf2); Assertions.assertEquals(buf2, buf1); } } private static void testEqualsCommutative(Fixture fixture, String value) { final byte[] data = value.getBytes(UTF_8); try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf1 = allocator.allocate(data.length); Buffer buf2 = allocator.allocate(data.length)) { buf1.writeBytes(data); buf2.writeBytes(data); Assertions.assertEquals(buf1, buf2); Assertions.assertEquals(buf2, buf1); } } }",data2,java,netty "package org.apache.dubbo.rpc.cluster.configurator.parser; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfigItem; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.IOException; import java.io.InputStream; import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; public class ConfigParserTest { private String streamToString(InputStream stream) throws IOException { byte[] bytes = new byte[stream.available()]; stream.read(bytes); return new String(bytes); } @Test public void snakeYamlBasicTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/ServiceNoApp.yml"")) { Constructor constructor = new Constructor(ConfiguratorConfig.class); TypeDescription [MASK] = new TypeDescription(ConfiguratorConfig.class); [MASK].addPropertyParameters(""items"", ConfigItem.class); constructor.addTypeDescription([MASK]); Yaml yaml = new Yaml(constructor); ConfiguratorConfig config = yaml.load(yamlStream); System.out.println(config); } } @Test public void parseConfiguratorsServiceNoAppTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/ServiceNoApp.yml"")) { List urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals(url.getAddress(), ""127.0.0.1:20880""); Assertions.assertEquals(url.getParameter(WEIGHT_KEY, 0), 222); } } @Test public void parseConfiguratorsServiceGroupVersionTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/ServiceGroupVersion.yml"")) { List urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""testgroup"", url.getParameter(GROUP_KEY)); Assertions.assertEquals(""1.0.0"", url.getParameter(VERSION_KEY)); } } @Test public void parseConfiguratorsServiceMultiAppsTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/ServiceMultiApps.yml"")) { List urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""127.0.0.1"", url.getAddress()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertNotNull(url.getParameter(APPLICATION_KEY)); } } @Test public void parseConfiguratorsServiceNoRuleTest() { Assertions.assertThrows(IllegalStateException.class, () -> { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/ServiceNoRule.yml"")) { ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.fail(); } }); } @Test public void parseConfiguratorsAppMultiServicesTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/AppMultiServices.yml"")) { String yamlFile = streamToString(yamlStream); List urls = ConfigParser.parseConfigurators(yamlFile); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""127.0.0.1"", url.getAddress()); Assertions.assertEquals(""service1"", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals(""random"", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), ""demo-consumer""); } } @Test public void parseConfiguratorsAppAnyServicesTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/AppAnyServices.yml"")) { List urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""127.0.0.1"", url.getAddress()); Assertions.assertEquals(""*"", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals(""random"", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), ""demo-consumer""); } } @Test public void parseConfiguratorsAppNoServiceTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/AppNoService.yml"")) { List urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""127.0.0.1"", url.getAddress()); Assertions.assertEquals(""*"", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals(""random"", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), ""demo-consumer""); } } @Test public void parseConsumerSpecificProvidersTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream(""/ConsumerSpecificProviders.yml"")) { List urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""127.0.0.1"", url.getAddress()); Assertions.assertEquals(""*"", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals(""random"", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(""127.0.0.1:20880"", url.getParameter(OVERRIDE_PROVIDERS_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), ""demo-consumer""); } } @Test public void parseURLJsonArrayCompatible() throws Exception { String configData = ""[\""override: List urls = ConfigParser.parseConfigurators(configData); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals(""0.0.0.0"", url.getAddress()); Assertions.assertEquals(""com.xx.Service"", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); } }",carDescription,java,incubator-dubbo "package jadx.core.plugins; import java.util.Objects; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.gui.JadxGuiContext; import jadx.core.plugins.files.IJadxFilesGetter; public class AppContext { private @Nullable JadxGuiContext [MASK]; private IJadxFilesGetter filesGetter; public @Nullable JadxGuiContext getGuiContext() { return [MASK]; } public void setGuiContext(@Nullable JadxGuiContext [MASK]) { this.[MASK] = [MASK]; } public IJadxFilesGetter getFilesGetter() { return Objects.requireNonNull(filesGetter); } public void setFilesGetter(IJadxFilesGetter filesGetter) { this.filesGetter = filesGetter; } }",guiContext,java,jadx "package com.facebook.imagepipeline.producers; import android.content.ContentResolver; import android.content.res.AssetFileDescriptor; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.util.Pair; import androidx.annotation.VisibleForTesting; import com.facebook.common.internal.ImmutableMap; import com.facebook.common.internal.Preconditions; import com.facebook.common.logging.FLog; import com.facebook.common.memory.PooledByteBuffer; import com.facebook.common.memory.PooledByteBufferFactory; import com.facebook.common.memory.PooledByteBufferInputStream; import com.facebook.common.references.CloseableReference; import com.facebook.common.util.UriUtil; import com.facebook.imageformat.DefaultImageFormats; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.image.EncodedImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imageutils.BitmapUtil; import com.facebook.imageutils.JfifUtil; import com.facebook.infer.annotation.Nullsafe; import com.facebook.soloader.DoNotOptimize; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.util.Map; import java.util.concurrent.Executor; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) public class LocalExifThumbnailProducer implements ThumbnailProducer { private static final int COMMON_EXIF_THUMBNAIL_MAX_DIMENSION = 512; public static final String PRODUCER_NAME = ""LocalExifThumbnailProducer""; @VisibleForTesting static final String CREATED_THUMBNAIL = ""createdThumbnail""; private final Executor mExecutor; private final PooledByteBufferFactory mPooledByteBufferFactory; private final ContentResolver mContentResolver; public LocalExifThumbnailProducer( Executor executor, PooledByteBufferFactory pooledByteBufferFactory, ContentResolver contentResolver) { mExecutor = executor; mPooledByteBufferFactory = pooledByteBufferFactory; mContentResolver = contentResolver; } @Override public boolean canProvideImageForSize(@Nullable ResizeOptions resizeOptions) { return ThumbnailSizeChecker.isImageBigEnough( COMMON_EXIF_THUMBNAIL_MAX_DIMENSION, COMMON_EXIF_THUMBNAIL_MAX_DIMENSION, resizeOptions); } @Override public void produceResults( final Consumer consumer, final ProducerContext producerContext) { final ProducerListener2 listener = producerContext.getProducerListener(); final ImageRequest imageRequest = producerContext.getImageRequest(); producerContext.putOriginExtra(""local"", ""exif""); final StatefulProducerRunnable cancellableProducerRunnable = new StatefulProducerRunnable( consumer, listener, producerContext, PRODUCER_NAME) { @Override protected @Nullable EncodedImage getResult() throws Exception { final Uri sourceUri = imageRequest.getSourceUri(); final ExifInterface exifInterface = getExifInterface(sourceUri); if (exifInterface == null || !exifInterface.hasThumbnail()) { return null; } byte[] bytes = Preconditions.checkNotNull(exifInterface.getThumbnail()); PooledByteBuffer pooledByteBuffer = mPooledByteBufferFactory.newByteBuffer(bytes); return buildEncodedImage(pooledByteBuffer, exifInterface); } @Override protected void disposeResult(@Nullable EncodedImage result) { EncodedImage.closeSafely(result); } @Override protected Map getExtraMapOnSuccess(final @Nullable EncodedImage result) { return ImmutableMap.of(CREATED_THUMBNAIL, Boolean.toString(result != null)); } }; producerContext.addCallbacks( new BaseProducerContextCallbacks() { @Override public void onCancellationRequested() { cancellableProducerRunnable.cancel(); } }); mExecutor.execute(cancellableProducerRunnable); } @VisibleForTesting @Nullable ExifInterface getExifInterface(Uri uri) { final @Nullable String realPath = UriUtil.getRealPathFromUri(mContentResolver, uri); if (realPath == null) { return null; } try { if (canReadAsFile(realPath)) { return new ExifInterface(realPath); } else { AssetFileDescriptor assetFileDescriptor = UriUtil.getAssetFileDescriptor(mContentResolver, uri); if (assetFileDescriptor != null && Build.VERSION.SDK_INT >= 24) { final ExifInterface exifInterface = (new Api24Utils()).getExifInterface(assetFileDescriptor.getFileDescriptor()); assetFileDescriptor.close(); return exifInterface; } } } catch (IOException e) { } catch (StackOverflowError e) { FLog.e(LocalExifThumbnailProducer.class, ""StackOverflowError in ExifInterface constructor""); } return null; } private EncodedImage buildEncodedImage(PooledByteBuffer imageBytes, ExifInterface exifInterface) { Pair dimensions = BitmapUtil.decodeDimensions(new PooledByteBufferInputStream(imageBytes)); int [MASK] = this.getRotationAngle(exifInterface); int width = dimensions != null ? dimensions.first : EncodedImage.UNKNOWN_WIDTH; int height = dimensions != null ? dimensions.second : EncodedImage.UNKNOWN_HEIGHT; EncodedImage encodedImage; CloseableReference closeableByteBuffer = CloseableReference.of(imageBytes); try { encodedImage = new EncodedImage(closeableByteBuffer); } finally { CloseableReference.closeSafely(closeableByteBuffer); } encodedImage.setImageFormat(DefaultImageFormats.JPEG); encodedImage.setRotationAngle([MASK]); encodedImage.setWidth(width); encodedImage.setHeight(height); return encodedImage; } private int getRotationAngle(final ExifInterface exifInterface) { String s = Preconditions.checkNotNull(exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION)); return JfifUtil.getAutoRotateAngleFromOrientation(Integer.parseInt(s)); } @VisibleForTesting boolean canReadAsFile(String realPath) throws IOException { if (realPath == null) { return false; } final File file = new File(realPath); return file.exists() && file.canRead(); } @DoNotOptimize private class Api24Utils { @Nullable ExifInterface getExifInterface(FileDescriptor fileDescriptor) throws IOException { return Build.VERSION.SDK_INT >= 24 ? new ExifInterface(fileDescriptor) : null; } } }",rotationAngle,java,fresco "package org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt; import org.apache.dubbo.common.extension.adaptive.impl.HasAdaptiveExt_ManualAdaptive; import org.apache.dubbo.common.extension.ext1.SimpleExt; import org.apache.dubbo.common.extension.ext2.Ext2; import org.apache.dubbo.common.extension.ext2.UrlHolder; import org.apache.dubbo.common.extension.ext3.UseProtocolKeyExt; import org.apache.dubbo.common.extension.ext4.NoUrlParamExt; import org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt; import org.apache.dubbo.common.extension.ext6_inject.Ext6; import org.apache.dubbo.common.extension.ext6_inject.impl.Ext6Impl2; import org.apache.dubbo.common.utils.LogUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ExtensionLoader_Adaptive_Test { @Test public void test_useAdaptiveClass() throws Exception { ExtensionLoader loader = ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class); HasAdaptiveExt [MASK] = loader.getAdaptiveExtension(); assertTrue([MASK] instanceof HasAdaptiveExt_ManualAdaptive); } @Test public void test_getAdaptiveExtension_defaultAdaptiveKey() throws Exception { { SimpleExt [MASK] = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map map = new HashMap(); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1"", map); String echo = [MASK].echo(url, ""haha""); assertEquals(""Ext1Impl1-echo"", echo); } { SimpleExt [MASK] = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map map = new HashMap(); map.put(""simple.[MASK]"", ""impl2""); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1"", map); String echo = [MASK].echo(url, ""haha""); assertEquals(""Ext1Impl2-echo"", echo); } } @Test public void test_getAdaptiveExtension_customizeAdaptiveKey() throws Exception { SimpleExt [MASK] = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map map = new HashMap(); map.put(""key2"", ""impl2""); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1"", map); String echo = [MASK].yell(url, ""haha""); assertEquals(""Ext1Impl2-yell"", echo); url = url.addParameter(""key1"", ""impl3""); echo = [MASK].yell(url, ""haha""); assertEquals(""Ext1Impl3-yell"", echo); } @Test public void test_getAdaptiveExtension_protocolKey() throws Exception { UseProtocolKeyExt [MASK] = ExtensionLoader.getExtensionLoader(UseProtocolKeyExt.class).getAdaptiveExtension(); { String echo = [MASK].echo(URL.valueOf(""1.2.3.4:20880""), ""s""); assertEquals(""Ext3Impl1-echo"", echo); Map map = new HashMap(); URL url = new URL(""impl3"", ""1.2.3.4"", 1010, ""path1"", map); echo = [MASK].echo(url, ""s""); assertEquals(""Ext3Impl3-echo"", echo); url = url.addParameter(""key1"", ""impl2""); echo = [MASK].echo(url, ""s""); assertEquals(""Ext3Impl2-echo"", echo); } { Map map = new HashMap(); URL url = new URL(null, ""1.2.3.4"", 1010, ""path1"", map); String yell = [MASK].yell(url, ""s""); assertEquals(""Ext3Impl1-yell"", yell); url = url.addParameter(""key2"", ""impl2""); yell = [MASK].yell(url, ""s""); assertEquals(""Ext3Impl2-yell"", yell); url = url.setProtocol(""impl3""); yell = [MASK].yell(url, ""d""); assertEquals(""Ext3Impl3-yell"", yell); } } @Test public void test_getAdaptiveExtension_UrlNpe() throws Exception { SimpleExt [MASK] = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); try { [MASK].echo(null, ""haha""); fail(); } catch (IllegalArgumentException e) { assertEquals(""url == null"", e.getMessage()); } } @Test public void test_getAdaptiveExtension_ExceptionWhenNoAdaptiveMethodOnInterface() throws Exception { try { ExtensionLoader.getExtensionLoader(NoAdaptiveMethodExt.class).getAdaptiveExtension(); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), allOf(containsString(""Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt""), containsString(""No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class""))); } try { ExtensionLoader.getExtensionLoader(NoAdaptiveMethodExt.class).getAdaptiveExtension(); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), allOf(containsString(""Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt""), containsString(""No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class""))); } } @Test public void test_getAdaptiveExtension_ExceptionWhenNotAdaptiveMethod() throws Exception { SimpleExt [MASK] = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map map = new HashMap(); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1"", map); try { [MASK].bang(url, 33); fail(); } catch (UnsupportedOperationException expected) { assertThat(expected.getMessage(), containsString(""method "")); assertThat( expected.getMessage(), containsString(""of interface org.apache.dubbo.common.extension.ext1.SimpleExt is not adaptive method!"")); } } @Test public void test_getAdaptiveExtension_ExceptionWhenNoUrlAttribute() throws Exception { try { ExtensionLoader.getExtensionLoader(NoUrlParamExt.class).getAdaptiveExtension(); fail(); } catch (Exception expected) { assertThat(expected.getMessage(), containsString(""Failed to create adaptive class for interface "")); assertThat(expected.getMessage(), containsString("": not found url parameter or url attribute in parameters of method "")); } } @Test public void test_urlHolder_getAdaptiveExtension() throws Exception { Ext2 [MASK] = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); Map map = new HashMap(); map.put(""ext2"", ""impl1""); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1"", map); UrlHolder holder = new UrlHolder(); holder.setUrl(url); String echo = [MASK].echo(holder, ""haha""); assertEquals(""Ext2Impl1-echo"", echo); } @Test public void test_urlHolder_getAdaptiveExtension_noExtension() throws Exception { Ext2 [MASK] = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1""); UrlHolder holder = new UrlHolder(); holder.setUrl(url); try { [MASK].echo(holder, ""haha""); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString(""Failed to get extension"")); } url = url.addParameter(""ext2"", ""XXX""); holder.setUrl(url); try { [MASK].echo(holder, ""haha""); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString(""No such extension"")); } } @Test public void test_urlHolder_getAdaptiveExtension_UrlNpe() throws Exception { Ext2 [MASK] = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); try { [MASK].echo(null, ""haha""); fail(); } catch (IllegalArgumentException e) { assertEquals(""org.apache.dubbo.common.extension.ext2.UrlHolder argument == null"", e.getMessage()); } try { [MASK].echo(new UrlHolder(), ""haha""); fail(); } catch (IllegalArgumentException e) { assertEquals(""org.apache.dubbo.common.extension.ext2.UrlHolder argument getUrl() == null"", e.getMessage()); } } @Test public void test_urlHolder_getAdaptiveExtension_ExceptionWhenNotAdativeMethod() throws Exception { Ext2 [MASK] = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); Map map = new HashMap(); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1"", map); try { [MASK].bang(url, 33); fail(); } catch (UnsupportedOperationException expected) { assertThat(expected.getMessage(), containsString(""method "")); assertThat( expected.getMessage(), containsString(""of interface org.apache.dubbo.common.extension.ext2.Ext2 is not adaptive method!"")); } } @Test public void test_urlHolder_getAdaptiveExtension_ExceptionWhenNameNotProvided() throws Exception { Ext2 [MASK] = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1""); UrlHolder holder = new UrlHolder(); holder.setUrl(url); try { [MASK].echo(holder, ""impl1""); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString(""Failed to get extension"")); } url = url.addParameter(""key1"", ""impl1""); holder.setUrl(url); try { [MASK].echo(holder, ""haha""); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString(""Failed to get extension (org.apache.dubbo.common.extension.ext2.Ext2) name from url"")); } } @Test public void test_getAdaptiveExtension_inject() throws Exception { LogUtil.start(); Ext6 [MASK] = ExtensionLoader.getExtensionLoader(Ext6.class).getAdaptiveExtension(); URL url = new URL(""p1"", ""1.2.3.4"", 1010, ""path1""); url = url.addParameters(""ext6"", ""impl1""); assertEquals(""Ext6Impl1-echo-Ext1Impl1-echo"", [MASK].echo(url, ""ha"")); Assertions.assertTrue(LogUtil.checkNoError(), ""can not find error.""); LogUtil.stop(); url = url.addParameters(""simple.[MASK]"", ""impl2""); assertEquals(""Ext6Impl1-echo-Ext1Impl2-echo"", [MASK].echo(url, ""ha"")); } @Test public void test_getAdaptiveExtension_InjectNotExtFail() throws Exception { Ext6 [MASK] = ExtensionLoader.getExtensionLoader(Ext6.class).getExtension(""impl2""); Ext6Impl2 impl = (Ext6Impl2) [MASK]; assertNull(impl.getList()); } }",ext,java,incubator-dubbo "package org.apache.dubbo.rpc.gen.thrift; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.BitSet; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public class Demo { public interface Iface { boolean echoBool(boolean arg) throws org.apache.thrift.TException; byte echoByte(byte arg) throws org.apache.thrift.TException; short echoI16(short arg) throws org.apache.thrift.TException; int echoI32(int arg) throws org.apache.thrift.TException; long echoI64(long arg) throws org.apache.thrift.TException; double echoDouble(double arg) throws org.apache.thrift.TException; String echoString(String arg) throws org.apache.thrift.TException; } public interface AsyncIface { void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; void echoDouble(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; void echoString(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; } public static class Client extends org.apache.thrift.TServiceClient implements Iface { public Client(org.apache.thrift.protocol.TProtocol prot) { super(prot, prot); } public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { super(iprot, oprot); } public boolean echoBool(boolean arg) throws org.apache.thrift.TException { send_echoBool(arg); return recv_echoBool(); } public void send_echoBool(boolean arg) throws org.apache.thrift.TException { echoBool_args args = new echoBool_args(); args.setArg(arg); sendBase(""echoBool"", args); } public boolean recv_echoBool() throws org.apache.thrift.TException { echoBool_result result = new echoBool_result(); receiveBase(result, ""echoBool""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoBool failed: unknown result""); } public byte echoByte(byte arg) throws org.apache.thrift.TException { send_echoByte(arg); return recv_echoByte(); } public void send_echoByte(byte arg) throws org.apache.thrift.TException { echoByte_args args = new echoByte_args(); args.setArg(arg); sendBase(""echoByte"", args); } public byte recv_echoByte() throws org.apache.thrift.TException { echoByte_result result = new echoByte_result(); receiveBase(result, ""echoByte""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoByte failed: unknown result""); } public short echoI16(short arg) throws org.apache.thrift.TException { send_echoI16(arg); return recv_echoI16(); } public void send_echoI16(short arg) throws org.apache.thrift.TException { echoI16_args args = new echoI16_args(); args.setArg(arg); sendBase(""echoI16"", args); } public short recv_echoI16() throws org.apache.thrift.TException { echoI16_result result = new echoI16_result(); receiveBase(result, ""echoI16""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoI16 failed: unknown result""); } public int echoI32(int arg) throws org.apache.thrift.TException { send_echoI32(arg); return recv_echoI32(); } public void send_echoI32(int arg) throws org.apache.thrift.TException { echoI32_args args = new echoI32_args(); args.setArg(arg); sendBase(""echoI32"", args); } public int recv_echoI32() throws org.apache.thrift.TException { echoI32_result result = new echoI32_result(); receiveBase(result, ""echoI32""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoI32 failed: unknown result""); } public long echoI64(long arg) throws org.apache.thrift.TException { send_echoI64(arg); return recv_echoI64(); } public void send_echoI64(long arg) throws org.apache.thrift.TException { echoI64_args args = new echoI64_args(); args.setArg(arg); sendBase(""echoI64"", args); } public long recv_echoI64() throws org.apache.thrift.TException { echoI64_result result = new echoI64_result(); receiveBase(result, ""echoI64""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoI64 failed: unknown result""); } public double echoDouble(double arg) throws org.apache.thrift.TException { send_echoDouble(arg); return recv_echoDouble(); } public void send_echoDouble(double arg) throws org.apache.thrift.TException { echoDouble_args args = new echoDouble_args(); args.setArg(arg); sendBase(""echoDouble"", args); } public double recv_echoDouble() throws org.apache.thrift.TException { echoDouble_result result = new echoDouble_result(); receiveBase(result, ""echoDouble""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoDouble failed: unknown result""); } public String echoString(String arg) throws org.apache.thrift.TException { send_echoString(arg); return recv_echoString(); } public void send_echoString(String arg) throws org.apache.thrift.TException { echoString_args args = new echoString_args(); args.setArg(arg); sendBase(""echoString"", args); } public String recv_echoString() throws org.apache.thrift.TException { echoString_result result = new echoString_result(); receiveBase(result, ""echoString""); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, ""echoString failed: unknown result""); } public static class Factory implements org.apache.thrift.TServiceClientFactory { public Factory() { } public Client getClient(org.apache.thrift.protocol.TProtocol prot) { return new Client(prot); } public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { return new Client(iprot, oprot); } } } public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoBool_call method_call = new echoBool_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoByte_call method_call = new echoByte_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoI16_call method_call = new echoI16_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoI32_call method_call = new echoI32_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoI64_call method_call = new echoI64_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public void echoDouble(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoDouble_call method_call = new echoDouble_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public void echoString(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); echoString_call method_call = new echoString_call(arg, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { private org.apache.thrift.async.TAsyncClientManager clientManager; private org.apache.thrift.protocol.TProtocolFactory protocolFactory; public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public static class echoBool_call extends org.apache.thrift.async.TAsyncMethodCall { private boolean arg; public echoBool_call(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoBool"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoBool_args args = new echoBool_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoBool(); } } public static class echoByte_call extends org.apache.thrift.async.TAsyncMethodCall { private byte arg; public echoByte_call(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoByte"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoByte_args args = new echoByte_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoByte(); } } public static class echoI16_call extends org.apache.thrift.async.TAsyncMethodCall { private short arg; public echoI16_call(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoI16"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoI16_args args = new echoI16_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoI16(); } } public static class echoI32_call extends org.apache.thrift.async.TAsyncMethodCall { private int arg; public echoI32_call(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoI32"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoI32_args args = new echoI32_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoI32(); } } public static class echoI64_call extends org.apache.thrift.async.TAsyncMethodCall { private long arg; public echoI64_call(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoI64"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoI64_args args = new echoI64_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoI64(); } } public static class echoDouble_call extends org.apache.thrift.async.TAsyncMethodCall { private double arg; public echoDouble_call(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoDouble"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoDouble_args args = new echoDouble_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoDouble(); } } public static class echoString_call extends org.apache.thrift.async.TAsyncMethodCall { private String arg; public echoString_call(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.arg = arg; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(""echoString"", org.apache.thrift.protocol.TMessageType.CALL, 0)); echoString_args args = new echoString_args(); args.setArg(arg); args.write(prot); prot.writeMessageEnd(); } public String getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException(""Method call not finished!""); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_echoString(); } } } public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(I iface) { super(iface, getProcessMap(new HashMap>())); } protected Processor(I iface, Map> processMap) { super(iface, getProcessMap(processMap)); } private static Map> getProcessMap(Map> processMap) { processMap.put(""echoBool"", new echoBool()); processMap.put(""echoByte"", new echoByte()); processMap.put(""echoI16"", new echoI16()); processMap.put(""echoI32"", new echoI32()); processMap.put(""echoI64"", new echoI64()); processMap.put(""echoDouble"", new echoDouble()); processMap.put(""echoString"", new echoString()); return processMap; } private static class echoBool extends org.apache.thrift.ProcessFunction { public echoBool() { super(""echoBool""); } public echoBool_args getEmptyArgsInstance() { return new echoBool_args(); } @Override protected boolean isOneway() { return false; } public echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { echoBool_result result = new echoBool_result(); result.success = iface.echoBool(args.arg); result.setSuccessIsSet(true); return result; } } private static class echoByte extends org.apache.thrift.ProcessFunction { public echoByte() { super(""echoByte""); } public echoByte_args getEmptyArgsInstance() { return new echoByte_args(); } @Override protected boolean isOneway() { return false; } public echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { echoByte_result result = new echoByte_result(); result.success = iface.echoByte(args.arg); result.setSuccessIsSet(true); return result; } } private static class echoI16 extends org.apache.thrift.ProcessFunction { public echoI16() { super(""echoI16""); } public echoI16_args getEmptyArgsInstance() { return new echoI16_args(); } @Override protected boolean isOneway() { return false; } public echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { echoI16_result result = new echoI16_result(); result.success = iface.echoI16(args.arg); result.setSuccessIsSet(true); return result; } } private static class echoI32 extends org.apache.thrift.ProcessFunction { public echoI32() { super(""echoI32""); } public echoI32_args getEmptyArgsInstance() { return new echoI32_args(); } @Override protected boolean isOneway() { return false; } public echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { echoI32_result result = new echoI32_result(); result.success = iface.echoI32(args.arg); result.setSuccessIsSet(true); return result; } } private static class echoI64 extends org.apache.thrift.ProcessFunction { public echoI64() { super(""echoI64""); } public echoI64_args getEmptyArgsInstance() { return new echoI64_args(); } @Override protected boolean isOneway() { return false; } public echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { echoI64_result result = new echoI64_result(); result.success = iface.echoI64(args.arg); result.setSuccessIsSet(true); return result; } } private static class echoDouble extends org.apache.thrift.ProcessFunction { public echoDouble() { super(""echoDouble""); } public echoDouble_args getEmptyArgsInstance() { return new echoDouble_args(); } @Override protected boolean isOneway() { return false; } public echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { echoDouble_result result = new echoDouble_result(); result.success = iface.echoDouble(args.arg); result.setSuccessIsSet(true); return result; } } private static class echoString extends org.apache.thrift.ProcessFunction { public echoString() { super(""echoString""); } public echoString_args getEmptyArgsInstance() { return new echoString_args(); } @Override protected boolean isOneway() { return false; } public echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { echoString_result result = new echoString_result(); result.success = iface.echoString(args.arg); return result; } } } public static class echoBool_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoBool_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.BOOL, (short) 1); private static final int __ARG_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_args.class, metaDataMap); } public boolean arg; private BitSet __isset_bit_vector = new BitSet(1); public echoBool_args() { } public echoBool_args( boolean arg) { this(); this.arg = arg; setArgIsSet(true); } public echoBool_args(echoBool_args other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.arg = other.arg; } public echoBool_args deepCopy() { return new echoBool_args(this); } public void clear() { setArgIsSet(false); this.arg = false; } public boolean isArg() { return this.arg; } public echoBool_args setArg(boolean arg) { this.arg = arg; setArgIsSet(true); return this; } public void unsetArg() { __isset_bit_vector.clear(__ARG_ISSET_ID); } public boolean isSetArg() { return __isset_bit_vector.get(__ARG_ISSET_ID); } public void setArgIsSet(boolean value) { __isset_bit_vector.set(__ARG_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((Boolean) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return Boolean.valueOf(isArg()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoBool_args) return this.equals((echoBool_args) that); return false; } public boolean equals(echoBool_args that) { if (that == null) return false; boolean this_present_arg = true; boolean that_present_arg = true; if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (this.arg != that.arg) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoBool_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoBool_args typedOther = (echoBool_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.BOOL) { this.arg = iprot.readBool(); setArgIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); if (!isSetArg()) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not found in serialized data! Struct: "" + toString()); } validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeBool(this.arg); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoBool_args(""); boolean first = true; sb.append(""arg:""); sb.append(this.arg); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoBool_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.BOOL, (short) 0); private static final int __SUCCESS_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_result.class, metaDataMap); } public boolean success; private BitSet __isset_bit_vector = new BitSet(1); public echoBool_result() { } public echoBool_result( boolean success) { this(); this.success = success; setSuccessIsSet(true); } public echoBool_result(echoBool_result other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.success = other.success; } public echoBool_result deepCopy() { return new echoBool_result(this); } public void clear() { setSuccessIsSet(false); this.success = false; } public boolean isSuccess() { return this.success; } public echoBool_result setSuccess(boolean success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bit_vector.clear(__SUCCESS_ISSET_ID); } public boolean isSetSuccess() { return __isset_bit_vector.get(__SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Boolean) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return Boolean.valueOf(isSuccess()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoBool_result) return this.equals((echoBool_result) that); return false; } public boolean equals(echoBool_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoBool_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoBool_result typedOther = (echoBool_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.BOOL) { this.success = iprot.readBool(); setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeBool(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoBool_result(""); boolean first = true; sb.append(""success:""); sb.append(this.success); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoByte_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.BYTE, (short) 1); private static final int __ARG_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_args.class, metaDataMap); } public byte arg; private BitSet __isset_bit_vector = new BitSet(1); public echoByte_args() { } public echoByte_args( byte arg) { this(); this.arg = arg; setArgIsSet(true); } public echoByte_args(echoByte_args other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.arg = other.arg; } public echoByte_args deepCopy() { return new echoByte_args(this); } public void clear() { setArgIsSet(false); this.arg = 0; } public byte getArg() { return this.arg; } public echoByte_args setArg(byte arg) { this.arg = arg; setArgIsSet(true); return this; } public void unsetArg() { __isset_bit_vector.clear(__ARG_ISSET_ID); } public boolean isSetArg() { return __isset_bit_vector.get(__ARG_ISSET_ID); } public void setArgIsSet(boolean value) { __isset_bit_vector.set(__ARG_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((Byte) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return Byte.valueOf(getArg()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoByte_args) return this.equals((echoByte_args) that); return false; } public boolean equals(echoByte_args that) { if (that == null) return false; boolean this_present_arg = true; boolean that_present_arg = true; if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (this.arg != that.arg) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoByte_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoByte_args typedOther = (echoByte_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.BYTE) { this.arg = iprot.readByte(); setArgIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); if (!isSetArg()) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not found in serialized data! Struct: "" + toString()); } validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeByte(this.arg); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoByte_args(""); boolean first = true; sb.append(""arg:""); sb.append(this.arg); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoByte_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.BYTE, (short) 0); private static final int __SUCCESS_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_result.class, metaDataMap); } public byte success; private BitSet __isset_bit_vector = new BitSet(1); public echoByte_result() { } public echoByte_result( byte success) { this(); this.success = success; setSuccessIsSet(true); } public echoByte_result(echoByte_result other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.success = other.success; } public echoByte_result deepCopy() { return new echoByte_result(this); } public void clear() { setSuccessIsSet(false); this.success = 0; } public byte getSuccess() { return this.success; } public echoByte_result setSuccess(byte success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bit_vector.clear(__SUCCESS_ISSET_ID); } public boolean isSetSuccess() { return __isset_bit_vector.get(__SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Byte) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return Byte.valueOf(getSuccess()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoByte_result) return this.equals((echoByte_result) that); return false; } public boolean equals(echoByte_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoByte_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoByte_result typedOther = (echoByte_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.BYTE) { this.success = iprot.readByte(); setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeByte(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoByte_result(""); boolean first = true; sb.append(""success:""); sb.append(this.success); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoI16_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.I16, (short) 1); private static final int __ARG_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_args.class, metaDataMap); } public short arg; private BitSet __isset_bit_vector = new BitSet(1); public echoI16_args() { } public echoI16_args( short arg) { this(); this.arg = arg; setArgIsSet(true); } public echoI16_args(echoI16_args other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.arg = other.arg; } public echoI16_args deepCopy() { return new echoI16_args(this); } public void clear() { setArgIsSet(false); this.arg = 0; } public short getArg() { return this.arg; } public echoI16_args setArg(short arg) { this.arg = arg; setArgIsSet(true); return this; } public void unsetArg() { __isset_bit_vector.clear(__ARG_ISSET_ID); } public boolean isSetArg() { return __isset_bit_vector.get(__ARG_ISSET_ID); } public void setArgIsSet(boolean value) { __isset_bit_vector.set(__ARG_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((Short) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return Short.valueOf(getArg()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoI16_args) return this.equals((echoI16_args) that); return false; } public boolean equals(echoI16_args that) { if (that == null) return false; boolean this_present_arg = true; boolean that_present_arg = true; if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (this.arg != that.arg) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoI16_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoI16_args typedOther = (echoI16_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.I16) { this.arg = iprot.readI16(); setArgIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); if (!isSetArg()) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not found in serialized data! Struct: "" + toString()); } validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeI16(this.arg); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoI16_args(""); boolean first = true; sb.append(""arg:""); sb.append(this.arg); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoI16_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.I16, (short) 0); private static final int __SUCCESS_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_result.class, metaDataMap); } public short success; private BitSet __isset_bit_vector = new BitSet(1); public echoI16_result() { } public echoI16_result( short success) { this(); this.success = success; setSuccessIsSet(true); } public echoI16_result(echoI16_result other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.success = other.success; } public echoI16_result deepCopy() { return new echoI16_result(this); } public void clear() { setSuccessIsSet(false); this.success = 0; } public short getSuccess() { return this.success; } public echoI16_result setSuccess(short success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bit_vector.clear(__SUCCESS_ISSET_ID); } public boolean isSetSuccess() { return __isset_bit_vector.get(__SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Short) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return Short.valueOf(getSuccess()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoI16_result) return this.equals((echoI16_result) that); return false; } public boolean equals(echoI16_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoI16_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoI16_result typedOther = (echoI16_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.I16) { this.success = iprot.readI16(); setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeI16(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoI16_result(""); boolean first = true; sb.append(""success:""); sb.append(this.success); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoI32_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.I32, (short) 1); private static final int __ARG_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_args.class, metaDataMap); } public int arg; private BitSet __isset_bit_vector = new BitSet(1); public echoI32_args() { } public echoI32_args( int arg) { this(); this.arg = arg; setArgIsSet(true); } public echoI32_args(echoI32_args other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.arg = other.arg; } public echoI32_args deepCopy() { return new echoI32_args(this); } public void clear() { setArgIsSet(false); this.arg = 0; } public int getArg() { return this.arg; } public echoI32_args setArg(int arg) { this.arg = arg; setArgIsSet(true); return this; } public void unsetArg() { __isset_bit_vector.clear(__ARG_ISSET_ID); } public boolean isSetArg() { return __isset_bit_vector.get(__ARG_ISSET_ID); } public void setArgIsSet(boolean value) { __isset_bit_vector.set(__ARG_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((Integer) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return Integer.valueOf(getArg()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoI32_args) return this.equals((echoI32_args) that); return false; } public boolean equals(echoI32_args that) { if (that == null) return false; boolean this_present_arg = true; boolean that_present_arg = true; if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (this.arg != that.arg) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoI32_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoI32_args typedOther = (echoI32_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.I32) { this.arg = iprot.readI32(); setArgIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); if (!isSetArg()) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not found in serialized data! Struct: "" + toString()); } validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeI32(this.arg); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoI32_args(""); boolean first = true; sb.append(""arg:""); sb.append(this.arg); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoI32_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.I32, (short) 0); private static final int __SUCCESS_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_result.class, metaDataMap); } public int success; private BitSet __isset_bit_vector = new BitSet(1); public echoI32_result() { } public echoI32_result( int success) { this(); this.success = success; setSuccessIsSet(true); } public echoI32_result(echoI32_result other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.success = other.success; } public echoI32_result deepCopy() { return new echoI32_result(this); } public void clear() { setSuccessIsSet(false); this.success = 0; } public int getSuccess() { return this.success; } public echoI32_result setSuccess(int success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bit_vector.clear(__SUCCESS_ISSET_ID); } public boolean isSetSuccess() { return __isset_bit_vector.get(__SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Integer) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return Integer.valueOf(getSuccess()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoI32_result) return this.equals((echoI32_result) that); return false; } public boolean equals(echoI32_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoI32_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoI32_result typedOther = (echoI32_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.I32) { this.success = iprot.readI32(); setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeI32(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoI32_result(""); boolean first = true; sb.append(""success:""); sb.append(this.success); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoI64_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.I64, (short) 1); private static final int __ARG_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_args.class, metaDataMap); } public long arg; private BitSet __isset_bit_vector = new BitSet(1); public echoI64_args() { } public echoI64_args( long arg) { this(); this.arg = arg; setArgIsSet(true); } public echoI64_args(echoI64_args other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.arg = other.arg; } public echoI64_args deepCopy() { return new echoI64_args(this); } public void clear() { setArgIsSet(false); this.arg = 0; } public long getArg() { return this.arg; } public echoI64_args setArg(long arg) { this.arg = arg; setArgIsSet(true); return this; } public void unsetArg() { __isset_bit_vector.clear(__ARG_ISSET_ID); } public boolean isSetArg() { return __isset_bit_vector.get(__ARG_ISSET_ID); } public void setArgIsSet(boolean value) { __isset_bit_vector.set(__ARG_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((Long) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return Long.valueOf(getArg()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoI64_args) return this.equals((echoI64_args) that); return false; } public boolean equals(echoI64_args that) { if (that == null) return false; boolean this_present_arg = true; boolean that_present_arg = true; if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (this.arg != that.arg) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoI64_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoI64_args typedOther = (echoI64_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.I64) { this.arg = iprot.readI64(); setArgIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); if (!isSetArg()) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not found in serialized data! Struct: "" + toString()); } validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeI64(this.arg); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoI64_args(""); boolean first = true; sb.append(""arg:""); sb.append(this.arg); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoI64_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.I64, (short) 0); private static final int __SUCCESS_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_result.class, metaDataMap); } public long success; private BitSet __isset_bit_vector = new BitSet(1); public echoI64_result() { } public echoI64_result( long success) { this(); this.success = success; setSuccessIsSet(true); } public echoI64_result(echoI64_result other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.success = other.success; } public echoI64_result deepCopy() { return new echoI64_result(this); } public void clear() { setSuccessIsSet(false); this.success = 0; } public long getSuccess() { return this.success; } public echoI64_result setSuccess(long success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bit_vector.clear(__SUCCESS_ISSET_ID); } public boolean isSetSuccess() { return __isset_bit_vector.get(__SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Long) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return Long.valueOf(getSuccess()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoI64_result) return this.equals((echoI64_result) that); return false; } public boolean equals(echoI64_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoI64_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoI64_result typedOther = (echoI64_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.I64) { this.success = iprot.readI64(); setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeI64(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoI64_result(""); boolean first = true; sb.append(""success:""); sb.append(this.success); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoDouble_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.DOUBLE, (short) 1); private static final int __ARG_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_args.class, metaDataMap); } public double arg; private BitSet __isset_bit_vector = new BitSet(1); public echoDouble_args() { } public echoDouble_args( double arg) { this(); this.arg = arg; setArgIsSet(true); } public echoDouble_args(echoDouble_args other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.arg = other.arg; } public echoDouble_args deepCopy() { return new echoDouble_args(this); } public void clear() { setArgIsSet(false); this.arg = 0.0; } public double getArg() { return this.arg; } public echoDouble_args setArg(double arg) { this.arg = arg; setArgIsSet(true); return this; } public void unsetArg() { __isset_bit_vector.clear(__ARG_ISSET_ID); } public boolean isSetArg() { return __isset_bit_vector.get(__ARG_ISSET_ID); } public void setArgIsSet(boolean value) { __isset_bit_vector.set(__ARG_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((Double) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return Double.valueOf(getArg()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoDouble_args) return this.equals((echoDouble_args) that); return false; } public boolean equals(echoDouble_args that) { if (that == null) return false; boolean this_present_arg = true; boolean that_present_arg = true; if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (this.arg != that.arg) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoDouble_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoDouble_args typedOther = (echoDouble_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.DOUBLE) { this.arg = iprot.readDouble(); setArgIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); if (!isSetArg()) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not found in serialized data! Struct: "" + toString()); } validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeDouble(this.arg); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoDouble_args(""); boolean first = true; sb.append(""arg:""); sb.append(this.arg); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoDouble_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.DOUBLE, (short) 0); private static final int __SUCCESS_ISSET_ID = 0; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_result.class, metaDataMap); } public double success; private BitSet __isset_bit_vector = new BitSet(1); public echoDouble_result() { } public echoDouble_result( double success) { this(); this.success = success; setSuccessIsSet(true); } public echoDouble_result(echoDouble_result other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.success = other.success; } public echoDouble_result deepCopy() { return new echoDouble_result(this); } public void clear() { setSuccessIsSet(false); this.success = 0.0; } public double getSuccess() { return this.success; } public echoDouble_result setSuccess(double success) { this.success = success; setSuccessIsSet(true); return this; } public void unsetSuccess() { __isset_bit_vector.clear(__SUCCESS_ISSET_ID); } public boolean isSetSuccess() { return __isset_bit_vector.get(__SUCCESS_ISSET_ID); } public void setSuccessIsSet(boolean value) { __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((Double) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return Double.valueOf(getSuccess()); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoDouble_result) return this.equals((echoDouble_result) that); return false; } public boolean equals(echoDouble_result that) { if (that == null) return false; boolean this_present_success = true; boolean that_present_success = true; if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (this.success != that.success) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoDouble_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoDouble_result typedOther = (echoDouble_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.DOUBLE) { this.success = iprot.readDouble(); setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeDouble(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoDouble_result(""); boolean first = true; sb.append(""success:""); sb.append(this.success); first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoString_args""); private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField(""arg"", org.apache.thrift.protocol.TType.STRING, (short) 1); static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData(""arg"", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_args.class, metaDataMap); } public String arg; public echoString_args() { } public echoString_args( String arg) { this(); this.arg = arg; } public echoString_args(echoString_args other) { if (other.isSetArg()) { this.arg = other.arg; } } public echoString_args deepCopy() { return new echoString_args(this); } public void clear() { this.arg = null; } public String getArg() { return this.arg; } public echoString_args setArg(String arg) { this.arg = arg; return this; } public void unsetArg() { this.arg = null; } public boolean isSetArg() { return this.arg != null; } public void setArgIsSet(boolean value) { if (!value) { this.arg = null; } } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case ARG: if (value == null) { unsetArg(); } else { setArg((String) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case ARG: return getArg(); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case ARG: return isSetArg(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoString_args) return this.equals((echoString_args) that); return false; } public boolean equals(echoString_args that) { if (that == null) return false; boolean this_present_arg = true && this.isSetArg(); boolean that_present_arg = true && that.isSetArg(); if (this_present_arg || that_present_arg) { if (!(this_present_arg && that_present_arg)) return false; if (!this.arg.equals(that.arg)) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoString_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoString_args typedOther = (echoString_args) other; lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); if (lastComparison != 0) { return lastComparison; } if (isSetArg()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 1: if ([MASK].type == org.apache.thrift.protocol.TType.STRING) { this.arg = iprot.readString(); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); if (this.arg != null) { oprot.writeFieldBegin(ARG_FIELD_DESC); oprot.writeString(this.arg); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoString_args(""); boolean first = true; sb.append(""arg:""); if (this.arg == null) { sb.append(""null""); } else { sb.append(this.arg); } first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { if (arg == null) { throw new org.apache.thrift.protocol.TProtocolException(""Required [MASK] 'arg' was not present! Struct: "" + toString()); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { ARG((short) 1, ""arg""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 1: return ARG; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(""echoString_result""); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(""success"", org.apache.thrift.protocol.TType.STRING, (short) 0); static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(""success"", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_result.class, metaDataMap); } public String success; public echoString_result() { } public echoString_result( String success) { this(); this.success = success; } public echoString_result(echoString_result other) { if (other.isSetSuccess()) { this.success = other.success; } } public echoString_result deepCopy() { return new echoString_result(this); } public void clear() { this.success = null; } public String getSuccess() { return this.success; } public echoString_result setSuccess(String success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public void setFieldValue(_Fields [MASK], Object value) { switch ([MASK]) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((String) value); } break; } } public Object getFieldValue(_Fields [MASK]) { switch ([MASK]) { case SUCCESS: return getSuccess(); } throw new IllegalStateException(); } public boolean isSet(_Fields [MASK]) { if ([MASK] == null) { throw new IllegalArgumentException(); } switch ([MASK]) { case SUCCESS: return isSetSuccess(); } throw new IllegalStateException(); } public boolean equals(Object that) { if (that == null) return false; if (that instanceof echoString_result) return this.equals((echoString_result) that); return false; } public boolean equals(echoString_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } return true; } public int hashCode() { return 0; } public int compareTo(echoString_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; echoString_result typedOther = (echoString_result) other; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField [MASK]; iprot.readStructBegin(); while (true) { [MASK] = iprot.readFieldBegin(); if ([MASK].type == org.apache.thrift.protocol.TType.STOP) { break; } switch ([MASK].id) { case 0: if ([MASK].type == org.apache.thrift.protocol.TType.STRING) { this.success = iprot.readString(); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, [MASK].type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { oprot.writeStructBegin(STRUCT_DESC); if (this.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeString(this.success); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } public String toString() { StringBuilder sb = new StringBuilder(""echoString_result(""); boolean first = true; sb.append(""success:""); if (this.success == null) { sb.append(""null""); } else { sb.append(this.success); } first = false; sb.append("")""); return sb.toString(); } public void validate() throws org.apache.thrift.TException { } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short) 0, ""success""); private static final Map byName = new HashMap(); static { for (_Fields [MASK] : EnumSet.allOf(_Fields.class)) { byName.put([MASK].getFieldName(), [MASK]); } } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public static _Fields findByThriftId(int fieldId) { switch (fieldId) { case 0: return SUCCESS; default: return null; } } public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException(""Field "" + fieldId + "" doesn't exist!""); return fields; } public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } } }",field,java,incubator-dubbo "package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.qos.legacy.service.DemoServiceImpl; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceRepository; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; public class InvokerTelnetHandlerTest { private static TelnetHandler invoke = new InvokeTelnetHandler(); private static TelnetHandler select = new SelectTelnetHandler(); private Channel mockChannel; private final ServiceRepository repository = ApplicationModel.getServiceRepository(); @BeforeEach public void setup() { ApplicationModel.reset(); } @AfterEach public void after() { ProtocolUtils.closeAll(); } @SuppressWarnings(""unchecked"") @Test public void testInvokeDefaultService() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(DemoService.class.getName()); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.telnet(mockChannel, ""echo(\""ok\"")""); assertTrue(result.contains(""result: \""ok\"""")); } @SuppressWarnings(""unchecked"") @Test public void testInvokeWithSpecifyService() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(null); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.telnet(mockChannel, ""DemoService.echo(\""ok\"")""); assertTrue(result.contains(""result: \""ok\"""")); } @SuppressWarnings(""unchecked"") @Test public void testInvokeByPassingNullValue() { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(DemoService.class.getName()); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); try { invoke.telnet(mockChannel, ""sayHello(null)""); } catch (Exception ex) { assertTrue(ex instanceof NullPointerException); } } @Test public void testInvokeByPassingEnumValue() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(null); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.telnet(mockChannel, ""getType(\""High\"")""); assertTrue(result.contains(""result: \""High\"""")); } @SuppressWarnings(""unchecked"") @Test public void testOverriddenMethodWithSpecifyParamType() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(DemoService.class.getName()); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.telnet(mockChannel, ""getPerson({\""name\"":\""zhangsan\"",\""age\"":12,\""class\"":\""org.apache.dubbo.qos.legacy.service.Person\""})""); assertTrue(result.contains(""result: 12"")); } @Test public void testInvokeOverriddenMethodBySelect() throws RemotingException { mockChannel = spy(getChannelInstance()); given(mockChannel.getAttribute(""telnet.service"")).willReturn(DemoService.class.getName()); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = ""{\""name\"":\""Dubbo\"",\""age\"":8}""; String result = invoke.telnet(mockChannel, ""getPerson("" + param + "")""); assertTrue(result.contains(""Please use the select command to select the method you want to invoke. eg: select 1"")); result = select.telnet(mockChannel, ""1""); assertTrue(result.contains(""result: 8"") || result.contains(""result: \""Dubbo\"""")); result = select.telnet(mockChannel, ""2""); assertTrue(result.contains(""result: 8"") || result.contains(""result: \""Dubbo\"""")); } @Test public void testInvokeMethodWithMapParameter() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(DemoService.class.getName()); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = ""{1:\""Dubbo\"",2:\""test\""}""; String result = invoke.telnet(mockChannel, ""getMap("" + param + "")""); assertTrue(result.contains(""result: {1:\""Dubbo\"",2:\""test\""}"")); } @Test public void testInvokeMultiJsonParamMethod() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(null); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:5555"")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress(""127.0.0.1:20886"")); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = ""{\""name\"":\""Dubbo\"",\""age\"":8},{\""name\"":\""Apache\"",\""age\"":20}""; String result = invoke.telnet(mockChannel, ""getPerson("" + param + "")""); assertTrue(result.contains(""result: 28"")); } @Test public void testMessageNull() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(null); String result = invoke.telnet(mockChannel, null); assertEquals(""Please input method name, eg: \r\ninvoke xxxMethod(1234, \""abcd\"", {\""prop\"" : \""value\""})\r\ninvoke XxxService.xxxMethod(1234, \""abcd\"", {\""prop\"" : \""value\""})\r\ninvoke com.xxx.XxxService.xxxMethod(1234, \""abcd\"", {\""prop\"" : \""value\""})"", result); } @Test public void testInvalidMessage() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute(""telnet.service"")).willReturn(null); String result = invoke.telnet(mockChannel, ""(""); assertEquals(""Invalid parameters, format: service.method(args)"", result); } private void registerProvider(String key, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); repository.registerProvider( key, impl, serviceDescriptor, null, null ); } private Channel getChannelInstance() { return new Channel() { private final Map attributes = new ConcurrentHashMap(); @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public boolean isConnected() { return false; } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void setAttribute(String key, Object value) { if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public URL getUrl() { return null; } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException { } @Override public void send(Object message, boolean sent) throws RemotingException { } @Override public void close() { } @Override public void close(int [MASK]) { } @Override public void startClose() { } @Override public boolean isClosed() { return false; } }; } }",timeout,java,incubator-dubbo "package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue_for_huangfeng extends TestCase { public void test_for_huangfeng() throws Exception { String json = ""{\""[MASK]\"":\""Y\""}""; Model model = JSON.parseObject(json, Model.class); assertTrue(model.isSuccess()); } public void test_for_huangfeng_t() throws Exception { String json = ""{\""[MASK]\"":\""T\""}""; Model model = JSON.parseObject(json, Model.class); assertTrue(model.isSuccess()); } public void test_for_huangfeng_is_t() throws Exception { String json = ""{\""isSuccess\"":\""T\""}""; Model model = JSON.parseObject(json, Model.class); assertTrue(model.isSuccess()); } public void test_for_huangfeng_false() throws Exception { String json = ""{\""[MASK]\"":\""N\""}""; Model model = JSON.parseObject(json, Model.class); assertFalse(model.isSuccess()); } public void test_for_huangfeng_false_f() throws Exception { String json = ""{\""[MASK]\"":\""F\""}""; Model model = JSON.parseObject(json, Model.class); assertFalse(model.isSuccess()); } public static class Model { private boolean [MASK]; public boolean isSuccess() { return [MASK]; } public void setSuccess(boolean [MASK]) { this.[MASK] = [MASK]; } } }",success,java,fastjson "package com.alibaba.json.bvt.[MASK]; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.[MASK].DefaultJSONParser; import com.alibaba.fastjson.[MASK].JSONReaderScanner; public class JSONReaderScannerTest_decimal extends TestCase { public void test_scanInt() throws Exception { StringBuffer buf = new StringBuffer(); buf.append('['); for (int i = 0; i < 1024; ++i) { if (i != 0) { buf.append(','); } buf.append(i + "".0""); } buf.append(']'); Reader reader = new StringReader(buf.toString()); JSONReaderScanner scanner = new JSONReaderScanner(reader); DefaultJSONParser [MASK] = new DefaultJSONParser(scanner); JSONArray array = (JSONArray) [MASK].parse(); for (int i = 0; i < array.size(); ++i) { BigDecimal value = new BigDecimal(i + "".0""); Assert.assertEquals(value, array.get(i)); } } }",parser,java,fastjson "package io.netty5.handler.codec.compression; import io.netty5.buffer.BufferInputStream; import io.netty5.buffer.Buffer; import io.netty5.buffer.CompositeBuffer; import io.netty5.channel.embedded.EmbeddedChannel; import lzma.sdk.lzma.Decoder; import lzma.streams.LzmaInputStream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class LzmaFrameEncoderTest extends AbstractEncoderTest { @Override protected EmbeddedChannel createChannel() { return new EmbeddedChannel(new CompressionHandler(LzmaCompressor.newFactory())); } @ParameterizedTest @MethodSource(""smallData"") @Override public void testCompressionOfBatchedFlowOfData(Buffer data) throws Exception { testCompressionOfBatchedFlow(data); } @Override protected void testCompressionOfBatchedFlow(final Buffer data) throws Exception { try (Buffer expected = data.copy()) { List [MASK] = new ArrayList<>(); final int dataLength = data.readableBytes(); int written = 0, length = rand.nextInt(50); while (written + length < dataLength) { Buffer in = data.readSplit(length); assertTrue(channel.writeOutbound(in)); written += length; [MASK].add(length); length = rand.nextInt(50); } length = dataLength - written; Buffer in = data.readSplit(length); [MASK].add(length); assertTrue(channel.writeOutbound(in)); assertTrue(channel.finish()); class TestSupplier implements Supplier { int proccessed; @Override public Buffer get() { Buffer msg = channel.readOutbound(); if (msg == null) { return null; } try { return decompress(msg, [MASK].get(proccessed++)); } catch (Exception e) { throw new IllegalStateException(e); } } } TestSupplier supplier = new TestSupplier(); try (CompositeBuffer decompressed = CompressionTestUtils.compose(channel.bufferAllocator(), supplier)) { assertEquals([MASK].size(), supplier.proccessed); assertEquals(expected, decompressed); } } } @Override protected Buffer decompress(Buffer compressed, int originalLength) throws Exception { InputStream is = new BufferInputStream(compressed.send()); LzmaInputStream lzmaIs = null; byte[] decompressed = new byte[originalLength]; try { lzmaIs = new LzmaInputStream(is, new Decoder()); int remaining = originalLength; while (remaining > 0) { int read = lzmaIs.read(decompressed, originalLength - remaining, remaining); if (read > 0) { remaining -= read; } else { break; } } assertEquals(-1, lzmaIs.read()); } finally { if (lzmaIs != null) { lzmaIs.close(); } if (is != null) { is.close(); } } return channel.bufferAllocator().copyOf(decompressed); } }",originalLengths,java,netty "package jadx.core.dex.visitors.regions; import java.util.ArrayDeque; import java.util.Deque; import jadx.core.dex.nodes.IBlock; import jadx.core.dex.nodes.IRegion; import jadx.core.dex.nodes.MethodNode; public abstract class TracedRegionVisitor implements IRegionVisitor { protected final Deque [MASK] = new ArrayDeque<>(); @Override public boolean enterRegion(MethodNode mth, IRegion region) { [MASK].push(region); return true; } @Override public void processBlock(MethodNode mth, IBlock container) { IRegion curRegion = [MASK].peek(); processBlockTraced(mth, container, curRegion); } public abstract void processBlockTraced(MethodNode mth, IBlock container, IRegion currentRegion); @Override public void leaveRegion(MethodNode mth, IRegion region) { [MASK].pop(); } }",regionStack,java,jadx "package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import com.alibaba.fastjson.JSON; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX; import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX; import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX; import static org.apache.dubbo.rpc.Constants.THROW_PREFIX; final public class MockInvoker implements Invoker { private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private static final Map> MOCK_MAP = new ConcurrentHashMap>(); private static final Map THROWABLE_MAP = new ConcurrentHashMap(); private final URL url; private final Class type; public MockInvoker(URL url, Class type) { this.url = url; this.type = type; } public static Object parseMockValue(String [MASK]) throws Exception { return parseMockValue([MASK], null); } public static Object parseMockValue(String [MASK], Type[] returnTypes) throws Exception { Object value = null; if (""empty"".equals([MASK])) { value = ReflectUtils.getEmptyObject(returnTypes != null && returnTypes.length > 0 ? (Class) returnTypes[0] : null); } else if (""null"".equals([MASK])) { value = null; } else if (""true"".equals([MASK])) { value = true; } else if (""false"".equals([MASK])) { value = false; } else if ([MASK].length() >= 2 && ([MASK].startsWith(""\"""") && [MASK].endsWith(""\"""") || [MASK].startsWith(""\'"") && [MASK].endsWith(""\'""))) { value = [MASK].subSequence(1, [MASK].length() - 1); } else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) { value = [MASK]; } else if (StringUtils.isNumeric([MASK], false)) { value = JSON.parse([MASK]); } else if ([MASK].startsWith(""{"")) { value = JSON.parseObject([MASK], Map.class); } else if ([MASK].startsWith(""["")) { value = JSON.parseObject([MASK], List.class); } else { value = [MASK]; } if (ArrayUtils.isNotEmpty(returnTypes)) { value = PojoUtils.realize(value, (Class) returnTypes[0], returnTypes.length > 1 ? returnTypes[1] : null); } return value; } @Override public Result invoke(Invocation invocation) throws RpcException { if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(this); } String [MASK] = getUrl().getMethodParameter(invocation.getMethodName(),MOCK_KEY); if (StringUtils.isBlank([MASK])) { throw new RpcException(new IllegalAccessException(""[MASK] can not be null. url :"" + url)); } [MASK] = normalizeMock(URL.decode([MASK])); if ([MASK].startsWith(RETURN_PREFIX)) { [MASK] = [MASK].substring(RETURN_PREFIX.length()).trim(); try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value = parseMockValue([MASK], returnTypes); return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } catch (Exception ew) { throw new RpcException(""[MASK] return invoke error. method :"" + invocation.getMethodName() + "", [MASK]:"" + [MASK] + "", url: "" + url, ew); } } else if ([MASK].startsWith(THROW_PREFIX)) { [MASK] = [MASK].substring(THROW_PREFIX.length()).trim(); if (StringUtils.isBlank([MASK])) { throw new RpcException(""mocked exception for service degradation.""); } else { Throwable t = getThrowable([MASK]); throw new RpcException(RpcException.BIZ_EXCEPTION, t); } } else { try { Invoker invoker = getInvoker([MASK]); return invoker.invoke(invocation); } catch (Throwable t) { throw new RpcException(""Failed to create [MASK] implementation class "" + [MASK], t); } } } public static Throwable getThrowable(String throwstr) { Throwable throwable = THROWABLE_MAP.get(throwstr); if (throwable != null) { return throwable; } try { Throwable t; Class bizException = ReflectUtils.forName(throwstr); Constructor constructor; constructor = ReflectUtils.findConstructor(bizException, String.class); t = (Throwable) constructor.newInstance(new Object[]{""mocked exception for service degradation.""}); if (THROWABLE_MAP.size() < 1000) { THROWABLE_MAP.put(throwstr, t); } return t; } catch (Exception e) { throw new RpcException(""[MASK] throw error :"" + throwstr + "" argument error."", e); } } @SuppressWarnings(""unchecked"") private Invoker getInvoker(String [MASK]) { Class serviceType = (Class) ReflectUtils.forName(url.getServiceInterface()); final boolean isDefault = ConfigUtils.isDefault([MASK]); String mockService = isDefault ? serviceType.getName() + ""Mock"" : [MASK]; Invoker invoker = (Invoker) MOCK_MAP.get(mockService); if (invoker != null) { return invoker; } T mockObject = (T) getMockObject([MASK], serviceType); invoker = PROXY_FACTORY.getInvoker(mockObject, serviceType, url); if (MOCK_MAP.size() < 10000) { MOCK_MAP.put(mockService, invoker); } return invoker; } @SuppressWarnings(""unchecked"") public static Object getMockObject(String mockService, Class serviceType) { boolean isDefault = ConfigUtils.isDefault(mockService); if (isDefault) { mockService = serviceType.getName() + ""Mock""; } Class mockClass; try { mockClass = ReflectUtils.forName(mockService); } catch (Exception e) { if (!isDefault) { ExtensionFactory extensionFactory = ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension(); Object obj = extensionFactory.getExtension(serviceType, mockService); if (obj != null) { return obj; } } throw new IllegalStateException(""Did not find [MASK] class or instance "" + mockService + "", please check if there's [MASK] class or instance implementing interface "" + serviceType.getName(), e); } if (mockClass == null || !serviceType.isAssignableFrom(mockClass)) { throw new IllegalStateException(""The [MASK] class "" + mockClass.getName() + "" not implement interface "" + serviceType.getName()); } try { return mockClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(""No default constructor from [MASK] class "" + mockClass.getName(), e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } public static String normalizeMock(String [MASK]) { if ([MASK] == null) { return [MASK]; } [MASK] = [MASK].trim(); if ([MASK].length() == 0) { return [MASK]; } if (RETURN_KEY.equalsIgnoreCase([MASK])) { return RETURN_PREFIX + ""null""; } if (ConfigUtils.isDefault([MASK]) || ""fail"".equalsIgnoreCase([MASK]) || ""force"".equalsIgnoreCase([MASK])) { return ""default""; } if ([MASK].startsWith(FAIL_PREFIX)) { [MASK] = [MASK].substring(FAIL_PREFIX.length()).trim(); } if ([MASK].startsWith(FORCE_PREFIX)) { [MASK] = [MASK].substring(FORCE_PREFIX.length()).trim(); } if ([MASK].startsWith(RETURN_PREFIX) || [MASK].startsWith(THROW_PREFIX)) { [MASK] = [MASK].replace('`', '""'); } return [MASK]; } @Override public URL getUrl() { return this.url; } @Override public boolean isAvailable() { return true; } @Override public void destroy() { } @Override public Class getInterface() { return type; } }",mock,java,incubator-dubbo "package com.netflix.hystrix; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import org.junit.Test; import rx.Observable; import rx.Subscriber; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import rx.Subscription; import rx.subjects.ReplaySubject; public class HystrixRequestCacheTest { @Test public void testCache() { HystrixConcurrencyStrategy strategy = HystrixConcurrencyStrategyDefault.getInstance(); HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { HystrixRequestCache cache1 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(""command1""), strategy); cache1.putIfAbsent(""valueA"", new TestObservable(""a1"")); cache1.putIfAbsent(""valueA"", new TestObservable(""a2"")); cache1.putIfAbsent(""valueB"", new TestObservable(""b1"")); HystrixRequestCache [MASK] = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(""command2""), strategy); [MASK].putIfAbsent(""valueA"", new TestObservable(""a3"")); assertEquals(""a1"", cache1.get(""valueA"").toObservable().toBlocking().last()); assertEquals(""b1"", cache1.get(""valueB"").toObservable().toBlocking().last()); assertEquals(""a3"", [MASK].get(""valueA"").toObservable().toBlocking().last()); assertNull([MASK].get(""valueB"")); } catch (Exception e) { fail(""Exception: "" + e.getMessage()); e.printStackTrace(); } finally { context.shutdown(); } context = HystrixRequestContext.initializeContext(); try { HystrixRequestCache cache = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(""command1""), strategy); assertNull(cache.get(""valueA"")); assertNull(cache.get(""valueB"")); } finally { context.shutdown(); } } @Test(expected = IllegalStateException.class) public void testCacheWithoutContext() { HystrixRequestCache.getInstance( HystrixCommandKey.Factory.asKey(""command1""), HystrixConcurrencyStrategyDefault.getInstance() ).get(""any""); } @Test public void testClearCache() { HystrixConcurrencyStrategy strategy = HystrixConcurrencyStrategyDefault.getInstance(); HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { HystrixRequestCache cache1 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(""command1""), strategy); cache1.putIfAbsent(""valueA"", new TestObservable(""a1"")); assertEquals(""a1"", cache1.get(""valueA"").toObservable().toBlocking().last()); cache1.clear(""valueA""); assertNull(cache1.get(""valueA"")); } catch (Exception e) { fail(""Exception: "" + e.getMessage()); e.printStackTrace(); } finally { context.shutdown(); } } @Test public void testCacheWithoutRequestContext() { HystrixConcurrencyStrategy strategy = HystrixConcurrencyStrategyDefault.getInstance(); try { HystrixRequestCache cache1 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(""command1""), strategy); cache1.putIfAbsent(""valueA"", new TestObservable(""a1"")); fail(""should throw an exception on cache put""); } catch (Exception e) { e.printStackTrace(); } } private static class TestObservable extends HystrixCachedObservable { public TestObservable(String arg) { super(Observable.just(arg)); } } }",cache2,java,Hystrix "package com.alibaba.json.bvt.issue_1300; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.io.Serializable; import java.util.Arrays; import java.util.List; public class Issue1306 extends TestCase { public void test_for_issue() { Goods goods = new Goods(); goods.setProperties(Arrays.asList(new Goods.Property())); TT tt = new TT(goods); String json = JSON.toJSONString(tt); assertEquals(""{\""goodsList\"":[{\""[MASK]\"":[{}]}]}"", json); TT n = JSON.parseObject(json, TT.class); assertNotNull(n); assertNotNull(n.getGoodsList()); assertNotNull(n.getGoodsList().get(0)); assertNotNull(n.getGoodsList().get(0).getProperties()); } public static abstract class IdEntity implements Cloneable, Serializable{ private static final long serialVersionUID = 4877536176216854937L; public IdEntity() {} public abstract ID getId(); public abstract void setId(ID id); } public static class LongEntity extends IdEntity { private static final long serialVersionUID = -2740365657805589848L; private Long id; @Override public Long getId() { return id; } public void setId(Long id) { this.id = id; } } public static class Goods extends LongEntity{ private static final long serialVersionUID = -5751106975913625097L; private List [MASK]; public List getProperties() { return [MASK]; } public void setProperties(List [MASK]) { this.[MASK] = [MASK]; } public static class Property extends LongEntity{ private static final long serialVersionUID = 7941148286688199390L; } } public static class TT extends LongEntity { private static final long serialVersionUID = 2988415809510669142L; public TT(){} public TT(Goods goods){ goodsList = Arrays.asList(goods); } private List goodsList; public List getGoodsList() { return goodsList; } public void setGoodsList(List goodsList) { this.goodsList = goodsList; } } }",properties,java,fastjson "package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import org.junit.Assert; import org.junit.Test; public final class FieldParserTest extends Assert { private static void checkFields(String expected) throws NotFoundException { String field = expected.replace(""("", """").replace("")"",""""); String [MASK] = FieldParser.parseFieldsInGeneralPurpose(field); assertEquals(expected, [MASK]); } @Test public void testParseField() throws Exception { checkFields(""(15)991231(3103)001750(10)12A""); } @Test public void testParseField2() throws Exception { checkFields(""(15)991231(15)991231(3103)001750(10)12A""); } }",actual,java,zxing "package io.netty5.resolver; import io.netty5.util.concurrent.Future; import io.netty5.util.concurrent.Promise; import java.io.Closeable; import java.util.List; public interface NameResolver extends Closeable { Future resolve(String inetHost); Future resolve(String inetHost, Promise [MASK]); Future> resolveAll(String inetHost); Future> resolveAll(String inetHost, Promise> [MASK]); @Override void close(); }",promise,java,netty "package com.facebook.imagepipeline.memory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import com.facebook.imagepipeline.testing.MockBitmapFactory; import com.facebook.imageutils.BitmapUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.[MASK].InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({""org.mockito.*"", ""org.robolectric.*"", ""androidx.*"", ""android.*""}) @org.robolectric.annotation.Config(manifest = org.robolectric.annotation.Config.NONE) public class BitmapPoolTest { @Mock(answer = Answers.CALLS_REAL_METHODS) public BucketsBitmapPool mPool; @Before public void setup() { MockitoAnnotations.initMocks(this); doAnswer( new Answer() { @Override public Object answer(InvocationOnMock [MASK]) throws Throwable { int size = (Integer) [MASK].getArguments()[0]; return MockBitmapFactory.create( 1, (int) Math.ceil(size / (double) BitmapUtil.RGB_565_BYTES_PER_PIXEL), Bitmap.Config.RGB_565); } }) .when(mPool) .alloc(any(Integer.class)); doAnswer( new Answer() { @Override public Object answer(InvocationOnMock [MASK]) throws Throwable { final Bitmap bitmap = (Bitmap) [MASK].getArguments()[0]; return BitmapUtil.getSizeInByteForBitmap( bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); } }) .when(mPool) .getBucketedSizeForValue(any(Bitmap.class)); } @Test public void testFree() throws Exception { Bitmap bitmap = mPool.alloc(12); mPool.free(bitmap); verify(bitmap).recycle(); } @Test public void testGetBucketedSize() throws Exception { assertEquals(12, (int) mPool.getBucketedSize(12)); assertEquals(56, (int) mPool.getBucketedSize(56)); } @Test public void testGetBucketedSizeForValue() throws Exception { Bitmap bitmap1 = mPool.alloc(12); Bitmap bitmap2 = mPool.alloc(56); Bitmap bitmap3 = MockBitmapFactory.create(7, 8, Config.RGB_565); Bitmap bitmap4 = MockBitmapFactory.create(7, 8, Config.ARGB_8888); assertEquals(12, (int) mPool.getBucketedSizeForValue(bitmap1)); assertEquals(56, (int) mPool.getBucketedSizeForValue(bitmap2)); assertEquals(112, (int) mPool.getBucketedSizeForValue(bitmap3)); assertEquals(224, (int) mPool.getBucketedSizeForValue(bitmap4)); } @Test public void testGetSizeInBytes() throws Exception { assertEquals(48, mPool.getSizeInBytes(48)); assertEquals(224, mPool.getSizeInBytes(224)); } @Test public void testIsReusable() throws Exception { Bitmap b1 = mPool.alloc(12); assertTrue(mPool.isReusable(b1)); Bitmap b2 = MockBitmapFactory.create(3, 4, Bitmap.Config.ARGB_8888); assertTrue(mPool.isReusable(b2)); Bitmap b3 = MockBitmapFactory.create(3, 4, Config.ARGB_4444); assertTrue(mPool.isReusable(b3)); Bitmap b4 = MockBitmapFactory.create(3, 4, Bitmap.Config.ARGB_8888); doReturn(true).when(b4).isRecycled(); assertFalse(mPool.isReusable(b4)); Bitmap b5 = MockBitmapFactory.create(3, 4, Bitmap.Config.ARGB_8888); doReturn(false).when(b5).isMutable(); assertFalse(mPool.isReusable(b5)); } }",invocation,java,fresco "package com.alibaba.json.bvt.bug; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSONObject; public class Bug_for_gongwenhua extends TestCase { public void test_0() throws Exception { String [MASK] = ""{\""FH2\\\""\u0005\\v\u0010\u000e\u0011\u0000\"":0,\""alipa9_login\"":0,\""alipay_login\"":14164,\""durex\"":317,\""intl.datasky\"":0,\""taobao_refund\"":880}""; JSONObject obj = JSONObject.parseObject([MASK]); Assert.assertNotNull(obj); Assert.assertEquals(0, obj.get(""FH2\""\u0005\u000B\u0010\u000e\u0011\u0000"")); } }",text,java,fastjson "package com.facebook.drawee.backends.pipeline; import android.content.res.Resources; import com.facebook.cache.common.CacheKey; import com.facebook.common.internal.ImmutableList; import com.facebook.common.internal.Supplier; import com.facebook.drawee.components.DeferredReleaser; import com.facebook.imagepipeline.cache.MemoryCache; import com.facebook.imagepipeline.drawable.DrawableFactory; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.infer.annotation.Nullsafe; import java.util.concurrent.Executor; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) public class PipelineDraweeControllerFactory { private Resources mResources; private DeferredReleaser mDeferredReleaser; @Nullable private DrawableFactory mAnimatedDrawableFactory; @Nullable private DrawableFactory [MASK]; private Executor mUiThreadExecutor; @Nullable private MemoryCache mMemoryCache; @Nullable private ImmutableList mDrawableFactories; @Nullable private Supplier mDebugOverlayEnabledSupplier; public void init( Resources resources, DeferredReleaser deferredReleaser, @Nullable DrawableFactory animatedDrawableFactory, @Nullable DrawableFactory xmlDrawableFactory, Executor uiThreadExecutor, MemoryCache memoryCache, @Nullable ImmutableList drawableFactories, @Nullable Supplier debugOverlayEnabledSupplier) { mResources = resources; mDeferredReleaser = deferredReleaser; mAnimatedDrawableFactory = animatedDrawableFactory; [MASK] = xmlDrawableFactory; mUiThreadExecutor = uiThreadExecutor; mMemoryCache = memoryCache; mDrawableFactories = drawableFactories; mDebugOverlayEnabledSupplier = debugOverlayEnabledSupplier; } public PipelineDraweeController newController() { PipelineDraweeController controller = internalCreateController( mResources, mDeferredReleaser, mAnimatedDrawableFactory, [MASK], mUiThreadExecutor, mMemoryCache, mDrawableFactories); if (mDebugOverlayEnabledSupplier != null) { controller.setDrawDebugOverlay(mDebugOverlayEnabledSupplier.get()); } return controller; } protected PipelineDraweeController internalCreateController( Resources resources, DeferredReleaser deferredReleaser, @Nullable DrawableFactory animatedDrawableFactory, @Nullable DrawableFactory xmlDrawableFactory, Executor uiThreadExecutor, @Nullable MemoryCache memoryCache, @Nullable ImmutableList drawableFactories) { return new PipelineDraweeController( resources, deferredReleaser, animatedDrawableFactory, xmlDrawableFactory, uiThreadExecutor, memoryCache, drawableFactories); } }",mXmlDrawableFactory,java,fresco "package jadx.api; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import jadx.core.xmlgen.ResContainer; import jadx.plugins.input.dex.DexInputPlugin; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class JadxDecompilerTest { @TempDir File testDir; @Test public void testExampleUsage() { File sampleApk = getFileFromSampleDir(""app-with-fake-dex.apk""); JadxArgs args = new JadxArgs(); args.getInputFiles().add(sampleApk); args.setOutDir(testDir); try (JadxDecompiler jadx = new JadxDecompiler(args)) { jadx.load(); jadx.save(); jadx.printErrorsReport(); for (JavaClass cls : jadx.getClasses()) { System.out.println(cls.getCode()); } assertThat(jadx.getClasses()).hasSize(3); assertThat(jadx.getErrorsCount()).isEqualTo(0); } } @Test public void testDirectDexInput() throws IOException { try (JadxDecompiler jadx = new JadxDecompiler(); InputStream in = new FileInputStream(getFileFromSampleDir(""hello.dex""))) { jadx.addCustomCodeLoader(new DexInputPlugin().loadDexFromInputStream(in, ""input"")); jadx.load(); for (JavaClass cls : jadx.getClasses()) { System.out.println(cls.getCode()); } assertThat(jadx.getClasses()).hasSize(1); assertThat(jadx.getErrorsCount()).isEqualTo(0); } } @Test public void testResourcesLoad() { File sampleApk = getFileFromSampleDir(""app-with-fake-dex.apk""); JadxArgs args = new JadxArgs(); args.getInputFiles().add(sampleApk); args.setOutDir(testDir); args.setSkipSources(true); try (JadxDecompiler jadx = new JadxDecompiler(args)) { jadx.load(); List resources = jadx.getResources(); assertThat(resources).hasSize(8); ResourceFile arsc = resources.stream() .filter(r -> r.getType() == ResourceType.ARSC) .findFirst().orElseThrow(); ResContainer resContainer = arsc.loadContent(); ResContainer xmlRes = resContainer.getSubFiles().stream() .filter(r -> r.getName().equals(""res/values/colors.xml"")) .findFirst().orElseThrow(); assertThat(xmlRes.getText()) .code() .containsOne(""#008577""); } } private static final String TEST_SAMPLES_DIR = ""test-samples/""; public static File getFileFromSampleDir(String [MASK]) { URL resource = JadxDecompilerTest.class.getClassLoader().getResource(TEST_SAMPLES_DIR + [MASK]); assertThat(resource).isNotNull(); String pathStr = resource.getFile(); return new File(pathStr); } }",fileName,java,jadx "package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; @JSONType(typeName = ""Polygon"", orders = {""type"", ""bbox"", ""[MASK]""}) public class Polygon extends Geometry { private double[][][] [MASK]; public Polygon() { super(""Polygon""); } public double[][][] getCoordinates() { return [MASK]; } public void setCoordinates(double[][][] [MASK]) { this.[MASK] = [MASK]; } }",coordinates,java,fastjson "package org.apache.dubbo.registry.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Inject; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; public class ZookeeperRegistryFactory extends AbstractRegistryFactory { private ZookeeperTransporter [MASK]; public ZookeeperRegistryFactory() { this.[MASK] = ZookeeperTransporter.getExtension(); } @Inject(enable = false) public void setZookeeperTransporter(ZookeeperTransporter [MASK]) { this.[MASK] = [MASK]; } @Override public Registry createRegistry(URL url) { return new ZookeeperRegistry(url, [MASK]); } }",zookeeperTransporter,java,incubator-dubbo "package com.alibaba.json.bvt.ref; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSON; public class RefTest3 extends TestCase { public void test_ref() throws Exception { Object[] array = new Object[1]; array[0] = array; Assert.assertEquals(""[{\""$ref\"":\""@\""}]"", JSON.toJSONString(array)); } public void test_parse() throws Exception { Object[] [MASK] = JSON.parseObject(""[{\""$ref\"":\""$\""}]"", Object[].class); Assert.assertSame([MASK], [MASK][0]); } public void test_parse_1() throws Exception { Object[] [MASK] = JSON.parseObject(""[{\""$ref\"":\""@\""}]"", Object[].class); Assert.assertSame([MASK], [MASK][0]); } }",array2,java,fastjson "package com.facebook.imagepipeline.producers; import android.os.SystemClock; import androidx.annotation.VisibleForTesting; import com.facebook.imagepipeline.image.EncodedImage; import com.facebook.imagepipeline.instrumentation.FrescoInstrumenter; import com.facebook.infer.annotation.FalseOnNull; import com.facebook.infer.annotation.Nullsafe; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; @Nullsafe(Nullsafe.Mode.LOCAL) public class JobScheduler { static final String QUEUE_TIME_KEY = ""queueTime""; @VisibleForTesting static class JobStartExecutorSupplier { private static ScheduledExecutorService sJobStarterExecutor; static ScheduledExecutorService get() { if (sJobStarterExecutor == null) { sJobStarterExecutor = Executors.newSingleThreadScheduledExecutor(); } return sJobStarterExecutor; } } public interface JobRunnable { void run(@Nullable EncodedImage encodedImage, @Consumer.Status int [MASK]); } private final Executor mExecutor; private final JobRunnable mJobRunnable; private final Runnable mDoJobRunnable; private final Runnable mSubmitJobRunnable; private final int mMinimumJobIntervalMs; @VisibleForTesting enum JobState { IDLE, QUEUED, RUNNING, RUNNING_AND_PENDING } @GuardedBy(""this"") @VisibleForTesting @Nullable EncodedImage mEncodedImage; @GuardedBy(""this"") @VisibleForTesting @Consumer.Status int mStatus; @GuardedBy(""this"") @VisibleForTesting JobState mJobState; @GuardedBy(""this"") @VisibleForTesting long mJobSubmitTime; @GuardedBy(""this"") @VisibleForTesting long mJobStartTime; public JobScheduler(Executor executor, JobRunnable jobRunnable, int minimumJobIntervalMs) { mExecutor = executor; mJobRunnable = jobRunnable; mMinimumJobIntervalMs = minimumJobIntervalMs; mDoJobRunnable = new Runnable() { @Override public void run() { doJob(); } }; mSubmitJobRunnable = new Runnable() { @Override public void run() { submitJob(); } }; mEncodedImage = null; mStatus = 0; mJobState = JobState.IDLE; mJobSubmitTime = 0; mJobStartTime = 0; } public void clearJob() { EncodedImage oldEncodedImage; synchronized (this) { oldEncodedImage = mEncodedImage; mEncodedImage = null; mStatus = 0; } EncodedImage.closeSafely(oldEncodedImage); } public boolean updateJob(@Nullable EncodedImage encodedImage, @Consumer.Status int [MASK]) { if (!shouldProcess(encodedImage, [MASK])) { return false; } EncodedImage oldEncodedImage; synchronized (this) { oldEncodedImage = mEncodedImage; this.mEncodedImage = EncodedImage.cloneOrNull(encodedImage); this.mStatus = [MASK]; } EncodedImage.closeSafely(oldEncodedImage); return true; } public boolean scheduleJob() { long now = SystemClock.uptimeMillis(); long when = 0; boolean shouldEnqueue = false; synchronized (this) { if (!shouldProcess(mEncodedImage, mStatus)) { return false; } switch (mJobState) { case IDLE: when = Math.max(mJobStartTime + mMinimumJobIntervalMs, now); shouldEnqueue = true; mJobSubmitTime = now; mJobState = JobState.QUEUED; break; case QUEUED: break; case RUNNING: mJobState = JobState.RUNNING_AND_PENDING; break; case RUNNING_AND_PENDING: break; } } if (shouldEnqueue) { enqueueJob(when - now); } return true; } private void enqueueJob(long delay) { final Runnable submitJobRunnable = FrescoInstrumenter.decorateRunnable(mSubmitJobRunnable, ""JobScheduler_enqueueJob""); if (delay > 0) { JobStartExecutorSupplier.get().schedule(submitJobRunnable, delay, TimeUnit.MILLISECONDS); } else { submitJobRunnable.run(); } } private void submitJob() { mExecutor.execute( FrescoInstrumenter.decorateRunnable(mDoJobRunnable, ""JobScheduler_submitJob"")); } private void doJob() { long now = SystemClock.uptimeMillis(); EncodedImage input; int [MASK]; synchronized (this) { input = mEncodedImage; [MASK] = mStatus; mEncodedImage = null; this.mStatus = 0; mJobState = JobState.RUNNING; mJobStartTime = now; } try { if (shouldProcess(input, [MASK])) { mJobRunnable.run(input, [MASK]); } } finally { EncodedImage.closeSafely(input); onJobFinished(); } } private void onJobFinished() { long now = SystemClock.uptimeMillis(); long when = 0; boolean shouldEnqueue = false; synchronized (this) { if (mJobState == JobState.RUNNING_AND_PENDING) { when = Math.max(mJobStartTime + mMinimumJobIntervalMs, now); shouldEnqueue = true; mJobSubmitTime = now; mJobState = JobState.QUEUED; } else { mJobState = JobState.IDLE; } } if (shouldEnqueue) { enqueueJob(when - now); } } @FalseOnNull private static boolean shouldProcess( @Nullable EncodedImage encodedImage, @Consumer.Status int [MASK]) { return BaseConsumer.isLast([MASK]) || BaseConsumer.statusHasFlag([MASK], Consumer.IS_PLACEHOLDER) || EncodedImage.isValid(encodedImage); } public synchronized long getQueuedTime() { return mJobStartTime - mJobSubmitTime; } }",status,java,fresco "package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.utils.Align; public class IntegerBitmapFontTest extends GdxTest { BitmapFont font; BitmapFontCache singleLineCacheNonInteger; BitmapFontCache [MASK]; BitmapFontCache singleLineCache; BitmapFontCache multiLineCache; SpriteBatch batch; public void create () { TextureAtlas textureAtlas = new TextureAtlas(""data/pack.atlas""); font = new BitmapFont(Gdx.files.internal(""data/verdana39.fnt""), textureAtlas.findRegion(""verdana39""), false); singleLineCache = new BitmapFontCache(font, true); multiLineCache = new BitmapFontCache(font, true); singleLineCacheNonInteger = new BitmapFontCache(font, false); [MASK] = new BitmapFontCache(font, false); batch = new SpriteBatch(); fillCaches(); } @Override public void dispose () { batch.dispose(); font.dispose(); } public void render () { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); font.setUseIntegerPositions(false); font.setColor(1, 0, 0, 1); singleLineCacheNonInteger.draw(batch); [MASK].draw(batch); drawTexts(); font.setUseIntegerPositions(true); font.setColor(1, 1, 1, 1); singleLineCache.draw(batch); multiLineCache.draw(batch); drawTexts(); batch.end(); } private void fillCaches () { String text = ""This is a TEST\nxahsdhwekjhasd23���$%$%/%&""; singleLineCache.setColor(0, 0, 1, 1); singleLineCache.setText(text, 10.2f, 30.5f); multiLineCache.setColor(0, 0, 1, 1); multiLineCache.setText(text, 10.5f, 180.5f, 200, Align.center, false); singleLineCacheNonInteger.setColor(0, 1, 0, 1); singleLineCacheNonInteger.setText(text, 10.2f, 30.5f); [MASK].setColor(0, 1, 0, 1); [MASK].setText(text, 10.5f, 180.5f, 200, Align.center, false); } private void drawTexts () { String text = ""This is a TEST\nxahsdhwekjhasd23���$%$%/%&""; font.draw(batch, text, 10.2f, 30.5f); font.draw(batch, text, 10.5f, 120.5f); font.draw(batch, text, 10.5f, 180.5f, 200, Align.center, false); } }",multiLineCacheNonInteger,java,libgdx "package com.alibaba.fastjson.[MASK].deserializer; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.[MASK].DefaultJSONParser; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; public class EnumCreatorDeserializer implements ObjectDeserializer { private final Method creator; private final Class paramType; public EnumCreatorDeserializer(Method creator) { this.creator = creator; paramType = creator.getParameterTypes()[0]; } public T deserialze(DefaultJSONParser [MASK], Type type, Object fieldName) { Object arg = [MASK].parseObject(paramType); try { return (T) creator.invoke(null, arg); } catch (IllegalAccessException e) { throw new JSONException(""parse enum error"", e); } catch (InvocationTargetException e) { throw new JSONException(""parse enum error"", e); } } public int getFastMatchToken() { return 0; } }",parser,java,fastjson "package com.alibaba.json.bvt; import java.io.StringWriter; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class StringFieldTest_special_singquote extends TestCase { public void test_special() throws Exception { Model model = new Model(); StringBuilder buf = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { buf.append((char) i); } model.name = buf.toString(); StringWriter [MASK] = new StringWriter(); JSON.writeJSONString([MASK], model); Model model2 = JSON.parseObject([MASK].toString(), Model.class); Assert.assertEquals(model.name, model2.name); } public void test_special_browsecue() throws Exception { Model model = new Model(); StringBuilder buf = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { buf.append((char) i); } model.name = buf.toString(); StringWriter [MASK] = new StringWriter(); JSON.writeJSONString([MASK], model, SerializerFeature.UseSingleQuotes); Model model2 = JSON.parseObject([MASK].toString(), Model.class); Assert.assertEquals(model.name, model2.name); } public void test_special_browsecompatible() throws Exception { Model model = new Model(); StringBuilder buf = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { buf.append((char) i); } model.name = buf.toString(); StringWriter [MASK] = new StringWriter(); JSON.writeJSONString([MASK], model, SerializerFeature.UseSingleQuotes); Model model2 = JSON.parseObject([MASK].toString(), Model.class); Assert.assertEquals(model.name, model2.name); } private static class Model { public String name; } }",writer,java,fastjson "package com.alibaba.json.bvt.bug; import java.io.InputStream; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import com.alibaba.fastjson.JSON; import com.alibaba.json.bvtVO.WareHouseInfo; public class Bug_for_maiksagill extends TestCase { public void test_for_maiksagill() throws Exception { String [MASK] = ""json/maiksagill.json""; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream([MASK]); String text = IOUtils.toString(is); JSON.parseObject(text, WareHouseInfo[].class); } }",resource,java,fastjson "package com.badlogic.gdx.backends.lwjgl3; import java.util.HashMap; import java.util.Map; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWImage; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Blending; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; public class Lwjgl3Cursor implements Cursor { static final Array cursors = new Array(); static final Map [MASK] = new HashMap(); private static int inputModeBeforeNoneCursor = -1; final Lwjgl3Window window; Pixmap pixmapCopy; GLFWImage glfwImage; final long glfwCursor; Lwjgl3Cursor (Lwjgl3Window window, Pixmap pixmap, int xHotspot, int yHotspot) { this.window = window; if (pixmap.getFormat() != Pixmap.Format.RGBA8888) { throw new GdxRuntimeException(""Cursor image pixmap is not in RGBA8888 format.""); } if ((pixmap.getWidth() & (pixmap.getWidth() - 1)) != 0) { throw new GdxRuntimeException( ""Cursor image pixmap width of "" + pixmap.getWidth() + "" is not a power-of-two greater than zero.""); } if ((pixmap.getHeight() & (pixmap.getHeight() - 1)) != 0) { throw new GdxRuntimeException( ""Cursor image pixmap height of "" + pixmap.getHeight() + "" is not a power-of-two greater than zero.""); } if (xHotspot < 0 || xHotspot >= pixmap.getWidth()) { throw new GdxRuntimeException( ""xHotspot coordinate of "" + xHotspot + "" is not within image width bounds: [0, "" + pixmap.getWidth() + "").""); } if (yHotspot < 0 || yHotspot >= pixmap.getHeight()) { throw new GdxRuntimeException( ""yHotspot coordinate of "" + yHotspot + "" is not within image height bounds: [0, "" + pixmap.getHeight() + "").""); } this.pixmapCopy = new Pixmap(pixmap.getWidth(), pixmap.getHeight(), Pixmap.Format.RGBA8888); this.pixmapCopy.setBlending(Blending.None); this.pixmapCopy.drawPixmap(pixmap, 0, 0); glfwImage = GLFWImage.malloc(); glfwImage.width(pixmapCopy.getWidth()); glfwImage.height(pixmapCopy.getHeight()); glfwImage.pixels(pixmapCopy.getPixels()); glfwCursor = GLFW.glfwCreateCursor(glfwImage, xHotspot, yHotspot); cursors.add(this); } @Override public void dispose () { if (pixmapCopy == null) { throw new GdxRuntimeException(""Cursor already disposed""); } cursors.removeValue(this, true); pixmapCopy.dispose(); pixmapCopy = null; glfwImage.free(); GLFW.glfwDestroyCursor(glfwCursor); } static void dispose (Lwjgl3Window window) { for (int i = cursors.size - 1; i >= 0; i--) { Lwjgl3Cursor cursor = cursors.get(i); if (cursor.window.equals(window)) { cursors.removeIndex(i).dispose(); } } } static void disposeSystemCursors () { for (long systemCursor : [MASK].values()) { GLFW.glfwDestroyCursor(systemCursor); } [MASK].clear(); } static void setSystemCursor (long windowHandle, SystemCursor systemCursor) { if (systemCursor == SystemCursor.None) { if (inputModeBeforeNoneCursor == -1) inputModeBeforeNoneCursor = GLFW.glfwGetInputMode(windowHandle, GLFW.GLFW_CURSOR); GLFW.glfwSetInputMode(windowHandle, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_HIDDEN); return; } else if (inputModeBeforeNoneCursor != -1) { GLFW.glfwSetInputMode(windowHandle, GLFW.GLFW_CURSOR, inputModeBeforeNoneCursor); inputModeBeforeNoneCursor = -1; } Long glfwCursor = [MASK].get(systemCursor); if (glfwCursor == null) { long handle = 0; if (systemCursor == SystemCursor.Arrow) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_ARROW_CURSOR); } else if (systemCursor == SystemCursor.Crosshair) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_CROSSHAIR_CURSOR); } else if (systemCursor == SystemCursor.Hand) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_HAND_CURSOR); } else if (systemCursor == SystemCursor.HorizontalResize) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_HRESIZE_CURSOR); } else if (systemCursor == SystemCursor.VerticalResize) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_VRESIZE_CURSOR); } else if (systemCursor == SystemCursor.Ibeam) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_IBEAM_CURSOR); } else if (systemCursor == SystemCursor.NWSEResize) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_RESIZE_NWSE_CURSOR); } else if (systemCursor == SystemCursor.NESWResize) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_RESIZE_NESW_CURSOR); } else if (systemCursor == SystemCursor.AllResize) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_RESIZE_ALL_CURSOR); } else if (systemCursor == SystemCursor.NotAllowed) { handle = GLFW.glfwCreateStandardCursor(GLFW.GLFW_NOT_ALLOWED_CURSOR); } else { throw new GdxRuntimeException(""Unknown system cursor "" + systemCursor); } if (handle == 0) { return; } glfwCursor = handle; [MASK].put(systemCursor, glfwCursor); } GLFW.glfwSetCursor(windowHandle, glfwCursor); } }",systemCursors,java,libgdx "package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.Transporter; import org.mockito.Mockito; public class MockTransporter implements Transporter { private RemotingServer server = Mockito.mock(RemotingServer.class); private Client [MASK] = Mockito.mock(Client.class); @Override public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException { return server; } @Override public Client connect(URL url, ChannelHandler handler) throws RemotingException { return [MASK]; } }",client,java,incubator-dubbo "package org.apache.dubbo.auth; import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.auth.spi.AccessKeyStorage; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; public class DefaultAccessKeyStorage implements AccessKeyStorage { @Override public AccessKeyPair getAccessKey(URL url, Invocation [MASK]) { AccessKeyPair accessKeyPair = new AccessKeyPair(); String accessKeyId = url.getParameter(Constants.ACCESS_KEY_ID_KEY, Constants.DEFAULT_ACCESS_KEY_ID); String secretAccessKey = url.getParameter(Constants.SECRET_ACCESS_KEY_KEY); accessKeyPair.setAccessKey(accessKeyId); accessKeyPair.setSecretKey(secretAccessKey); return accessKeyPair; } }",invocation,java,incubator-dubbo "package com.badlogic.gdx.physics.bullet.dynamics; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.physics.bullet.collision.*; public class btDiscreteDynamicsWorldMt extends btDiscreteDynamicsWorld { private long swigCPtr; protected btDiscreteDynamicsWorldMt (final String className, long cPtr, boolean cMemoryOwn) { super(className, DynamicsJNI.btDiscreteDynamicsWorldMt_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } public btDiscreteDynamicsWorldMt (long cPtr, boolean cMemoryOwn) { this(""btDiscreteDynamicsWorldMt"", cPtr, cMemoryOwn); construct(); } @Override protected void reset (long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(DynamicsJNI.btDiscreteDynamicsWorldMt_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn); } public static long getCPtr (btDiscreteDynamicsWorldMt obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; DynamicsJNI.delete_btDiscreteDynamicsWorldMt(swigCPtr); } swigCPtr = 0; } super.delete(); } public long operatorNew (long [MASK]) { return DynamicsJNI.btDiscreteDynamicsWorldMt_operatorNew__SWIG_0(swigCPtr, this, [MASK]); } public void operatorDelete (long ptr) { DynamicsJNI.btDiscreteDynamicsWorldMt_operatorDelete__SWIG_0(swigCPtr, this, ptr); } public long operatorNew (long arg0, long ptr) { return DynamicsJNI.btDiscreteDynamicsWorldMt_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr); } public void operatorDelete (long arg0, long arg1) { DynamicsJNI.btDiscreteDynamicsWorldMt_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1); } public long operatorNewArray (long [MASK]) { return DynamicsJNI.btDiscreteDynamicsWorldMt_operatorNewArray__SWIG_0(swigCPtr, this, [MASK]); } public void operatorDeleteArray (long ptr) { DynamicsJNI.btDiscreteDynamicsWorldMt_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr); } public long operatorNewArray (long arg0, long ptr) { return DynamicsJNI.btDiscreteDynamicsWorldMt_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr); } public void operatorDeleteArray (long arg0, long arg1) { DynamicsJNI.btDiscreteDynamicsWorldMt_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1); } public btDiscreteDynamicsWorldMt (btDispatcher dispatcher, btBroadphaseInterface pairCache, btConstraintSolverPoolMt constraintSolver, btCollisionConfiguration collisionConfiguration) { this(DynamicsJNI.new_btDiscreteDynamicsWorldMt(btDispatcher.getCPtr(dispatcher), dispatcher, btBroadphaseInterface.getCPtr(pairCache), pairCache, btConstraintSolverPoolMt.getCPtr(constraintSolver), constraintSolver, btCollisionConfiguration.getCPtr(collisionConfiguration), collisionConfiguration), true); } }",sizeInBytes,java,libgdx "package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.qos.common.QosConstants; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.net.InetSocketAddress; public class LocalHostPermitHandler extends ChannelHandlerAdapter { private boolean acceptForeignIp; public LocalHostPermitHandler(boolean acceptForeignIp) { this.acceptForeignIp = acceptForeignIp; } @Override public void handlerAdded(ChannelHandlerContext [MASK]) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) [MASK].channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + ""Foreign Ip Not Permitted."" + QosConstants.BR_STR).getBytes()); [MASK].writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } } } }",ctx,java,incubator-dubbo "package com.badlogic.gdx.tests.g3d.voxel; import com.badlogic.gdx.math.Vector3; public class VoxelChunk { public static final int VERTEX_SIZE = 6; public final byte[] voxels; public final int width; public final int height; public final int depth; public final Vector3 offset = new Vector3(); private final int widthTimesHeight; private final int [MASK]; private final int bottomOffset; private final int leftOffset; private final int rightOffset; private final int frontOffset; private final int backOffset; public VoxelChunk (int width, int height, int depth) { this.voxels = new byte[width * height * depth]; this.width = width; this.height = height; this.depth = depth; this.[MASK] = width * depth; this.bottomOffset = -width * depth; this.leftOffset = -1; this.rightOffset = 1; this.frontOffset = -width; this.backOffset = width; this.widthTimesHeight = width * height; } public byte get (int x, int y, int z) { if (x < 0 || x >= width) return 0; if (y < 0 || y >= height) return 0; if (z < 0 || z >= depth) return 0; return getFast(x, y, z); } public byte getFast (int x, int y, int z) { return voxels[x + z * width + y * widthTimesHeight]; } public void set (int x, int y, int z, byte voxel) { if (x < 0 || x >= width) return; if (y < 0 || y >= height) return; if (z < 0 || z >= depth) return; setFast(x, y, z, voxel); } public void setFast (int x, int y, int z, byte voxel) { voxels[x + z * width + y * widthTimesHeight] = voxel; } public int calculateVertices (float[] vertices) { int i = 0; int vertexOffset = 0; for (int y = 0; y < height; y++) { for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++, i++) { byte voxel = voxels[i]; if (voxel == 0) continue; if (y < height - 1) { if (voxels[i + [MASK]] == 0) vertexOffset = createTop(offset, x, y, z, vertices, vertexOffset); } else { vertexOffset = createTop(offset, x, y, z, vertices, vertexOffset); } if (y > 0) { if (voxels[i + bottomOffset] == 0) vertexOffset = createBottom(offset, x, y, z, vertices, vertexOffset); } else { vertexOffset = createBottom(offset, x, y, z, vertices, vertexOffset); } if (x > 0) { if (voxels[i + leftOffset] == 0) vertexOffset = createLeft(offset, x, y, z, vertices, vertexOffset); } else { vertexOffset = createLeft(offset, x, y, z, vertices, vertexOffset); } if (x < width - 1) { if (voxels[i + rightOffset] == 0) vertexOffset = createRight(offset, x, y, z, vertices, vertexOffset); } else { vertexOffset = createRight(offset, x, y, z, vertices, vertexOffset); } if (z > 0) { if (voxels[i + frontOffset] == 0) vertexOffset = createFront(offset, x, y, z, vertices, vertexOffset); } else { vertexOffset = createFront(offset, x, y, z, vertices, vertexOffset); } if (z < depth - 1) { if (voxels[i + backOffset] == 0) vertexOffset = createBack(offset, x, y, z, vertices, vertexOffset); } else { vertexOffset = createBack(offset, x, y, z, vertices, vertexOffset); } } } } return vertexOffset / VERTEX_SIZE; } public static int createTop (Vector3 offset, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; return vertexOffset; } public static int createBottom (Vector3 offset, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; return vertexOffset; } public static int createLeft (Vector3 offset, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; return vertexOffset; } public static int createRight (Vector3 offset, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; return vertexOffset; } public static int createFront (Vector3 offset, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; return vertexOffset; } public static int createBack (Vector3 offset, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; return vertexOffset; } }",topOffset,java,libgdx "package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FileTextureData; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.utils.ScreenUtils; public class GWTLossyPremultipliedAlphaTest extends GdxTest { private SpriteBatch batch; private Texture goodTexture; private Texture badTexture; public void create () { batch = new SpriteBatch(); FileTextureData data = new FileTextureData(Gdx.files.internal(""data/premultiplied_alpha_test.png""), null, null, false); goodTexture = new Texture(data); Pixmap pixmap = new Pixmap(Gdx.files.internal(""data/premultiplied_alpha_test.png"")); pixmap.getPixel(0, 0); FileTextureData [MASK] = new FileTextureData(null, pixmap, null, false); badTexture = new Texture([MASK]); } public void render () { ScreenUtils.clear(0, 0, 0, 1); batch.begin(); batch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA); batch.draw(badTexture, 0, Gdx.graphics.getHeight(), Gdx.graphics.getWidth() * 0.5f, -Gdx.graphics.getHeight()); batch.draw(goodTexture, Gdx.graphics.getWidth() * 0.5f, Gdx.graphics.getHeight(), Gdx.graphics.getWidth() * 0.5f, -Gdx.graphics.getHeight()); batch.end(); } public boolean needsGL20 () { return false; } }",data1,java,libgdx "package jadx.core.dex.visitors.typeinference; public class TypeUpdateFlags { private static final int ALLOW_WIDER = 1; private static final int IGNORE_SAME = 2; private static final int IGNORE_UNKNOWN = 4; public static final TypeUpdateFlags FLAGS_EMPTY = build(0); public static final TypeUpdateFlags FLAGS_WIDER = build(ALLOW_WIDER); public static final TypeUpdateFlags FLAGS_WIDER_IGNORE_SAME = build(ALLOW_WIDER | IGNORE_SAME); public static final TypeUpdateFlags FLAGS_WIDER_IGNORE_UNKNOWN = build(ALLOW_WIDER | IGNORE_UNKNOWN); private final int [MASK]; private static TypeUpdateFlags build(int [MASK]) { return new TypeUpdateFlags([MASK]); } private TypeUpdateFlags(int [MASK]) { this.[MASK] = [MASK]; } public boolean isAllowWider() { return ([MASK] & ALLOW_WIDER) != 0; } public boolean isIgnoreSame() { return ([MASK] & IGNORE_SAME) != 0; } public boolean isIgnoreUnknown() { return ([MASK] & IGNORE_UNKNOWN) != 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (isAllowWider()) { sb.append(""ALLOW_WIDER""); } if (isIgnoreSame()) { if (sb.length() != 0) { sb.append('|'); } sb.append(""IGNORE_SAME""); } if (isIgnoreUnknown()) { if (sb.length() != 0) { sb.append('|'); } sb.append(""IGNORE_UNKNOWN""); } return sb.toString(); } }",flags,java,jadx "package com.alibaba.json.bvt.writeAsArray; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class WriteAsArray_byte_public extends TestCase { public void test_0 () throws Exception { VO vo = new VO(); vo.setId((byte)123); vo.setName(""wenshao""); String [MASK] = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals(""[123,\""wenshao\""]"", [MASK]); } public static class VO { private byte id; private String name; public byte getId() { return id; } public void setId(byte id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }",text,java,fastjson "package org.apache.dubbo.config; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.support.Parameter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_KEY; import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_KEY; import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_KEY; import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_KEY; import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_KEY; import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_KEY; public class MethodConfig extends AbstractMethodConfig { private static final long serialVersionUID = 884908855422675941L; private String name; private Integer stat; private Boolean retry; private Boolean reliable; private Integer executes; private Boolean deprecated; private Boolean sticky; private Boolean isReturn; private Object oninvoke; private String oninvokeMethod; private Object onreturn; private String onreturnMethod; private Object onthrow; private String onthrowMethod; private List arguments; private String service; private String serviceId; @Parameter(excluded = true) public String getName() { return name; } public MethodConfig() { } public MethodConfig(Method method) { appendAnnotation(Method.class, method); this.setReturn(method.isReturn()); String split = "".""; if (!"""".equals(method.oninvoke()) && method.oninvoke().lastIndexOf(split) > 0) { int index = method.oninvoke().lastIndexOf(split); String ref = method.oninvoke().substring(0, index); String methodName = method.oninvoke().substring(index + 1); this.setOninvoke(ref); this.setOninvokeMethod(methodName); } if (!"""".equals(method.onreturn()) && method.onreturn().lastIndexOf(split) > 0) { int index = method.onreturn().lastIndexOf(split); String ref = method.onreturn().substring(0, index); String methodName = method.onreturn().substring(index + 1); this.setOnreturn(ref); this.setOnreturnMethod(methodName); } if (!"""".equals(method.onthrow()) && method.onthrow().lastIndexOf(split) > 0) { int index = method.onthrow().lastIndexOf(split); String ref = method.onthrow().substring(0, index); String methodName = method.onthrow().substring(index + 1); this.setOnthrow(ref); this.setOnthrowMethod(methodName); } if (method.arguments() != null && method.arguments().length != 0) { List argumentConfigs = new ArrayList(method.arguments().length); this.setArguments(argumentConfigs); for (int i = 0; i < method.arguments().length; i++) { ArgumentConfig argumentConfig = new ArgumentConfig(method.arguments()[i]); argumentConfigs.add(argumentConfig); } } } public static List constructMethodConfig(Method[] [MASK]) { if ([MASK] != null && [MASK].length != 0) { List methodConfigs = new ArrayList([MASK].length); for (int i = 0; i < [MASK].length; i++) { MethodConfig methodConfig = new MethodConfig([MASK][i]); methodConfigs.add(methodConfig); } return methodConfigs; } return Collections.emptyList(); } public void setName(String name) { this.name = name; } public Integer getStat() { return stat; } @Deprecated public void setStat(Integer stat) { this.stat = stat; } @Deprecated public Boolean isRetry() { return retry; } @Deprecated public void setRetry(Boolean retry) { this.retry = retry; } @Deprecated public Boolean isReliable() { return reliable; } @Deprecated public void setReliable(Boolean reliable) { this.reliable = reliable; } public Integer getExecutes() { return executes; } public void setExecutes(Integer executes) { this.executes = executes; } public Boolean getDeprecated() { return deprecated; } public void setDeprecated(Boolean deprecated) { this.deprecated = deprecated; } public List getArguments() { return arguments; } @SuppressWarnings(""unchecked"") public void setArguments(List arguments) { this.arguments = (List) arguments; } public Boolean getSticky() { return sticky; } public void setSticky(Boolean sticky) { this.sticky = sticky; } @Parameter(key = ON_RETURN_INSTANCE_KEY, excluded = true, attribute = true) public Object getOnreturn() { return onreturn; } public void setOnreturn(Object onreturn) { this.onreturn = onreturn; } @Parameter(key = ON_RETURN_METHOD_KEY, excluded = true, attribute = true) public String getOnreturnMethod() { return onreturnMethod; } public void setOnreturnMethod(String onreturnMethod) { this.onreturnMethod = onreturnMethod; } @Parameter(key = ON_THROW_INSTANCE_KEY, excluded = true, attribute = true) public Object getOnthrow() { return onthrow; } public void setOnthrow(Object onthrow) { this.onthrow = onthrow; } @Parameter(key = ON_THROW_METHOD_KEY, excluded = true, attribute = true) public String getOnthrowMethod() { return onthrowMethod; } public void setOnthrowMethod(String onthrowMethod) { this.onthrowMethod = onthrowMethod; } @Parameter(key = ON_INVOKE_INSTANCE_KEY, excluded = true, attribute = true) public Object getOninvoke() { return oninvoke; } public void setOninvoke(Object oninvoke) { this.oninvoke = oninvoke; } @Parameter(key = ON_INVOKE_METHOD_KEY, excluded = true, attribute = true) public String getOninvokeMethod() { return oninvokeMethod; } public void setOninvokeMethod(String oninvokeMethod) { this.oninvokeMethod = oninvokeMethod; } public Boolean isReturn() { return isReturn; } public void setReturn(Boolean isReturn) { this.isReturn = isReturn; } @Parameter(excluded = true) public String getService() { return service; } public void setService(String service) { this.service = service; } @Parameter(excluded = true) public String getServiceId() { return serviceId; } public void setServiceId(String serviceId) { this.serviceId = serviceId; } @Override @Parameter(excluded = true) public String getPrefix() { return CommonConstants.DUBBO + ""."" + service + (StringUtils.isEmpty(serviceId) ? """" : (""."" + serviceId)) + ""."" + getName(); } }",methods,java,incubator-dubbo "package io.netty5.handler.ssl; import io.netty.internal.tcnative.SSL; import io.netty5.util.ReferenceCounted; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; import java.nio.ByteBuffer; import java.util.List; import java.util.function.BiFunction; import static org.junit.jupiter.api.Assertions.assertEquals; final class OpenSslErrorStackAssertSSLEngine extends JdkSslEngine implements ReferenceCounted { OpenSslErrorStackAssertSSLEngine(ReferenceCountedOpenSslEngine engine) { super(engine); } @Override public String getPeerHost() { try { return getWrappedEngine().getPeerHost(); } finally { assertErrorStackEmpty(); } } @Override public int getPeerPort() { try { return getWrappedEngine().getPeerPort(); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException { try { return getWrappedEngine().wrap(src, dst); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult wrap(ByteBuffer[] srcs, ByteBuffer dst) throws SSLException { try { return getWrappedEngine().wrap(srcs, dst); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult wrap(ByteBuffer[] byteBuffers, int i, int i1, ByteBuffer byteBuffer) throws SSLException { try { return getWrappedEngine().wrap(byteBuffers, i, i1, byteBuffer); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException { try { return getWrappedEngine().unwrap(src, dst); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException { try { return getWrappedEngine().unwrap(src, dsts); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult unwrap(ByteBuffer byteBuffer, ByteBuffer[] byteBuffers, int i, int i1) throws SSLException { try { return getWrappedEngine().unwrap(byteBuffer, byteBuffers, i, i1); } finally { assertErrorStackEmpty(); } } @Override public Runnable getDelegatedTask() { try { return getWrappedEngine().getDelegatedTask(); } finally { assertErrorStackEmpty(); } } @Override public void closeInbound() throws SSLException { try { getWrappedEngine().closeInbound(); } finally { assertErrorStackEmpty(); } } @Override public boolean isInboundDone() { try { return getWrappedEngine().isInboundDone(); } finally { assertErrorStackEmpty(); } } @Override public void closeOutbound() { try { getWrappedEngine().closeOutbound(); } finally { assertErrorStackEmpty(); } } @Override public boolean isOutboundDone() { try { return getWrappedEngine().isOutboundDone(); } finally { assertErrorStackEmpty(); } } @Override public String[] getSupportedCipherSuites() { try { return getWrappedEngine().getSupportedCipherSuites(); } finally { assertErrorStackEmpty(); } } @Override public String[] getEnabledCipherSuites() { try { return getWrappedEngine().getEnabledCipherSuites(); } finally { assertErrorStackEmpty(); } } @Override public void setEnabledCipherSuites(String[] [MASK]) { try { getWrappedEngine().setEnabledCipherSuites([MASK]); } finally { assertErrorStackEmpty(); } } @Override public String[] getSupportedProtocols() { try { return getWrappedEngine().getSupportedProtocols(); } finally { assertErrorStackEmpty(); } } @Override public String[] getEnabledProtocols() { try { return getWrappedEngine().getEnabledProtocols(); } finally { assertErrorStackEmpty(); } } @Override public void setEnabledProtocols(String[] [MASK]) { try { getWrappedEngine().setEnabledProtocols([MASK]); } finally { assertErrorStackEmpty(); } } @Override public SSLSession getSession() { try { return getWrappedEngine().getSession(); } finally { assertErrorStackEmpty(); } } @Override public SSLSession getHandshakeSession() { try { return getWrappedEngine().getHandshakeSession(); } finally { assertErrorStackEmpty(); } } @Override public void beginHandshake() throws SSLException { try { getWrappedEngine().beginHandshake(); } finally { assertErrorStackEmpty(); } } @Override public SSLEngineResult.HandshakeStatus getHandshakeStatus() { try { return getWrappedEngine().getHandshakeStatus(); } finally { assertErrorStackEmpty(); } } @Override public void setUseClientMode(boolean b) { try { getWrappedEngine().setUseClientMode(b); } finally { assertErrorStackEmpty(); } } @Override public boolean getUseClientMode() { try { return getWrappedEngine().getUseClientMode(); } finally { assertErrorStackEmpty(); } } @Override public void setNeedClientAuth(boolean b) { try { getWrappedEngine().setNeedClientAuth(b); } finally { assertErrorStackEmpty(); } } @Override public boolean getNeedClientAuth() { try { return getWrappedEngine().getNeedClientAuth(); } finally { assertErrorStackEmpty(); } } @Override public void setWantClientAuth(boolean b) { try { getWrappedEngine().setWantClientAuth(b); } finally { assertErrorStackEmpty(); } } @Override public boolean getWantClientAuth() { try { return getWrappedEngine().getWantClientAuth(); } finally { assertErrorStackEmpty(); } } @Override public void setEnableSessionCreation(boolean b) { try { getWrappedEngine().setEnableSessionCreation(b); } finally { assertErrorStackEmpty(); } } @Override public boolean getEnableSessionCreation() { try { return getWrappedEngine().getEnableSessionCreation(); } finally { assertErrorStackEmpty(); } } @Override public SSLParameters getSSLParameters() { try { return getWrappedEngine().getSSLParameters(); } finally { assertErrorStackEmpty(); } } @Override public void setSSLParameters(SSLParameters params) { try { getWrappedEngine().setSSLParameters(params); } finally { assertErrorStackEmpty(); } } @Override public String getApplicationProtocol() { try { return JdkAlpnSslUtils.getApplicationProtocol(getWrappedEngine()); } finally { assertErrorStackEmpty(); } } @Override public String getHandshakeApplicationProtocol() { try { return JdkAlpnSslUtils.getHandshakeApplicationProtocol(getWrappedEngine()); } finally { assertErrorStackEmpty(); } } @Override public void setHandshakeApplicationProtocolSelector(BiFunction, String> selector) { try { JdkAlpnSslUtils.setHandshakeApplicationProtocolSelector(getWrappedEngine(), selector); } finally { assertErrorStackEmpty(); } } @Override public BiFunction, String> getHandshakeApplicationProtocolSelector() { try { return JdkAlpnSslUtils.getHandshakeApplicationProtocolSelector(getWrappedEngine()); } finally { assertErrorStackEmpty(); } } @Override public int refCnt() { return getWrappedEngine().refCnt(); } @Override public OpenSslErrorStackAssertSSLEngine retain() { getWrappedEngine().retain(); return this; } @Override public OpenSslErrorStackAssertSSLEngine retain(int increment) { getWrappedEngine().retain(increment); return this; } @Override public OpenSslErrorStackAssertSSLEngine touch() { getWrappedEngine().touch(); return this; } @Override public OpenSslErrorStackAssertSSLEngine touch(Object hint) { getWrappedEngine().touch(hint); return this; } @Override public boolean release() { return getWrappedEngine().release(); } @Override public boolean release(int decrement) { return getWrappedEngine().release(decrement); } @Override public String getNegotiatedApplicationProtocol() { return getWrappedEngine().getNegotiatedApplicationProtocol(); } @Override void setNegotiatedApplicationProtocol(String applicationProtocol) { throw new UnsupportedOperationException(); } @Override public ReferenceCountedOpenSslEngine getWrappedEngine() { return (ReferenceCountedOpenSslEngine) super.getWrappedEngine(); } private static void assertErrorStackEmpty() { long error = SSL.getLastErrorNumber(); assertEquals(0, error, ""SSL error stack non-empty: "" + SSL.getErrorString(error)); } }",strings,java,netty "package io.netty5.handler.codec.http2; import io.netty5.util.internal.StringUtil; import io.netty5.util.internal.UnstableApi; @UnstableApi public class DefaultHttp2WindowUpdateFrame extends AbstractHttp2StreamFrame implements Http2WindowUpdateFrame { private final int windowUpdateIncrement; public DefaultHttp2WindowUpdateFrame(int windowUpdateIncrement) { this.windowUpdateIncrement = windowUpdateIncrement; } @Override public DefaultHttp2WindowUpdateFrame [MASK](Http2FrameStream [MASK]) { super.[MASK]([MASK]); return this; } @Override public String name() { return ""WINDOW_UPDATE""; } @Override public int windowSizeIncrement() { return windowUpdateIncrement; } @Override public String toString() { return StringUtil.simpleClassName(this) + ""([MASK]="" + [MASK]() + "", windowUpdateIncrement="" + windowUpdateIncrement + ')'; } }",stream,java,netty "package data.media.writeAsArray; import java.io.IOException; import java.lang.reflect.Type; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; import data.media.Media; public class MediaSerializer implements ObjectSerializer { public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { Media media = (Media) object; SerializeWriter [MASK] = serializer.getWriter(); [MASK].write('['); [MASK].writeInt(media.getBitrate()); [MASK].write(','); [MASK].writeInt(media.getHeight()); [MASK].write(','); [MASK].writeInt(media.getWidth()); [MASK].write(','); [MASK].writeString(media.getCopyright(), ','); [MASK].writeLong(media.getDuration()); [MASK].write(','); [MASK].writeString(media.getFormat(), ','); [MASK].write('['); for (int i = 0; i < media.getPersons().size(); ++i) { if(i != 0) { [MASK].write(','); } [MASK].writeString(media.getPersons().get(i)); } [MASK].write(""],""); [MASK].writeString(media.getPlayer().name(), ','); [MASK].writeLong(media.getSize()); [MASK].write(','); [MASK].writeString(media.getTitle(), ','); [MASK].writeString(media.getUri(), ']'); } }",out,java,fastjson "package com.badlogic.gdx.physics.bullet.dynamics; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.physics.bullet.collision.*; import com.badlogic.gdx.math.Vector3; public class btGearConstraint extends btTypedConstraint { private long swigCPtr; protected btGearConstraint (final String className, long cPtr, boolean [MASK]) { super(className, DynamicsJNI.btGearConstraint_SWIGUpcast(cPtr), [MASK]); swigCPtr = cPtr; } public btGearConstraint (long cPtr, boolean [MASK]) { this(""btGearConstraint"", cPtr, [MASK]); construct(); } @Override protected void reset (long cPtr, boolean [MASK]) { if (!destroyed) destroy(); super.reset(DynamicsJNI.btGearConstraint_SWIGUpcast(swigCPtr = cPtr), [MASK]); } public static long getCPtr (btGearConstraint obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; DynamicsJNI.delete_btGearConstraint(swigCPtr); } swigCPtr = 0; } super.delete(); } public btGearConstraint (btRigidBody rbA, btRigidBody rbB, Vector3 axisInA, Vector3 axisInB, float ratio) { this(DynamicsJNI.new_btGearConstraint__SWIG_0(btRigidBody.getCPtr(rbA), rbA, btRigidBody.getCPtr(rbB), rbB, axisInA, axisInB, ratio), true); } public btGearConstraint (btRigidBody rbA, btRigidBody rbB, Vector3 axisInA, Vector3 axisInB) { this( DynamicsJNI.new_btGearConstraint__SWIG_1(btRigidBody.getCPtr(rbA), rbA, btRigidBody.getCPtr(rbB), rbB, axisInA, axisInB), true); } public void setAxisA (Vector3 axisA) { DynamicsJNI.btGearConstraint_setAxisA(swigCPtr, this, axisA); } public void setAxisB (Vector3 axisB) { DynamicsJNI.btGearConstraint_setAxisB(swigCPtr, this, axisB); } public void setRatio (float ratio) { DynamicsJNI.btGearConstraint_setRatio(swigCPtr, this, ratio); } public Vector3 getAxisA () { return DynamicsJNI.btGearConstraint_getAxisA(swigCPtr, this); } public Vector3 getAxisB () { return DynamicsJNI.btGearConstraint_getAxisB(swigCPtr, this); } public float getRatio () { return DynamicsJNI.btGearConstraint_getRatio(swigCPtr, this); } public void setParam (int num, float value, int axis) { DynamicsJNI.btGearConstraint_setParam__SWIG_0(swigCPtr, this, num, value, axis); } public void setParam (int num, float value) { DynamicsJNI.btGearConstraint_setParam__SWIG_1(swigCPtr, this, num, value); } public float getParam (int num, int axis) { return DynamicsJNI.btGearConstraint_getParam__SWIG_0(swigCPtr, this, num, axis); } public float getParam (int num) { return DynamicsJNI.btGearConstraint_getParam__SWIG_1(swigCPtr, this, num); } }",cMemoryOwn,java,libgdx "package org.apache.dubbo.remoting.zookeeper.curator5; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.curator.test.TestingServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; public class Curator5ZookeeperTransporterTest { private TestingServer zkServer; private ZookeeperClient zookeeperClient; private Curator5ZookeeperTransporter [MASK]; private int zkServerPort; @BeforeEach public void setUp() throws Exception { zkServerPort = NetUtils.getAvailablePort(); zkServer = new TestingServer(zkServerPort, true); zookeeperClient = new Curator5ZookeeperTransporter().connect(URL.valueOf(""zookeeper: zkServerPort + ""/service"")); [MASK] = new Curator5ZookeeperTransporter(); } @Test public void testZookeeperClient() { assertThat(zookeeperClient, not(nullValue())); zookeeperClient.close(); } @AfterEach public void tearDown() throws Exception { zkServer.stop(); } }",curatorZookeeperTransporter,java,incubator-dubbo "package com.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; public class CommandUsingRequestCache extends HystrixCommand { private final int value; protected CommandUsingRequestCache(int value) { super(HystrixCommandGroupKey.Factory.asKey(""ExampleGroup"")); this.value = value; } @Override protected Boolean run() { return value == 0 || value % 2 == 0; } @Override protected String getCacheKey() { return String.valueOf(value); } public static class UnitTest { @Test public void testWithoutCacheHits() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { assertTrue(new CommandUsingRequestCache(2).execute()); assertFalse(new CommandUsingRequestCache(1).execute()); assertTrue(new CommandUsingRequestCache(0).execute()); assertTrue(new CommandUsingRequestCache(58672).execute()); } finally { context.shutdown(); } } @Test public void testWithCacheHits() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { CommandUsingRequestCache command2a = new CommandUsingRequestCache(2); CommandUsingRequestCache [MASK] = new CommandUsingRequestCache(2); assertTrue(command2a.execute()); assertFalse(command2a.isResponseFromCache()); assertTrue([MASK].execute()); assertTrue([MASK].isResponseFromCache()); } finally { context.shutdown(); } context = HystrixRequestContext.initializeContext(); try { CommandUsingRequestCache command3b = new CommandUsingRequestCache(2); assertTrue(command3b.execute()); assertFalse(command3b.isResponseFromCache()); } finally { context.shutdown(); } } } }",command2b,java,Hystrix "package com.badlogic.gdx.utils; public class GdxRuntimeException extends RuntimeException { private static final long serialVersionUID = 6735854402467673117L; public GdxRuntimeException (String [MASK]) { super([MASK]); } public GdxRuntimeException (Throwable t) { super(t); } public GdxRuntimeException (String [MASK], Throwable t) { super([MASK], t); } }",message,java,libgdx "package jadx.gui.ui.panel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import ch.qos.logback.classic.Level; import jadx.gui.logs.IssuesListener; import jadx.gui.logs.LogCollector; import jadx.gui.logs.LogOptions; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class IssuesPanel extends JPanel { private static final long serialVersionUID = -7720576036668459218L; private static final ImageIcon ERROR_ICON = UiUtils.openSvgIcon(""ui/error""); private static final ImageIcon WARN_ICON = UiUtils.openSvgIcon(""ui/warning""); private final MainWindow mainWindow; private final IssuesListener issuesListener; private JLabel errorLabel; private JLabel warnLabel; public IssuesPanel(MainWindow mainWindow) { this.mainWindow = mainWindow; initUI(); this.issuesListener = new IssuesListener(this); LogCollector.getInstance().registerListener(issuesListener); } public int getErrorsCount() { return issuesListener.getErrors(); } private void initUI() { JLabel [MASK] = new JLabel(NLS.str(""issues_panel.[MASK]"")); errorLabel = new JLabel(ERROR_ICON); warnLabel = new JLabel(WARN_ICON); String toolTipText = NLS.str(""issues_panel.tooltip""); errorLabel.setToolTipText(toolTipText); warnLabel.setToolTipText(toolTipText); errorLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainWindow.showLogViewer(LogOptions.allWithLevel(Level.ERROR)); } }); warnLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainWindow.showLogViewer(LogOptions.allWithLevel(Level.WARN)); } }); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setVisible(false); add([MASK]); add(Box.createHorizontalGlue()); add(errorLabel); add(Box.createHorizontalGlue()); add(warnLabel); } public void onUpdate(int error, int warnings) { if (error == 0 && warnings == 0) { setVisible(false); return; } setVisible(true); errorLabel.setText(NLS.str(""issues_panel.errors"", error)); errorLabel.setVisible(error != 0); warnLabel.setText(NLS.str(""issues_panel.warnings"", warnings)); warnLabel.setVisible(warnings != 0); } }",label,java,jadx "package jadx.api.plugins.input.data.attributes.types; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.annotations.AnnotationVisibility; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.PinnedAttribute; public class AnnotationsAttr extends PinnedAttribute { @Nullable public static AnnotationsAttr pack(List annotationList) { if (annotationList.isEmpty()) { return null; } Map annMap = new HashMap<>(annotationList.size()); for (IAnnotation ann : annotationList) { if (ann.getVisibility() != AnnotationVisibility.SYSTEM) { annMap.put(ann.getAnnotationClass(), ann); } } if (annMap.isEmpty()) { return null; } return new AnnotationsAttr(annMap); } private final Map map; public AnnotationsAttr(Map map) { this.map = map; } public IAnnotation get(String [MASK]) { return map.get([MASK]); } public Collection getAll() { return map.values(); } public List getList() { return map.isEmpty() ? Collections.emptyList() : new ArrayList<>(map.values()); } public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } @Override public JadxAttrType getAttrType() { return JadxAttrType.ANNOTATION_LIST; } @Override public String toString() { return map.toString(); } }",className,java,jadx "package com.badlogic.gdx.physics.box2d; public class JointEdge { public final Body [MASK]; public final Joint joint; protected JointEdge (Body [MASK], Joint joint) { this.[MASK] = [MASK]; this.joint = joint; } }",other,java,libgdx "package jadx.tests.integration.[MASK]; import org.junit.jupiter.api.Test; import jadx.NotYetImplemented; import jadx.api.CommentsLevel; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestAnonymousClass3a extends IntegrationTest { public static class TestCls { public static class Inner { private int f; private int r; public void test() { new Runnable() { @Override public void run() { int a = --Inner.this.f; p(a); } public void p(int a) { Inner.this.r = a; } }.run(); } } public void check() { Inner [MASK] = new Inner(); [MASK].f = 2; [MASK].test(); assertThat([MASK].f).isEqualTo(1); assertThat([MASK].r).isEqualTo(1); } } @Test @NotYetImplemented public void test() { getArgs().setCommentsLevel(CommentsLevel.NONE); assertThat(getClassNode(TestCls.class)) .code() .doesNotContain(""synthetic"") .doesNotContain(""access$00"") .doesNotContain(""AnonymousClass_"") .doesNotContain(""unused = "") .containsLine(4, ""public void run() {"") .containsLine(3, ""}.run();""); } }",inner,java,jadx "package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.junit.Assert; public class JSONPath_issue1208 extends TestCase { public void test_largeNumberProperty() throws Exception { String [MASK] = ""{\""articles\"":{\""2147483647\"":{\""XXX\"":\""xiu\""}}}""; String path1 = ""$.articles.2147483647.XXX""; Object read = JSONPath.read([MASK], path1); Assert.assertEquals(""xiu"", read); String json2 = ""{\""articles\"":{\""2147483648\"":{\""XXX\"":\""xiu\""}}}""; String path2 = ""$.articles.2147483648.XXX""; Object read2 = JSONPath.read(json2, path2); Assert.assertEquals(""xiu"", read2); } }",json1,java,fastjson "package org.apache.dubbo.remoting.telnet.support; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.support.command.ClearTelnetHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class ClearTelnetHandlerTest { @Test public void test() { StringBuilder [MASK] = new StringBuilder(); for (int i = 0; i < 50; i++) { [MASK].append(""\r\n""); } ClearTelnetHandler telnetHandler = new ClearTelnetHandler(); Assertions.assertEquals([MASK].toString(), telnetHandler.telnet(Mockito.mock(Channel.class), ""50"")); Assertions.assertTrue(telnetHandler.telnet(Mockito.mock(Channel.class), ""Illegal"").contains(""Illegal"")); for (int i = 0; i < 50; i++) { [MASK].append(""\r\n""); } Assertions.assertEquals([MASK].toString(), telnetHandler.telnet(Mockito.mock(Channel.class), """")); } }",buf,java,incubator-dubbo "package org.apache.dubbo.common.config.configcenter; import java.util.EventListener; public interface ConfigurationListener extends EventListener { void process(ConfigChangedEvent [MASK]); }",event,java,incubator-dubbo "package com.google.zxing.oned.rss.expanded; import java.util.ArrayList; import java.util.List; final class ExpandedRow { private final List [MASK]; private final int rowNumber; ExpandedRow(List [MASK], int rowNumber) { this.[MASK] = new ArrayList<>([MASK]); this.rowNumber = rowNumber; } List getPairs() { return this.[MASK]; } int getRowNumber() { return this.rowNumber; } boolean isEquivalent(List otherPairs) { return this.[MASK].equals(otherPairs); } @Override public String toString() { return ""{ "" + [MASK] + "" }""; } @Override public boolean equals(Object o) { if (!(o instanceof ExpandedRow)) { return false; } ExpandedRow that = (ExpandedRow) o; return this.[MASK].equals(that.[MASK]); } @Override public int hashCode() { return [MASK].hashCode(); } }",pairs,java,zxing "package com.alibaba.json.bvt.parser; import java.io.Reader; import java.io.StringReader; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONReaderScanner; public class JSONReaderScannerTest_long extends TestCase { public void test_scanInt() throws Exception { StringBuffer buf = new StringBuffer(); buf.append('['); for (int i = 0; i < 1024; ++i) { if (i != 0) { buf.append(','); } long value = (long) Integer.MAX_VALUE + 1L + (long) i; buf.append(value); } buf.append(']'); Reader [MASK] = new StringReader(buf.toString()); JSONReaderScanner scanner = new JSONReaderScanner([MASK]); DefaultJSONParser parser = new DefaultJSONParser(scanner); JSONArray array = (JSONArray) parser.parse(); for (int i = 0; i < array.size(); ++i) { long value = (long) Integer.MAX_VALUE + 1L + (long) i; Assert.assertEquals(value, ((Long) array.get(i)).longValue()); } } }",reader,java,fastjson "package com.badlogic.gdx.scenes.scene2d.actions; abstract public class RelativeTemporalAction extends TemporalAction { private float [MASK]; protected void begin () { [MASK] = 0; } protected void update (float percent) { updateRelative(percent - [MASK]); [MASK] = percent; } abstract protected void updateRelative (float percentDelta); }",lastPercent,java,libgdx "package org.apache.dubbo.remoting.p2p.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.p2p.Peer; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; public class MulticastGroup extends AbstractGroup { private static final String JOIN = ""join""; private static final String LEAVE = ""leave""; private InetAddress multicastAddress; private MulticastSocket multicastSocket; public MulticastGroup(URL url) { super(url); if (!NetUtils.isMulticastAddress(url.getHost())) { throw new IllegalArgumentException(""Invalid multicast address "" + url.getHost() + "", scope: 224.0.0.0 - 239.255.255.255""); } try { multicastAddress = InetAddress.getByName(url.getHost()); multicastSocket = new MulticastSocket(url.getPort()); multicastSocket.setLoopbackMode(false); multicastSocket.joinGroup(multicastAddress); Thread thread = new Thread(new Runnable() { @Override public void run() { byte[] buf = new byte[1024]; DatagramPacket [MASK] = new DatagramPacket(buf, buf.length); while (true) { try { multicastSocket.receive([MASK]); MulticastGroup.this.receive(new String([MASK].getData()).trim(), (InetSocketAddress) [MASK].getSocketAddress()); } catch (Exception e) { logger.error(e.getMessage(), e); } } } }, ""MulticastGroupReceiver""); thread.setDaemon(true); thread.start(); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } } private void send(String msg) throws RemotingException { DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), multicastAddress, multicastSocket.getLocalPort()); try { multicastSocket.send(hi); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } } private void receive(String msg, InetSocketAddress remoteAddress) throws RemotingException { if (msg.startsWith(JOIN)) { String url = msg.substring(JOIN.length()).trim(); connect(URL.valueOf(url)); } else if (msg.startsWith(LEAVE)) { String url = msg.substring(LEAVE.length()).trim(); disconnect(URL.valueOf(url)); } } @Override public Peer join(URL url, ChannelHandler handler) throws RemotingException { Peer peer = super.join(url, handler); send(JOIN + "" "" + url.toFullString()); return peer; } @Override public void leave(URL url) throws RemotingException { super.leave(url); send(LEAVE + "" "" + url.toFullString()); } }",recv,java,incubator-dubbo "package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class AutoTypeCheckHandlerTest extends TestCase { public void test_for_issue() throws Exception { ParserConfig config = new ParserConfig(); String str = ""{\""@type\"":\""com.alibaba.json.bvt.parser.autoType.AutoTypeCheckHandlerTest$Model\""}""; JSONException error = null; try { JSON.parse(str, config); } catch (JSONException ex) { error = ex; } assertNotNull(error); config.addAutoTypeCheckHandler(new ParserConfig.AutoTypeCheckHandler() { public Class handler(String typeName, Class [MASK], int features) { if (""com.alibaba.json.bvt.parser.autoType.AutoTypeCheckHandlerTest$Model"".equals(typeName)) { return Model.class; } return null; } }); JSON.parse(str, config); } public static class Model { } }",expectClass,java,fastjson "package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ConsumerConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ConsumerBuilderTest { @Test void isDefault() { ConsumerBuilder builder = new ConsumerBuilder(); builder.isDefault(false); Assertions.assertFalse(builder.build().isDefault()); } @Test void client() { ConsumerBuilder builder = new ConsumerBuilder(); builder.client(""client""); Assertions.assertEquals(""client"", builder.build().getClient()); } @Test void threadPool() { ConsumerBuilder builder = new ConsumerBuilder(); builder.threadPool(""threadPool""); Assertions.assertEquals(""threadPool"", builder.build().getThreadpool()); } @Test void coreThreads() { ConsumerBuilder builder = new ConsumerBuilder(); builder.coreThreads(10); Assertions.assertEquals(10, builder.build().getCorethreads()); } @Test void threads() { ConsumerBuilder builder = new ConsumerBuilder(); builder.threads(100); Assertions.assertEquals(100, builder.build().getThreads()); } @Test void queues() { ConsumerBuilder builder = new ConsumerBuilder(); builder.queues(200); Assertions.assertEquals(200, builder.build().getQueues()); } @Test void shareConnections() { ConsumerBuilder builder = new ConsumerBuilder(); builder.shareConnections(300); Assertions.assertEquals(300, builder.build().getShareconnections()); } @Test void build() { ConsumerBuilder builder = new ConsumerBuilder(); builder.isDefault(true).client(""client"").threadPool(""threadPool"").coreThreads(10).threads(100).queues(200) .shareConnections(300).id(""id"").prefix(""prefix""); ConsumerConfig config = builder.build(); ConsumerConfig [MASK] = builder.build(); Assertions.assertTrue(config.isDefault()); Assertions.assertEquals(""client"", config.getClient()); Assertions.assertEquals(""threadPool"", config.getThreadpool()); Assertions.assertEquals(""id"", config.getId()); Assertions.assertEquals(""prefix"", config.getPrefix()); Assertions.assertEquals(10, config.getCorethreads()); Assertions.assertEquals(100, config.getThreads()); Assertions.assertEquals(200, config.getQueues()); Assertions.assertEquals(300, config.getShareconnections()); Assertions.assertNotSame(config, [MASK]); } }",config2,java,incubator-dubbo "package com.badlogic.gdx.physics.bullet.dynamics; import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.physics.bullet.collision.*; public class btPoint2PointConstraintDoubleData extends BulletBase { private long [MASK]; protected btPoint2PointConstraintDoubleData (final String className, long cPtr, boolean cMemoryOwn) { super(className, cPtr, cMemoryOwn); [MASK] = cPtr; } public btPoint2PointConstraintDoubleData (long cPtr, boolean cMemoryOwn) { this(""btPoint2PointConstraintDoubleData"", cPtr, cMemoryOwn); construct(); } @Override protected void reset (long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset([MASK] = cPtr, cMemoryOwn); } public static long getCPtr (btPoint2PointConstraintDoubleData obj) { return (obj == null) ? 0 : obj.[MASK]; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if ([MASK] != 0) { if (swigCMemOwn) { swigCMemOwn = false; DynamicsJNI.delete_btPoint2PointConstraintDoubleData([MASK]); } [MASK] = 0; } super.delete(); } public void setTypeConstraintData (btTypedConstraintData value) { DynamicsJNI.btPoint2PointConstraintDoubleData_typeConstraintData_set([MASK], this, btTypedConstraintData.getCPtr(value), value); } public btTypedConstraintData getTypeConstraintData () { long cPtr = DynamicsJNI.btPoint2PointConstraintDoubleData_typeConstraintData_get([MASK], this); return (cPtr == 0) ? null : new btTypedConstraintData(cPtr, false); } public void setPivotInA (btVector3DoubleData value) { DynamicsJNI.btPoint2PointConstraintDoubleData_pivotInA_set([MASK], this, btVector3DoubleData.getCPtr(value), value); } public btVector3DoubleData getPivotInA () { long cPtr = DynamicsJNI.btPoint2PointConstraintDoubleData_pivotInA_get([MASK], this); return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false); } public void setPivotInB (btVector3DoubleData value) { DynamicsJNI.btPoint2PointConstraintDoubleData_pivotInB_set([MASK], this, btVector3DoubleData.getCPtr(value), value); } public btVector3DoubleData getPivotInB () { long cPtr = DynamicsJNI.btPoint2PointConstraintDoubleData_pivotInB_get([MASK], this); return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false); } public btPoint2PointConstraintDoubleData () { this(DynamicsJNI.new_btPoint2PointConstraintDoubleData(), true); } }",swigCPtr,java,libgdx "package com.alibaba.fastjson.[MASK].deserializer; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.[MASK].DefaultJSONParser; import com.alibaba.fastjson.[MASK].JSONToken; import java.lang.reflect.Type; public class PropertyProcessableDeserializer implements ObjectDeserializer { public final Class type; public PropertyProcessableDeserializer(Class type) { this.type = type; } public T deserialze(DefaultJSONParser [MASK], Type type, Object fieldName) { PropertyProcessable processable; try { processable = this.type.newInstance(); } catch (Exception e) { throw new JSONException(""craete instance error""); } Object object =[MASK].parse(processable, fieldName); return (T) object; } public int getFastMatchToken() { return JSONToken.LBRACE; } }",parser,java,fastjson "package com.facebook.drawee.span; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; import com.facebook.infer.annotation.Nullsafe; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) public class SimpleDraweeSpanTextView extends TextView { @Nullable private DraweeSpanStringBuilder mDraweeStringBuilder; private boolean mIsAttached = false; public SimpleDraweeSpanTextView(Context context) { super(context); } public SimpleDraweeSpanTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public SimpleDraweeSpanTextView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mIsAttached = true; if (mDraweeStringBuilder != null) { mDraweeStringBuilder.onAttachToView(this); } } @Override public void onFinishTemporaryDetach() { super.onFinishTemporaryDetach(); mIsAttached = true; if (mDraweeStringBuilder != null) { mDraweeStringBuilder.onAttachToView(this); } } @Override protected void onDetachedFromWindow() { mIsAttached = false; if (mDraweeStringBuilder != null) { mDraweeStringBuilder.onDetachFromView(this); } super.onDetachedFromWindow(); } @Override public void onStartTemporaryDetach() { mIsAttached = false; if (mDraweeStringBuilder != null) { mDraweeStringBuilder.onDetachFromView(this); } super.onStartTemporaryDetach(); } public void setDraweeSpanStringBuilder(DraweeSpanStringBuilder [MASK]) { setText([MASK], BufferType.SPANNABLE); mDraweeStringBuilder = [MASK]; if (mDraweeStringBuilder != null && mIsAttached) { mDraweeStringBuilder.onAttachToView(this); } } public void detachCurrentDraweeSpanStringBuilder() { if (mDraweeStringBuilder != null) { mDraweeStringBuilder.onDetachFromView(this); } mDraweeStringBuilder = null; } @Override public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); detachCurrentDraweeSpanStringBuilder(); } }",draweeSpanStringBuilder,java,fresco "package jadx.gui.settings.data; public class TabViewState { private String type; private String tabPath; private String subPath; private int caret; private ViewPoint view; boolean [MASK]; boolean pinned; boolean bookmarked; boolean hidden; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTabPath() { return tabPath; } public void setTabPath(String tabPath) { this.tabPath = tabPath; } public String getSubPath() { return subPath; } public void setSubPath(String subPath) { this.subPath = subPath; } public int getCaret() { return caret; } public void setCaret(int caret) { this.caret = caret; } public ViewPoint getView() { return view; } public void setView(ViewPoint view) { this.view = view; } public boolean isActive() { return [MASK]; } public void setActive(boolean [MASK]) { this.[MASK] = [MASK]; } public boolean isPinned() { return pinned; } public void setPinned(boolean pinned) { this.pinned = pinned; } public boolean isBookmarked() { return bookmarked; } public void setBookmarked(boolean bookmarked) { this.bookmarked = bookmarked; } public boolean isHidden() { return hidden; } public void setHidden(boolean hidden) { this.hidden = hidden; } }",active,java,jadx "package org.jbox2d.dynamics.contacts; import org.jbox2d.collision.Manifold; import org.jbox2d.collision.ManifoldPoint; import org.jbox2d.collision.WorldManifold; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.common.Mat22; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Rot; import org.jbox2d.common.Settings; import org.jbox2d.common.Transform; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.Fixture; import org.jbox2d.dynamics.TimeStep; import org.jbox2d.dynamics.contacts.ContactVelocityConstraint.VelocityConstraintPoint; public class ContactSolver { public static final boolean DEBUG_SOLVER = false; public static final float k_errorTol = 1e-3f; public static final int INITIAL_NUM_CONSTRAINTS = 256; public static final float k_maxConditionNumber = 100.0f; public TimeStep m_step; public Position[] m_positions; public Velocity[] m_velocities; public ContactPositionConstraint[] m_positionConstraints; public ContactVelocityConstraint[] m_velocityConstraints; public Contact[] m_contacts; public int m_count; public ContactSolver () { m_positionConstraints = new ContactPositionConstraint[INITIAL_NUM_CONSTRAINTS]; m_velocityConstraints = new ContactVelocityConstraint[INITIAL_NUM_CONSTRAINTS]; for (int i = 0; i < INITIAL_NUM_CONSTRAINTS; i++) { m_positionConstraints[i] = new ContactPositionConstraint(); m_velocityConstraints[i] = new ContactVelocityConstraint(); } } public final void init (ContactSolverDef def) { m_step = def.step; m_count = def.count; if (m_positionConstraints.length < m_count) { ContactPositionConstraint[] old = m_positionConstraints; m_positionConstraints = new ContactPositionConstraint[MathUtils.max(old.length * 2, m_count)]; System.arraycopy(old, 0, m_positionConstraints, 0, old.length); for (int i = old.length; i < m_positionConstraints.length; i++) { m_positionConstraints[i] = new ContactPositionConstraint(); } } if (m_velocityConstraints.length < m_count) { ContactVelocityConstraint[] old = m_velocityConstraints; m_velocityConstraints = new ContactVelocityConstraint[MathUtils.max(old.length * 2, m_count)]; System.arraycopy(old, 0, m_velocityConstraints, 0, old.length); for (int i = old.length; i < m_velocityConstraints.length; i++) { m_velocityConstraints[i] = new ContactVelocityConstraint(); } } m_positions = def.positions; m_velocities = def.velocities; m_contacts = def.contacts; for (int i = 0; i < m_count; ++i) { final Contact contact = m_contacts[i]; final Fixture fixtureA = contact.m_fixtureA; final Fixture fixtureB = contact.m_fixtureB; final Shape shapeA = fixtureA.getShape(); final Shape shapeB = fixtureB.getShape(); final float radiusA = shapeA.m_radius; final float radiusB = shapeB.m_radius; final Body bodyA = fixtureA.getBody(); final Body bodyB = fixtureB.getBody(); final Manifold manifold = contact.getManifold(); int pointCount = manifold.pointCount; assert (pointCount > 0); ContactVelocityConstraint vc = m_velocityConstraints[i]; vc.friction = contact.m_friction; vc.restitution = contact.m_restitution; vc.tangentSpeed = contact.m_tangentSpeed; vc.indexA = bodyA.m_islandIndex; vc.indexB = bodyB.m_islandIndex; vc.invMassA = bodyA.m_invMass; vc.invMassB = bodyB.m_invMass; vc.invIA = bodyA.m_invI; vc.invIB = bodyB.m_invI; vc.contactIndex = i; vc.pointCount = pointCount; vc.K.setZero(); vc.normalMass.setZero(); ContactPositionConstraint pc = m_positionConstraints[i]; pc.indexA = bodyA.m_islandIndex; pc.indexB = bodyB.m_islandIndex; pc.invMassA = bodyA.m_invMass; pc.invMassB = bodyB.m_invMass; pc.localCenterA.set(bodyA.m_sweep.localCenter); pc.localCenterB.set(bodyB.m_sweep.localCenter); pc.invIA = bodyA.m_invI; pc.invIB = bodyB.m_invI; pc.localNormal.set(manifold.localNormal); pc.localPoint.set(manifold.localPoint); pc.pointCount = pointCount; pc.radiusA = radiusA; pc.radiusB = radiusB; pc.type = manifold.type; for (int j = 0; j < pointCount; j++) { ManifoldPoint cp = manifold.points[j]; VelocityConstraintPoint vcp = vc.points[j]; if (m_step.warmStarting) { vcp.normalImpulse = m_step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = m_step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; pc.localPoints[j].x = cp.localPoint.x; pc.localPoints[j].y = cp.localPoint.y; } } } public void warmStart () { for (int i = 0; i < m_count; ++i) { final ContactVelocityConstraint vc = m_velocityConstraints[i]; int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float iA = vc.invIA; float mB = vc.invMassB; float iB = vc.invIB; int pointCount = vc.pointCount; Vec2 vA = m_velocities[indexA].v; float wA = m_velocities[indexA].w; Vec2 vB = m_velocities[indexB].v; float wB = m_velocities[indexB].w; Vec2 normal = vc.normal; float tangentx = 1.0f * normal.y; float tangenty = -1.0f * normal.x; for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; float Px = tangentx * vcp.tangentImpulse + normal.x * vcp.normalImpulse; float Py = tangenty * vcp.tangentImpulse + normal.y * vcp.normalImpulse; wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px); vA.x -= Px * mA; vA.y -= Py * mA; wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px); vB.x += Px * mB; vB.y += Py * mB; } m_velocities[indexA].w = wA; m_velocities[indexB].w = wB; } } private final Transform xfA = new Transform(); private final Transform xfB = new Transform(); private final WorldManifold worldManifold = new WorldManifold(); public final void initializeVelocityConstraints () { for (int i = 0; i < m_count; ++i) { ContactVelocityConstraint vc = m_velocityConstraints[i]; ContactPositionConstraint pc = m_positionConstraints[i]; float radiusA = pc.radiusA; float radiusB = pc.radiusB; Manifold manifold = m_contacts[vc.contactIndex].getManifold(); int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float mB = vc.invMassB; float iA = vc.invIA; float iB = vc.invIB; Vec2 localCenterA = pc.localCenterA; Vec2 localCenterB = pc.localCenterB; Vec2 cA = m_positions[indexA].c; float aA = m_positions[indexA].a; Vec2 vA = m_velocities[indexA].v; float wA = m_velocities[indexA].w; Vec2 cB = m_positions[indexB].c; float aB = m_positions[indexB].a; Vec2 vB = m_velocities[indexB].v; float wB = m_velocities[indexB].w; assert (manifold.pointCount > 0); final Rot xfAq = xfA.q; final Rot xfBq = xfB.q; xfAq.set(aA); xfBq.set(aB); xfA.p.x = cA.x - (xfAq.c * localCenterA.x - xfAq.s * localCenterA.y); xfA.p.y = cA.y - (xfAq.s * localCenterA.x + xfAq.c * localCenterA.y); xfB.p.x = cB.x - (xfBq.c * localCenterB.x - xfBq.s * localCenterB.y); xfB.p.y = cB.y - (xfBq.s * localCenterB.x + xfBq.c * localCenterB.y); worldManifold.initialize(manifold, xfA, radiusA, xfB, radiusB); final Vec2 vcnormal = vc.normal; vcnormal.x = worldManifold.normal.x; vcnormal.y = worldManifold.normal.y; int pointCount = vc.pointCount; for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; Vec2 wmPj = worldManifold.points[j]; final Vec2 vcprA = vcp.rA; final Vec2 vcprB = vcp.rB; vcprA.x = wmPj.x - cA.x; vcprA.y = wmPj.y - cA.y; vcprB.x = wmPj.x - cB.x; vcprB.y = wmPj.y - cB.y; float rnA = vcprA.x * vcnormal.y - vcprA.y * vcnormal.x; float rnB = vcprB.x * vcnormal.y - vcprB.y * vcnormal.x; float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; float tangentx = 1.0f * vcnormal.y; float tangenty = -1.0f * vcnormal.x; float rtA = vcprA.x * tangenty - vcprA.y * tangentx; float rtB = vcprB.x * tangenty - vcprB.y * tangentx; float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; vcp.velocityBias = 0.0f; float tempx = vB.x + -wB * vcprB.y - vA.x - (-wA * vcprA.y); float tempy = vB.y + wB * vcprB.x - vA.y - (wA * vcprA.x); float vRel = vcnormal.x * tempx + vcnormal.y * tempy; if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -vc.restitution * vRel; } } if (vc.pointCount == 2) { VelocityConstraintPoint vcp1 = vc.points[0]; VelocityConstraintPoint vcp2 = vc.points[1]; float rn1A = vcp1.rA.x * vcnormal.y - vcp1.rA.y * vcnormal.x; float rn1B = vcp1.rB.x * vcnormal.y - vcp1.rB.y * vcnormal.x; float rn2A = vcp2.rA.x * vcnormal.y - vcp2.rA.y * vcnormal.x; float rn2B = vcp2.rB.x * vcnormal.y - vcp2.rB.y * vcnormal.x; float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { vc.K.ex.x = k11; vc.K.ex.y = k12; vc.K.ey.x = k12; vc.K.ey.y = k22; vc.K.invertToOut(vc.normalMass); } else { vc.pointCount = 1; } } } } public final void solveVelocityConstraints () { for (int i = 0; i < m_count; ++i) { final ContactVelocityConstraint vc = m_velocityConstraints[i]; int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float mB = vc.invMassB; float iA = vc.invIA; float iB = vc.invIB; int pointCount = vc.pointCount; Vec2 vA = m_velocities[indexA].v; float wA = m_velocities[indexA].w; Vec2 vB = m_velocities[indexB].v; float wB = m_velocities[indexB].w; Vec2 normal = vc.normal; final float normalx = normal.x; final float normaly = normal.y; float tangentx = 1.0f * vc.normal.y; float tangenty = -1.0f * vc.normal.x; final float friction = vc.friction; assert (pointCount == 1 || pointCount == 2); for (int j = 0; j < pointCount; ++j) { final VelocityConstraintPoint vcp = vc.points[j]; final Vec2 a = vcp.rA; float dvx = -wB * vcp.rB.y + vB.x - vA.x + wA * a.y; float dvy = wB * vcp.rB.x + vB.y - vA.y - wA * a.x; final float vt = dvx * tangentx + dvy * tangenty - vc.tangentSpeed; float lambda = vcp.tangentMass * (-vt); final float maxFriction = friction * vcp.normalImpulse; final float newImpulse = MathUtils.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; final float Px = tangentx * lambda; final float Py = tangenty * lambda; vA.x -= Px * mA; vA.y -= Py * mA; wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px); vB.x += Px * mB; vB.y += Py * mB; wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px); } if (vc.pointCount == 1) { final VelocityConstraintPoint vcp = vc.points[0]; float dvx = -wB * vcp.rB.y + vB.x - vA.x + wA * vcp.rA.y; float dvy = wB * vcp.rB.x + vB.y - vA.y - wA * vcp.rA.x; final float vn = dvx * normalx + dvy * normaly; float lambda = -vcp.normalMass * (vn - vcp.velocityBias); float a = vcp.normalImpulse + lambda; final float newImpulse = (a > 0.0f ? a : 0.0f); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; float Px = normalx * lambda; float Py = normaly * lambda; vA.x -= Px * mA; vA.y -= Py * mA; wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px); vB.x += Px * mB; vB.y += Py * mB; wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px); } else { final VelocityConstraintPoint [MASK] = vc.points[0]; final VelocityConstraintPoint cp2 = vc.points[1]; final Vec2 cp1rA = [MASK].rA; final Vec2 cp1rB = [MASK].rB; final Vec2 cp2rA = cp2.rA; final Vec2 cp2rB = cp2.rB; float ax = [MASK].normalImpulse; float ay = cp2.normalImpulse; assert (ax >= 0.0f && ay >= 0.0f); float dv1x = -wB * cp1rB.y + vB.x - vA.x + wA * cp1rA.y; float dv1y = wB * cp1rB.x + vB.y - vA.y - wA * cp1rA.x; float dv2x = -wB * cp2rB.y + vB.x - vA.x + wA * cp2rA.y; float dv2y = wB * cp2rB.x + vB.y - vA.y - wA * cp2rA.x; float vn1 = dv1x * normalx + dv1y * normaly; float vn2 = dv2x * normalx + dv2y * normaly; float bx = vn1 - [MASK].velocityBias; float by = vn2 - cp2.velocityBias; Mat22 R = vc.K; bx -= R.ex.x * ax + R.ey.x * ay; by -= R.ex.y * ax + R.ey.y * ay; for (;;) { Mat22 R1 = vc.normalMass; float xx = R1.ex.x * bx + R1.ey.x * by; float xy = R1.ex.y * bx + R1.ey.y * by; xx *= -1; xy *= -1; if (xx >= 0.0f && xy >= 0.0f) { float dx = xx - ax; float dy = xy - ay; float P1x = dx * normalx; float P1y = dx * normaly; float P2x = dy * normalx; float P2y = dy * normaly; vA.x -= mA * (P1x + P2x); vA.y -= mA * (P1y + P2y); vB.x += mB * (P1x + P2x); vB.y += mB * (P1y + P2y); wA -= iA * (cp1rA.x * P1y - cp1rA.y * P1x + (cp2rA.x * P2y - cp2rA.y * P2x)); wB += iB * (cp1rB.x * P1y - cp1rB.y * P1x + (cp2rB.x * P2y - cp2rB.y * P2x)); [MASK].normalImpulse = xx; cp2.normalImpulse = xy; if (DEBUG_SOLVER) { Vec2 dv1 = vB.add(Vec2.cross(wB, cp1rB).subLocal(vA).subLocal(Vec2.cross(wA, cp1rA))); Vec2 dv2 = vB.add(Vec2.cross(wB, cp2rB).subLocal(vA).subLocal(Vec2.cross(wA, cp2rA))); vn1 = Vec2.dot(dv1, normal); vn2 = Vec2.dot(dv2, normal); assert (MathUtils.abs(vn1 - [MASK].velocityBias) < k_errorTol); assert (MathUtils.abs(vn2 - cp2.velocityBias) < k_errorTol); } break; } xx = -[MASK].normalMass * bx; xy = 0.0f; vn1 = 0.0f; vn2 = vc.K.ex.y * xx + by; if (xx >= 0.0f && vn2 >= 0.0f) { float dx = xx - ax; float dy = xy - ay; float P1x = normalx * dx; float P1y = normaly * dx; float P2x = normalx * dy; float P2y = normaly * dy; vA.x -= mA * (P1x + P2x); vA.y -= mA * (P1y + P2y); vB.x += mB * (P1x + P2x); vB.y += mB * (P1y + P2y); wA -= iA * (cp1rA.x * P1y - cp1rA.y * P1x + (cp2rA.x * P2y - cp2rA.y * P2x)); wB += iB * (cp1rB.x * P1y - cp1rB.y * P1x + (cp2rB.x * P2y - cp2rB.y * P2x)); [MASK].normalImpulse = xx; cp2.normalImpulse = xy; if (DEBUG_SOLVER) { Vec2 dv1 = vB.add(Vec2.cross(wB, cp1rB).subLocal(vA).subLocal(Vec2.cross(wA, cp1rA))); vn1 = Vec2.dot(dv1, normal); assert (MathUtils.abs(vn1 - [MASK].velocityBias) < k_errorTol); } break; } xx = 0.0f; xy = -cp2.normalMass * by; vn1 = vc.K.ey.x * xy + bx; vn2 = 0.0f; if (xy >= 0.0f && vn1 >= 0.0f) { float dx = xx - ax; float dy = xy - ay; float P1x = normalx * dx; float P1y = normaly * dx; float P2x = normalx * dy; float P2y = normaly * dy; vA.x -= mA * (P1x + P2x); vA.y -= mA * (P1y + P2y); vB.x += mB * (P1x + P2x); vB.y += mB * (P1y + P2y); wA -= iA * (cp1rA.x * P1y - cp1rA.y * P1x + (cp2rA.x * P2y - cp2rA.y * P2x)); wB += iB * (cp1rB.x * P1y - cp1rB.y * P1x + (cp2rB.x * P2y - cp2rB.y * P2x)); [MASK].normalImpulse = xx; cp2.normalImpulse = xy; if (DEBUG_SOLVER) { Vec2 dv2 = vB.add(Vec2.cross(wB, cp2rB).subLocal(vA).subLocal(Vec2.cross(wA, cp2rA))); vn2 = Vec2.dot(dv2, normal); assert (MathUtils.abs(vn2 - cp2.velocityBias) < k_errorTol); } break; } xx = 0.0f; xy = 0.0f; vn1 = bx; vn2 = by; if (vn1 >= 0.0f && vn2 >= 0.0f) { float dx = xx - ax; float dy = xy - ay; float P1x = normalx * dx; float P1y = normaly * dx; float P2x = normalx * dy; float P2y = normaly * dy; vA.x -= mA * (P1x + P2x); vA.y -= mA * (P1y + P2y); vB.x += mB * (P1x + P2x); vB.y += mB * (P1y + P2y); wA -= iA * (cp1rA.x * P1y - cp1rA.y * P1x + (cp2rA.x * P2y - cp2rA.y * P2x)); wB += iB * (cp1rB.x * P1y - cp1rB.y * P1x + (cp2rB.x * P2y - cp2rB.y * P2x)); [MASK].normalImpulse = xx; cp2.normalImpulse = xy; break; } break; } } m_velocities[indexA].w = wA; m_velocities[indexB].w = wB; } } public void storeImpulses () { for (int i = 0; i < m_count; i++) { final ContactVelocityConstraint vc = m_velocityConstraints[i]; final Manifold manifold = m_contacts[vc.contactIndex].getManifold(); for (int j = 0; j < vc.pointCount; j++) { manifold.points[j].normalImpulse = vc.points[j].normalImpulse; manifold.points[j].tangentImpulse = vc.points[j].tangentImpulse; } } } private final PositionSolverManifold psolver = new PositionSolverManifold(); public final boolean solvePositionConstraints () { float minSeparation = 0.0f; for (int i = 0; i < m_count; ++i) { ContactPositionConstraint pc = m_positionConstraints[i]; int indexA = pc.indexA; int indexB = pc.indexB; float mA = pc.invMassA; float iA = pc.invIA; Vec2 localCenterA = pc.localCenterA; final float localCenterAx = localCenterA.x; final float localCenterAy = localCenterA.y; float mB = pc.invMassB; float iB = pc.invIB; Vec2 localCenterB = pc.localCenterB; final float localCenterBx = localCenterB.x; final float localCenterBy = localCenterB.y; int pointCount = pc.pointCount; Vec2 cA = m_positions[indexA].c; float aA = m_positions[indexA].a; Vec2 cB = m_positions[indexB].c; float aB = m_positions[indexB].a; for (int j = 0; j < pointCount; ++j) { final Rot xfAq = xfA.q; final Rot xfBq = xfB.q; xfAq.set(aA); xfBq.set(aB); xfA.p.x = cA.x - xfAq.c * localCenterAx + xfAq.s * localCenterAy; xfA.p.y = cA.y - xfAq.s * localCenterAx - xfAq.c * localCenterAy; xfB.p.x = cB.x - xfBq.c * localCenterBx + xfBq.s * localCenterBy; xfB.p.y = cB.y - xfBq.s * localCenterBx - xfBq.c * localCenterBy; final PositionSolverManifold psm = psolver; psm.initialize(pc, xfA, xfB, j); final Vec2 normal = psm.normal; final Vec2 point = psm.point; final float separation = psm.separation; float rAx = point.x - cA.x; float rAy = point.y - cA.y; float rBx = point.x - cB.x; float rBy = point.y - cB.y; minSeparation = MathUtils.min(minSeparation, separation); final float C = MathUtils.clamp(Settings.baumgarte * (separation + Settings.linearSlop), -Settings.maxLinearCorrection, 0.0f); final float rnA = rAx * normal.y - rAy * normal.x; final float rnB = rBx * normal.y - rBy * normal.x; final float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; final float impulse = K > 0.0f ? -C / K : 0.0f; float Px = normal.x * impulse; float Py = normal.y * impulse; cA.x -= Px * mA; cA.y -= Py * mA; aA -= iA * (rAx * Py - rAy * Px); cB.x += Px * mB; cB.y += Py * mB; aB += iB * (rBx * Py - rBy * Px); } m_positions[indexA].a = aA; m_positions[indexB].a = aB; } return minSeparation >= -3.0f * Settings.linearSlop; } public boolean solveTOIPositionConstraints (int toiIndexA, int toiIndexB) { float minSeparation = 0.0f; for (int i = 0; i < m_count; ++i) { ContactPositionConstraint pc = m_positionConstraints[i]; int indexA = pc.indexA; int indexB = pc.indexB; Vec2 localCenterA = pc.localCenterA; Vec2 localCenterB = pc.localCenterB; final float localCenterAx = localCenterA.x; final float localCenterAy = localCenterA.y; final float localCenterBx = localCenterB.x; final float localCenterBy = localCenterB.y; int pointCount = pc.pointCount; float mA = 0.0f; float iA = 0.0f; if (indexA == toiIndexA || indexA == toiIndexB) { mA = pc.invMassA; iA = pc.invIA; } float mB = 0f; float iB = 0f; if (indexB == toiIndexA || indexB == toiIndexB) { mB = pc.invMassB; iB = pc.invIB; } Vec2 cA = m_positions[indexA].c; float aA = m_positions[indexA].a; Vec2 cB = m_positions[indexB].c; float aB = m_positions[indexB].a; for (int j = 0; j < pointCount; ++j) { final Rot xfAq = xfA.q; final Rot xfBq = xfB.q; xfAq.set(aA); xfBq.set(aB); xfA.p.x = cA.x - xfAq.c * localCenterAx + xfAq.s * localCenterAy; xfA.p.y = cA.y - xfAq.s * localCenterAx - xfAq.c * localCenterAy; xfB.p.x = cB.x - xfBq.c * localCenterBx + xfBq.s * localCenterBy; xfB.p.y = cB.y - xfBq.s * localCenterBx - xfBq.c * localCenterBy; final PositionSolverManifold psm = psolver; psm.initialize(pc, xfA, xfB, j); Vec2 normal = psm.normal; Vec2 point = psm.point; float separation = psm.separation; float rAx = point.x - cA.x; float rAy = point.y - cA.y; float rBx = point.x - cB.x; float rBy = point.y - cB.y; minSeparation = MathUtils.min(minSeparation, separation); float C = MathUtils.clamp(Settings.toiBaugarte * (separation + Settings.linearSlop), -Settings.maxLinearCorrection, 0.0f); float rnA = rAx * normal.y - rAy * normal.x; float rnB = rBx * normal.y - rBy * normal.x; float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; float impulse = K > 0.0f ? -C / K : 0.0f; float Px = normal.x * impulse; float Py = normal.y * impulse; cA.x -= Px * mA; cA.y -= Py * mA; aA -= iA * (rAx * Py - rAy * Px); cB.x += Px * mB; cB.y += Py * mB; aB += iB * (rBx * Py - rBy * Px); } m_positions[indexA].a = aA; m_positions[indexB].a = aB; } return minSeparation >= -1.5f * Settings.linearSlop; } public static class ContactSolverDef { public TimeStep step; public Contact[] contacts; public int count; public Position[] positions; public Velocity[] velocities; } } class PositionSolverManifold { public final Vec2 normal = new Vec2(); public final Vec2 point = new Vec2(); public float separation; public void initialize (ContactPositionConstraint pc, Transform xfA, Transform xfB, int index) { assert (pc.pointCount > 0); final Rot xfAq = xfA.q; final Rot xfBq = xfB.q; final Vec2 pcLocalPointsI = pc.localPoints[index]; switch (pc.type) { case CIRCLES: { final Vec2 plocalPoint = pc.localPoint; final Vec2 pLocalPoints0 = pc.localPoints[0]; final float pointAx = (xfAq.c * plocalPoint.x - xfAq.s * plocalPoint.y) + xfA.p.x; final float pointAy = (xfAq.s * plocalPoint.x + xfAq.c * plocalPoint.y) + xfA.p.y; final float pointBx = (xfBq.c * pLocalPoints0.x - xfBq.s * pLocalPoints0.y) + xfB.p.x; final float pointBy = (xfBq.s * pLocalPoints0.x + xfBq.c * pLocalPoints0.y) + xfB.p.y; normal.x = pointBx - pointAx; normal.y = pointBy - pointAy; normal.normalize(); point.x = (pointAx + pointBx) * .5f; point.y = (pointAy + pointBy) * .5f; final float tempx = pointBx - pointAx; final float tempy = pointBy - pointAy; separation = tempx * normal.x + tempy * normal.y - pc.radiusA - pc.radiusB; break; } case FACE_A: { final Vec2 pcLocalNormal = pc.localNormal; final Vec2 pcLocalPoint = pc.localPoint; normal.x = xfAq.c * pcLocalNormal.x - xfAq.s * pcLocalNormal.y; normal.y = xfAq.s * pcLocalNormal.x + xfAq.c * pcLocalNormal.y; final float planePointx = (xfAq.c * pcLocalPoint.x - xfAq.s * pcLocalPoint.y) + xfA.p.x; final float planePointy = (xfAq.s * pcLocalPoint.x + xfAq.c * pcLocalPoint.y) + xfA.p.y; final float clipPointx = (xfBq.c * pcLocalPointsI.x - xfBq.s * pcLocalPointsI.y) + xfB.p.x; final float clipPointy = (xfBq.s * pcLocalPointsI.x + xfBq.c * pcLocalPointsI.y) + xfB.p.y; final float tempx = clipPointx - planePointx; final float tempy = clipPointy - planePointy; separation = tempx * normal.x + tempy * normal.y - pc.radiusA - pc.radiusB; point.x = clipPointx; point.y = clipPointy; break; } case FACE_B: { final Vec2 pcLocalNormal = pc.localNormal; final Vec2 pcLocalPoint = pc.localPoint; normal.x = xfBq.c * pcLocalNormal.x - xfBq.s * pcLocalNormal.y; normal.y = xfBq.s * pcLocalNormal.x + xfBq.c * pcLocalNormal.y; final float planePointx = (xfBq.c * pcLocalPoint.x - xfBq.s * pcLocalPoint.y) + xfB.p.x; final float planePointy = (xfBq.s * pcLocalPoint.x + xfBq.c * pcLocalPoint.y) + xfB.p.y; final float clipPointx = (xfAq.c * pcLocalPointsI.x - xfAq.s * pcLocalPointsI.y) + xfA.p.x; final float clipPointy = (xfAq.s * pcLocalPointsI.x + xfAq.c * pcLocalPointsI.y) + xfA.p.y; final float tempx = clipPointx - planePointx; final float tempy = clipPointy - planePointy; separation = tempx * normal.x + tempy * normal.y - pc.radiusA - pc.radiusB; point.x = clipPointx; point.y = clipPointy; normal.x *= -1; normal.y *= -1; } break; } } }",cp1,java,libgdx "package com.alibaba.json.bvt.serializer; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestPivateStaticClass extends TestCase { public void test_inner() throws Exception { VO vo = new VO(); String [MASK] = JSON.toJSONString(vo); Assert.assertEquals(""{\""value\"":234}"", [MASK]); VO v1 = JSON.parseObject([MASK], VO.class); } private static class VO { private int value = 234; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } }",text,java,fastjson "package org.jbox2d.particle; import java.util.Arrays; import org.jbox2d.callbacks.ParticleDestructionListener; import org.jbox2d.callbacks.ParticleQueryCallback; import org.jbox2d.callbacks.ParticleRaycastCallback; import org.jbox2d.callbacks.QueryCallback; import org.jbox2d.collision.AABB; import org.jbox2d.collision.RayCastInput; import org.jbox2d.collision.RayCastOutput; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.common.BufferUtils; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Rot; import org.jbox2d.common.Settings; import org.jbox2d.common.Transform; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.Fixture; import org.jbox2d.dynamics.TimeStep; import org.jbox2d.dynamics.World; import org.jbox2d.particle.VoronoiDiagram.VoronoiDiagramCallback; import com.badlogic.gdx.utils.reflect.ArrayReflection; import com.badlogic.gdx.utils.reflect.ClassReflection; public class ParticleSystem { private static final int k_pairFlags = ParticleType.b2_springParticle; private static final int k_triadFlags = ParticleType.b2_elasticParticle; private static final int k_noPressureFlags = ParticleType.b2_powderParticle; static final int xTruncBits = 12; static final int yTruncBits = 12; static final int tagBits = 8 * 4 - 1 ; static final long yOffset = 1 << (yTruncBits - 1); static final int yShift = tagBits - yTruncBits; static final int xShift = tagBits - yTruncBits - xTruncBits; static final long xScale = 1 << xShift; static final long xOffset = xScale * (1 << (xTruncBits - 1)); static final int xMask = (1 << xTruncBits) - 1; static final int yMask = (1 << yTruncBits) - 1; static long computeTag (float x, float y) { return (((long)(y + yOffset)) << yShift) + (((long)(xScale * x)) + xOffset); } static long computeRelativeTag (long tag, int x, int y) { return tag + (y << yShift) + (x << xShift); } static int limitCapacity (int capacity, int maxCount) { return maxCount != 0 && capacity > maxCount ? maxCount : capacity; } int m_timestamp; int m_allParticleFlags; int m_allGroupFlags; float m_density; float m_inverseDensity; float m_gravityScale; float m_particleDiameter; float m_inverseDiameter; float m_squaredDiameter; int m_count; int m_internalAllocatedCapacity; int m_maxCount; ParticleBufferInt m_flagsBuffer; ParticleBuffer m_positionBuffer; ParticleBuffer m_velocityBuffer; float[] m_accumulationBuffer; Vec2[] m_accumulation2Buffer; float[] m_depthBuffer; public ParticleBuffer m_colorBuffer; ParticleGroup[] m_groupBuffer; ParticleBuffer m_userDataBuffer; int m_proxyCount; int m_proxyCapacity; Proxy[] m_proxyBuffer; public int m_contactCount; int m_contactCapacity; public ParticleContact[] m_contactBuffer; public int m_bodyContactCount; int m_bodyContactCapacity; public ParticleBodyContact[] m_bodyContactBuffer; int m_pairCount; int m_pairCapacity; Pair[] m_pairBuffer; int m_triadCount; int m_triadCapacity; Triad[] m_triadBuffer; int m_groupCount; ParticleGroup m_groupList; float m_pressureStrength; float m_dampingStrength; float m_elasticStrength; float m_springStrength; float m_viscousStrength; float m_surfaceTensionStrengthA; float m_surfaceTensionStrengthB; float m_powderStrength; float m_ejectionStrength; float m_colorMixingStrength; World m_world; public ParticleSystem (World world) { m_world = world; m_timestamp = 0; m_allParticleFlags = 0; m_allGroupFlags = 0; m_density = 1; m_inverseDensity = 1; m_gravityScale = 1; m_particleDiameter = 1; m_inverseDiameter = 1; m_squaredDiameter = 1; m_count = 0; m_internalAllocatedCapacity = 0; m_maxCount = 0; m_proxyCount = 0; m_proxyCapacity = 0; m_contactCount = 0; m_contactCapacity = 0; m_bodyContactCount = 0; m_bodyContactCapacity = 0; m_pairCount = 0; m_pairCapacity = 0; m_triadCount = 0; m_triadCapacity = 0; m_groupCount = 0; m_pressureStrength = 0.05f; m_dampingStrength = 1.0f; m_elasticStrength = 0.25f; m_springStrength = 0.25f; m_viscousStrength = 0.25f; m_surfaceTensionStrengthA = 0.1f; m_surfaceTensionStrengthB = 0.2f; m_powderStrength = 0.5f; m_ejectionStrength = 0.5f; m_colorMixingStrength = 0.5f; m_flagsBuffer = new ParticleBufferInt(); m_positionBuffer = new ParticleBuffer(Vec2.class); m_velocityBuffer = new ParticleBuffer(Vec2.class); m_colorBuffer = new ParticleBuffer(ParticleColor.class); m_userDataBuffer = new ParticleBuffer(Object.class); } public int createParticle (ParticleDef def) { if (m_count >= m_internalAllocatedCapacity) { int capacity = m_count != 0 ? 2 * m_count : Settings.minParticleBufferCapacity; capacity = limitCapacity(capacity, m_maxCount); capacity = limitCapacity(capacity, m_flagsBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_positionBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_velocityBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_colorBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_userDataBuffer.userSuppliedCapacity); if (m_internalAllocatedCapacity < capacity) { m_flagsBuffer.data = reallocateBuffer(m_flagsBuffer, m_internalAllocatedCapacity, capacity, false); m_positionBuffer.data = reallocateBuffer(m_positionBuffer, m_internalAllocatedCapacity, capacity, false); m_velocityBuffer.data = reallocateBuffer(m_velocityBuffer, m_internalAllocatedCapacity, capacity, false); m_accumulationBuffer = BufferUtils.reallocateBuffer(m_accumulationBuffer, 0, m_internalAllocatedCapacity, capacity, false); m_accumulation2Buffer = BufferUtils.reallocateBuffer(Vec2.class, m_accumulation2Buffer, 0, m_internalAllocatedCapacity, capacity, true); m_depthBuffer = BufferUtils.reallocateBuffer(m_depthBuffer, 0, m_internalAllocatedCapacity, capacity, true); m_colorBuffer.data = reallocateBuffer(m_colorBuffer, m_internalAllocatedCapacity, capacity, true); m_groupBuffer = BufferUtils.reallocateBuffer(ParticleGroup.class, m_groupBuffer, 0, m_internalAllocatedCapacity, capacity, false); m_userDataBuffer.data = reallocateBuffer(m_userDataBuffer, m_internalAllocatedCapacity, capacity, true); m_internalAllocatedCapacity = capacity; } } if (m_count >= m_internalAllocatedCapacity) { return Settings.invalidParticleIndex; } int index = m_count++; m_flagsBuffer.data[index] = def.flags; m_positionBuffer.data[index].set(def.position); m_velocityBuffer.data[index].set(def.velocity); m_groupBuffer[index] = null; if (m_depthBuffer != null) { m_depthBuffer[index] = 0; } if (m_colorBuffer.data != null || def.color != null) { m_colorBuffer.data = requestParticleBuffer(m_colorBuffer.dataClass, m_colorBuffer.data); m_colorBuffer.data[index].set(def.color); } if (m_userDataBuffer.data != null || def.userData != null) { m_userDataBuffer.data = requestParticleBuffer(m_userDataBuffer.dataClass, m_userDataBuffer.data); m_userDataBuffer.data[index] = def.userData; } if (m_proxyCount >= m_proxyCapacity) { int oldCapacity = m_proxyCapacity; int newCapacity = m_proxyCount != 0 ? 2 * m_proxyCount : Settings.minParticleBufferCapacity; m_proxyBuffer = BufferUtils.reallocateBuffer(Proxy.class, m_proxyBuffer, oldCapacity, newCapacity); m_proxyCapacity = newCapacity; } m_proxyBuffer[m_proxyCount++].index = index; return index; } public void destroyParticle (int index, boolean callDestructionListener) { int flags = ParticleType.b2_zombieParticle; if (callDestructionListener) { flags |= ParticleType.b2_destructionListener; } m_flagsBuffer.data[index] |= flags; } private final AABB temp = new AABB(); private final DestroyParticlesInShapeCallback dpcallback = new DestroyParticlesInShapeCallback(); public int destroyParticlesInShape (Shape shape, Transform xf, boolean callDestructionListener) { dpcallback.init(this, shape, xf, callDestructionListener); shape.computeAABB(temp, xf, 0); m_world.queryAABB(dpcallback, temp); return dpcallback.destroyed; } public void destroyParticlesInGroup (ParticleGroup group, boolean callDestructionListener) { for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { destroyParticle(i, callDestructionListener); } } private final AABB temp2 = new AABB(); private final Vec2 tempVec = new Vec2(); private final Transform tempTransform = new Transform(); private final Transform tempTransform2 = new Transform(); private CreateParticleGroupCallback createParticleGroupCallback = new CreateParticleGroupCallback(); private final ParticleDef tempParticleDef = new ParticleDef(); public ParticleGroup createParticleGroup (ParticleGroupDef groupDef) { float [MASK] = getParticleStride(); final Transform identity = tempTransform; identity.setIdentity(); Transform transform = tempTransform2; transform.setIdentity(); int firstIndex = m_count; if (groupDef.shape != null) { final ParticleDef particleDef = tempParticleDef; particleDef.flags = groupDef.flags; particleDef.color = groupDef.color; particleDef.userData = groupDef.userData; Shape shape = groupDef.shape; transform.set(groupDef.position, groupDef.angle); AABB aabb = temp; int childCount = shape.getChildCount(); for (int childIndex = 0; childIndex < childCount; childIndex++) { if (childIndex == 0) { shape.computeAABB(aabb, identity, childIndex); } else { AABB childAABB = temp2; shape.computeAABB(childAABB, identity, childIndex); aabb.combine(childAABB); } } final float upperBoundY = aabb.upperBound.y; final float upperBoundX = aabb.upperBound.x; for (float y = MathUtils.floor(aabb.lowerBound.y / [MASK]) * [MASK]; y < upperBoundY; y += [MASK]) { for (float x = MathUtils.floor(aabb.lowerBound.x / [MASK]) * [MASK]; x < upperBoundX; x += [MASK]) { Vec2 p = tempVec; p.x = x; p.y = y; if (shape.testPoint(identity, p)) { Transform.mulToOut(transform, p, p); particleDef.position.x = p.x; particleDef.position.y = p.y; p.subLocal(groupDef.position); Vec2.crossToOutUnsafe(groupDef.angularVelocity, p, particleDef.velocity); particleDef.velocity.addLocal(groupDef.linearVelocity); createParticle(particleDef); } } } } int lastIndex = m_count; ParticleGroup group = new ParticleGroup(); group.m_system = this; group.m_firstIndex = firstIndex; group.m_lastIndex = lastIndex; group.m_groupFlags = groupDef.groupFlags; group.m_strength = groupDef.strength; group.m_userData = groupDef.userData; group.m_transform.set(transform); group.m_destroyAutomatically = groupDef.destroyAutomatically; group.m_prev = null; group.m_next = m_groupList; if (m_groupList != null) { m_groupList.m_prev = group; } m_groupList = group; ++m_groupCount; for (int i = firstIndex; i < lastIndex; i++) { m_groupBuffer[i] = group; } updateContacts(true); if ((groupDef.flags & k_pairFlags) != 0) { for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a > b) { int temp = a; a = b; b = temp; } if (firstIndex <= a && b < lastIndex) { if (m_pairCount >= m_pairCapacity) { int oldCapacity = m_pairCapacity; int newCapacity = m_pairCount != 0 ? 2 * m_pairCount : Settings.minParticleBufferCapacity; m_pairBuffer = BufferUtils.reallocateBuffer(Pair.class, m_pairBuffer, oldCapacity, newCapacity); m_pairCapacity = newCapacity; } Pair pair = m_pairBuffer[m_pairCount]; pair.indexA = a; pair.indexB = b; pair.flags = contact.flags; pair.strength = groupDef.strength; pair.distance = MathUtils.distance(m_positionBuffer.data[a], m_positionBuffer.data[b]); m_pairCount++; } } } if ((groupDef.flags & k_triadFlags) != 0) { VoronoiDiagram diagram = new VoronoiDiagram(lastIndex - firstIndex); for (int i = firstIndex; i < lastIndex; i++) { diagram.addGenerator(m_positionBuffer.data[i], i); } diagram.generate([MASK] / 2); createParticleGroupCallback.system = this; createParticleGroupCallback.def = groupDef; createParticleGroupCallback.firstIndex = firstIndex; diagram.getNodes(createParticleGroupCallback); } if ((groupDef.groupFlags & ParticleGroupType.b2_solidParticleGroup) != 0) { computeDepthForGroup(group); } return group; } public void joinParticleGroups (ParticleGroup groupA, ParticleGroup groupB) { assert (groupA != groupB); RotateBuffer(groupB.m_firstIndex, groupB.m_lastIndex, m_count); assert (groupB.m_lastIndex == m_count); RotateBuffer(groupA.m_firstIndex, groupA.m_lastIndex, groupB.m_firstIndex); assert (groupA.m_lastIndex == groupB.m_firstIndex); int particleFlags = 0; for (int i = groupA.m_firstIndex; i < groupB.m_lastIndex; i++) { particleFlags |= m_flagsBuffer.data[i]; } updateContacts(true); if ((particleFlags & k_pairFlags) != 0) { for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a > b) { int temp = a; a = b; b = temp; } if (groupA.m_firstIndex <= a && a < groupA.m_lastIndex && groupB.m_firstIndex <= b && b < groupB.m_lastIndex) { if (m_pairCount >= m_pairCapacity) { int oldCapacity = m_pairCapacity; int newCapacity = m_pairCount != 0 ? 2 * m_pairCount : Settings.minParticleBufferCapacity; m_pairBuffer = BufferUtils.reallocateBuffer(Pair.class, m_pairBuffer, oldCapacity, newCapacity); m_pairCapacity = newCapacity; } Pair pair = m_pairBuffer[m_pairCount]; pair.indexA = a; pair.indexB = b; pair.flags = contact.flags; pair.strength = MathUtils.min(groupA.m_strength, groupB.m_strength); pair.distance = MathUtils.distance(m_positionBuffer.data[a], m_positionBuffer.data[b]); m_pairCount++; } } } if ((particleFlags & k_triadFlags) != 0) { VoronoiDiagram diagram = new VoronoiDiagram(groupB.m_lastIndex - groupA.m_firstIndex); for (int i = groupA.m_firstIndex; i < groupB.m_lastIndex; i++) { if ((m_flagsBuffer.data[i] & ParticleType.b2_zombieParticle) == 0) { diagram.addGenerator(m_positionBuffer.data[i], i); } } diagram.generate(getParticleStride() / 2); JoinParticleGroupsCallback callback = new JoinParticleGroupsCallback(); callback.system = this; callback.groupA = groupA; callback.groupB = groupB; diagram.getNodes(callback); } for (int i = groupB.m_firstIndex; i < groupB.m_lastIndex; i++) { m_groupBuffer[i] = groupA; } int groupFlags = groupA.m_groupFlags | groupB.m_groupFlags; groupA.m_groupFlags = groupFlags; groupA.m_lastIndex = groupB.m_lastIndex; groupB.m_firstIndex = groupB.m_lastIndex; destroyParticleGroup(groupB); if ((groupFlags & ParticleGroupType.b2_solidParticleGroup) != 0) { computeDepthForGroup(groupA); } } void destroyParticleGroup (ParticleGroup group) { assert (m_groupCount > 0); assert (group != null); if (m_world.getParticleDestructionListener() != null) { m_world.getParticleDestructionListener().sayGoodbye(group); } for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { m_groupBuffer[i] = null; } if (group.m_prev != null) { group.m_prev.m_next = group.m_next; } if (group.m_next != null) { group.m_next.m_prev = group.m_prev; } if (group == m_groupList) { m_groupList = group.m_next; } --m_groupCount; } public void computeDepthForGroup (ParticleGroup group) { for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { m_accumulationBuffer[i] = 0; } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a >= group.m_firstIndex && a < group.m_lastIndex && b >= group.m_firstIndex && b < group.m_lastIndex) { float w = contact.weight; m_accumulationBuffer[a] += w; m_accumulationBuffer[b] += w; } } m_depthBuffer = requestParticleBuffer(m_depthBuffer); for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { float w = m_accumulationBuffer[i]; m_depthBuffer[i] = w < 0.8f ? 0 : Float.MAX_VALUE; } int interationCount = group.getParticleCount(); for (int t = 0; t < interationCount; t++) { boolean updated = false; for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a >= group.m_firstIndex && a < group.m_lastIndex && b >= group.m_firstIndex && b < group.m_lastIndex) { float r = 1 - contact.weight; float ap0 = m_depthBuffer[a]; float bp0 = m_depthBuffer[b]; float ap1 = bp0 + r; float bp1 = ap0 + r; if (ap0 > ap1) { m_depthBuffer[a] = ap1; updated = true; } if (bp0 > bp1) { m_depthBuffer[b] = bp1; updated = true; } } } if (!updated) { break; } } for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { float p = m_depthBuffer[i]; if (p < Float.MAX_VALUE) { m_depthBuffer[i] *= m_particleDiameter; } else { m_depthBuffer[i] = 0; } } } public void addContact (int a, int b) { assert (a != b); Vec2 pa = m_positionBuffer.data[a]; Vec2 pb = m_positionBuffer.data[b]; float dx = pb.x - pa.x; float dy = pb.y - pa.y; float d2 = dx * dx + dy * dy; if (d2 < m_squaredDiameter) { if (m_contactCount >= m_contactCapacity) { int oldCapacity = m_contactCapacity; int newCapacity = m_contactCount != 0 ? 2 * m_contactCount : Settings.minParticleBufferCapacity; m_contactBuffer = BufferUtils.reallocateBuffer(ParticleContact.class, m_contactBuffer, oldCapacity, newCapacity); m_contactCapacity = newCapacity; } float invD = d2 != 0 ? MathUtils.sqrt(1 / d2) : Float.MAX_VALUE; ParticleContact contact = m_contactBuffer[m_contactCount]; contact.indexA = a; contact.indexB = b; contact.flags = m_flagsBuffer.data[a] | m_flagsBuffer.data[b]; contact.weight = 1 - d2 * invD * m_inverseDiameter; contact.normal.x = invD * dx; contact.normal.y = invD * dy; m_contactCount++; } } public void updateContacts (boolean exceptZombie) { for (int p = 0; p < m_proxyCount; p++) { Proxy proxy = m_proxyBuffer[p]; int i = proxy.index; Vec2 pos = m_positionBuffer.data[i]; proxy.tag = computeTag(m_inverseDiameter * pos.x, m_inverseDiameter * pos.y); } Arrays.sort(m_proxyBuffer, 0, m_proxyCount); m_contactCount = 0; int c_index = 0; for (int i = 0; i < m_proxyCount; i++) { Proxy a = m_proxyBuffer[i]; long rightTag = computeRelativeTag(a.tag, 1, 0); for (int j = i + 1; j < m_proxyCount; j++) { Proxy b = m_proxyBuffer[j]; if (rightTag < b.tag) { break; } addContact(a.index, b.index); } long bottomLeftTag = computeRelativeTag(a.tag, -1, 1); for (; c_index < m_proxyCount; c_index++) { Proxy c = m_proxyBuffer[c_index]; if (bottomLeftTag <= c.tag) { break; } } long bottomRightTag = computeRelativeTag(a.tag, 1, 1); for (int b_index = c_index; b_index < m_proxyCount; b_index++) { Proxy b = m_proxyBuffer[b_index]; if (bottomRightTag < b.tag) { break; } addContact(a.index, b.index); } } if (exceptZombie) { int j = m_contactCount; for (int i = 0; i < j; i++) { if ((m_contactBuffer[i].flags & ParticleType.b2_zombieParticle) != 0) { --j; ParticleContact temp = m_contactBuffer[j]; m_contactBuffer[j] = m_contactBuffer[i]; m_contactBuffer[i] = temp; --i; } } m_contactCount = j; } } private final UpdateBodyContactsCallback ubccallback = new UpdateBodyContactsCallback(); public void updateBodyContacts () { final AABB aabb = temp; aabb.lowerBound.x = Float.MAX_VALUE; aabb.lowerBound.y = Float.MAX_VALUE; aabb.upperBound.x = -Float.MAX_VALUE; aabb.upperBound.y = -Float.MAX_VALUE; for (int i = 0; i < m_count; i++) { Vec2 p = m_positionBuffer.data[i]; Vec2.minToOut(aabb.lowerBound, p, aabb.lowerBound); Vec2.maxToOut(aabb.upperBound, p, aabb.upperBound); } aabb.lowerBound.x -= m_particleDiameter; aabb.lowerBound.y -= m_particleDiameter; aabb.upperBound.x += m_particleDiameter; aabb.upperBound.y += m_particleDiameter; m_bodyContactCount = 0; ubccallback.system = this; m_world.queryAABB(ubccallback, aabb); } private SolveCollisionCallback sccallback = new SolveCollisionCallback(); public void solveCollision (TimeStep step) { final AABB aabb = temp; final Vec2 lowerBound = aabb.lowerBound; final Vec2 upperBound = aabb.upperBound; lowerBound.x = Float.MAX_VALUE; lowerBound.y = Float.MAX_VALUE; upperBound.x = -Float.MAX_VALUE; upperBound.y = -Float.MAX_VALUE; for (int i = 0; i < m_count; i++) { final Vec2 v = m_velocityBuffer.data[i]; final Vec2 p1 = m_positionBuffer.data[i]; final float p1x = p1.x; final float p1y = p1.y; final float p2x = p1x + step.dt * v.x; final float p2y = p1y + step.dt * v.y; final float bx = p1x < p2x ? p1x : p2x; final float by = p1y < p2y ? p1y : p2y; lowerBound.x = lowerBound.x < bx ? lowerBound.x : bx; lowerBound.y = lowerBound.y < by ? lowerBound.y : by; final float b1x = p1x > p2x ? p1x : p2x; final float b1y = p1y > p2y ? p1y : p2y; upperBound.x = upperBound.x > b1x ? upperBound.x : b1x; upperBound.y = upperBound.y > b1y ? upperBound.y : b1y; } sccallback.step = step; sccallback.system = this; m_world.queryAABB(sccallback, aabb); } public void solve (TimeStep step) { ++m_timestamp; if (m_count == 0) { return; } m_allParticleFlags = 0; for (int i = 0; i < m_count; i++) { m_allParticleFlags |= m_flagsBuffer.data[i]; } if ((m_allParticleFlags & ParticleType.b2_zombieParticle) != 0) { solveZombie(); } if (m_count == 0) { return; } m_allGroupFlags = 0; for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { m_allGroupFlags |= group.m_groupFlags; } final float gravityx = step.dt * m_gravityScale * m_world.getGravity().x; final float gravityy = step.dt * m_gravityScale * m_world.getGravity().y; float criticalVelocytySquared = getCriticalVelocitySquared(step); for (int i = 0; i < m_count; i++) { Vec2 v = m_velocityBuffer.data[i]; v.x += gravityx; v.y += gravityy; float v2 = v.x * v.x + v.y * v.y; if (v2 > criticalVelocytySquared) { float a = v2 == 0 ? Float.MAX_VALUE : MathUtils.sqrt(criticalVelocytySquared / v2); v.x *= a; v.y *= a; } } solveCollision(step); if ((m_allGroupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { solveRigid(step); } if ((m_allParticleFlags & ParticleType.b2_wallParticle) != 0) { solveWall(step); } for (int i = 0; i < m_count; i++) { Vec2 pos = m_positionBuffer.data[i]; Vec2 vel = m_velocityBuffer.data[i]; pos.x += step.dt * vel.x; pos.y += step.dt * vel.y; } updateBodyContacts(); updateContacts(false); if ((m_allParticleFlags & ParticleType.b2_viscousParticle) != 0) { solveViscous(step); } if ((m_allParticleFlags & ParticleType.b2_powderParticle) != 0) { solvePowder(step); } if ((m_allParticleFlags & ParticleType.b2_tensileParticle) != 0) { solveTensile(step); } if ((m_allParticleFlags & ParticleType.b2_elasticParticle) != 0) { solveElastic(step); } if ((m_allParticleFlags & ParticleType.b2_springParticle) != 0) { solveSpring(step); } if ((m_allGroupFlags & ParticleGroupType.b2_solidParticleGroup) != 0) { solveSolid(step); } if ((m_allParticleFlags & ParticleType.b2_colorMixingParticle) != 0) { solveColorMixing(step); } solvePressure(step); solveDamping(step); } void solvePressure (TimeStep step) { for (int i = 0; i < m_count; i++) { m_accumulationBuffer[i] = 0; } for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; float w = contact.weight; m_accumulationBuffer[a] += w; } for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; float w = contact.weight; m_accumulationBuffer[a] += w; m_accumulationBuffer[b] += w; } if ((m_allParticleFlags & k_noPressureFlags) != 0) { for (int i = 0; i < m_count; i++) { if ((m_flagsBuffer.data[i] & k_noPressureFlags) != 0) { m_accumulationBuffer[i] = 0; } } } float pressurePerWeight = m_pressureStrength * getCriticalPressure(step); for (int i = 0; i < m_count; i++) { float w = m_accumulationBuffer[i]; float h = pressurePerWeight * MathUtils.max(0.0f, MathUtils.min(w, Settings.maxParticleWeight) - Settings.minParticleWeight); m_accumulationBuffer[i] = h; } float velocityPerPressure = step.dt / (m_density * m_particleDiameter); for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; Body b = contact.body; float w = contact.weight; float m = contact.mass; Vec2 n = contact.normal; Vec2 p = m_positionBuffer.data[a]; float h = m_accumulationBuffer[a] + pressurePerWeight * w; final Vec2 f = tempVec; final float coef = velocityPerPressure * w * m * h; f.x = coef * n.x; f.y = coef * n.y; final Vec2 velData = m_velocityBuffer.data[a]; final float particleInvMass = getParticleInvMass(); velData.x -= particleInvMass * f.x; velData.y -= particleInvMass * f.y; b.applyLinearImpulse(f, p, true); } for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vec2 n = contact.normal; float h = m_accumulationBuffer[a] + m_accumulationBuffer[b]; final float fx = velocityPerPressure * w * h * n.x; final float fy = velocityPerPressure * w * h * n.y; final Vec2 velDataA = m_velocityBuffer.data[a]; final Vec2 velDataB = m_velocityBuffer.data[b]; velDataA.x -= fx; velDataA.y -= fy; velDataB.x += fx; velDataB.y += fy; } } void solveDamping (TimeStep step) { float damping = m_dampingStrength; for (int k = 0; k < m_bodyContactCount; k++) { final ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; Body b = contact.body; float w = contact.weight; float m = contact.mass; Vec2 n = contact.normal; Vec2 p = m_positionBuffer.data[a]; final float tempX = p.x - b.m_sweep.c.x; final float tempY = p.y - b.m_sweep.c.y; final Vec2 velA = m_velocityBuffer.data[a]; float vx = -b.m_angularVelocity * tempY + b.m_linearVelocity.x - velA.x; float vy = b.m_angularVelocity * tempX + b.m_linearVelocity.y - velA.y; float vn = vx * n.x + vy * n.y; if (vn < 0) { final Vec2 f = tempVec; f.x = damping * w * m * vn * n.x; f.y = damping * w * m * vn * n.y; final float invMass = getParticleInvMass(); velA.x += invMass * f.x; velA.y += invMass * f.y; f.x = -f.x; f.y = -f.y; b.applyLinearImpulse(f, p, true); } } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vec2 n = contact.normal; final Vec2 velA = m_velocityBuffer.data[a]; final Vec2 velB = m_velocityBuffer.data[b]; final float vx = velB.x - velA.x; final float vy = velB.y - velA.y; float vn = vx * n.x + vy * n.y; if (vn < 0) { float fx = damping * w * vn * n.x; float fy = damping * w * vn * n.y; velA.x += fx; velA.y += fy; velB.x -= fx; velB.y -= fy; } } } public void solveWall (TimeStep step) { for (int i = 0; i < m_count; i++) { if ((m_flagsBuffer.data[i] & ParticleType.b2_wallParticle) != 0) { final Vec2 r = m_velocityBuffer.data[i]; r.x = 0.0f; r.y = 0.0f; } } } private final Vec2 tempVec2 = new Vec2(); private final Rot tempRot = new Rot(); private final Transform tempXf = new Transform(); private final Transform tempXf2 = new Transform(); void solveRigid (final TimeStep step) { for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { if ((group.m_groupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { group.updateStatistics(); Vec2 temp = tempVec; Vec2 cross = tempVec2; Rot rotation = tempRot; rotation.set(step.dt * group.m_angularVelocity); Rot.mulToOutUnsafe(rotation, group.m_center, cross); temp.set(group.m_linearVelocity).mulLocal(step.dt).addLocal(group.m_center).subLocal(cross); tempXf.p.set(temp); tempXf.q.set(rotation); Transform.mulToOut(tempXf, group.m_transform, group.m_transform); final Transform velocityTransform = tempXf2; velocityTransform.p.x = step.inv_dt * tempXf.p.x; velocityTransform.p.y = step.inv_dt * tempXf.p.y; velocityTransform.q.s = step.inv_dt * tempXf.q.s; velocityTransform.q.c = step.inv_dt * (tempXf.q.c - 1); for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { Transform.mulToOutUnsafe(velocityTransform, m_positionBuffer.data[i], m_velocityBuffer.data[i]); } } } } void solveElastic (final TimeStep step) { float elasticStrength = step.inv_dt * m_elasticStrength; for (int k = 0; k < m_triadCount; k++) { final Triad triad = m_triadBuffer[k]; if ((triad.flags & ParticleType.b2_elasticParticle) != 0) { int a = triad.indexA; int b = triad.indexB; int c = triad.indexC; final Vec2 oa = triad.pa; final Vec2 ob = triad.pb; final Vec2 oc = triad.pc; final Vec2 pa = m_positionBuffer.data[a]; final Vec2 pb = m_positionBuffer.data[b]; final Vec2 pc = m_positionBuffer.data[c]; final float px = 1f / 3 * (pa.x + pb.x + pc.x); final float py = 1f / 3 * (pa.y + pb.y + pc.y); float rs = Vec2.cross(oa, pa) + Vec2.cross(ob, pb) + Vec2.cross(oc, pc); float rc = Vec2.dot(oa, pa) + Vec2.dot(ob, pb) + Vec2.dot(oc, pc); float r2 = rs * rs + rc * rc; float invR = r2 == 0 ? Float.MAX_VALUE : MathUtils.sqrt(1f / r2); rs *= invR; rc *= invR; final float strength = elasticStrength * triad.strength; final float roax = rc * oa.x - rs * oa.y; final float roay = rs * oa.x + rc * oa.y; final float robx = rc * ob.x - rs * ob.y; final float roby = rs * ob.x + rc * ob.y; final float rocx = rc * oc.x - rs * oc.y; final float rocy = rs * oc.x + rc * oc.y; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; final Vec2 vc = m_velocityBuffer.data[c]; va.x += strength * (roax - (pa.x - px)); va.y += strength * (roay - (pa.y - py)); vb.x += strength * (robx - (pb.x - px)); vb.y += strength * (roby - (pb.y - py)); vc.x += strength * (rocx - (pc.x - px)); vc.y += strength * (rocy - (pc.y - py)); } } } void solveSpring (final TimeStep step) { float springStrength = step.inv_dt * m_springStrength; for (int k = 0; k < m_pairCount; k++) { final Pair pair = m_pairBuffer[k]; if ((pair.flags & ParticleType.b2_springParticle) != 0) { int a = pair.indexA; int b = pair.indexB; final Vec2 pa = m_positionBuffer.data[a]; final Vec2 pb = m_positionBuffer.data[b]; final float dx = pb.x - pa.x; final float dy = pb.y - pa.y; float r0 = pair.distance; float r1 = MathUtils.sqrt(dx * dx + dy * dy); if (r1 == 0) r1 = Float.MAX_VALUE; float strength = springStrength * pair.strength; final float fx = strength * (r0 - r1) / r1 * dx; final float fy = strength * (r0 - r1) / r1 * dy; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } void solveTensile (final TimeStep step) { m_accumulation2Buffer = requestParticleBuffer(Vec2.class, m_accumulation2Buffer); for (int i = 0; i < m_count; i++) { m_accumulationBuffer[i] = 0; m_accumulation2Buffer[i].setZero(); } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_tensileParticle) != 0) { int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vec2 n = contact.normal; m_accumulationBuffer[a] += w; m_accumulationBuffer[b] += w; final Vec2 a2A = m_accumulation2Buffer[a]; final Vec2 a2B = m_accumulation2Buffer[b]; final float inter = (1 - w) * w; a2A.x -= inter * n.x; a2A.y -= inter * n.y; a2B.x += inter * n.x; a2B.y += inter * n.y; } } float strengthA = m_surfaceTensionStrengthA * getCriticalVelocity(step); float strengthB = m_surfaceTensionStrengthB * getCriticalVelocity(step); for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_tensileParticle) != 0) { int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vec2 n = contact.normal; final Vec2 a2A = m_accumulation2Buffer[a]; final Vec2 a2B = m_accumulation2Buffer[b]; float h = m_accumulationBuffer[a] + m_accumulationBuffer[b]; final float sx = a2B.x - a2A.x; final float sy = a2B.y - a2A.y; float fn = (strengthA * (h - 2) + strengthB * (sx * n.x + sy * n.y)) * w; final float fx = fn * n.x; final float fy = fn * n.y; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } void solveViscous (final TimeStep step) { float viscousStrength = m_viscousStrength; for (int k = 0; k < m_bodyContactCount; k++) { final ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; if ((m_flagsBuffer.data[a] & ParticleType.b2_viscousParticle) != 0) { Body b = contact.body; float w = contact.weight; float m = contact.mass; Vec2 p = m_positionBuffer.data[a]; final Vec2 va = m_velocityBuffer.data[a]; final float tempX = p.x - b.m_sweep.c.x; final float tempY = p.y - b.m_sweep.c.y; final float vx = -b.m_angularVelocity * tempY + b.m_linearVelocity.x - va.x; final float vy = b.m_angularVelocity * tempX + b.m_linearVelocity.y - va.y; final Vec2 f = tempVec; final float pInvMass = getParticleInvMass(); f.x = viscousStrength * m * w * vx; f.y = viscousStrength * m * w * vy; va.x += pInvMass * f.x; va.y += pInvMass * f.y; f.x = -f.x; f.y = -f.y; b.applyLinearImpulse(f, p, true); } } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_viscousParticle) != 0) { int a = contact.indexA; int b = contact.indexB; float w = contact.weight; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; final float vx = vb.x - va.x; final float vy = vb.y - va.y; final float fx = viscousStrength * w * vx; final float fy = viscousStrength * w * vy; va.x += fx; va.y += fy; vb.x -= fx; vb.y -= fy; } } } void solvePowder (final TimeStep step) { float powderStrength = m_powderStrength * getCriticalVelocity(step); float minWeight = 1.0f - Settings.particleStride; for (int k = 0; k < m_bodyContactCount; k++) { final ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; if ((m_flagsBuffer.data[a] & ParticleType.b2_powderParticle) != 0) { float w = contact.weight; if (w > minWeight) { Body b = contact.body; float m = contact.mass; Vec2 p = m_positionBuffer.data[a]; Vec2 n = contact.normal; final Vec2 f = tempVec; final Vec2 va = m_velocityBuffer.data[a]; final float inter = powderStrength * m * (w - minWeight); final float pInvMass = getParticleInvMass(); f.x = inter * n.x; f.y = inter * n.y; va.x -= pInvMass * f.x; va.y -= pInvMass * f.y; b.applyLinearImpulse(f, p, true); } } } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_powderParticle) != 0) { float w = contact.weight; if (w > minWeight) { int a = contact.indexA; int b = contact.indexB; Vec2 n = contact.normal; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; final float inter = powderStrength * (w - minWeight); final float fx = inter * n.x; final float fy = inter * n.y; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } } void solveSolid (final TimeStep step) { m_depthBuffer = requestParticleBuffer(m_depthBuffer); float ejectionStrength = step.inv_dt * m_ejectionStrength; for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (m_groupBuffer[a] != m_groupBuffer[b]) { float w = contact.weight; Vec2 n = contact.normal; float h = m_depthBuffer[a] + m_depthBuffer[b]; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; final float inter = ejectionStrength * h * w; final float fx = inter * n.x; final float fy = inter * n.y; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } void solveColorMixing (final TimeStep step) { m_colorBuffer.data = requestParticleBuffer(ParticleColor.class, m_colorBuffer.data); int colorMixing256 = (int)(256 * m_colorMixingStrength); for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if ((m_flagsBuffer.data[a] & m_flagsBuffer.data[b] & ParticleType.b2_colorMixingParticle) != 0) { ParticleColor colorA = m_colorBuffer.data[a]; ParticleColor colorB = m_colorBuffer.data[b]; int dr = (colorMixing256 * (colorB.r - colorA.r)) >> 8; int dg = (colorMixing256 * (colorB.g - colorA.g)) >> 8; int db = (colorMixing256 * (colorB.b - colorA.b)) >> 8; int da = (colorMixing256 * (colorB.a - colorA.a)) >> 8; colorA.r += dr; colorA.g += dg; colorA.b += db; colorA.a += da; colorB.r -= dr; colorB.g -= dg; colorB.b -= db; colorB.a -= da; } } } void solveZombie () { int newCount = 0; int[] newIndices = new int[m_count]; for (int i = 0; i < m_count; i++) { int flags = m_flagsBuffer.data[i]; if ((flags & ParticleType.b2_zombieParticle) != 0) { ParticleDestructionListener destructionListener = m_world.getParticleDestructionListener(); if ((flags & ParticleType.b2_destructionListener) != 0 && destructionListener != null) { destructionListener.sayGoodbye(i); } newIndices[i] = Settings.invalidParticleIndex; } else { newIndices[i] = newCount; if (i != newCount) { m_flagsBuffer.data[newCount] = m_flagsBuffer.data[i]; m_positionBuffer.data[newCount].set(m_positionBuffer.data[i]); m_velocityBuffer.data[newCount].set(m_velocityBuffer.data[i]); m_groupBuffer[newCount] = m_groupBuffer[i]; if (m_depthBuffer != null) { m_depthBuffer[newCount] = m_depthBuffer[i]; } if (m_colorBuffer.data != null) { m_colorBuffer.data[newCount].set(m_colorBuffer.data[i]); } if (m_userDataBuffer.data != null) { m_userDataBuffer.data[newCount] = m_userDataBuffer.data[i]; } } newCount++; } } for (int k = 0; k < m_proxyCount; k++) { Proxy proxy = m_proxyBuffer[k]; proxy.index = newIndices[proxy.index]; } int j = m_proxyCount; for (int i = 0; i < j; i++) { if (Test.IsProxyInvalid(m_proxyBuffer[i])) { --j; Proxy temp = m_proxyBuffer[j]; m_proxyBuffer[j] = m_proxyBuffer[i]; m_proxyBuffer[i] = temp; --i; } } m_proxyCount = j; for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; contact.indexA = newIndices[contact.indexA]; contact.indexB = newIndices[contact.indexB]; } j = m_contactCount; for (int i = 0; i < j; i++) { if (Test.IsContactInvalid(m_contactBuffer[i])) { --j; ParticleContact temp = m_contactBuffer[j]; m_contactBuffer[j] = m_contactBuffer[i]; m_contactBuffer[i] = temp; --i; } } m_contactCount = j; for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; contact.index = newIndices[contact.index]; } j = m_bodyContactCount; for (int i = 0; i < j; i++) { if (Test.IsBodyContactInvalid(m_bodyContactBuffer[i])) { --j; ParticleBodyContact temp = m_bodyContactBuffer[j]; m_bodyContactBuffer[j] = m_bodyContactBuffer[i]; m_bodyContactBuffer[i] = temp; --i; } } m_bodyContactCount = j; for (int k = 0; k < m_pairCount; k++) { Pair pair = m_pairBuffer[k]; pair.indexA = newIndices[pair.indexA]; pair.indexB = newIndices[pair.indexB]; } j = m_pairCount; for (int i = 0; i < j; i++) { if (Test.IsPairInvalid(m_pairBuffer[i])) { --j; Pair temp = m_pairBuffer[j]; m_pairBuffer[j] = m_pairBuffer[i]; m_pairBuffer[i] = temp; --i; } } m_pairCount = j; for (int k = 0; k < m_triadCount; k++) { Triad triad = m_triadBuffer[k]; triad.indexA = newIndices[triad.indexA]; triad.indexB = newIndices[triad.indexB]; triad.indexC = newIndices[triad.indexC]; } j = m_triadCount; for (int i = 0; i < j; i++) { if (Test.IsTriadInvalid(m_triadBuffer[i])) { --j; Triad temp = m_triadBuffer[j]; m_triadBuffer[j] = m_triadBuffer[i]; m_triadBuffer[i] = temp; --i; } } m_triadCount = j; for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { int firstIndex = newCount; int lastIndex = 0; boolean modified = false; for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { j = newIndices[i]; if (j >= 0) { firstIndex = MathUtils.min(firstIndex, j); lastIndex = MathUtils.max(lastIndex, j + 1); } else { modified = true; } } if (firstIndex < lastIndex) { group.m_firstIndex = firstIndex; group.m_lastIndex = lastIndex; if (modified) { if ((group.m_groupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { group.m_toBeSplit = true; } } } else { group.m_firstIndex = 0; group.m_lastIndex = 0; if (group.m_destroyAutomatically) { group.m_toBeDestroyed = true; } } } m_count = newCount; for (ParticleGroup group = m_groupList; group != null;) { ParticleGroup next = group.getNext(); if (group.m_toBeDestroyed) { destroyParticleGroup(group); } else if (group.m_toBeSplit) { } group = next; } } private static class NewIndices { int start, mid, end; final int getIndex (final int i) { if (i < start) { return i; } else if (i < mid) { return i + end - mid; } else if (i < end) { return i + start - mid; } else { return i; } } } private final NewIndices newIndices = new NewIndices(); void RotateBuffer (int start, int mid, int end) { if (start == mid || mid == end) { return; } newIndices.start = start; newIndices.mid = mid; newIndices.end = end; BufferUtils.rotate(m_flagsBuffer.data, start, mid, end); BufferUtils.rotate(m_positionBuffer.data, start, mid, end); BufferUtils.rotate(m_velocityBuffer.data, start, mid, end); BufferUtils.rotate(m_groupBuffer, start, mid, end); if (m_depthBuffer != null) { BufferUtils.rotate(m_depthBuffer, start, mid, end); } if (m_colorBuffer.data != null) { BufferUtils.rotate(m_colorBuffer.data, start, mid, end); } if (m_userDataBuffer.data != null) { BufferUtils.rotate(m_userDataBuffer.data, start, mid, end); } for (int k = 0; k < m_proxyCount; k++) { Proxy proxy = m_proxyBuffer[k]; proxy.index = newIndices.getIndex(proxy.index); } for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; contact.indexA = newIndices.getIndex(contact.indexA); contact.indexB = newIndices.getIndex(contact.indexB); } for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; contact.index = newIndices.getIndex(contact.index); } for (int k = 0; k < m_pairCount; k++) { Pair pair = m_pairBuffer[k]; pair.indexA = newIndices.getIndex(pair.indexA); pair.indexB = newIndices.getIndex(pair.indexB); } for (int k = 0; k < m_triadCount; k++) { Triad triad = m_triadBuffer[k]; triad.indexA = newIndices.getIndex(triad.indexA); triad.indexB = newIndices.getIndex(triad.indexB); triad.indexC = newIndices.getIndex(triad.indexC); } for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { group.m_firstIndex = newIndices.getIndex(group.m_firstIndex); group.m_lastIndex = newIndices.getIndex(group.m_lastIndex - 1) + 1; } } public void setParticleRadius (float radius) { m_particleDiameter = 2 * radius; m_squaredDiameter = m_particleDiameter * m_particleDiameter; m_inverseDiameter = 1 / m_particleDiameter; } public void setParticleDensity (float density) { m_density = density; m_inverseDensity = 1 / m_density; } public float getParticleDensity () { return m_density; } public void setParticleGravityScale (float gravityScale) { m_gravityScale = gravityScale; } public float getParticleGravityScale () { return m_gravityScale; } public void setParticleDamping (float damping) { m_dampingStrength = damping; } public float getParticleDamping () { return m_dampingStrength; } public float getParticleRadius () { return m_particleDiameter / 2; } float getCriticalVelocity (final TimeStep step) { return m_particleDiameter * step.inv_dt; } float getCriticalVelocitySquared (final TimeStep step) { float velocity = getCriticalVelocity(step); return velocity * velocity; } float getCriticalPressure (final TimeStep step) { return m_density * getCriticalVelocitySquared(step); } float getParticleStride () { return Settings.particleStride * m_particleDiameter; } float getParticleMass () { float [MASK] = getParticleStride(); return m_density * [MASK] * [MASK]; } float getParticleInvMass () { return 1.777777f * m_inverseDensity * m_inverseDiameter * m_inverseDiameter; } public int[] getParticleFlagsBuffer () { return m_flagsBuffer.data; } public Vec2[] getParticlePositionBuffer () { return m_positionBuffer.data; } public Vec2[] getParticleVelocityBuffer () { return m_velocityBuffer.data; } public ParticleColor[] getParticleColorBuffer () { m_colorBuffer.data = requestParticleBuffer(ParticleColor.class, m_colorBuffer.data); return m_colorBuffer.data; } public Object[] getParticleUserDataBuffer () { m_userDataBuffer.data = requestParticleBuffer(Object.class, m_userDataBuffer.data); return m_userDataBuffer.data; } public int getParticleMaxCount () { return m_maxCount; } public void setParticleMaxCount (int count) { assert (m_count <= count); m_maxCount = count; } void setParticleBuffer (ParticleBufferInt buffer, int[] newData, int newCapacity) { assert ((newData != null && newCapacity != 0) || (newData == null && newCapacity == 0)); if (buffer.userSuppliedCapacity != 0) { } buffer.data = newData; buffer.userSuppliedCapacity = newCapacity; } void setParticleBuffer (ParticleBuffer buffer, T[] newData, int newCapacity) { assert ((newData != null && newCapacity != 0) || (newData == null && newCapacity == 0)); if (buffer.userSuppliedCapacity != 0) { } buffer.data = newData; buffer.userSuppliedCapacity = newCapacity; } public void setParticleFlagsBuffer (int[] buffer, int capacity) { setParticleBuffer(m_flagsBuffer, buffer, capacity); } public void setParticlePositionBuffer (Vec2[] buffer, int capacity) { setParticleBuffer(m_positionBuffer, buffer, capacity); } public void setParticleVelocityBuffer (Vec2[] buffer, int capacity) { setParticleBuffer(m_velocityBuffer, buffer, capacity); } public void setParticleColorBuffer (ParticleColor[] buffer, int capacity) { setParticleBuffer(m_colorBuffer, buffer, capacity); } public ParticleGroup[] getParticleGroupBuffer () { return m_groupBuffer; } public int getParticleGroupCount () { return m_groupCount; } public ParticleGroup[] getParticleGroupList () { return m_groupBuffer; } public int getParticleCount () { return m_count; } public void setParticleUserDataBuffer (Object[] buffer, int capacity) { setParticleBuffer(m_userDataBuffer, buffer, capacity); } private static final int lowerBound (Proxy[] ray, int length, long tag) { int left = 0; int step, curr; while (length > 0) { step = length / 2; curr = left + step; if (ray[curr].tag < tag) { left = curr + 1; length -= step + 1; } else { length = step; } } return left; } private static final int upperBound (Proxy[] ray, int length, long tag) { int left = 0; int step, curr; while (length > 0) { step = length / 2; curr = left + step; if (ray[curr].tag <= tag) { left = curr + 1; length -= step + 1; } else { length = step; } } return left; } public void queryAABB (ParticleQueryCallback callback, final AABB aabb) { if (m_proxyCount == 0) { return; } final float lowerBoundX = aabb.lowerBound.x; final float lowerBoundY = aabb.lowerBound.y; final float upperBoundX = aabb.upperBound.x; final float upperBoundY = aabb.upperBound.y; int firstProxy = lowerBound(m_proxyBuffer, m_proxyCount, computeTag(m_inverseDiameter * lowerBoundX, m_inverseDiameter * lowerBoundY)); int lastProxy = upperBound(m_proxyBuffer, m_proxyCount, computeTag(m_inverseDiameter * upperBoundX, m_inverseDiameter * upperBoundY)); for (int proxy = firstProxy; proxy < lastProxy; ++proxy) { int i = m_proxyBuffer[proxy].index; final Vec2 p = m_positionBuffer.data[i]; if (lowerBoundX < p.x && p.x < upperBoundX && lowerBoundY < p.y && p.y < upperBoundY) { if (!callback.reportParticle(i)) { break; } } } } public void raycast (ParticleRaycastCallback callback, final Vec2 point1, final Vec2 point2) { if (m_proxyCount == 0) { return; } int firstProxy = lowerBound(m_proxyBuffer, m_proxyCount, computeTag( m_inverseDiameter * MathUtils.min(point1.x, point2.x) - 1, m_inverseDiameter * MathUtils.min(point1.y, point2.y) - 1)); int lastProxy = upperBound(m_proxyBuffer, m_proxyCount, computeTag( m_inverseDiameter * MathUtils.max(point1.x, point2.x) + 1, m_inverseDiameter * MathUtils.max(point1.y, point2.y) + 1)); float fraction = 1; final float vx = point2.x - point1.x; final float vy = point2.y - point1.y; float v2 = vx * vx + vy * vy; if (v2 == 0) v2 = Float.MAX_VALUE; for (int proxy = firstProxy; proxy < lastProxy; ++proxy) { int i = m_proxyBuffer[proxy].index; final Vec2 posI = m_positionBuffer.data[i]; final float px = point1.x - posI.x; final float py = point1.y - posI.y; float pv = px * vx + py * vy; float p2 = px * px + py * py; float determinant = pv * pv - v2 * (p2 - m_squaredDiameter); if (determinant >= 0) { float sqrtDeterminant = MathUtils.sqrt(determinant); float t = (-pv - sqrtDeterminant) / v2; if (t > fraction) { continue; } if (t < 0) { t = (-pv + sqrtDeterminant) / v2; if (t < 0 || t > fraction) { continue; } } final Vec2 n = tempVec; tempVec.x = px + t * vx; tempVec.y = py + t * vy; n.normalize(); final Vec2 point = tempVec2; point.x = point1.x + t * vx; point.y = point1.y + t * vy; float f = callback.reportParticle(i, point, n, t); fraction = MathUtils.min(fraction, f); if (fraction <= 0) { break; } } } } public float computeParticleCollisionEnergy () { float sum_v2 = 0; for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; Vec2 n = contact.normal; final Vec2 va = m_velocityBuffer.data[a]; final Vec2 vb = m_velocityBuffer.data[b]; final float vx = vb.x - va.x; final float vy = vb.y - va.y; float vn = vx * n.x + vy * n.y; if (vn < 0) { sum_v2 += vn * vn; } } return 0.5f * getParticleMass() * sum_v2; } static T[] reallocateBuffer (ParticleBuffer buffer, int oldCapacity, int newCapacity, boolean deferred) { assert (newCapacity > oldCapacity); return BufferUtils.reallocateBuffer(buffer.dataClass, buffer.data, buffer.userSuppliedCapacity, oldCapacity, newCapacity, deferred); } static int[] reallocateBuffer (ParticleBufferInt buffer, int oldCapacity, int newCapacity, boolean deferred) { assert (newCapacity > oldCapacity); return BufferUtils.reallocateBuffer(buffer.data, buffer.userSuppliedCapacity, oldCapacity, newCapacity, deferred); } @SuppressWarnings(""unchecked"") T[] requestParticleBuffer (Class klass, T[] buffer) { if (buffer == null) { buffer = (T[])ArrayReflection.newInstance(klass, m_internalAllocatedCapacity); for (int i = 0; i < m_internalAllocatedCapacity; i++) { try { buffer[i] = ClassReflection.newInstance(klass); } catch (Exception e) { throw new RuntimeException(e); } } } return buffer; } float[] requestParticleBuffer (float[] buffer) { if (buffer == null) { buffer = new float[m_internalAllocatedCapacity]; } return buffer; } public static class ParticleBuffer { public T[] data; final Class dataClass; int userSuppliedCapacity; public ParticleBuffer (Class dataClass) { this.dataClass = dataClass; } } static class ParticleBufferInt { int[] data; int userSuppliedCapacity; } public static class Proxy implements Comparable { int index; long tag; @Override public int compareTo (Proxy o) { return (tag - o.tag) < 0 ? -1 : (o.tag == tag ? 0 : 1); } @Override public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Proxy other = (Proxy)obj; if (tag != other.tag) return false; return true; } } public static class Pair { int indexA, indexB; int flags; float strength; float distance; } public static class Triad { int indexA, indexB, indexC; int flags; float strength; final Vec2 pa = new Vec2(), pb = new Vec2(), pc = new Vec2(); float ka, kb, kc, s; } static class CreateParticleGroupCallback implements VoronoiDiagramCallback { public void callback (int a, int b, int c) { final Vec2 pa = system.m_positionBuffer.data[a]; final Vec2 pb = system.m_positionBuffer.data[b]; final Vec2 pc = system.m_positionBuffer.data[c]; final float dabx = pa.x - pb.x; final float daby = pa.y - pb.y; final float dbcx = pb.x - pc.x; final float dbcy = pb.y - pc.y; final float dcax = pc.x - pa.x; final float dcay = pc.y - pa.y; float maxDistanceSquared = Settings.maxTriadDistanceSquared * system.m_squaredDiameter; if (dabx * dabx + daby * daby < maxDistanceSquared && dbcx * dbcx + dbcy * dbcy < maxDistanceSquared && dcax * dcax + dcay * dcay < maxDistanceSquared) { if (system.m_triadCount >= system.m_triadCapacity) { int oldCapacity = system.m_triadCapacity; int newCapacity = system.m_triadCount != 0 ? 2 * system.m_triadCount : Settings.minParticleBufferCapacity; system.m_triadBuffer = BufferUtils.reallocateBuffer(Triad.class, system.m_triadBuffer, oldCapacity, newCapacity); system.m_triadCapacity = newCapacity; } Triad triad = system.m_triadBuffer[system.m_triadCount]; triad.indexA = a; triad.indexB = b; triad.indexC = c; triad.flags = system.m_flagsBuffer.data[a] | system.m_flagsBuffer.data[b] | system.m_flagsBuffer.data[c]; triad.strength = def.strength; final float midPointx = (float)1 / 3 * (pa.x + pb.x + pc.x); final float midPointy = (float)1 / 3 * (pa.y + pb.y + pc.y); triad.pa.x = pa.x - midPointx; triad.pa.y = pa.y - midPointy; triad.pb.x = pb.x - midPointx; triad.pb.y = pb.y - midPointy; triad.pc.x = pc.x - midPointx; triad.pc.y = pc.y - midPointy; triad.ka = -(dcax * dabx + dcay * daby); triad.kb = -(dabx * dbcx + daby * dbcy); triad.kc = -(dbcx * dcax + dbcy * dcay); triad.s = Vec2.cross(pa, pb) + Vec2.cross(pb, pc) + Vec2.cross(pc, pa); system.m_triadCount++; } } ParticleSystem system; ParticleGroupDef def; int firstIndex; } static class JoinParticleGroupsCallback implements VoronoiDiagramCallback { public void callback (int a, int b, int c) { int countA = ((a < groupB.m_firstIndex) ? 1 : 0) + ((b < groupB.m_firstIndex) ? 1 : 0) + ((c < groupB.m_firstIndex) ? 1 : 0); if (countA > 0 && countA < 3) { int af = system.m_flagsBuffer.data[a]; int bf = system.m_flagsBuffer.data[b]; int cf = system.m_flagsBuffer.data[c]; if ((af & bf & cf & k_triadFlags) != 0) { final Vec2 pa = system.m_positionBuffer.data[a]; final Vec2 pb = system.m_positionBuffer.data[b]; final Vec2 pc = system.m_positionBuffer.data[c]; final float dabx = pa.x - pb.x; final float daby = pa.y - pb.y; final float dbcx = pb.x - pc.x; final float dbcy = pb.y - pc.y; final float dcax = pc.x - pa.x; final float dcay = pc.y - pa.y; float maxDistanceSquared = Settings.maxTriadDistanceSquared * system.m_squaredDiameter; if (dabx * dabx + daby * daby < maxDistanceSquared && dbcx * dbcx + dbcy * dbcy < maxDistanceSquared && dcax * dcax + dcay * dcay < maxDistanceSquared) { if (system.m_triadCount >= system.m_triadCapacity) { int oldCapacity = system.m_triadCapacity; int newCapacity = system.m_triadCount != 0 ? 2 * system.m_triadCount : Settings.minParticleBufferCapacity; system.m_triadBuffer = BufferUtils.reallocateBuffer(Triad.class, system.m_triadBuffer, oldCapacity, newCapacity); system.m_triadCapacity = newCapacity; } Triad triad = system.m_triadBuffer[system.m_triadCount]; triad.indexA = a; triad.indexB = b; triad.indexC = c; triad.flags = af | bf | cf; triad.strength = MathUtils.min(groupA.m_strength, groupB.m_strength); final float midPointx = (float)1 / 3 * (pa.x + pb.x + pc.x); final float midPointy = (float)1 / 3 * (pa.y + pb.y + pc.y); triad.pa.x = pa.x - midPointx; triad.pa.y = pa.y - midPointy; triad.pb.x = pb.x - midPointx; triad.pb.y = pb.y - midPointy; triad.pc.x = pc.x - midPointx; triad.pc.y = pc.y - midPointy; triad.ka = -(dcax * dabx + dcay * daby); triad.kb = -(dabx * dbcx + daby * dbcy); triad.kc = -(dbcx * dcax + dbcy * dcay); triad.s = Vec2.cross(pa, pb) + Vec2.cross(pb, pc) + Vec2.cross(pc, pa); system.m_triadCount++; } } } } ParticleSystem system; ParticleGroup groupA; ParticleGroup groupB; }; static class DestroyParticlesInShapeCallback implements ParticleQueryCallback { ParticleSystem system; Shape shape; Transform xf; boolean callDestructionListener; int destroyed; public DestroyParticlesInShapeCallback () { } public void init (ParticleSystem system, Shape shape, Transform xf, boolean callDestructionListener) { this.system = system; this.shape = shape; this.xf = xf; this.destroyed = 0; this.callDestructionListener = callDestructionListener; } @Override public boolean reportParticle (int index) { assert (index >= 0 && index < system.m_count); if (shape.testPoint(xf, system.m_positionBuffer.data[index])) { system.destroyParticle(index, callDestructionListener); destroyed++; } return true; } } static class UpdateBodyContactsCallback implements QueryCallback { ParticleSystem system; private final Vec2 tempVec = new Vec2(); @Override public boolean reportFixture (Fixture fixture) { if (fixture.isSensor()) { return true; } final Shape shape = fixture.getShape(); Body b = fixture.getBody(); Vec2 bp = b.getWorldCenter(); float bm = b.getMass(); float bI = b.getInertia() - bm * b.getLocalCenter().lengthSquared(); float invBm = bm > 0 ? 1 / bm : 0; float invBI = bI > 0 ? 1 / bI : 0; int childCount = shape.getChildCount(); for (int childIndex = 0; childIndex < childCount; childIndex++) { AABB aabb = fixture.getAABB(childIndex); final float aabblowerBoundx = aabb.lowerBound.x - system.m_particleDiameter; final float aabblowerBoundy = aabb.lowerBound.y - system.m_particleDiameter; final float aabbupperBoundx = aabb.upperBound.x + system.m_particleDiameter; final float aabbupperBoundy = aabb.upperBound.y + system.m_particleDiameter; int firstProxy = lowerBound(system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabblowerBoundx, system.m_inverseDiameter * aabblowerBoundy)); int lastProxy = upperBound(system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabbupperBoundx, system.m_inverseDiameter * aabbupperBoundy)); for (int proxy = firstProxy; proxy != lastProxy; ++proxy) { int a = system.m_proxyBuffer[proxy].index; Vec2 ap = system.m_positionBuffer.data[a]; if (aabblowerBoundx <= ap.x && ap.x <= aabbupperBoundx && aabblowerBoundy <= ap.y && ap.y <= aabbupperBoundy) { float d; final Vec2 n = tempVec; d = fixture.computeDistance(ap, childIndex, n); if (d < system.m_particleDiameter) { float invAm = (system.m_flagsBuffer.data[a] & ParticleType.b2_wallParticle) != 0 ? 0 : system.getParticleInvMass(); final float rpx = ap.x - bp.x; final float rpy = ap.y - bp.y; float rpn = rpx * n.y - rpy * n.x; if (system.m_bodyContactCount >= system.m_bodyContactCapacity) { int oldCapacity = system.m_bodyContactCapacity; int newCapacity = system.m_bodyContactCount != 0 ? 2 * system.m_bodyContactCount : Settings.minParticleBufferCapacity; system.m_bodyContactBuffer = BufferUtils.reallocateBuffer(ParticleBodyContact.class, system.m_bodyContactBuffer, oldCapacity, newCapacity); system.m_bodyContactCapacity = newCapacity; } ParticleBodyContact contact = system.m_bodyContactBuffer[system.m_bodyContactCount]; contact.index = a; contact.body = b; contact.weight = 1 - d * system.m_inverseDiameter; contact.normal.x = -n.x; contact.normal.y = -n.y; contact.mass = 1 / (invAm + invBm + invBI * rpn * rpn); system.m_bodyContactCount++; } } } } return true; } } static class SolveCollisionCallback implements QueryCallback { ParticleSystem system; TimeStep step; private final RayCastInput input = new RayCastInput(); private final RayCastOutput output = new RayCastOutput(); private final Vec2 tempVec = new Vec2(); private final Vec2 tempVec2 = new Vec2(); @Override public boolean reportFixture (Fixture fixture) { if (fixture.isSensor()) { return true; } final Shape shape = fixture.getShape(); Body body = fixture.getBody(); int childCount = shape.getChildCount(); for (int childIndex = 0; childIndex < childCount; childIndex++) { AABB aabb = fixture.getAABB(childIndex); final float aabblowerBoundx = aabb.lowerBound.x - system.m_particleDiameter; final float aabblowerBoundy = aabb.lowerBound.y - system.m_particleDiameter; final float aabbupperBoundx = aabb.upperBound.x + system.m_particleDiameter; final float aabbupperBoundy = aabb.upperBound.y + system.m_particleDiameter; int firstProxy = lowerBound(system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabblowerBoundx, system.m_inverseDiameter * aabblowerBoundy)); int lastProxy = upperBound(system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabbupperBoundx, system.m_inverseDiameter * aabbupperBoundy)); for (int proxy = firstProxy; proxy != lastProxy; ++proxy) { int a = system.m_proxyBuffer[proxy].index; Vec2 ap = system.m_positionBuffer.data[a]; if (aabblowerBoundx <= ap.x && ap.x <= aabbupperBoundx && aabblowerBoundy <= ap.y && ap.y <= aabbupperBoundy) { Vec2 av = system.m_velocityBuffer.data[a]; final Vec2 temp = tempVec; Transform.mulTransToOutUnsafe(body.m_xf0, ap, temp); Transform.mulToOutUnsafe(body.m_xf, temp, input.p1); input.p2.x = ap.x + step.dt * av.x; input.p2.y = ap.y + step.dt * av.y; input.maxFraction = 1; if (fixture.raycast(output, input, childIndex)) { final Vec2 p = tempVec; p.x = (1 - output.fraction) * input.p1.x + output.fraction * input.p2.x + Settings.linearSlop * output.normal.x; p.y = (1 - output.fraction) * input.p1.y + output.fraction * input.p2.y + Settings.linearSlop * output.normal.y; final float vx = step.inv_dt * (p.x - ap.x); final float vy = step.inv_dt * (p.y - ap.y); av.x = vx; av.y = vy; final float particleMass = system.getParticleMass(); final float ax = particleMass * (av.x - vx); final float ay = particleMass * (av.y - vy); Vec2 b = output.normal; final float fdn = ax * b.x + ay * b.y; final Vec2 f = tempVec2; f.x = fdn * b.x; f.y = fdn * b.y; body.applyLinearImpulse(f, p, true); } } } } return true; } } static class Test { static boolean IsProxyInvalid (final Proxy proxy) { return proxy.index < 0; } static boolean IsContactInvalid (final ParticleContact contact) { return contact.indexA < 0 || contact.indexB < 0; } static boolean IsBodyContactInvalid (final ParticleBodyContact contact) { return contact.index < 0; } static boolean IsPairInvalid (final Pair pair) { return pair.indexA < 0 || pair.indexB < 0; } static boolean IsTriadInvalid (final Triad triad) { return triad.indexA < 0 || triad.indexB < 0 || triad.indexC < 0; } }; }",stride,java,libgdx "package com.badlogic.gdx.tests.bullet; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.collision.*; public class PairCacheTest extends BaseBulletTest { final static float BOX_X_MIN = -25; final static float BOX_Y_MIN = -25; final static float BOX_Z_MIN = -25; final static float BOX_X_MAX = 25; final static float BOX_Y_MAX = 25; final static float BOX_Z_MAX = 25; final static float SPEED_X = 360f / 7f; final static float SPEED_Y = 360f / 19f; final static float SPEED_Z = 360f / 13f; final static int BOXCOUNT = 100; private boolean useFrustumCam = false; private btPairCachingGhostObject ghostObject; private BulletEntity ghostEntity; private btPersistentManifoldArray manifoldArray; private float angleX, angleY, angleZ; private ShapeRenderer shapeRenderer; private PerspectiveCamera frustumCam; private PerspectiveCamera [MASK]; @Override public void create () { super.create(); instructions = ""Tap to toggle view\nLong press to toggle debug mode\nSwipe for next test\nCtrl+drag to rotate\nScroll to zoom""; world.addConstructor(""collisionBox"", new BulletConstructor(world.getConstructor(""box"").model)); final float dX = BOX_X_MAX - BOX_X_MIN; final float dY = BOX_Y_MAX - BOX_Y_MIN; final float dZ = BOX_Z_MAX - BOX_Z_MIN; for (int i = 0; i < BOXCOUNT; i++) world.add(""collisionBox"", BOX_X_MIN + dX * (float)Math.random(), BOX_Y_MIN + dY * (float)Math.random(), BOX_Z_MIN + dZ * (float)Math.random()).setColor(0.25f + 0.5f * (float)Math.random(), 0.25f + 0.5f * (float)Math.random(), 0.25f + 0.5f * (float)Math.random(), 1f); manifoldArray = new btPersistentManifoldArray(); disposables.add(manifoldArray); [MASK] = camera; [MASK].position.set(BOX_X_MAX, BOX_Y_MAX, BOX_Z_MAX); [MASK].lookAt(Vector3.Zero); [MASK].far = 150f; [MASK].update(); frustumCam = new PerspectiveCamera(camera.fieldOfView, camera.viewportWidth, camera.viewportHeight); frustumCam.far = Vector3.len(BOX_X_MAX, BOX_Y_MAX, BOX_Z_MAX); frustumCam.update(); final Model ghostModel = FrustumCullingTest.createFrustumModel(frustumCam.frustum.planePoints); disposables.add(ghostModel); ghostObject = FrustumCullingTest.createFrustumObject(frustumCam.frustum.planePoints); disposables.add(ghostObject); world.add(ghostEntity = new BulletEntity(ghostModel, ghostObject, 0, 0, 0)); disposables.add(ghostEntity); shapeRenderer = new ShapeRenderer(); disposables.add(shapeRenderer); } @Override public BulletWorld createWorld () { btDbvtBroadphase broadphase = new btDbvtBroadphase(); btDefaultCollisionConfiguration collisionConfig = new btDefaultCollisionConfiguration(); btCollisionDispatcher dispatcher = new btCollisionDispatcher(collisionConfig); btCollisionWorld collisionWorld = new btCollisionWorld(dispatcher, broadphase, collisionConfig); return new BulletWorld(collisionConfig, dispatcher, broadphase, null, collisionWorld); } @Override public void render () { final float dt = Gdx.graphics.getDeltaTime(); ghostEntity.transform.idt(); ghostEntity.transform.rotate(Vector3.X, angleX = (angleX + dt * SPEED_X) % 360); ghostEntity.transform.rotate(Vector3.Y, angleY = (angleY + dt * SPEED_Y) % 360); ghostEntity.transform.rotate(Vector3.Z, angleZ = (angleZ + dt * SPEED_Z) % 360); ghostEntity.body.setWorldTransform(ghostEntity.transform); frustumCam.direction.set(0, 0, -1); frustumCam.up.set(0, 1, 0); frustumCam.position.set(0, 0, 0); frustumCam.rotate(ghostEntity.transform); frustumCam.update(); super.render(); shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Line); shapeRenderer.setColor(Color.WHITE); btBroadphasePairArray arr = world.broadphase.getOverlappingPairCache().getOverlappingPairArray(); int numPairs = arr.size(); for (int i = 0; i < numPairs; ++i) { manifoldArray.clear(); btBroadphasePair pair = arr.at(i); btBroadphaseProxy proxy0 = btBroadphaseProxy.obtain(pair.getPProxy0().getCPointer(), false); btBroadphaseProxy proxy1 = btBroadphaseProxy.obtain(pair.getPProxy1().getCPointer(), false); btBroadphasePair collisionPair = world.collisionWorld.getPairCache().findPair(proxy0, proxy1); if (collisionPair == null) continue; btCollisionAlgorithm algorithm = collisionPair.getAlgorithm(); if (algorithm != null) algorithm.getAllContactManifolds(manifoldArray); for (int j = 0; j < manifoldArray.size(); j++) { btPersistentManifold manifold = manifoldArray.atConst(j); boolean isFirstBody = manifold.getBody0() == ghostObject; int otherObjectIndex = isFirstBody ? manifold.getBody1().getUserValue() : manifold.getBody0().getUserValue(); Color otherObjectColor = world.entities.get(otherObjectIndex).getColor(); for (int p = 0; p < manifold.getNumContacts(); ++p) { btManifoldPoint pt = manifold.getContactPoint(p); if (pt.getDistance() < 0.f) { if (isFirstBody) { pt.getPositionWorldOnA(tmpV2); pt.getPositionWorldOnB(tmpV1); } else { pt.getPositionWorldOnA(tmpV1); pt.getPositionWorldOnB(tmpV2); } shapeRenderer.line(tmpV1.x, tmpV1.y, tmpV1.z, tmpV2.x, tmpV2.y, tmpV2.z, otherObjectColor, Color.WHITE); } } } btBroadphaseProxy.free(proxy0); btBroadphaseProxy.free(proxy1); } shapeRenderer.end(); } @Override public boolean tap (float x, float y, int count, int button) { useFrustumCam = !useFrustumCam; if (useFrustumCam) camera = frustumCam; else camera = [MASK]; return true; } @Override public void update () { super.update(); world.collisionWorld.performDiscreteCollisionDetection(); } }",overviewCam,java,libgdx "package com.alibaba.json.bvt.bug; import java.util.concurrent.TimeUnit; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; public class Bug_for_leupom_2 extends TestCase { public void test_0() throws Exception { Time time = new Time(1000, TimeUnit.MILLISECONDS); String text = JSON.toJSONString(time); System.out.println(text); Time time2 = JSON.parseObject(text, Time.class); Assert.assertEquals(time2.getValue(), time.getValue()); Assert.assertEquals(time2.getUnit(), time.getUnit()); } public static class Time { private long value; private TimeUnit [MASK]; public Time(){ super(); } public Time(long value, TimeUnit [MASK]){ super(); this.value = value; this.[MASK] = [MASK]; } public long getValue() { return value; } @JSONField(serialzeFeatures={SerializerFeature.WriteEnumUsingToString}) public TimeUnit getUnit() { return [MASK]; } public void setValue(long value) { this.value = value; } public void setUnit(TimeUnit [MASK]) { this.[MASK] = [MASK]; } } }",unit,java,fastjson "package com.google.zxing.client.android.result.supplement; import android.content.Context; import android.widget.TextView; import com.google.zxing.client.android.HttpHelper; import com.google.zxing.client.android.history.HistoryManager; import com.google.zxing.client.android.R; import com.google.zxing.client.result.URIParsedResult; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; final class URIResultInfoRetriever extends SupplementalInfoRetriever { private static final int MAX_REDIRECTS = 5; private final URIParsedResult result; private final String [MASK]; URIResultInfoRetriever(TextView textView, URIParsedResult result, HistoryManager historyManager, Context context) { super(textView, historyManager); [MASK] = context.getString(R.string.msg_redirect); this.result = result; } @Override void retrieveSupplementalInfo() throws IOException { URI oldURI; try { oldURI = new URI(result.getURI()); } catch (URISyntaxException ignored) { return; } URI newURI = HttpHelper.unredirect(oldURI); int count = 0; while (count++ < MAX_REDIRECTS && !oldURI.equals(newURI)) { append(result.getDisplayResult(), null, new String[] { [MASK] + "" : "" + newURI }, newURI.toString()); oldURI = newURI; newURI = HttpHelper.unredirect(newURI); } } }",redirectString,java,zxing "package com.alibaba.json.bvt.issue_1500; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; public class Issue1555 extends TestCase { public void test_for_issue() throws Exception { Model model = new Model(); model.userId = 1001; model.userName = ""test""; String text = JSON.toJSONString(model); assertEquals(""{\""userName\"":\""test\"",\""user_id\"":1001}"", text); Model [MASK] = JSON.parseObject(text, Model.class); assertEquals(1001, [MASK].userId); assertEquals(""test"", [MASK].userName); } public void test_when_JSONField_have_not_name_attr() throws Exception { ModelTwo modelTwo = new ModelTwo(); modelTwo.userId = 1001; modelTwo.userName = ""test""; String text = JSON.toJSONString(modelTwo); assertEquals(""{\""userName\"":\""test\"",\""user_id\"":\""1001\""}"", text); Model [MASK] = JSON.parseObject(text, Model.class); assertEquals(1001, [MASK].userId); assertEquals(""test"", [MASK].userName); } @JSONType(naming = PropertyNamingStrategy.SnakeCase) public static class Model { private int userId; @JSONField(name = ""userName"") private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } @JSONType(naming = PropertyNamingStrategy.SnakeCase) public static class ModelTwo { @JSONField(serializeUsing = StringSerializer.class) private int userId; @JSONField(name = ""userName"") private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } }",model2,java,fastjson "package com.google.zxing.datamatrix.encoder; import org.junit.Assert; import org.junit.Test; public final class ErrorCorrectionTestCase extends Assert { @Test public void testRS() { char[] cw = {142, 164, 186}; SymbolInfo [MASK] = SymbolInfo.lookup(3); CharSequence s = ErrorCorrection.encodeECC200(String.valueOf(cw), [MASK]); assertEquals(""142 164 186 114 25 5 88 102"", HighLevelEncodeTestCase.visualize(s)); cw = new char[]{66, 129, 70}; s = ErrorCorrection.encodeECC200(String.valueOf(cw), [MASK]); assertEquals(""66 129 70 138 234 82 82 95"", HighLevelEncodeTestCase.visualize(s)); } }",symbolInfo,java,zxing "package org.apache.dubbo.remoting.exchange.codec; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; public class ExchangeCodec extends TelnetCodec { protected static final int HEADER_LENGTH = 16; protected static final short MAGIC = (short) 0xdabb; protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; protected static final byte FLAG_REQUEST = (byte) 0x80; protected static final byte FLAG_TWOWAY = (byte) 0x40; protected static final byte FLAG_EVENT = (byte) 0x20; protected static final int SERIALIZATION_MASK = 0x1f; private static final Logger logger = LoggerFactory.getLogger(ExchangeCodec.class); public Short getMagicCode() { return MAGIC; } @Override public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException { if (msg instanceof Request) { encodeRequest(channel, buffer, (Request) msg); } else if (msg instanceof Response) { encodeResponse(channel, buffer, (Response) msg); } else { super.encode(channel, buffer, msg); } } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int readable = buffer.readableBytes(); byte[] header = new byte[Math.min(readable, HEADER_LENGTH)]; buffer.readBytes(header); return decode(channel, buffer, readable, header); } @Override protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); buffer.readBytes(header, length, readable - length); } for (int i = 1; i < header.length - 1; i++) { if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { buffer.readerIndex(buffer.readerIndex() - header.length + i); header = Bytes.copyOf(header, i); break; } } return super.decode(channel, buffer, readable, header); } if (readable < HEADER_LENGTH) { return DecodeResult.NEED_MORE_INPUT; } int len = Bytes.bytes2int(header, 12); Object obj = finishRespWhenOverPayload(channel, len, header); if (null != obj) { return obj; } checkPayload(channel, len); int tt = len + HEADER_LENGTH; if (readable < tt) { return DecodeResult.NEED_MORE_INPUT; } ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, len); try { return decodeBody(channel, is, header); } finally { if (is.available() > 0) { try { if (logger.isWarnEnabled()) { logger.warn(""Skip input stream "" + is.available()); } StreamUtils.skipUnusedStream(is); } catch (IOException e) { logger.warn(e.getMessage(), e); } } } } protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } byte status = header[3]; res.setStatus(status); try { if (status == Response.OK) { Object data; if (res.isEvent()) { byte[] [MASK] = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat([MASK], proto)) { data = null; } else { data = decodeEventData(channel, CodecSupport.deserialize(channel.getUrl(), new ByteArrayInputStream([MASK]), proto), [MASK]); } } else { data = decodeResponseData(channel, CodecSupport.deserialize(channel.getUrl(), is, proto), getRequestData(channel, res, id)); } res.setResult(data); } else { res.setErrorMessage(CodecSupport.deserialize(channel.getUrl(), is, proto).readUTF()); } } catch (Throwable t) { res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { Request req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); if ((flag & FLAG_EVENT) != 0) { req.setEvent(true); } try { Object data; if (req.isEvent()) { byte[] [MASK] = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat([MASK], proto)) { data = null; } else { data = decodeEventData(channel, CodecSupport.deserialize(channel.getUrl(), new ByteArrayInputStream([MASK]), proto), [MASK]); } } else { data = decodeRequestData(channel, CodecSupport.deserialize(channel.getUrl(), is, proto)); } req.setData(data); } catch (Throwable t) { req.setBroken(true); req.setData(t); } return req; } } protected Object getRequestData(Channel channel, Response response, long id) { DefaultFuture future = DefaultFuture.getFuture(id); if (future != null) { Request req = future.getRequest(); if (req != null) { return req.getData(); } } logger.warn(""The timeout response finally returned at "" + (new SimpleDateFormat(""yyyy-MM-dd HH:mm:ss.SSS"").format(new Date())) + "", response status is "" + response.getStatus() + "", response id is "" + response.getId() + (channel == null ? """" : "", channel: "" + channel.getLocalAddress() + "" -> "" + channel.getRemoteAddress()) + "", please check provider side for detailed result.""); throw new IllegalArgumentException(""Failed to find any request match the response, response id: "" + id); } protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException { Serialization serialization = getSerialization(channel, req); byte[] header = new byte[HEADER_LENGTH]; Bytes.short2bytes(MAGIC, header); header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); if (req.isTwoWay()) { header[2] |= FLAG_TWOWAY; } if (req.isEvent()) { header[2] |= FLAG_EVENT; } Bytes.long2bytes(req.getId(), header, 4); int savedWriteIndex = buffer.writerIndex(); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); if (req.isHeartbeat()) { bos.write(CodecSupport.getNullBytesOf(serialization)); } else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (req.isEvent()) { encodeEventData(channel, out, req.getData()); } else { encodeRequestData(channel, out, req.getData(), req.getVersion()); } out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); } } bos.flush(); bos.close(); int len = bos.writtenBytes(); checkPayload(channel, len); Bytes.int2bytes(len, header, 12); buffer.writerIndex(savedWriteIndex); buffer.writeBytes(header); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException { int savedWriteIndex = buffer.writerIndex(); try { Serialization serialization = getSerialization(channel, res); byte[] header = new byte[HEADER_LENGTH]; Bytes.short2bytes(MAGIC, header); header[2] = serialization.getContentTypeId(); if (res.isHeartbeat()) { header[2] |= FLAG_EVENT; } byte status = res.getStatus(); header[3] = status; Bytes.long2bytes(res.getId(), header, 4); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); if (status == Response.OK) { if(res.isHeartbeat()){ bos.write(CodecSupport.getNullBytesOf(serialization)); }else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (res.isEvent()) { encodeEventData(channel, out, res.getResult()); } else { encodeResponseData(channel, out, res.getResult(), res.getVersion()); } out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); } } } else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); out.writeUTF(res.getErrorMessage()); out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); } } bos.flush(); bos.close(); int len = bos.writtenBytes(); checkPayload(channel, len); Bytes.int2bytes(len, header, 12); buffer.writerIndex(savedWriteIndex); buffer.writeBytes(header); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } catch (Throwable t) { buffer.writerIndex(savedWriteIndex); if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { Response r = new Response(res.getId(), res.getVersion()); r.setStatus(Response.SERIALIZATION_ERROR); if (t instanceof ExceedPayloadLimitException) { logger.warn(t.getMessage(), t); try { r.setErrorMessage(t.getMessage()); channel.send(r); return; } catch (RemotingException e) { logger.warn(""Failed to send bad_response info back: "" + t.getMessage() + "", cause: "" + e.getMessage(), e); } } else { logger.warn(""Fail to encode response: "" + res + "", send bad_response info instead, cause: "" + t.getMessage(), t); try { r.setErrorMessage(""Failed to send response: "" + res + "", cause: "" + StringUtils.toString(t)); channel.send(r); return; } catch (RemotingException e) { logger.warn(""Failed to send bad_response info back: "" + res + "", cause: "" + e.getMessage(), e); } } } if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t.getMessage(), t); } } } @Override protected Object decodeData(ObjectInput in) throws IOException { return decodeRequestData(in); } protected Object decodeRequestData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString(""Read object failed."", e)); } } protected Object decodeResponseData(ObjectInput in) throws IOException { try { return in.readObject(); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString(""Read object failed."", e)); } } @Override protected void encodeData(ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } private void encodeEventData(ObjectOutput out, Object data) throws IOException { out.writeEvent(data); } @Deprecated protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } protected void encodeRequestData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } protected void encodeResponseData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } @Override protected Object decodeData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(channel, in); } protected Object decodeEventData(Channel channel, ObjectInput in, byte[] eventBytes) throws IOException { try { if (eventBytes != null) { int dataLen = eventBytes.length; int threshold = ConfigurationUtils.getSystemConfiguration().getInt(""deserialization.event.size"", 15); if (dataLen > threshold) { throw new IllegalArgumentException(""Event data too long, actual size "" + dataLen + "", threshold "" + threshold + "" rejected for security consideration.""); } } return in.readEvent(); } catch (IOException | ClassNotFoundException e) { throw new IOException(StringUtils.toString(""Decode dubbo protocol event failed."", e)); } } protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(in); } protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException { return decodeResponseData(in); } protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { return decodeResponseData(channel, in); } @Override protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data); } private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } @Deprecated protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeHeartbeatData(out, data); } protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeResponseData(out, data); } protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { encodeRequestData(out, data); } protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { encodeResponseData(out, data); } private Object finishRespWhenOverPayload(Channel channel, long size, byte[] header) { int payload = getPayload(channel); boolean overPayload = isOverPayload(payload, size); if (overPayload) { long reqId = Bytes.bytes2long(header, 4); byte flag = header[2]; if ((flag & FLAG_REQUEST) == 0) { Response res = new Response(reqId); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } res.setStatus(Response.CLIENT_ERROR); String errorMsg = ""Data length too large: "" + size + "", max payload: "" + payload + "", channel: "" + channel; logger.error(errorMsg); res.setErrorMessage(errorMsg); return res; } } return null; } }",eventPayload,java,incubator-dubbo "package jadx.core.dex.attributes; import java.util.Collections; import java.util.List; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; public final class EmptyAttrStorage extends AttributeStorage { public static final AttributeStorage INSTANCE = new EmptyAttrStorage(); private EmptyAttrStorage() { } @Override public boolean contains(AFlag flag) { return false; } @Override public boolean contains(IJadxAttrType type) { return false; } @Override public T get(IJadxAttrType type) { return null; } @Override public IAnnotation getAnnotation(String [MASK]) { return null; } @Override public List getAll(IJadxAttrType> type) { return Collections.emptyList(); } @Override public void remove(AFlag flag) { } @Override public void remove(IJadxAttrType type) { } @Override public void remove(IJadxAttribute attr) { } @Override public List getAttributeStrings() { return Collections.emptyList(); } @Override public boolean isEmpty() { return true; } @Override public String toString() { return """"; } }",cls,java,jadx "package jadx.gui.settings.ui.cache; import java.util.Collections; import java.util.List; import javax.swing.table.AbstractTableModel; import jadx.gui.utils.NLS; public class CachesTableModel extends AbstractTableModel { private static final long serialVersionUID = -7725573085995496397L; private static final String[] COLUMN_NAMES = { NLS.str(""preferences.cache.table.project""), NLS.str(""preferences.cache.table.size"") }; private transient List rows = Collections.emptyList(); public void setRows(List list) { this.rows = list; } public List getRows() { return rows; } @Override public int getRowCount() { return rows.size(); } @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int index) { return COLUMN_NAMES[index]; } @Override public Class getColumnClass(int columnIndex) { return TableRow.class; } @Override public TableRow getValueAt(int [MASK], int columnIndex) { return rows.get([MASK]); } public void changeSelection(int idx) { TableRow row = rows.get(idx); row.setSelected(!row.isSelected()); } }",rowIndex,java,jadx "package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.junit.Assert; import java.util.LinkedHashMap; import java.util.Map; public class JSONFieldTest_unwrapped_4 extends TestCase { public void test_jsonField() throws Exception { Health vo = new Health(); vo.id = 123; vo.border = 234; vo.details.put(""latitude"", 37); vo.details.put(""longitude"", 127); String [MASK] = JSON.toJSONString(vo); Assert.assertEquals(""{\""border\"":234,\""latitude\"":37,\""longitude\"":127,\""id\"":123}"", [MASK]); Health vo2 = JSON.parseObject([MASK], Health.class); assertNotNull(vo2.details); assertEquals(37, vo2.details.get(""latitude"")); assertEquals(127, vo2.details.get(""longitude"")); } public void test_null() throws Exception { Health vo = new Health(); vo.id = 123; vo.border = 234; vo.details = null; String [MASK] = JSON.toJSONString(vo); Assert.assertEquals(""{\""border\"":234,\""id\"":123}"", [MASK]); } public void test_empty() throws Exception { Health vo = new Health(); vo.id = 123; vo.border = 234; String [MASK] = JSON.toJSONString(vo); Assert.assertEquals(""{\""border\"":234,\""id\"":123}"", [MASK]); } public static class Health { public int id; public int border; @JSONField(unwrapped = true) public Map details = new LinkedHashMap(); } }",text,java,fastjson "package io.netty5.handler.codec.http2; import io.netty5.buffer.Buffer; import io.netty5.channel.ChannelHandlerContext; import io.netty5.util.internal.UnstableApi; import java.io.Closeable; @UnstableApi public interface Http2ConnectionDecoder extends Closeable { void [MASK](Http2LifecycleManager [MASK]); Http2Connection connection(); Http2LocalFlowController flowController(); void frameListener(Http2FrameListener listener); Http2FrameListener frameListener(); void decodeFrame(ChannelHandlerContext ctx, Buffer in) throws Http2Exception; Http2Settings localSettings(); boolean prefaceReceived(); @Override void close(); }",lifecycleManager,java,netty "package com.alibaba.json.bvt.parser.deser.generic; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; public class GenericArrayTest4 extends TestCase { public void test_generic() throws Exception { VO vo = new VO(); vo.[MASK] = new Pair[] {null, null}; String text = JSON.toJSONString(vo); VO vo1 = JSON.parseObject(text, VO.class); Assert.assertNotNull(vo1.[MASK]); Assert.assertEquals(2, vo1.[MASK].length); } public static class A { public Pair[] [MASK]; } public static class VO extends A { } public static class Pair { public A a; public B b; } }",values,java,fastjson "package com.alibaba.json.bvt.[MASK]; import java.io.StringWriter; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.[MASK].JSONSerializer; import com.alibaba.fastjson.[MASK].SerializeWriter; import com.alibaba.fastjson.[MASK].SerializerFeature; public class StringSerializerTest extends TestCase { public void test_0() throws Exception { Assert.assertEquals(""{\""value\"":null}"", JSON.toJSONString( new TestEntity(null), SerializerFeature.WriteMapNullValue)); SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, (Object) ""123""); Assert.assertEquals(""\""123\"""", out.toString()); JSONSerializer.write(out, (Object) ""456""); Assert.assertEquals(""\""123\""\""456\"""", out.toString()); } public void test_2() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, new TestEntity(null)); Assert.assertEquals(""{}"", out.toString()); } public void test_2_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, new TestEntity(null)); Assert.assertEquals(""{}"", out.toString()); } public void test_3() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer [MASK] = new JSONSerializer(out); [MASK].config(SerializerFeature.UseSingleQuotes, true); [MASK].write(new TestEntity(""张三"")); Assert.assertEquals(""{'value':'张三'}"", out.toString()); } public void test_4() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, new TestEntity(""张三"")); Assert.assertEquals(""{\""value\"":\""张三\""}"", out.toString()); } public void test_5() throws Exception { SerializeWriter out = new SerializeWriter(); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString((String) null); Assert.assertEquals(""null"", out.toString()); } public void test_5_d() throws Exception { SerializeWriter out = new SerializeWriter(); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString((String) null); Assert.assertEquals(""null"", out.toString()); } public void test_6() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString((String) null); Assert.assertEquals(""null"", out.toString()); } public void test_6_d() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString((String) null); Assert.assertEquals(""null"", out.toString()); } public void test_7() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString(""中国""); Assert.assertEquals(""'中国'"", out.toString()); } public void test_7_d() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.UseSingleQuotes, false); out.writeString(""中国""); Assert.assertEquals(""\""中国\"""", out.toString()); } public void test_8() throws Exception { SerializeWriter out = new SerializeWriter(); out = new SerializeWriter(); out.config(SerializerFeature.UseSingleQuotes, false); out.writeString(""\na\nb\nc\nd\""'""); Assert.assertEquals(""\""\\na\\nb\\nc\\nd\\\""'\"""", out.toString()); } public void test_8_s() throws Exception { SerializeWriter out = new SerializeWriter(); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString(""\na\nb\nc\nd\""'""); Assert.assertEquals(""'\\na\\nb\\nc\\nd\""\\''"", out.toString()); } public void test_9() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName(""\na\nb\nc\nd\""'e""); Assert.assertEquals(""'\\na\\nb\\nc\\nd\""\\'e':"", out.toString()); } public void test_9_d() throws Exception { SerializeWriter out = new SerializeWriter(1); out.writeFieldName(""\na\nb\nc\nd\""'e""); Assert.assertEquals(""\""\\na\\nb\\nc\\nd\\\""'e\"":"", out.toString()); } public void test_10() throws Exception { SerializeWriter out = new SerializeWriter(); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName(""123\na\nb\nc\nd\""'e""); Assert.assertEquals(""'123\\na\\nb\\nc\\nd\""\\'e':"", out.toString()); } public void test_10_d() throws Exception { SerializeWriter out = new SerializeWriter(); out.writeFieldName(""123\na\nb\nc\nd\""'e"", true); Assert.assertEquals(""\""123\\na\\nb\\nc\\nd\\\""'e\"":"", out.toString()); } public void test_11() throws Exception { SerializeWriter out = new SerializeWriter(); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName(""123\na\nb\nc\nd\""'e""); Assert.assertEquals(""'123\\na\\nb\\nc\\nd\""\\'e':"", out.toString()); } public void test_11_d() throws Exception { SerializeWriter out = new SerializeWriter(); out.writeString(""123\na\nb\nc\nd\""'e"", ':'); Assert.assertEquals(""\""123\\na\\nb\\nc\\nd\\\""'e\"":"", out.toString()); } public void test_12() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName(""123\na\nb\nc\nd\""'e""); Assert.assertEquals(""'123\\na\\nb\\nc\\nd\""\\'e':"", out.toString()); } public void test_12_d() throws Exception { SerializeWriter out = new SerializeWriter(1); out.writeString(""123\na\nb\nc\nd\""'e"", ':'); Assert.assertEquals(""\""123\\na\\nb\\nc\\nd\\\""'e\"":"", out.toString()); } public void test_13() throws Exception { SerializeWriter out = new SerializeWriter(4); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString(""1'""); Assert.assertEquals(""'1\\''"", out.toString()); } public void test_14() throws Exception { SerializeWriter out = new SerializeWriter(4); out.config(SerializerFeature.UseSingleQuotes, false); out.writeString(""1\""""); Assert.assertEquals(""\""1\\\""\"""", out.toString()); } public static class TestEntity { private String value; public TestEntity(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }",serializer,java,fastjson "package io.netty5.handler.ipfilter; import io.netty5.channel.Channel; import io.netty5.channel.ChannelHandlerContext; import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import static java.util.Objects.requireNonNull; public class IpSubnetFilter extends AbstractRemoteAddressFilter { private final boolean acceptIfNotFound; private final IpSubnetFilterRule[] ipv4Rules; private final IpSubnetFilterRule[] ipv6Rules; private final IpFilterRuleType ipFilterRuleTypeIPv4; private final IpFilterRuleType ipFilterRuleTypeIPv6; public IpSubnetFilter(IpSubnetFilterRule... rules) { this(true, Arrays.asList(requireNonNull(rules, ""rules""))); } public IpSubnetFilter(boolean acceptIfNotFound, IpSubnetFilterRule... rules) { this(acceptIfNotFound, Arrays.asList(requireNonNull(rules, ""rules""))); } public IpSubnetFilter(List rules) { this(true, rules); } public IpSubnetFilter(boolean acceptIfNotFound, List rules) { requireNonNull(rules, ""rules""); this.acceptIfNotFound = acceptIfNotFound; int numAcceptIPv4 = 0; int numRejectIPv4 = 0; int numAcceptIPv6 = 0; int numRejectIPv6 = 0; List unsortedIPv4Rules = new ArrayList<>(); List unsortedIPv6Rules = new ArrayList<>(); for (IpSubnetFilterRule ipSubnetFilterRule : rules) { requireNonNull(ipSubnetFilterRule, ""rule""); if (ipSubnetFilterRule.getFilterRule() instanceof IpSubnetFilterRule.Ip4SubnetFilterRule) { unsortedIPv4Rules.add(ipSubnetFilterRule); if (ipSubnetFilterRule.ruleType() == IpFilterRuleType.ACCEPT) { numAcceptIPv4++; } else { numRejectIPv4++; } } else { unsortedIPv6Rules.add(ipSubnetFilterRule); if (ipSubnetFilterRule.ruleType() == IpFilterRuleType.ACCEPT) { numAcceptIPv6++; } else { numRejectIPv6++; } } } if (numAcceptIPv4 == 0 && numRejectIPv4 > 0) { ipFilterRuleTypeIPv4 = IpFilterRuleType.REJECT; } else if (numAcceptIPv4 > 0 && numRejectIPv4 == 0) { ipFilterRuleTypeIPv4 = IpFilterRuleType.ACCEPT; } else { ipFilterRuleTypeIPv4 = null; } if (numAcceptIPv6 == 0 && numRejectIPv6 > 0) { ipFilterRuleTypeIPv6 = IpFilterRuleType.REJECT; } else if (numAcceptIPv6 > 0 && numRejectIPv6 == 0) { ipFilterRuleTypeIPv6 = IpFilterRuleType.ACCEPT; } else { ipFilterRuleTypeIPv6 = null; } this.ipv4Rules = unsortedIPv4Rules.isEmpty() ? null : sortAndFilter(unsortedIPv4Rules); this.ipv6Rules = unsortedIPv6Rules.isEmpty() ? null : sortAndFilter(unsortedIPv6Rules); } @Override public boolean isSharable() { return true; } @Override protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) { if (ipv4Rules != null && remoteAddress.getAddress() instanceof Inet4Address) { int indexOf = Arrays.binarySearch(ipv4Rules, remoteAddress, IpSubnetFilterRuleComparator.INSTANCE); if (indexOf >= 0) { if (ipFilterRuleTypeIPv4 == null) { return ipv4Rules[indexOf].ruleType() == IpFilterRuleType.ACCEPT; } else { return ipFilterRuleTypeIPv4 == IpFilterRuleType.ACCEPT; } } } else if (ipv6Rules != null) { int indexOf = Arrays.binarySearch(ipv6Rules, remoteAddress, IpSubnetFilterRuleComparator.INSTANCE); if (indexOf >= 0) { if (ipFilterRuleTypeIPv6 == null) { return ipv6Rules[indexOf].ruleType() == IpFilterRuleType.ACCEPT; } else { return ipFilterRuleTypeIPv6 == IpFilterRuleType.ACCEPT; } } } return acceptIfNotFound; } @SuppressWarnings(""ZeroLengthArrayAllocation"") private static IpSubnetFilterRule[] sortAndFilter(List rules) { Collections.sort(rules); Iterator iterator = rules.iterator(); List [MASK] = new ArrayList<>(); IpSubnetFilterRule parentRule = iterator.hasNext() ? iterator.next() : null; if (parentRule != null) { [MASK].add(parentRule); } while (iterator.hasNext()) { IpSubnetFilterRule childRule = iterator.next(); if (!parentRule.matches(new InetSocketAddress(childRule.getIpAddress(), 1))) { [MASK].add(childRule); parentRule = childRule; } } return [MASK].toArray(new IpSubnetFilterRule[0]); } }",toKeep,java,netty "package com.badlogic.gdx.physics.bullet.dynamics; public class SWIGTYPE_p_btAlignedObjectArrayT_btTypedConstraint_p_t { private transient long swigCPtr; protected SWIGTYPE_p_btAlignedObjectArrayT_btTypedConstraint_p_t (long cPtr, @SuppressWarnings(""unused"") boolean [MASK]) { swigCPtr = cPtr; } protected SWIGTYPE_p_btAlignedObjectArrayT_btTypedConstraint_p_t () { swigCPtr = 0; } protected static long getCPtr (SWIGTYPE_p_btAlignedObjectArrayT_btTypedConstraint_p_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } }",futureUse,java,libgdx "package com.alibaba.fastjson; import java.io.IOException; public interface JSONStreamAware { void writeJSONString(Appendable [MASK]) throws IOException; }",out,java,fastjson "package jadx.gui.utils; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; public class PathTypeAdapter { private static final TypeAdapter SINGLETON = new TypeAdapter() { @Override public void write(JsonWriter [MASK], Path value) throws IOException { if (value == null) { [MASK].nullValue(); } else { [MASK].value(value.toAbsolutePath().toString()); } } @Override public Path read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } return Paths.get(in.nextString()); } }; public static TypeAdapter singleton() { return SINGLETON; } private PathTypeAdapter() { } }",out,java,jadx "package com.netflix.hystrix.contrib.javanica.command; import com.netflix.hystrix.HystrixCollapser; import com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContext; import com.netflix.hystrix.contrib.javanica.cache.HystrixCacheKeyGenerator; import com.netflix.hystrix.contrib.javanica.cache.HystrixGeneratedCacheKey; import com.netflix.hystrix.contrib.javanica.cache.HystrixRequestCacheManager; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult; import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; import javax.annotation.concurrent.ThreadSafe; import java.util.Collection; import java.util.List; @ThreadSafe public abstract class AbstractHystrixCommand extends com.netflix.hystrix.HystrixCommand { private final CommandActions commandActions; private final CacheInvocationContext cacheResultInvocationContext; private final CacheInvocationContext cacheRemoveInvocationContext; private final Collection> collapsedRequests; private final List> ignoreExceptions; private final ExecutionType executionType; private final HystrixCacheKeyGenerator defaultCacheKeyGenerator = HystrixCacheKeyGenerator.getInstance(); protected AbstractHystrixCommand(HystrixCommandBuilder [MASK]) { super([MASK].getSetterBuilder().build()); this.commandActions = [MASK].getCommandActions(); this.collapsedRequests = [MASK].getCollapsedRequests(); this.cacheResultInvocationContext = [MASK].getCacheResultInvocationContext(); this.cacheRemoveInvocationContext = [MASK].getCacheRemoveInvocationContext(); this.ignoreExceptions = [MASK].getIgnoreExceptions(); this.executionType = [MASK].getExecutionType(); } protected CommandAction getCommandAction() { return commandActions.getCommandAction(); } protected CommandAction getFallbackAction() { return commandActions.getFallbackAction(); } protected Collection> getCollapsedRequests() { return collapsedRequests; } protected List> getIgnoreExceptions() { return ignoreExceptions; } protected ExecutionType getExecutionType() { return executionType; } @Override protected String getCacheKey() { String key = null; if (cacheResultInvocationContext != null) { HystrixGeneratedCacheKey hystrixGeneratedCacheKey = defaultCacheKeyGenerator.generateCacheKey(cacheResultInvocationContext); key = hystrixGeneratedCacheKey.getCacheKey(); } return key; } boolean isIgnorable(Throwable throwable) { if (ignoreExceptions == null || ignoreExceptions.isEmpty()) { return false; } for (Class ignoreException : ignoreExceptions) { if (ignoreException.isAssignableFrom(throwable.getClass())) { return true; } } return false; } Object process(Action action) throws Exception { Object result; try { result = action.execute(); flushCache(); } catch (CommandActionExecutionException throwable) { Throwable cause = throwable.getCause(); if (isIgnorable(cause)) { throw new HystrixBadRequestException(cause.getMessage(), cause); } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Exception) { throw (Exception) cause; } else { throw new CommandActionExecutionException(cause); } } return result; } @Override protected abstract T run() throws Exception; protected void flushCache() { if (cacheRemoveInvocationContext != null) { HystrixRequestCacheManager.getInstance().clearCache(cacheRemoveInvocationContext); } } abstract class Action { abstract Object execute() throws CommandActionExecutionException; } static class FallbackErrorMessageBuilder { private StringBuilder [MASK] = new StringBuilder(""failed to process fallback""); static FallbackErrorMessageBuilder create() { return new FallbackErrorMessageBuilder(); } public FallbackErrorMessageBuilder append(CommandAction action, Throwable throwable) { return commandAction(action).exception(throwable); } private FallbackErrorMessageBuilder commandAction(CommandAction action) { if (action instanceof CommandExecutionAction || action instanceof LazyCommandExecutionAction) { [MASK].append("": '"").append(action.getActionName()).append(""'. "") .append(action.getActionName()).append("" fallback is a hystrix command. ""); } else if (action instanceof MethodExecutionAction) { [MASK].append("" is the method: '"").append(action.getActionName()).append(""'. ""); } return this; } private FallbackErrorMessageBuilder exception(Throwable throwable) { if (throwable instanceof HystrixBadRequestException) { [MASK].append(""exception: '"").append(throwable.getCause().getClass()) .append(""' occurred in fallback was ignored and wrapped to HystrixBadRequestException.\n""); } else if (throwable instanceof HystrixRuntimeException) { [MASK].append(""exception: '"").append(throwable.getCause().getClass()) .append(""' occurred in fallback wasn't ignored.\n""); } return this; } public String build() { return [MASK].toString(); } } }",builder,java,Hystrix "package com.alibaba.json.bvt.bug; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class Bug_for_smoothrat2 extends TestCase { public void test_0() throws Exception { long millis = System.currentTimeMillis(); java.sql.Time time = new java.sql.Time(millis); Entity entity = new Entity(); entity.setValue(new java.sql.Time(millis)); String [MASK] = JSON.toJSONString(entity); Assert.assertEquals(""{\""value\"":"" + millis + ""}"", [MASK]); Entity entity2 = JSON.parseObject([MASK], Entity.class); Assert.assertEquals(time, entity2.getValue()); } public static class Entity { private java.sql.Time value; public java.sql.Time getValue() { return value; } public void setValue(java.sql.Time value) { this.value = value; } } }",text,java,fastjson "package java.nio; import com.google.gwt.corp.compatibility.Numbers; final class ReadWriteHeapByteBuffer extends HeapByteBuffer { static ReadWriteHeapByteBuffer copy (HeapByteBuffer other, int markOfOther) { ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer(other.backingArray, other.[MASK](), other.offset); buf.limit = other.limit(); buf.position = other.position(); buf.mark = markOfOther; buf.order(other.order()); return buf; } ReadWriteHeapByteBuffer (byte[] backingArray) { super(backingArray); } ReadWriteHeapByteBuffer (int [MASK]) { super([MASK]); } ReadWriteHeapByteBuffer (byte[] backingArray, int [MASK], int arrayOffset) { super(backingArray, [MASK], arrayOffset); } public ByteBuffer asReadOnlyBuffer () { return ReadOnlyHeapByteBuffer.copy(this, mark); } public ByteBuffer compact () { System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); position = limit - position; limit = [MASK]; mark = UNSET_MARK; return this; } public ByteBuffer duplicate () { return copy(this, mark); } public boolean isReadOnly () { return false; } protected byte[] protectedArray () { return backingArray; } protected int protectedArrayOffset () { return offset; } protected boolean protectedHasArray () { return true; } public ByteBuffer put (byte b) { if (position == limit) { throw new BufferOverflowException(); } backingArray[offset + position++] = b; return this; } public ByteBuffer put (int index, byte b) { if (index < 0 || index >= limit) { throw new IndexOutOfBoundsException(); } backingArray[offset + index] = b; return this; } public ByteBuffer put (byte[] src, int off, int len) { if (off < 0 || len < 0 || (long)off + (long)len > src.length) { throw new IndexOutOfBoundsException(); } if (len > remaining()) { throw new BufferOverflowException(); } if (isReadOnly()) { throw new ReadOnlyBufferException(); } System.arraycopy(src, off, backingArray, offset + position, len); position += len; return this; } public ByteBuffer putDouble (double value) { return putLong(Numbers.doubleToRawLongBits(value)); } public ByteBuffer putDouble (int index, double value) { return putLong(index, Numbers.doubleToRawLongBits(value)); } public ByteBuffer putFloat (float value) { return putInt(Numbers.floatToIntBits(value)); } public ByteBuffer putFloat (int index, float value) { return putInt(index, Numbers.floatToIntBits(value)); } public ByteBuffer putInt (int value) { int newPosition = position + 4; if (newPosition > limit) { throw new BufferOverflowException(); } store(position, value); position = newPosition; return this; } public ByteBuffer putInt (int index, int value) { if (index < 0 || (long)index + 4 > limit) { throw new IndexOutOfBoundsException(); } store(index, value); return this; } public ByteBuffer putLong (int index, long value) { if (index < 0 || (long)index + 8 > limit) { throw new IndexOutOfBoundsException(); } store(index, value); return this; } public ByteBuffer putLong (long value) { int newPosition = position + 8; if (newPosition > limit) { throw new BufferOverflowException(); } store(position, value); position = newPosition; return this; } public ByteBuffer putShort (int index, short value) { if (index < 0 || (long)index + 2 > limit) { throw new IndexOutOfBoundsException(); } store(index, value); return this; } public ByteBuffer putShort (short value) { int newPosition = position + 2; if (newPosition > limit) { throw new BufferOverflowException(); } store(position, value); position = newPosition; return this; } public ByteBuffer slice () { ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer(backingArray, remaining(), offset + position); slice.order = order; return slice; } }",capacity,java,libgdx "package org.apache.dubbo.metadata.store.consul; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.Response; import com.ecwid.consul.v1.kv.model.GetValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.apache.dubbo.common.constants.ConsulConstants.DEFAULT_PORT; import static org.apache.dubbo.common.constants.ConsulConstants.INVALID_PORT; public class ConsulMetadataReport extends AbstractMetadataReport { private ConsulClient client; public ConsulMetadataReport(URL url) { super(url); String host = url.getHost(); int port = INVALID_PORT != url.getPort() ? url.getPort() : DEFAULT_PORT; client = new ConsulClient(host, port); } @Override protected void doStoreProviderMetadata(MetadataIdentifier [MASK], String serviceDefinitions) { this.storeMetadata([MASK], serviceDefinitions); } @Override protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { this.storeMetadata(consumerMetadataIdentifier, value); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { this.storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString())); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { this.deleteMetadata(serviceMetadataIdentifier); } @Override protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { String content = getMetadata(metadataIdentifier); if (StringUtils.isEmpty(content)) { return Collections.emptyList(); } return new ArrayList(Arrays.asList(URL.decode(content))); } @Override protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { this.storeMetadata(subscriberMetadataIdentifier, urlListStr); } @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { return getMetadata(subscriberMetadataIdentifier); } private void storeMetadata(BaseMetadataIdentifier identifier, String v) { try { client.setKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), v); } catch (Throwable t) { logger.error(""Failed to put "" + identifier + "" to consul "" + v + "", cause: "" + t.getMessage(), t); throw new RpcException(""Failed to put "" + identifier + "" to consul "" + v + "", cause: "" + t.getMessage(), t); } } private void deleteMetadata(BaseMetadataIdentifier identifier) { try { client.deleteKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); } catch (Throwable t) { logger.error(""Failed to delete "" + identifier + "" from consul , cause: "" + t.getMessage(), t); throw new RpcException(""Failed to delete "" + identifier + "" from consul , cause: "" + t.getMessage(), t); } } private String getMetadata(BaseMetadataIdentifier identifier) { try { Response value = client.getKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); if (value != null && value.getValue() != null) { return value.getValue().getValue(); } return null; } catch (Throwable t) { logger.error(""Failed to get "" + identifier + "" from consul , cause: "" + t.getMessage(), t); throw new RpcException(""Failed to get "" + identifier + "" from consul , cause: "" + t.getMessage(), t); } } @Override public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { return getMetadata(metadataIdentifier); } }",providerMetadataIdentifier,java,incubator-dubbo "package com.alibaba.json.bvt.[MASK]; import java.io.Reader; import java.io.StringReader; import java.util.List; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.[MASK].DefaultJSONParser; import com.alibaba.fastjson.[MASK].JSONReaderScanner; public class JSONReaderScannerTest__entity_float extends TestCase { public void test_scanFloat() throws Exception { StringBuffer buf = new StringBuffer(); buf.append('['); for (int i = 0; i < 1024; ++i) { if (i != 0) { buf.append(','); } buf.append(""{\""id\"":"" + i + "".0}""); } buf.append(']'); Reader reader = new StringReader(buf.toString()); JSONReaderScanner scanner = new JSONReaderScanner(reader); DefaultJSONParser [MASK] = new DefaultJSONParser(scanner); List array = [MASK].parseArray(VO.class); for (int i = 0; i < array.size(); ++i) { Assert.assertTrue((float) i == array.get(i).getId()); } [MASK].close(); } public static class VO { private float id; public float getId() { return id; } public void setId(float id) { this.id = id; } } }",parser,java,fastjson "package org.apache.dubbo.common.extension.wrapper.impl; import org.apache.dubbo.common.extension.wrapper.Demo; public class DemoImpl implements Demo { @Override public String echo(String [MASK]) { return [MASK]; } }",msg,java,incubator-dubbo "package com.badlogic.gdx.backends.iosrobovm; import com.badlogic.gdx.graphics.GL30; import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; public class IOSGLES30 extends IOSGLES20 implements GL30 { public IOSGLES30 () { init(); } private static native void init (); public native void glReadBuffer (int mode); public native void glDrawRangeElements (int mode, int start, int end, int count, int type, Buffer indices); public native void glDrawRangeElements (int mode, int start, int end, int count, int type, int offset); public native void glTexImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, int offset); public void glTexImage3D (int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, Buffer pixels) { if (!shouldConvert16bit) { glTexImage3DJNI(target, level, internalformat, width, height, depth, border, format, type, pixels); return; } if (type != GL_UNSIGNED_SHORT_5_6_5 && type != GL_UNSIGNED_SHORT_5_5_5_1 && type != GL_UNSIGNED_SHORT_4_4_4_4) { glTexImage3DJNI(target, level, internalformat, width, height, depth, border, format, type, pixels); return; } Buffer converted = convert16bitBufferToRGBA8888(pixels, type); glTexImage3DJNI(target, level, GL_RGBA, width, height, border, depth, GL_RGBA, GL_UNSIGNED_BYTE, converted); } public native void glTexImage3DJNI (int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, Buffer pixels); public native void glTexImage3D (int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, int offset); public native void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, int offset); public void glTexSubImage3D (int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, int type, Buffer pixels) { if (!shouldConvert16bit) { glTexSubImage3DJNI(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); return; } if (type != GL_UNSIGNED_SHORT_5_6_5 && type != GL_UNSIGNED_SHORT_5_5_5_1 && type != GL_UNSIGNED_SHORT_4_4_4_4) { glTexSubImage3DJNI(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); return; } Buffer converted = convert16bitBufferToRGBA8888(pixels, type); glTexSubImage3DJNI(target, level, xoffset, yoffset, zoffset, width, height, depth, GL_RGBA, GL_UNSIGNED_BYTE, converted); } public native void glTexSubImage3DJNI (int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, int type, Buffer pixels); public native void glTexSubImage3D (int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, int type, int offset); public native void glCopyTexSubImage3D (int target, int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height); public native void glGenQueries (int n, int[] ids, int offset); public native void glGenQueries (int n, IntBuffer ids); public native void glDeleteQueries (int n, int[] ids, int offset); public native void glDeleteQueries (int n, IntBuffer ids); public native boolean glIsQuery (int id); public native void glBeginQuery (int target, int id); public native void glEndQuery (int target); public native void glGetQueryiv (int target, int pname, IntBuffer params); public native void glGetQueryObjectuiv (int id, int pname, IntBuffer params); public native boolean glUnmapBuffer (int target); public native Buffer glGetBufferPointerv (int target, int pname); public native void glDrawBuffers (int n, IntBuffer bufs); public native void glUniformMatrix2x3fv (int location, int count, boolean transpose, FloatBuffer value); public native void glUniformMatrix3x2fv (int location, int count, boolean transpose, FloatBuffer value); public native void glUniformMatrix2x4fv (int location, int count, boolean transpose, FloatBuffer value); public native void glUniformMatrix4x2fv (int location, int count, boolean transpose, FloatBuffer value); public native void glUniformMatrix3x4fv (int location, int count, boolean transpose, FloatBuffer value); public native void glUniformMatrix4x3fv (int location, int count, boolean transpose, FloatBuffer value); public native void glBlitFramebuffer (int srcX0, int srcY0, int [MASK], int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter); public native void glRenderbufferStorageMultisample (int target, int samples, int internalformat, int width, int height); public native void glFramebufferTextureLayer (int target, int attachment, int texture, int level, int layer); public native java.nio.Buffer glMapBufferRange (int target, int offset, int length, int access); public native void glFlushMappedBufferRange (int target, int offset, int length); public native void glBindVertexArray (int array); public native void glDeleteVertexArrays (int n, int[] arrays, int offset); public native void glDeleteVertexArrays (int n, IntBuffer arrays); public native void glGenVertexArrays (int n, int[] arrays, int offset); public native void glGenVertexArrays (int n, IntBuffer arrays); public native boolean glIsVertexArray (int array); public native void glBeginTransformFeedback (int primitiveMode); public native void glEndTransformFeedback (); public native void glBindBufferRange (int target, int index, int buffer, int offset, int size); public native void glBindBufferBase (int target, int index, int buffer); public native void glTransformFeedbackVaryings (int program, String[] varyings, int bufferMode); public native void glVertexAttribIPointer (int index, int size, int type, int stride, int offset); public native void glGetVertexAttribIiv (int index, int pname, IntBuffer params); public native void glGetVertexAttribIuiv (int index, int pname, IntBuffer params); public native void glVertexAttribI4i (int index, int x, int y, int z, int w); public native void glVertexAttribI4ui (int index, int x, int y, int z, int w); public native void glGetUniformuiv (int program, int location, IntBuffer params); public native int glGetFragDataLocation (int program, String name); public native void glUniform1uiv (int location, int count, IntBuffer value); public native void glUniform3uiv (int location, int count, IntBuffer value); public native void glUniform4uiv (int location, int count, IntBuffer value); public native void glClearBufferiv (int buffer, int drawbuffer, IntBuffer value); public native void glClearBufferuiv (int buffer, int drawbuffer, IntBuffer value); public native void glClearBufferfv (int buffer, int drawbuffer, FloatBuffer value); public native void glClearBufferfi (int buffer, int drawbuffer, float depth, int stencil); public native String glGetStringi (int name, int index); public native void glCopyBufferSubData (int readTarget, int writeTarget, int readOffset, int writeOffset, int size); public native void glGetUniformIndices (int program, String[] uniformNames, IntBuffer uniformIndices); public native void glGetActiveUniformsiv (int program, int uniformCount, IntBuffer uniformIndices, int pname, IntBuffer params); public native int glGetUniformBlockIndex (int program, String uniformBlockName); public native void glGetActiveUniformBlockiv (int program, int uniformBlockIndex, int pname, IntBuffer params); public native void glGetActiveUniformBlockName (int program, int uniformBlockIndex, Buffer length, Buffer uniformBlockName); public native String glGetActiveUniformBlockName (int program, int uniformBlockIndex); public native void glUniformBlockBinding (int program, int uniformBlockIndex, int uniformBlockBinding); public native void glDrawArraysInstanced (int mode, int first, int count, int instanceCount); public native void glDrawElementsInstanced (int mode, int count, int type, int indicesOffset, int instanceCount); public native void glGetInteger64v (int pname, LongBuffer params); public native void glGetBufferParameteri64v (int target, int pname, LongBuffer params); public native void glGenSamplers (int count, int[] samplers, int offset); public native void glGenSamplers (int count, IntBuffer samplers); public native void glDeleteSamplers (int count, int[] samplers, int offset); public native void glDeleteSamplers (int count, IntBuffer samplers); public native boolean glIsSampler (int sampler); public native void glBindSampler (int unit, int sampler); public native void glSamplerParameteri (int sampler, int pname, int param); public native void glSamplerParameteriv (int sampler, int pname, IntBuffer param); public native void glSamplerParameterf (int sampler, int pname, float param); public native void glSamplerParameterfv (int sampler, int pname, FloatBuffer param); public native void glGetSamplerParameteriv (int sampler, int pname, IntBuffer params); public native void glGetSamplerParameterfv (int sampler, int pname, FloatBuffer params); public native void glVertexAttribDivisor (int index, int divisor); public native void glBindTransformFeedback (int target, int id); public native void glDeleteTransformFeedbacks (int n, int[] ids, int offset); public native void glDeleteTransformFeedbacks (int n, IntBuffer ids); public native void glGenTransformFeedbacks (int n, int[] ids, int offset); public native void glGenTransformFeedbacks (int n, IntBuffer ids); public native boolean glIsTransformFeedback (int id); public native void glPauseTransformFeedback (); public native void glResumeTransformFeedback (); public native void glProgramParameteri (int program, int pname, int value); public native void glInvalidateFramebuffer (int target, int numAttachments, IntBuffer attachments); public native void glInvalidateSubFramebuffer (int target, int numAttachments, IntBuffer attachments, int x, int y, int width, int height); }",srcX1,java,libgdx "package com.badlogic.gdx.physics.bullet.collision; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.math.Vector3; public class btTetrahedronShapeEx extends btBU_Simplex1to4 { private long swigCPtr; protected btTetrahedronShapeEx (final String className, long [MASK], boolean cMemoryOwn) { super(className, CollisionJNI.btTetrahedronShapeEx_SWIGUpcast([MASK]), cMemoryOwn); swigCPtr = [MASK]; } public btTetrahedronShapeEx (long [MASK], boolean cMemoryOwn) { this(""btTetrahedronShapeEx"", [MASK], cMemoryOwn); construct(); } @Override protected void reset (long [MASK], boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(CollisionJNI.btTetrahedronShapeEx_SWIGUpcast(swigCPtr = [MASK]), cMemoryOwn); } public static long getCPtr (btTetrahedronShapeEx obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; CollisionJNI.delete_btTetrahedronShapeEx(swigCPtr); } swigCPtr = 0; } super.delete(); } public btTetrahedronShapeEx () { this(CollisionJNI.new_btTetrahedronShapeEx(), true); } public void setVertices (Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3) { CollisionJNI.btTetrahedronShapeEx_setVertices(swigCPtr, this, v0, v1, v2, v3); } }",cPtr,java,libgdx "package com.alibaba.json.bvtVO; import java.io.Serializable; public class OptionValue implements Serializable { private static final long [MASK] = -1158546247925194748L; private E value; public void setValue(E value) { this.value = value; } public E getValue() { return value; } }",serialVersionUID,java,fastjson "package org.apache.dubbo.remoting.transport.grizzly; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer; import org.glassfish.grizzly.Buffer; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.filterchain.BaseFilter; import org.glassfish.grizzly.filterchain.FilterChainContext; import org.glassfish.grizzly.filterchain.NextAction; import java.io.IOException; import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE; public class GrizzlyCodecAdapter extends BaseFilter { private final Codec2 codec; private final URL url; private final ChannelHandler handler; private final int bufferSize; private ChannelBuffer previousData = ChannelBuffers.EMPTY_BUFFER; public GrizzlyCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE); this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE; } @Override public NextAction handleWrite(FilterChainContext context) throws IOException { Connection connection = context.getConnection(); GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); try { ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024); Object [MASK] = context.getMessage(); codec.encode(channel, channelBuffer, [MASK]); GrizzlyChannel.removeChannelIfDisconnected(connection); Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes()); buffer.put(channelBuffer.toByteBuffer()); buffer.flip(); buffer.allowBufferDispose(true); context.setMessage(buffer); } finally { GrizzlyChannel.removeChannelIfDisconnected(connection); } return context.getInvokeAction(); } @Override public NextAction handleRead(FilterChainContext context) throws IOException { Object message = context.getMessage(); Connection connection = context.getConnection(); Channel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); try { if (message instanceof Buffer) { Buffer grizzlyBuffer = (Buffer) message; ChannelBuffer frame; if (previousData.readable()) { if (previousData instanceof DynamicChannelBuffer) { previousData.writeBytes(grizzlyBuffer.toByteBuffer()); frame = previousData; } else { int size = previousData.readableBytes() + grizzlyBuffer.remaining(); frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); frame.writeBytes(previousData, previousData.readableBytes()); frame.writeBytes(grizzlyBuffer.toByteBuffer()); } } else { frame = ChannelBuffers.wrappedBuffer(grizzlyBuffer.toByteBuffer()); } Object [MASK]; int savedReadIndex; do { savedReadIndex = frame.readerIndex(); try { [MASK] = codec.decode(channel, frame); } catch (Exception e) { previousData = ChannelBuffers.EMPTY_BUFFER; throw new IOException(e.getMessage(), e); } if ([MASK] == Codec2.DecodeResult.NEED_MORE_INPUT) { frame.readerIndex(savedReadIndex); return context.getStopAction(); } else { if (savedReadIndex == frame.readerIndex()) { previousData = ChannelBuffers.EMPTY_BUFFER; throw new IOException(""Decode without read data.""); } if ([MASK] != null) { context.setMessage([MASK]); } return context.getInvokeAction(); } } while (frame.readable()); } else { return context.getInvokeAction(); } } finally { GrizzlyChannel.removeChannelIfDisconnected(connection); } } }",msg,java,incubator-dubbo "package com.alibaba.[MASK].bvt.bug; import java.util.Date; import org.junit.Assert; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Bug_for_issue_336 extends TestCase { public void test_for_issue() throws Exception { RemoteInvocation remoteInvocation = new RemoteInvocation(); remoteInvocation.setMethodName(""test""); remoteInvocation.setParameterTypes(new Class[] { int.class, Date.class, String.class }); remoteInvocation.setArguments(new Object[] { 1, new Date(1460538273131L), ""this is a test"" }); String [MASK] = JSON.toJSONString(remoteInvocation); Assert.assertEquals(""{\""arguments\"":[1,1460538273131,\""this is a test\""],\""methodName\"":\""test\"",\""parameterTypes\"":[\""int\"",\""java.util.Date\"",\""java.lang.String\""]}"", [MASK]); remoteInvocation = JSON.parseObject([MASK], RemoteInvocation.class); Assert.assertEquals(3, remoteInvocation.parameterTypes.length); Assert.assertEquals(int.class, remoteInvocation.parameterTypes[0]); Assert.assertEquals(Date.class, remoteInvocation.parameterTypes[1]); Assert.assertEquals(String.class, remoteInvocation.parameterTypes[2]); } public static class RemoteInvocation { private String methodName; private Class[] parameterTypes; private Object[] arguments; public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public Class[] getParameterTypes() { return parameterTypes; } public void setParameterTypes(Class[] parameterTypes) { this.parameterTypes = parameterTypes; } public Object[] getArguments() { return arguments; } public void setArguments(Object[] arguments) { this.arguments = arguments; } } }",json,java,fastjson "package com.netflix.hystrix.metric; import com.netflix.hystrix.HystrixCommandKey; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class HystrixCommandCompletionStream implements HystrixEventStream { private final HystrixCommandKey commandKey; private final Subject [MASK]; private final Observable readOnlyStream; private static final ConcurrentMap streams = new ConcurrentHashMap(); public static HystrixCommandCompletionStream getInstance(HystrixCommandKey commandKey) { HystrixCommandCompletionStream initialStream = streams.get(commandKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (HystrixCommandCompletionStream.class) { HystrixCommandCompletionStream existingStream = streams.get(commandKey.name()); if (existingStream == null) { HystrixCommandCompletionStream newStream = new HystrixCommandCompletionStream(commandKey); streams.putIfAbsent(commandKey.name(), newStream); return newStream; } else { return existingStream; } } } } HystrixCommandCompletionStream(final HystrixCommandKey commandKey) { this.commandKey = commandKey; this.[MASK] = new SerializedSubject(PublishSubject.create()); this.readOnlyStream = [MASK].share(); } public static void reset() { streams.clear(); } public void write(HystrixCommandCompletion event) { [MASK].onNext(event); } @Override public Observable observe() { return readOnlyStream; } @Override public String toString() { return ""HystrixCommandCompletionStream("" + commandKey.name() + "")""; } }",writeOnlySubject,java,Hystrix "package com.badlogic.gdx.assets.loaders; import java.util.Locale; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.I18NBundle; public class I18NBundleLoader extends AsynchronousAssetLoader { public I18NBundleLoader (FileHandleResolver resolver) { super(resolver); } I18NBundle bundle; @Override public void loadAsync (AssetManager manager, String [MASK], FileHandle file, I18NBundleParameter parameter) { this.bundle = null; Locale locale; String encoding; if (parameter == null) { locale = Locale.getDefault(); encoding = null; } else { locale = parameter.locale == null ? Locale.getDefault() : parameter.locale; encoding = parameter.encoding; } if (encoding == null) { this.bundle = I18NBundle.createBundle(file, locale); } else { this.bundle = I18NBundle.createBundle(file, locale, encoding); } } @Override public I18NBundle loadSync (AssetManager manager, String [MASK], FileHandle file, I18NBundleParameter parameter) { I18NBundle bundle = this.bundle; this.bundle = null; return bundle; } @Override public Array getDependencies (String [MASK], FileHandle file, I18NBundleParameter parameter) { return null; } static public class I18NBundleParameter extends AssetLoaderParameters { public final Locale locale; public final String encoding; public I18NBundleParameter () { this(null, null); } public I18NBundleParameter (Locale locale) { this(locale, null); } public I18NBundleParameter (Locale locale, String encoding) { this.locale = locale; this.encoding = encoding; } } }",fileName,java,libgdx "package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue995 extends TestCase { public void test_for_issue() throws Exception { Person person = new Person(); JSONPath.set(person, ""$.[MASK].name"", ""xxx""); } public static class Person { public Nose [MASK]; } public static class Nose { public String name; } }",nose,java,fastjson "package com.google.zxing.common; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.List; public final class ECIEncoderSet { private static final List ENCODERS = new ArrayList<>(); static { String[] names = { ""IBM437"", ""ISO-8859-2"", ""ISO-8859-3"", ""ISO-8859-4"", ""ISO-8859-5"", ""ISO-8859-6"", ""ISO-8859-7"", ""ISO-8859-8"", ""ISO-8859-9"", ""ISO-8859-10"", ""ISO-8859-11"", ""ISO-8859-13"", ""ISO-8859-14"", ""ISO-8859-15"", ""ISO-8859-16"", ""windows-1250"", ""windows-1251"", ""windows-1252"", ""windows-1256"", ""Shift_JIS"" }; for (String name : names) { if (CharacterSetECI.getCharacterSetECIByName(name) != null) { try { ENCODERS.add(Charset.forName(name).newEncoder()); } catch (UnsupportedCharsetException e) { } } } } private final CharsetEncoder[] encoders; private final int priorityEncoderIndex; public ECIEncoderSet(String stringToEncode, Charset priorityCharset, int fnc1) { List [MASK] = new ArrayList<>(); [MASK].add(StandardCharsets.ISO_8859_1.newEncoder()); boolean needUnicodeEncoder = priorityCharset != null && priorityCharset.name().startsWith(""UTF""); for (int i = 0; i < stringToEncode.length(); i++) { boolean canEncode = false; for (CharsetEncoder encoder : [MASK]) { char c = stringToEncode.charAt(i); if (c == fnc1 || encoder.canEncode(c)) { canEncode = true; break; } } if (!canEncode) { for (CharsetEncoder encoder : ENCODERS) { if (encoder.canEncode(stringToEncode.charAt(i))) { [MASK].add(encoder); canEncode = true; break; } } } if (!canEncode) { needUnicodeEncoder = true; } } if ([MASK].size() == 1 && !needUnicodeEncoder) { encoders = new CharsetEncoder[] { [MASK].get(0) }; } else { encoders = new CharsetEncoder[[MASK].size() + 2]; int index = 0; for (CharsetEncoder encoder : [MASK]) { encoders[index++] = encoder; } encoders[index] = StandardCharsets.UTF_8.newEncoder(); encoders[index + 1] = StandardCharsets.UTF_16BE.newEncoder(); } int priorityEncoderIndexValue = -1; if (priorityCharset != null) { for (int i = 0; i < encoders.length; i++) { if (encoders[i] != null && priorityCharset.name().equals(encoders[i].charset().name())) { priorityEncoderIndexValue = i; break; } } } priorityEncoderIndex = priorityEncoderIndexValue; assert encoders[0].charset().equals(StandardCharsets.ISO_8859_1); } public int length() { return encoders.length; } public String getCharsetName(int index) { assert index < length(); return encoders[index].charset().name(); } public Charset getCharset(int index) { assert index < length(); return encoders[index].charset(); } public int getECIValue(int encoderIndex) { return CharacterSetECI.getCharacterSetECI(encoders[encoderIndex].charset()).getValue(); } public int getPriorityEncoderIndex() { return priorityEncoderIndex; } public boolean canEncode(char c, int encoderIndex) { assert encoderIndex < length(); CharsetEncoder encoder = encoders[encoderIndex]; return encoder.canEncode("""" + c); } public byte[] encode(char c, int encoderIndex) { assert encoderIndex < length(); CharsetEncoder encoder = encoders[encoderIndex]; assert encoder.canEncode("""" + c); return ("""" + c).getBytes(encoder.charset()); } public byte[] encode(String s, int encoderIndex) { assert encoderIndex < length(); CharsetEncoder encoder = encoders[encoderIndex]; return s.getBytes(encoder.charset()); } }",neededEncoders,java,zxing "package io.netty5.example.dns.tcp; import io.netty5.bootstrap.Bootstrap; import io.netty5.bootstrap.ServerBootstrap; import io.netty5.buffer.BufferUtil; import io.netty5.channel.Channel; import io.netty5.channel.ChannelHandlerContext; import io.netty5.channel.ChannelInitializer; import io.netty5.channel.IoHandlerFactory; import io.netty5.channel.MultithreadEventLoopGroup; import io.netty5.channel.SimpleChannelInboundHandler; import io.netty5.channel.nio.NioIoHandler; import io.netty5.channel.socket.SocketChannel; import io.netty5.channel.socket.nio.NioServerSocketChannel; import io.netty5.channel.socket.nio.NioSocketChannel; import io.netty5.handler.codec.dns.DefaultDnsQuery; import io.netty5.handler.codec.dns.DefaultDnsQuestion; import io.netty5.handler.codec.dns.DefaultDnsRawRecord; import io.netty5.handler.codec.dns.DefaultDnsResponse; import io.netty5.handler.codec.dns.DnsOpCode; import io.netty5.handler.codec.dns.DnsQuery; import io.netty5.handler.codec.dns.DnsQuestion; import io.netty5.handler.codec.dns.DnsRawRecord; import io.netty5.handler.codec.dns.DnsRecord; import io.netty5.handler.codec.dns.DnsRecordType; import io.netty5.handler.codec.dns.DnsSection; import io.netty5.handler.codec.dns.TcpDnsQueryDecoder; import io.netty5.handler.codec.dns.TcpDnsQueryEncoder; import io.netty5.handler.codec.dns.TcpDnsResponseDecoder; import io.netty5.handler.codec.dns.TcpDnsResponseEncoder; import io.netty5.handler.logging.LogLevel; import io.netty5.handler.logging.LoggingHandler; import io.netty5.util.NetUtil; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public final class TcpDnsServer { private static final String QUERY_DOMAIN = ""www.example.com""; private static final int DNS_SERVER_PORT = 53; private static final String DNS_SERVER_HOST = ""127.0.0.1""; private static final byte[] QUERY_RESULT = {(byte) 192, (byte) 168, 1, 1}; public static void main(String[] args) throws Exception { IoHandlerFactory ioHandlerFactory = NioIoHandler.newFactory(); ServerBootstrap bootstrap = new ServerBootstrap() .group(new MultithreadEventLoopGroup(1, ioHandlerFactory), new MultithreadEventLoopGroup(ioHandlerFactory)) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new TcpDnsQueryDecoder(), new TcpDnsResponseEncoder(), new SimpleChannelInboundHandler() { @Override protected void messageReceived(ChannelHandlerContext ctx, DnsQuery msg) throws Exception { DnsQuestion [MASK] = msg.recordAt(DnsSection.QUESTION); System.out.println(""Query domain: "" + [MASK]); ctx.writeAndFlush(newResponse(ctx, msg, [MASK], 600, QUERY_RESULT)); } private DefaultDnsResponse newResponse(ChannelHandlerContext ctx, DnsQuery query, DnsQuestion [MASK], long ttl, byte[]... addresses) { DefaultDnsResponse response = new DefaultDnsResponse(query.id()); response.addRecord(DnsSection.QUESTION, [MASK]); for (byte[] address : addresses) { DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord( [MASK].name(), DnsRecordType.A, ttl, ctx.bufferAllocator().copyOf(address)); response.addRecord(DnsSection.ANSWER, queryAnswer); } return response; } }); } }); final Channel channel = bootstrap.bind(DNS_SERVER_PORT).asStage().get(); Executors.newSingleThreadScheduledExecutor().schedule(() -> { try { clientQuery(); channel.close(); } catch (Exception e) { e.printStackTrace(); } }, 1000, TimeUnit.MILLISECONDS); channel.closeFuture().asStage().sync(); } private static void clientQuery() throws Exception { MultithreadEventLoopGroup group = new MultithreadEventLoopGroup(NioIoHandler.newFactory()); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new TcpDnsQueryEncoder()) .addLast(new TcpDnsResponseDecoder()) .addLast(new SimpleChannelInboundHandler() { @Override protected void messageReceived( ChannelHandlerContext ctx, DefaultDnsResponse msg) { try { handleQueryResp(msg); } finally { ctx.close(); } } }); } }); final Channel ch = b.connect(DNS_SERVER_HOST, DNS_SERVER_PORT).asStage().get(); int randomID = new Random().nextInt(60000 - 1000) + 1000; DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY) .setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A)); ch.writeAndFlush(query).asStage().sync(); boolean success = ch.closeFuture().asStage().await(10, TimeUnit.SECONDS); if (!success) { System.err.println(""dns query timeout!""); ch.close().asStage().sync(); } } finally { group.shutdownGracefully(); } } private static void handleQueryResp(DefaultDnsResponse msg) { if (msg.count(DnsSection.QUESTION) > 0) { DnsQuestion [MASK] = msg.recordAt(DnsSection.QUESTION, 0); System.out.printf(""name: %s%n"", [MASK].name()); } for (int i = 0, count = msg.count(DnsSection.ANSWER); i < count; i++) { DnsRecord record = msg.recordAt(DnsSection.ANSWER, i); if (record.type() == DnsRecordType.A) { DnsRawRecord raw = (DnsRawRecord) record; System.out.println(NetUtil.bytesToIpAddress(BufferUtil.getBytes(raw.content()))); } } } }",question,java,netty "package com.badlogic.gdx.physics.bullet.collision; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.math.Vector3; public class btGjkPairDetector extends btDiscreteCollisionDetectorInterface { private long swigCPtr; protected btGjkPairDetector (final String className, long cPtr, boolean cMemoryOwn) { super(className, CollisionJNI.btGjkPairDetector_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } public btGjkPairDetector (long cPtr, boolean cMemoryOwn) { this(""btGjkPairDetector"", cPtr, cMemoryOwn); construct(); } @Override protected void reset (long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(CollisionJNI.btGjkPairDetector_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn); } public static long getCPtr (btGjkPairDetector obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; CollisionJNI.delete_btGjkPairDetector(swigCPtr); } swigCPtr = 0; } super.delete(); } public void setLastUsedMethod (int value) { CollisionJNI.btGjkPairDetector_lastUsedMethod_set(swigCPtr, this, value); } public int getLastUsedMethod () { return CollisionJNI.btGjkPairDetector_lastUsedMethod_get(swigCPtr, this); } public void setCurIter (int value) { CollisionJNI.btGjkPairDetector_curIter_set(swigCPtr, this, value); } public int getCurIter () { return CollisionJNI.btGjkPairDetector_curIter_get(swigCPtr, this); } public void setDegenerateSimplex (int value) { CollisionJNI.btGjkPairDetector_degenerateSimplex_set(swigCPtr, this, value); } public int getDegenerateSimplex () { return CollisionJNI.btGjkPairDetector_degenerateSimplex_get(swigCPtr, this); } public void setCatchDegeneracies (int value) { CollisionJNI.btGjkPairDetector_catchDegeneracies_set(swigCPtr, this, value); } public int getCatchDegeneracies () { return CollisionJNI.btGjkPairDetector_catchDegeneracies_get(swigCPtr, this); } public void setFixContactNormalDirection (int value) { CollisionJNI.btGjkPairDetector_fixContactNormalDirection_set(swigCPtr, this, value); } public int getFixContactNormalDirection () { return CollisionJNI.btGjkPairDetector_fixContactNormalDirection_get(swigCPtr, this); } public btGjkPairDetector (btConvexShape objectA, btConvexShape [MASK], btVoronoiSimplexSolver simplexSolver, btConvexPenetrationDepthSolver penetrationDepthSolver) { this(CollisionJNI.new_btGjkPairDetector__SWIG_0(btConvexShape.getCPtr(objectA), objectA, btConvexShape.getCPtr([MASK]), [MASK], btVoronoiSimplexSolver.getCPtr(simplexSolver), simplexSolver, btConvexPenetrationDepthSolver.getCPtr(penetrationDepthSolver), penetrationDepthSolver), true); } public btGjkPairDetector (btConvexShape objectA, btConvexShape [MASK], int shapeTypeA, int shapeTypeB, float marginA, float marginB, btVoronoiSimplexSolver simplexSolver, btConvexPenetrationDepthSolver penetrationDepthSolver) { this(CollisionJNI.new_btGjkPairDetector__SWIG_1(btConvexShape.getCPtr(objectA), objectA, btConvexShape.getCPtr([MASK]), [MASK], shapeTypeA, shapeTypeB, marginA, marginB, btVoronoiSimplexSolver.getCPtr(simplexSolver), simplexSolver, btConvexPenetrationDepthSolver.getCPtr(penetrationDepthSolver), penetrationDepthSolver), true); } public void getClosestPoints (btDiscreteCollisionDetectorInterface.ClosestPointInput input, btDiscreteCollisionDetectorInterface.Result output, btIDebugDraw debugDraw, boolean swapResults) { CollisionJNI.btGjkPairDetector_getClosestPoints__SWIG_0(swigCPtr, this, btDiscreteCollisionDetectorInterface.ClosestPointInput.getCPtr(input), input, btDiscreteCollisionDetectorInterface.Result.getCPtr(output), output, btIDebugDraw.getCPtr(debugDraw), debugDraw, swapResults); } public void getClosestPoints (btDiscreteCollisionDetectorInterface.ClosestPointInput input, btDiscreteCollisionDetectorInterface.Result output, btIDebugDraw debugDraw) { CollisionJNI.btGjkPairDetector_getClosestPoints__SWIG_1(swigCPtr, this, btDiscreteCollisionDetectorInterface.ClosestPointInput.getCPtr(input), input, btDiscreteCollisionDetectorInterface.Result.getCPtr(output), output, btIDebugDraw.getCPtr(debugDraw), debugDraw); } public void getClosestPointsNonVirtual (btDiscreteCollisionDetectorInterface.ClosestPointInput input, btDiscreteCollisionDetectorInterface.Result output, btIDebugDraw debugDraw) { CollisionJNI.btGjkPairDetector_getClosestPointsNonVirtual(swigCPtr, this, btDiscreteCollisionDetectorInterface.ClosestPointInput.getCPtr(input), input, btDiscreteCollisionDetectorInterface.Result.getCPtr(output), output, btIDebugDraw.getCPtr(debugDraw), debugDraw); } public void setMinkowskiA (btConvexShape minkA) { CollisionJNI.btGjkPairDetector_setMinkowskiA(swigCPtr, this, btConvexShape.getCPtr(minkA), minkA); } public void setMinkowskiB (btConvexShape minkB) { CollisionJNI.btGjkPairDetector_setMinkowskiB(swigCPtr, this, btConvexShape.getCPtr(minkB), minkB); } public void setCachedSeperatingAxis (Vector3 seperatingAxis) { CollisionJNI.btGjkPairDetector_setCachedSeperatingAxis(swigCPtr, this, seperatingAxis); } public Vector3 getCachedSeparatingAxis () { return CollisionJNI.btGjkPairDetector_getCachedSeparatingAxis(swigCPtr, this); } public float getCachedSeparatingDistance () { return CollisionJNI.btGjkPairDetector_getCachedSeparatingDistance(swigCPtr, this); } public void setPenetrationDepthSolver (btConvexPenetrationDepthSolver penetrationDepthSolver) { CollisionJNI.btGjkPairDetector_setPenetrationDepthSolver(swigCPtr, this, btConvexPenetrationDepthSolver.getCPtr(penetrationDepthSolver), penetrationDepthSolver); } public void setIgnoreMargin (boolean ignoreMargin) { CollisionJNI.btGjkPairDetector_setIgnoreMargin(swigCPtr, this, ignoreMargin); } }",objectB,java,libgdx "package jadx.gui.treemodel; import java.util.List; import java.util.Set; import javax.swing.Icon; import jadx.api.JavaNode; import jadx.api.data.ICodeRename; import jadx.gui.ui.MainWindow; public interface JRenameNode { JavaNode getJavaNode(); String getTitle(); String getName(); Icon getIcon(); boolean canRename(); default JRenameNode replace() { return this; } ICodeRename buildCodeRename(String newName, Set [MASK]); boolean isValidName(String newName); void removeAlias(); void addUpdateNodes(List toUpdate); void reload(MainWindow mainWindow); }",renames,java,jadx "package io.netty5.handler.ssl; import io.netty5.buffer.Buffer; import io.netty5.channel.ChannelHandler; import io.netty5.channel.ChannelHandlerContext; import io.netty5.channel.ChannelPipeline; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import static io.netty5.buffer.DefaultBufferAllocators.onHeapAllocator; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class OptionalSslHandlerTest { private static final String SSL_HANDLER_NAME = ""sslhandler""; private static final String HANDLER_NAME = ""handler""; @Mock private ChannelHandlerContext context; @Mock private SslContext sslContext; @Mock private ChannelPipeline [MASK]; @BeforeEach public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(context.[MASK]()).thenReturn([MASK]); } @Test public void handlerRemoved() throws Exception { OptionalSslHandler handler = new OptionalSslHandler(sslContext); try (Buffer payload = onHeapAllocator().copyOf(""plaintext"", UTF_8)) { handler.decode(context, payload); verify([MASK]).remove(handler); } } @Test public void handlerReplaced() throws Exception { final ChannelHandler nonSslHandler = Mockito.mock(ChannelHandler.class); OptionalSslHandler handler = new OptionalSslHandler(sslContext) { @Override protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) { return nonSslHandler; } @Override protected String newNonSslHandlerName() { return HANDLER_NAME; } }; try (Buffer payload = onHeapAllocator().copyOf(""plaintext"", UTF_8)) { handler.decode(context, payload); verify([MASK]).replace(handler, HANDLER_NAME, nonSslHandler); } } @Test public void sslHandlerReplaced() throws Exception { final SslHandler sslHandler = Mockito.mock(SslHandler.class); OptionalSslHandler handler = new OptionalSslHandler(sslContext) { @Override protected SslHandler newSslHandler(ChannelHandlerContext context, SslContext sslContext) { return sslHandler; } @Override protected String newSslHandlerName() { return SSL_HANDLER_NAME; } }; try (Buffer payload = onHeapAllocator().copyOf(new byte[] { 22, 3, 1, 0, 5 })) { handler.decode(context, payload); verify([MASK]).replace(handler, SSL_HANDLER_NAME, sslHandler); } } @Test public void decodeBuffered() throws Exception { OptionalSslHandler handler = new OptionalSslHandler(sslContext); try (Buffer payload = onHeapAllocator().copyOf(new byte[] { 22, 3 })) { handler.decode(context, payload); verifyZeroInteractions([MASK]); } } }",pipeline,java,netty "package com.alibaba.json.test.deny; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import java.lang.reflect.Field; import java.util.concurrent.ConcurrentMap; public class NotExistsTest extends TestCase { public void test_0() throws Exception { Field [MASK] = TypeUtils.class.getDeclaredField(""mappings""); [MASK].setAccessible(true); ConcurrentMap> mappings = (ConcurrentMap>) [MASK].get(null); System.out.println(mappings.size()); for (int i = 0; i < 10; ++i) { long start = System.currentTimeMillis(); perf(); long millis = System.currentTimeMillis() - start; System.out.println(""millis : "" + millis); } } private void perf() { for (int i = 0; i < 1000 * 1; ++i) { String text = ""[{\""@type\"":\""x0\""},{\""@type\"":\""x1\""},{\""@type\"":\""x2\""},{\""@type\"":\""x3\""},{\""@type\"":\""x4\""}]""; try { JSON.parseObject(text); } catch (Exception ex) { } } } }",field,java,fastjson "package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue3452 extends TestCase { public void test_for_issue() throws Exception { String s = ""{ \""componentKey\"" : \""CMDB_UPDATE_SERVER\""}""; Step [MASK] = JSON.parseObject(s, Step.class); assertEquals(""CMDB_UPDATE_SERVER"",[MASK].getComponentKey()); System.out.println([MASK].getComponentKey()); } private static class Step { @JSONField(name = ""component_key"", alternateNames = {""componentKey""}) private String componentKey; public String getComponentKey() { return componentKey; } public void setComponentKey(String componentKey) { this.componentKey = componentKey; } } }",step,java,fastjson "package com.alibaba.json.test.entity.pagemodel; import java.util.List; public class RegionInstance { private List [MASK]; public List getWidgtes() { return [MASK]; } public void setWidgtes(List [MASK]) { this.[MASK] = [MASK]; } }",widgtes,java,fastjson "package com.alibaba.json.bvt.parser.stream; import java.io.StringReader; import org.junit.Assert; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONReader; import junit.framework.TestCase; public class JSONReaderTest_3 extends TestCase { public void test_read_Long() throws Exception { String [MASK] = ""1001""; JSONReader reader = new JSONReader(new StringReader([MASK])); Exception error = null; try { reader.hasNext(); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } }",text,java,fastjson "package com.netflix.hystrix; import org.junit.Test; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import rx.Observable; import java.util.ArrayList; import java.util.List; public class HystrixCommandTimeoutConcurrencyTesting { private final static int NUM_CONCURRENT_COMMANDS = 30; @Test public void testTimeoutRace() throws InterruptedException { final int NUM_TRIALS = 10; for (int i = 0; i < NUM_TRIALS; i++) { List> [MASK] = new ArrayList>(); HystrixRequestContext context = null; try { context = HystrixRequestContext.initializeContext(); for (int j = 0; j < NUM_CONCURRENT_COMMANDS; j++) { [MASK].add(new TestCommand().observe()); } Observable overall = Observable.merge([MASK]); List results = overall.toList().toBlocking().first(); for (String s : results) { if (s == null) { System.err.println(""Received NULL!""); throw new RuntimeException(""Received NULL""); } } for (HystrixInvokableInfo hi : HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()) { if (!hi.isResponseTimedOut()) { System.err.println(""Timeout not found in executed command""); throw new RuntimeException(""Timeout not found in executed command""); } if (hi.isResponseTimedOut() && hi.getExecutionEvents().size() == 1) { System.err.println(""Missing fallback status!""); throw new RuntimeException(""Missing fallback status on timeout.""); } } } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); e.printStackTrace(); throw new RuntimeException(e); } finally { System.out.println(HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); if (context != null) { context.shutdown(); } } System.out.println(""*************** TRIAL "" + i + "" ******************""); System.out.println(); Thread.sleep(50); } Hystrix.reset(); } public static class TestCommand extends HystrixCommand { protected TestCommand() { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(""testTimeoutConcurrency"")) .andCommandKey(HystrixCommandKey.Factory.asKey(""testTimeoutConcurrencyCommand"")) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withExecutionTimeoutInMilliseconds(3) .withCircuitBreakerEnabled(false) .withFallbackIsolationSemaphoreMaxConcurrentRequests(NUM_CONCURRENT_COMMANDS)) .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() .withCoreSize(NUM_CONCURRENT_COMMANDS) .withMaxQueueSize(NUM_CONCURRENT_COMMANDS) .withQueueSizeRejectionThreshold(NUM_CONCURRENT_COMMANDS))); } @Override protected String run() throws Exception { Thread.sleep(500); return ""hello""; } @Override protected String getFallback() { return ""failed""; } } }",observables,java,Hystrix "package io.netty5.handler.codec.http2; public final class Http2MultiplexActiveStreamsException extends Exception { public Http2MultiplexActiveStreamsException(Throwable [MASK]) { super([MASK]); } @Override public Throwable fillInStackTrace() { return this; } }",cause,java,netty "package com.alibaba.json.bvt.issue_1100; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.text.SimpleDateFormat; import java.util.Date; public class Issue1152 extends TestCase { public void test_for_issue() throws Exception { TestBean tb = JSONObject.parseObject(""{[MASK]:\""0000-00-00T00:00:00\""}"",TestBean.class); assertNull(tb.getShijian()); } public void test_for_issue_2() throws Exception { TestBean tb = JSONObject.parseObject(""{[MASK]:\""0001-01-01T00:00:00+08:00\""}"",TestBean.class); assertNotNull(tb.getShijian()); } public static class TestBean { private Date [MASK]; public Date getShijian() { return [MASK]; } @JSONField(name=""[MASK]"" ) public void setShijian(Date [MASK]) { this.[MASK] = [MASK]; } } }",shijian,java,fastjson "package jadx.tests.integration.conditions; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestInnerAssign2 extends IntegrationTest { public static class TestCls { private String field; private String swapField; @SuppressWarnings(""checkstyle:InnerAssignment"") public boolean test(String str) { String sub; return call(str) || ((sub = this.field) != null && sub.isEmpty()); } private boolean call(String str) { this.field = swapField; return str.isEmpty(); } public boolean testWrap(String str, String [MASK]) { this.field = null; this.swapField = [MASK]; return test(str); } public void check() { assertThat(testWrap("""", null)).isTrue(); assertThat(testWrap(""a"", """")).isTrue(); assertThat(testWrap(""b"", null)).isFalse(); assertThat(testWrap(""c"", ""d"")).isFalse(); } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsOne(""sub = this.field"") .containsOne(""return call(str) || ((sub = this.field) != null && sub.isEmpty());""); } }",fieldValue,java,jadx "package com.facebook.datasource; import java.util.Map; import java.util.concurrent.Executor; import javax.annotation.Nullable; public interface DataSource { boolean isClosed(); @Nullable T getResult(); boolean hasResult(); @Nullable Map getExtras(); boolean hasMultipleResults(); boolean isFinished(); boolean hasFailed(); @Nullable Throwable getFailureCause(); float getProgress(); boolean close(); void subscribe(DataSubscriber dataSubscriber, Executor [MASK]); }",executor,java,fresco "package jadx.tests.integration.variables; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import jadx.tests.api.utils.assertj.JadxAssertions; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestVariablesIfElseChain extends IntegrationTest { public static class TestCls { String [MASK]; public String test(int a) { if (a == 0) { use(""zero""); } else if (a == 1) { String r = m(a); if (r != null) { use(r); } } else if (a == 2) { String r = m(a); if (r != null) { use(r); } } else { return ""miss""; } return null; } public String m(int a) { return ""hit"" + a; } public void use(String s) { [MASK] = s; } public void check() { test(0); assertThat([MASK]).isEqualTo(""zero""); test(1); assertThat([MASK]).isEqualTo(""hit1""); test(2); assertThat([MASK]).isEqualTo(""hit2""); assertThat(test(5)).isEqualTo(""miss""); } } @Test public void test() { JadxAssertions.assertThat(getClassNode(TestCls.class)) .code() .containsOne(""return \""miss\"";""); } }",used,java,jadx "package com.badlogic.gdx.physics.bullet.collision; import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.math.Vector3; public class btQuantizedBvh extends BulletBase { private long swigCPtr; protected btQuantizedBvh (final String className, long cPtr, boolean cMemoryOwn) { super(className, cPtr, cMemoryOwn); swigCPtr = cPtr; } public btQuantizedBvh (long cPtr, boolean cMemoryOwn) { this(""btQuantizedBvh"", cPtr, cMemoryOwn); construct(); } @Override protected void reset (long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(swigCPtr = cPtr, cMemoryOwn); } public static long getCPtr (btQuantizedBvh obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; CollisionJNI.delete_btQuantizedBvh(swigCPtr); } swigCPtr = 0; } super.delete(); } public long operatorNew (long sizeInBytes) { return CollisionJNI.btQuantizedBvh_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes); } public void operatorDelete (long ptr) { CollisionJNI.btQuantizedBvh_operatorDelete__SWIG_0(swigCPtr, this, ptr); } public long operatorNew (long arg0, long ptr) { return CollisionJNI.btQuantizedBvh_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr); } public void operatorDelete (long arg0, long arg1) { CollisionJNI.btQuantizedBvh_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1); } public long operatorNewArray (long sizeInBytes) { return CollisionJNI.btQuantizedBvh_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes); } public void operatorDeleteArray (long ptr) { CollisionJNI.btQuantizedBvh_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr); } public long operatorNewArray (long arg0, long ptr) { return CollisionJNI.btQuantizedBvh_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr); } public void operatorDeleteArray (long arg0, long arg1) { CollisionJNI.btQuantizedBvh_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1); } public btQuantizedBvh () { this(CollisionJNI.new_btQuantizedBvh(), true); } public void setQuantizationValues (Vector3 bvhAabbMin, Vector3 bvhAabbMax, float quantizationMargin) { CollisionJNI.btQuantizedBvh_setQuantizationValues__SWIG_0(swigCPtr, this, bvhAabbMin, bvhAabbMax, quantizationMargin); } public void setQuantizationValues (Vector3 bvhAabbMin, Vector3 bvhAabbMax) { CollisionJNI.btQuantizedBvh_setQuantizationValues__SWIG_1(swigCPtr, this, bvhAabbMin, bvhAabbMax); } public SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t getLeafNodeArray () { return new SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t( CollisionJNI.btQuantizedBvh_getLeafNodeArray(swigCPtr, this), false); } public void buildInternal () { CollisionJNI.btQuantizedBvh_buildInternal(swigCPtr, this); } public void reportAabbOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 aabbMin, Vector3 aabbMax) { CollisionJNI.btQuantizedBvh_reportAabbOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback), nodeCallback, aabbMin, aabbMax); } public void reportRayOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget) { CollisionJNI.btQuantizedBvh_reportRayOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback), nodeCallback, raySource, rayTarget); } public void reportBoxCastOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget, Vector3 aabbMin, Vector3 aabbMax) { CollisionJNI.btQuantizedBvh_reportBoxCastOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback), nodeCallback, raySource, rayTarget, aabbMin, aabbMax); } public void quantize (java.nio.IntBuffer out, Vector3 point, int isMax) { assert out.isDirect() : ""Buffer must be allocated direct.""; { CollisionJNI.btQuantizedBvh_quantize(swigCPtr, this, out, point, isMax); } } public void quantizeWithClamp (java.nio.IntBuffer out, Vector3 point2, int isMax) { assert out.isDirect() : ""Buffer must be allocated direct.""; { CollisionJNI.btQuantizedBvh_quantizeWithClamp(swigCPtr, this, out, point2, isMax); } } public Vector3 unQuantize (java.nio.IntBuffer vecIn) { assert vecIn.isDirect() : ""Buffer must be allocated direct.""; { return CollisionJNI.btQuantizedBvh_unQuantize(swigCPtr, this, vecIn); } } public void setTraversalMode (int traversalMode) { CollisionJNI.btQuantizedBvh_setTraversalMode(swigCPtr, this, traversalMode); } public SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t getQuantizedNodeArray () { return new SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t( CollisionJNI.btQuantizedBvh_getQuantizedNodeArray(swigCPtr, this), false); } public SWIGTYPE_p_btAlignedObjectArrayT_btBvhSubtreeInfo_t getSubtreeInfoArray () { return new SWIGTYPE_p_btAlignedObjectArrayT_btBvhSubtreeInfo_t( CollisionJNI.btQuantizedBvh_getSubtreeInfoArray(swigCPtr, this), false); } public long calculateSerializeBufferSize () { return CollisionJNI.btQuantizedBvh_calculateSerializeBufferSize(swigCPtr, this); } public boolean serialize (long o_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) { return CollisionJNI.btQuantizedBvh_serialize__SWIG_0(swigCPtr, this, o_alignedDataBuffer, i_dataBufferSize, i_swapEndian); } public static btQuantizedBvh deSerializeInPlace (long i_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) { long cPtr = CollisionJNI.btQuantizedBvh_deSerializeInPlace(i_alignedDataBuffer, i_dataBufferSize, i_swapEndian); return (cPtr == 0) ? null : new btQuantizedBvh(cPtr, false); } public static long getAlignmentSerializationPadding () { return CollisionJNI.btQuantizedBvh_getAlignmentSerializationPadding(); } public int calculateSerializeBufferSizeNew () { return CollisionJNI.btQuantizedBvh_calculateSerializeBufferSizeNew(swigCPtr, this); } public String serialize (long dataBuffer, btSerializer [MASK]) { return CollisionJNI.btQuantizedBvh_serialize__SWIG_1(swigCPtr, this, dataBuffer, btSerializer.getCPtr([MASK]), [MASK]); } public void deSerializeFloat (btQuantizedBvhFloatData quantizedBvhFloatData) { CollisionJNI.btQuantizedBvh_deSerializeFloat(swigCPtr, this, btQuantizedBvhFloatData.getCPtr(quantizedBvhFloatData), quantizedBvhFloatData); } public void deSerializeDouble (btQuantizedBvhDoubleData quantizedBvhDoubleData) { CollisionJNI.btQuantizedBvh_deSerializeDouble(swigCPtr, this, btQuantizedBvhDoubleData.getCPtr(quantizedBvhDoubleData), quantizedBvhDoubleData); } public boolean isQuantized () { return CollisionJNI.btQuantizedBvh_isQuantized(swigCPtr, this); } public final static class btTraversalMode { public final static int TRAVERSAL_STACKLESS = 0; public final static int TRAVERSAL_STACKLESS_CACHE_FRIENDLY = TRAVERSAL_STACKLESS + 1; public final static int TRAVERSAL_RECURSIVE = TRAVERSAL_STACKLESS_CACHE_FRIENDLY + 1; } }",serializer,java,libgdx "package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; public class Manifold { long [MASK]; final ManifoldPoint[] points = new ManifoldPoint[] {new ManifoldPoint(), new ManifoldPoint()}; final Vector2 localNormal = new Vector2(); final Vector2 localPoint = new Vector2(); final int[] tmpInt = new int[2]; final float[] tmpFloat = new float[4]; protected Manifold (long [MASK]) { this.[MASK] = [MASK]; } public ManifoldType getType () { int type = jniGetType([MASK]); if (type == 0) return ManifoldType.Circle; if (type == 1) return ManifoldType.FaceA; if (type == 2) return ManifoldType.FaceB; return ManifoldType.Circle; } private native int jniGetType (long [MASK]); public int getPointCount () { return jniGetPointCount([MASK]); } private native int jniGetPointCount (long [MASK]); public Vector2 getLocalNormal () { jniGetLocalNormal([MASK], tmpFloat); localNormal.set(tmpFloat[0], tmpFloat[1]); return localNormal; } private native void jniGetLocalNormal (long [MASK], float[] values); public Vector2 getLocalPoint () { jniGetLocalPoint([MASK], tmpFloat); localPoint.set(tmpFloat[0], tmpFloat[1]); return localPoint; } private native void jniGetLocalPoint (long [MASK], float[] values); public ManifoldPoint[] getPoints () { int count = jniGetPointCount([MASK]); for (int i = 0; i < count; i++) { int contactID = jniGetPoint([MASK], tmpFloat, i); ManifoldPoint point = points[i]; point.contactID = contactID; point.localPoint.set(tmpFloat[0], tmpFloat[1]); point.normalImpulse = tmpFloat[2]; point.tangentImpulse = tmpFloat[3]; } return points; } private native int jniGetPoint (long [MASK], float[] values, int idx); public class ManifoldPoint { public final Vector2 localPoint = new Vector2(); public float normalImpulse; public float tangentImpulse; public int contactID = 0; public String toString () { return ""id: "" + contactID + "", "" + localPoint + "", "" + normalImpulse + "", "" + tangentImpulse; } } public enum ManifoldType { Circle, FaceA, FaceB } }",addr,java,libgdx "package com.alibaba.json.bvt.bug; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Bug_for_issue_352 extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.name = ""张三""; String [MASK] = JSON.toJSONString(vo); Assert.assertEquals(""{\""index\"":0,\""名\"":\""张三\""}"", [MASK]); VO v1 = JSON.parseObject([MASK], VO.class); Assert.assertEquals(vo.name, v1.name); } public static class VO { public int index; @JSONField(name=""名"") public String name; } }",text,java,fastjson "package com.alibaba.json.test.epubview; import java.util.HashMap; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestKlutz2 extends TestCase { public void test_page () throws Exception { EpubViewPage x = new EpubViewPage(); x.setImageUrl(""xxx""); String [MASK] = JSON.toJSONString(x); System.out.println([MASK]); JSON.parseObject([MASK], EpubViewPage.class); } }",str,java,fastjson "package io.netty5.handler.codec.compression; import io.netty5.buffer.Buffer; import io.netty5.buffer.BufferAllocator; import java.nio.ByteBuffer; import java.util.function.Supplier; import java.util.zip.CRC32; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; import static java.util.Objects.requireNonNull; public final class ZlibDecompressor implements Decompressor { private static final int FHCRC = 0x02; private static final int FEXTRA = 0x04; private static final int FNAME = 0x08; private static final int FCOMMENT = 0x10; private static final int FRESERVED = 0xE0; private Inflater inflater; private final byte[] dictionary; private final BufferChecksum crc; private final boolean decompressConcatenated; private final int maxAllocation; private enum GzipState { HEADER_START, HEADER_END, FLG_READ, XLEN_READ, SKIP_FNAME, SKIP_COMMENT, PROCESS_FHCRC, FOOTER_START, } private GzipState gzipState = GzipState.HEADER_START; private int flags = -1; private int xlen = -1; private boolean finished; private boolean [MASK]; private boolean decideZlibOrNone; private ZlibDecompressor(ZlibWrapper wrapper, byte[] dictionary, boolean decompressConcatenated, int maxAllocation) { this.maxAllocation = maxAllocation; this.decompressConcatenated = decompressConcatenated; switch (wrapper) { case GZIP: inflater = new Inflater(true); crc = new BufferChecksum(new CRC32()); break; case NONE: inflater = new Inflater(true); crc = null; break; case ZLIB: inflater = new Inflater(); crc = null; break; case ZLIB_OR_NONE: decideZlibOrNone = true; crc = null; break; default: throw new IllegalArgumentException(""Only GZIP or ZLIB is supported, but you used "" + wrapper); } this.dictionary = dictionary; } public static Supplier newFactory() { return newFactory(ZlibWrapper.ZLIB, null, false, 0); } public static Supplier newFactory(int maxAllocation) { return newFactory(ZlibWrapper.ZLIB, null, false, maxAllocation); } public static Supplier newFactory(byte[] dictionary) { return newFactory(ZlibWrapper.ZLIB, dictionary, false, 0); } public static Supplier newFactory(byte[] dictionary, int maxAllocation) { return newFactory(ZlibWrapper.ZLIB, dictionary, false, maxAllocation); } public static Supplier newFactory(ZlibWrapper wrapper) { return newFactory(wrapper, null, false, 0); } public static Supplier newFactory(ZlibWrapper wrapper, int maxAllocation) { return newFactory(wrapper, null, false, maxAllocation); } public static Supplier newFactory(ZlibWrapper wrapper, boolean decompressConcatenated) { return newFactory(wrapper, null, decompressConcatenated, 0); } public static Supplier newFactory( ZlibWrapper wrapper, boolean decompressConcatenated, int maxAllocation) { return newFactory(wrapper, null, decompressConcatenated, maxAllocation); } public static Supplier newFactory(boolean decompressConcatenated) { return newFactory(ZlibWrapper.GZIP, null, decompressConcatenated, 0); } public static Supplier newFactory(boolean decompressConcatenated, int maxAllocation) { return newFactory(ZlibWrapper.GZIP, null, decompressConcatenated, maxAllocation); } private static Supplier newFactory(ZlibWrapper wrapper, byte[] dictionary, boolean decompressConcatenated, int maxAllocation) { requireNonNull(wrapper, ""wrapper""); return () -> new ZlibDecompressor(wrapper, dictionary, decompressConcatenated, maxAllocation); } @Override public Buffer decompress(Buffer in, BufferAllocator allocator) throws DecompressionException { if ([MASK]) { throw new DecompressionException(""Decompressor [MASK]""); } if (finished) { return allocator.allocate(0); } int readableBytes = in.readableBytes(); if (readableBytes == 0) { return null; } if (decideZlibOrNone) { if (readableBytes < 2) { return null; } boolean nowrap = !looksLikeZlib(in.getShort(in.readerOffset())); inflater = new Inflater(nowrap); decideZlibOrNone = false; } if (crc != null) { if (gzipState != GzipState.HEADER_END) { if (gzipState == GzipState.FOOTER_START) { if (!handleGzipFooter(in)) { return null; } assert gzipState == GzipState.HEADER_START; } if (!readGZIPHeader(in)) { return null; } readableBytes = in.readableBytes(); if (readableBytes == 0) { return null; } } } if (inflater.needsInput()) { try (var readableIteration = in.forEachComponent()) { var readableComponent = readableIteration.firstReadable(); if (readableComponent.hasReadableArray()) { inflater.setInput(readableComponent.readableArray(), readableComponent.readableArrayOffset(), readableComponent.readableBytes()); } else { inflater.setInput(readableComponent.readableBuffer()); } } } Buffer decompressed = prepareDecompressBuffer(allocator, null, inflater.getRemaining() << 1); try { boolean readFooter = false; while (!inflater.needsInput()) { int writableComponents = decompressed.countWritableComponents(); if (writableComponents == 0) { break; } else if (writableComponents > 1) { throw new IllegalStateException( ""Decompress buffer must have array or exactly 1 NIO buffer: "" + decompressed); } try (var writableIteration = decompressed.forEachComponent()) { var writableComponent = writableIteration.firstWritable(); int writerIndex = decompressed.writerOffset(); int writable = decompressed.writableBytes(); int outputLength; if (writableComponent.hasWritableArray()) { byte[] outArray = writableComponent.writableArray(); int outIndex = writableComponent.writableArrayOffset(); outputLength = inflater.inflate(outArray, outIndex, writable); } else { ByteBuffer buffer = writableComponent.writableBuffer(); outputLength = inflater.inflate(buffer); } if (outputLength > 0) { writableComponent.skipWritableBytes(outputLength); if (crc != null) { crc.update(decompressed, writerIndex, outputLength); } } else if (inflater.needsDictionary()) { if (dictionary == null) { throw new DecompressionException( ""decompression failure, unable to set dictionary as non was specified""); } inflater.setDictionary(dictionary); } if (inflater.finished()) { if (crc == null) { finished = true; } else { readFooter = true; } break; } } decompressed = prepareDecompressBuffer(allocator, decompressed, inflater.getRemaining() << 1); } int remaining = inflater.getRemaining(); in.skipReadableBytes(readableBytes - remaining); if (readFooter) { gzipState = GzipState.FOOTER_START; handleGzipFooter(in); } if (decompressed.readableBytes() > 0) { return decompressed; } else { decompressed.close(); return null; } } catch (DataFormatException e) { decompressed.close(); throw new DecompressionException(""decompression failure"", e); } catch (Throwable cause) { decompressed.close(); throw cause; } } private boolean handleGzipFooter(Buffer in) { if (readGZIPFooter(in)) { finished = !decompressConcatenated; if (!finished) { inflater.reset(); crc.reset(); gzipState = GzipState.HEADER_START; return true; } } return false; } private boolean readGZIPHeader(Buffer in) { switch (gzipState) { case HEADER_START: if (in.readableBytes() < 10) { return false; } int magic0 = in.readByte(); int magic1 = in.readByte(); if (magic0 != 31) { throw new DecompressionException(""Input is not in the GZIP format""); } crc.update(magic0); crc.update(magic1); int method = in.readUnsignedByte(); if (method != Deflater.DEFLATED) { throw new DecompressionException(""Unsupported compression method "" + method + "" in the GZIP header""); } crc.update(method); flags = in.readUnsignedByte(); crc.update(flags); if ((flags & FRESERVED) != 0) { throw new DecompressionException( ""Reserved flags are set in the GZIP header""); } crc.update(in, in.readerOffset(), 4); in.skipReadableBytes(4); crc.update(in.readUnsignedByte()); crc.update(in.readUnsignedByte()); gzipState = GzipState.FLG_READ; case FLG_READ: if ((flags & FEXTRA) != 0) { if (in.readableBytes() < 2) { return false; } int xlen1 = in.readUnsignedByte(); int xlen2 = in.readUnsignedByte(); crc.update(xlen1); crc.update(xlen2); xlen |= xlen1 << 8 | xlen2; } gzipState = GzipState.XLEN_READ; case XLEN_READ: if (xlen != -1) { if (in.readableBytes() < xlen) { return false; } crc.update(in, in.readerOffset(), xlen); in.skipReadableBytes(xlen); } gzipState = GzipState.SKIP_FNAME; case SKIP_FNAME: if (!skipIfNeeded(in, FNAME)) { return false; } gzipState = GzipState.SKIP_COMMENT; case SKIP_COMMENT: if (!skipIfNeeded(in, FCOMMENT)) { return false; } gzipState = GzipState.PROCESS_FHCRC; case PROCESS_FHCRC: if ((flags & FHCRC) != 0) { if (!verifyCrc16(in)) { return false; } } crc.reset(); gzipState = GzipState.HEADER_END; case HEADER_END: return true; default: throw new IllegalStateException(); } } private boolean skipIfNeeded(Buffer in, int flagMask) { if ((flags & flagMask) != 0) { for (;;) { if (in.readableBytes() == 0) { return false; } int b = in.readUnsignedByte(); crc.update(b); if (b == 0x00) { break; } } } return true; } private boolean readGZIPFooter(Buffer in) { if (in.readableBytes() < 8) { return false; } boolean enoughData = verifyCrc(in); assert enoughData; int dataLength = 0; for (int i = 0; i < 4; ++i) { dataLength |= in.readUnsignedByte() << i * 8; } int readLength = inflater.getTotalOut(); if (dataLength != readLength) { throw new DecompressionException( ""Number of bytes mismatch. Expected: "" + dataLength + "", Got: "" + readLength); } return true; } private boolean verifyCrc(Buffer in) { if (in.readableBytes() < 4) { return false; } long crcValue = 0; for (int i = 0; i < 4; ++i) { crcValue |= (long) in.readUnsignedByte() << i * 8; } long readCrc = crc.getValue(); if (crcValue != readCrc) { throw new DecompressionException( ""CRC value mismatch. Expected: "" + crcValue + "", Got: "" + readCrc); } return true; } private boolean verifyCrc16(Buffer in) { if (in.readableBytes() < 2) { return false; } long readCrc32 = crc.getValue(); long crc16Value = 0; long readCrc16 = 0; for (int i = 0; i < 2; ++i) { crc16Value |= (long) in.readUnsignedByte() << (i * 8); readCrc16 |= ((readCrc32 >> (i * 8)) & 0xff) << (i * 8); } if (crc16Value != readCrc16) { throw new DecompressionException( ""CRC16 value mismatch. Expected: "" + crc16Value + "", Got: "" + readCrc16); } return true; } private static boolean looksLikeZlib(short cmf_flg) { return (cmf_flg & 0x7800) == 0x7800 && cmf_flg % 31 == 0; } protected Buffer prepareDecompressBuffer(BufferAllocator allocator, Buffer buffer, int preferredSize) { if (buffer == null) { if (maxAllocation == 0) { return allocator.allocate(preferredSize); } Buffer buf = allocator.allocate(Math.min(preferredSize, maxAllocation)); buf.implicitCapacityLimit(maxAllocation); return buf; } if (buffer.implicitCapacityLimit() < preferredSize) { decompressionBufferExhausted(buffer); buffer.skipReadableBytes(buffer.readableBytes()); throw new DecompressionException( ""Decompression buffer has reached maximum size: "" + buffer.implicitCapacityLimit()); } buffer.ensureWritable(preferredSize); return buffer; } protected void decompressionBufferExhausted(Buffer buffer) { finished = true; } @Override public boolean isFinished() { return finished; } @Override public void close() { [MASK] = true; finished = true; if (inflater != null) { inflater.end(); } } @Override public boolean isClosed() { return [MASK]; } }",closed,java,netty "package io.netty5.example.proxy; import io.netty5.bootstrap.ServerBootstrap; import io.netty5.channel.ChannelOption; import io.netty5.channel.EventLoopGroup; import io.netty5.channel.MultithreadEventLoopGroup; import io.netty5.channel.nio.NioIoHandler; import io.netty5.channel.socket.nio.NioServerSocketChannel; import io.netty5.handler.logging.LogLevel; import io.netty5.handler.logging.LoggingHandler; public final class HexDumpProxy { static final int LOCAL_PORT = Integer.parseInt(System.getProperty(""localPort"", ""8443"")); static final String REMOTE_HOST = System.getProperty(""remoteHost"", ""www.google.com""); static final int REMOTE_PORT = Integer.parseInt(System.getProperty(""remotePort"", ""443"")); public static void main(String[] args) throws Exception { System.err.println(""Proxying *:"" + LOCAL_PORT + "" to "" + REMOTE_HOST + ':' + REMOTE_PORT + "" ...""); EventLoopGroup bossGroup = new MultithreadEventLoopGroup(1, NioIoHandler.newFactory()); EventLoopGroup [MASK] = new MultithreadEventLoopGroup(NioIoHandler.newFactory()); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, [MASK]) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HexDumpProxyInitializer(REMOTE_HOST, REMOTE_PORT)) .childOption(ChannelOption.AUTO_READ, false) .bind(LOCAL_PORT).asStage().get().closeFuture().asStage().sync(); } finally { bossGroup.shutdownGracefully(); [MASK].shutdownGracefully(); } } }",workerGroup,java,netty "package org.apache.dubbo.rpc.cluster.configurator; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.cluster.Configurator; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACES; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.rpc.cluster.Constants.CONFIG_VERSION_KEY; import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; public abstract class AbstractConfigurator implements Configurator { private static final String TILDE = ""~""; private final URL configuratorUrl; public AbstractConfigurator(URL url) { if (url == null) { throw new IllegalArgumentException(""configurator url == null""); } this.configuratorUrl = url; } @Override public URL getUrl() { return configuratorUrl; } @Override public URL configure(URL url) { if (!configuratorUrl.getParameter(ENABLED_KEY, true) || configuratorUrl.getHost() == null || url == null || url.getHost() == null) { return url; } String [MASK] = configuratorUrl.getParameter(CONFIG_VERSION_KEY); if (StringUtils.isNotEmpty([MASK])) { String currentSide = url.getParameter(SIDE_KEY); String configuratorSide = configuratorUrl.getParameter(SIDE_KEY); if (currentSide.equals(configuratorSide) && CONSUMER.equals(configuratorSide) && 0 == configuratorUrl.getPort()) { url = configureIfMatch(NetUtils.getLocalHost(), url); } else if (currentSide.equals(configuratorSide) && PROVIDER.equals(configuratorSide) && url.getPort() == configuratorUrl.getPort()) { url = configureIfMatch(url.getHost(), url); } } else { url = configureDeprecated(url); } return url; } @Deprecated private URL configureDeprecated(URL url) { if (configuratorUrl.getPort() != 0) { if (url.getPort() == configuratorUrl.getPort()) { return configureIfMatch(url.getHost(), url); } } else { if (url.getParameter(SIDE_KEY, PROVIDER).equals(CONSUMER)) { return configureIfMatch(NetUtils.getLocalHost(), url); } else if (url.getParameter(SIDE_KEY, CONSUMER).equals(PROVIDER)) { return configureIfMatch(ANYHOST_VALUE, url); } } return url; } private URL configureIfMatch(String host, URL url) { if (ANYHOST_VALUE.equals(configuratorUrl.getHost()) || host.equals(configuratorUrl.getHost())) { String providers = configuratorUrl.getParameter(OVERRIDE_PROVIDERS_KEY); if (StringUtils.isEmpty(providers) || providers.contains(url.getAddress()) || providers.contains(ANYHOST_VALUE)) { String configApplication = configuratorUrl.getParameter(APPLICATION_KEY, configuratorUrl.getUsername()); String currentApplication = url.getParameter(APPLICATION_KEY, url.getUsername()); if (configApplication == null || ANY_VALUE.equals(configApplication) || configApplication.equals(currentApplication)) { Set tildeKeys = new HashSet<>(); for (Map.Entry entry : configuratorUrl.getParameters().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String tildeKey = StringUtils.isNotEmpty(key) && key.startsWith(TILDE) ? key : null; if (tildeKey != null || APPLICATION_KEY.equals(key) || SIDE_KEY.equals(key)) { if (value != null && !ANY_VALUE.equals(value) && !value.equals(url.getParameter(tildeKey != null ? key.substring(1) : key))) { return url; } } if (tildeKey != null) { tildeKeys.add(tildeKey); } } Set conditionKeys = new HashSet<>(); conditionKeys.add(CATEGORY_KEY); conditionKeys.add(Constants.CHECK_KEY); conditionKeys.add(DYNAMIC_KEY); conditionKeys.add(ENABLED_KEY); conditionKeys.add(GROUP_KEY); conditionKeys.add(VERSION_KEY); conditionKeys.add(APPLICATION_KEY); conditionKeys.add(SIDE_KEY); conditionKeys.add(CONFIG_VERSION_KEY); conditionKeys.add(COMPATIBLE_CONFIG_KEY); conditionKeys.add(INTERFACES); conditionKeys.addAll(tildeKeys); return doConfigure(url, configuratorUrl.removeParameters(conditionKeys)); } } } return url; } protected abstract URL doConfigure(URL currentUrl, URL configUrl); }",apiVersion,java,incubator-dubbo "package org.apache.dubbo.common.io; import java.io.IOException; import java.io.Writer; public class UnsafeStringWriter extends Writer { private StringBuilder mBuffer; public UnsafeStringWriter() { lock = mBuffer = new StringBuilder(); } public UnsafeStringWriter(int size) { if (size < 0) { throw new IllegalArgumentException(""Negative buffer size""); } lock = mBuffer = new StringBuilder(); } @Override public void write(int c) { mBuffer.append((char) c); } @Override public void write(char[] cs) throws IOException { mBuffer.append(cs, 0, cs.length); } @Override public void write(char[] cs, int off, int len) throws IOException { if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (len > 0) { mBuffer.append(cs, off, len); } } @Override public void write(String str) { mBuffer.append(str); } @Override public void write(String str, int off, int len) { mBuffer.append(str, off, off + len); } @Override public Writer append(CharSequence [MASK]) { if ([MASK] == null) { write(""null""); } else { write([MASK].toString()); } return this; } @Override public Writer append(CharSequence [MASK], int start, int end) { CharSequence cs = ([MASK] == null ? ""null"" : [MASK]); write(cs.subSequence(start, end).toString()); return this; } @Override public Writer append(char c) { mBuffer.append(c); return this; } @Override public void close() { } @Override public void flush() { } @Override public String toString() { return mBuffer.toString(); } }",csq,java,incubator-dubbo "package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.api.MethodCallback; import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration; import org.apache.dubbo.config.spring.impl.MethodCallbackImpl; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration( classes = { ProviderConfiguration.class, MethodConfigCallbackTest.class, MethodConfigCallbackTest.MethodCallbackConfiguration.class }) @TestPropertySource(properties = { ""dubbo.protocols.dubbo.port=-1"", }) @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class MethodConfigCallbackTest { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @Autowired private ConfigurableApplicationContext context; @DubboReference(check = false, methods = {@Method(name = ""sayHello"", oninvoke = ""methodCallback.oninvoke"", onreturn = ""methodCallback.onreturn"", onthrow = ""methodCallback.onthrow"")}) private HelloService helloServiceMethodCallBack; @Test public void testMethodAnnotationCallBack() { helloServiceMethodCallBack.sayHello(""dubbo""); MethodCallback [MASK] = (MethodCallback) context.getBean(""methodCallback""); Assertions.assertEquals(""dubbo invoke success"", [MASK].getOnInvoke()); Assertions.assertEquals(""dubbo return success"", [MASK].getOnReturn()); } @Configuration static class MethodCallbackConfiguration { @Bean(""methodCallback"") public MethodCallback methodCallback() { return new MethodCallbackImpl(); } } }",notify,java,incubator-dubbo "package com.alibaba.json.bvt; import java.awt.Rectangle; import com.alibaba.fastjson.parser.Feature; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.AwtCodec; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class RectangleTest extends TestCase { public void test_color() throws Exception { JSONSerializer serializer = new JSONSerializer(); Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Rectangle.class).getClass()); Rectangle v = new Rectangle(3, 4, 100, 200); String [MASK] = JSON.toJSONString(v, SerializerFeature.WriteClassName); System.out.println([MASK]); Rectangle v2 = (Rectangle) JSON.parse([MASK], Feature.SupportAutoType); Assert.assertEquals(v, v2); } }",text,java,fastjson "package jadx.gui.utils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.gui.treemodel.TextNode; import static org.assertj.core.api.Assertions.assertThat; class JumpManagerTest { private JumpManager jm; @BeforeEach public void setup() { jm = new JumpManager(); } @Test public void testEmptyHistory() { assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); } @Test public void testEmptyHistory2() { assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isNull(); } @Test public void testOneElement() { jm.addPosition(makeJumpPos()); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); } @Test public void testTwoElements() { JumpPosition pos1 = makeJumpPos(); jm.addPosition(pos1); JumpPosition pos2 = makeJumpPos(); jm.addPosition(pos2); assertThat(jm.getPrev()).isSameAs(pos1); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isSameAs(pos2); assertThat(jm.getNext()).isNull(); } @Test public void testNavigation() { JumpPosition pos1 = makeJumpPos(); jm.addPosition(pos1); JumpPosition pos2 = makeJumpPos(); jm.addPosition(pos2); assertThat(jm.getPrev()).isSameAs(pos1); JumpPosition [MASK] = makeJumpPos(); jm.addPosition([MASK]); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isSameAs(pos1); assertThat(jm.getNext()).isSameAs([MASK]); } @Test public void testNavigation2() { JumpPosition pos1 = makeJumpPos(); jm.addPosition(pos1); JumpPosition pos2 = makeJumpPos(); jm.addPosition(pos2); JumpPosition [MASK] = makeJumpPos(); jm.addPosition([MASK]); JumpPosition pos4 = makeJumpPos(); jm.addPosition(pos4); assertThat(jm.getPrev()).isSameAs([MASK]); assertThat(jm.getPrev()).isSameAs(pos2); JumpPosition pos5 = makeJumpPos(); jm.addPosition(pos5); assertThat(jm.getNext()).isNull(); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isSameAs(pos2); assertThat(jm.getPrev()).isSameAs(pos1); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isSameAs(pos2); assertThat(jm.getNext()).isSameAs(pos5); assertThat(jm.getNext()).isNull(); } @Test public void addSame() { JumpPosition pos = makeJumpPos(); jm.addPosition(pos); jm.addPosition(pos); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); } private JumpPosition makeJumpPos() { return new JumpPosition(new TextNode(""""), 0); } }",pos3,java,jadx "package com.alibaba.json.bvt.ref; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class RefTest10 extends TestCase { public void test_bug_for_wanglin() throws Exception { String text = ""{ \""schedulerCluster\"": \""xyQuestionImport\"", \""log\"": { \""abilityServiceId\"": \""-1\"", \""abilityServiceVersionId\"": \""-1\"", \""createTime\"": 1456832040060, \""ip\"": \""192.168.1.71\"", \""jobDataMap\"": { \""com.fjhb.context.v1.Context\"": { \""domain\"": \""dev.medical.com\"", \""gUID\"": \""25c5e12ec19946e8a6850237cd8182de\"", \""ip\"": \""127.0.0.1\"", \""organizationId\"": \""-1\"", \""platformId\"": \""2c9180e5520a5e70015214fb2849000a\"", \""platformVersionId\"": \""2c9180e5520a6063015214fc062d0006\"", \""projectId\"": \""2c9180e5520a60630152150b0b4a000e\"", \""recordChain\"": true, \""requestUrl\"": \""http: JSONObject [MASK] = JSON.parseObject(text); Assert.assertSame([MASK].getJSONObject(""log"").getJSONObject(""jobDataMap"").get(""com.fjhb.context.v1.Context""), [MASK].get(""context"")); } public static class VO { private A a; private Set values = new HashSet(); public A getA() { return a; } public void setA(A a) { this.a = a; } public Set getValues() { return values; } public void setValues(Set values) { this.values = values; } } public static class A { } }",jsonObj,java,fastjson "package com.facebook.imagepipeline.producers; import com.facebook.imagepipeline.image.EncodedImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.infer.annotation.Nullsafe; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) public class BranchOnSeparateImagesProducer implements Producer { private final Producer mInputProducer1; private final Producer mInputProducer2; public BranchOnSeparateImagesProducer( Producer inputProducer1, Producer inputProducer2) { mInputProducer1 = inputProducer1; mInputProducer2 = inputProducer2; } @Override public void produceResults(Consumer [MASK], ProducerContext context) { OnFirstImageConsumer onFirstImageConsumer = new OnFirstImageConsumer([MASK], context); mInputProducer1.produceResults(onFirstImageConsumer, context); } private class OnFirstImageConsumer extends DelegatingConsumer { private ProducerContext mProducerContext; private OnFirstImageConsumer(Consumer [MASK], ProducerContext producerContext) { super([MASK]); mProducerContext = producerContext; } @Override protected void onNewResultImpl(@Nullable EncodedImage newResult, @Status int status) { ImageRequest request = mProducerContext.getImageRequest(); boolean isLast = isLast(status); boolean isGoodEnough = ThumbnailSizeChecker.isImageBigEnough(newResult, request.getResizeOptions()); if (newResult != null && (isGoodEnough || request.getLocalThumbnailPreviewsEnabled())) { if (isLast && isGoodEnough) { getConsumer().onNewResult(newResult, status); } else { int alteredStatus = turnOffStatusFlag(status, IS_LAST); getConsumer().onNewResult(newResult, alteredStatus); } } if (isLast && !isGoodEnough && !request.getLoadThumbnailOnlyForAndroidSdkAboveQ()) { EncodedImage.closeSafely(newResult); mInputProducer2.produceResults(getConsumer(), mProducerContext); } } @Override protected void onFailureImpl(@Nullable Throwable t) { mInputProducer2.produceResults(getConsumer(), mProducerContext); } } }",consumer,java,fresco "package jadx.core.clsp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.DecodeException; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; public class ClsSet { private static final Logger LOG = LoggerFactory.getLogger(ClsSet.class); private static final String CLST_EXTENSION = "".jcst""; private static final String CLST_FILENAME = ""core"" + CLST_EXTENSION; private static final String CLST_PATH = ""/clst/"" + CLST_FILENAME; private static final String JADX_CLS_SET_HEADER = ""jadx-cst""; private static final int VERSION = 5; private static final String STRING_CHARSET = ""US-ASCII""; private static final ArgType[] EMPTY_ARGTYPE_ARRAY = new ArgType[0]; private static final ArgType[] OBJECT_ARGTYPE_ARRAY = new ArgType[] { ArgType.OBJECT }; private final RootNode root; private int androidApiLevel; public ClsSet(RootNode root) { this.root = root; } private enum TypeEnum { WILDCARD, GENERIC, GENERIC_TYPE_VARIABLE, OUTER_GENERIC, OBJECT, ARRAY, PRIMITIVE } private ClspClass[] classes; public void loadFromClstFile() throws IOException, DecodeException { long startTime = System.currentTimeMillis(); try (InputStream input = ClsSet.class.getResourceAsStream(CLST_PATH)) { if (input == null) { throw new JadxRuntimeException(""Can't load classpath file: "" + CLST_PATH); } load(input); } if (LOG.isDebugEnabled()) { long time = System.currentTimeMillis() - startTime; int methodsCount = Stream.of(classes).mapToInt(clspClass -> clspClass.getMethodsMap().size()).sum(); LOG.debug(""Clst file loaded in {}ms, android api: {}, classes: {}, methods: {}"", time, androidApiLevel, classes.length, methodsCount); } } public void loadFrom(RootNode root) { List list = root.getClasses(true); Map names = new HashMap<>(list.size()); int k = 0; for (ClassNode cls : list) { ArgType clsType = cls.getClassInfo().getType(); String clsRawName = clsType.getObject(); cls.load(); ClspClassSource source = getClspClassSource(cls); ClspClass nClass = new ClspClass(clsType, k, cls.getAccessFlags().rawValue(), source); if (names.put(clsRawName, nClass) != null) { throw new JadxRuntimeException(""Duplicate class: "" + clsRawName); } k++; nClass.setTypeParameters(cls.getGenericTypeParameters()); nClass.setMethods(getMethodsDetails(cls)); } classes = new ClspClass[k]; k = 0; for (ClassNode cls : list) { ClspClass nClass = getCls(cls, names); if (nClass == null) { throw new JadxRuntimeException(""Missing class: "" + cls); } nClass.setParents(makeParentsArray(cls)); classes[k] = nClass; k++; } } private static ClspClassSource getClspClassSource(ClassNode cls) { String inputFileName = cls.getClsData().getInputFileName(); int idx = inputFileName.indexOf(':'); String sourceFile = inputFileName.substring(0, idx); ClspClassSource source = ClspClassSource.getClspClassSource(sourceFile); if (source == ClspClassSource.APP) { throw new JadxRuntimeException(""Unexpected input file: "" + inputFileName); } return source; } private List getMethodsDetails(ClassNode cls) { List methodsList = cls.getMethods(); List methods = new ArrayList<>(methodsList.size()); for (MethodNode mth : methodsList) { processMethodDetails(mth, methods); } return methods; } private void processMethodDetails(MethodNode mth, List methods) { AccessInfo accessFlags = mth.getAccessFlags(); if (accessFlags.isPrivate() || accessFlags.isSynthetic() || accessFlags.isBridge()) { return; } ClspMethod clspMethod = new ClspMethod(mth.getMethodInfo(), mth.getArgTypes(), mth.getReturnType(), mth.getTypeParameters(), mth.getThrows(), accessFlags.rawValue()); methods.add(clspMethod); } public static ArgType[] makeParentsArray(ClassNode cls) { ArgType superClass = cls.getSuperClass(); if (superClass == null) { return EMPTY_ARGTYPE_ARRAY; } int interfacesCount = cls.getInterfaces().size(); if (interfacesCount == 0 && superClass == ArgType.OBJECT) { return OBJECT_ARGTYPE_ARRAY; } ArgType[] [MASK] = new ArgType[1 + interfacesCount]; [MASK][0] = superClass; int k = 1; for (ArgType iface : cls.getInterfaces()) { [MASK][k] = iface; k++; } return [MASK]; } private static ClspClass getCls(ClassNode cls, Map names) { return getCls(cls.getRawName(), names); } private static ClspClass getCls(ArgType clsType, Map names) { return getCls(clsType.getObject(), names); } private static ClspClass getCls(String fullName, Map names) { ClspClass cls = names.get(fullName); if (cls == null) { LOG.debug(""Class not found: {}"", fullName); } return cls; } public void save(Path path) throws IOException { FileUtils.makeDirsForFile(path); String outputName = path.getFileName().toString(); if (outputName.endsWith(CLST_EXTENSION)) { try (BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(path))) { save(outputStream); } } else { throw new JadxRuntimeException(""Unknown file format: "" + outputName); } } private void save(OutputStream output) throws IOException { DataOutputStream out = new DataOutputStream(output); out.writeBytes(JADX_CLS_SET_HEADER); out.writeByte(VERSION); out.writeInt(androidApiLevel); Map names = new HashMap<>(classes.length); out.writeInt(classes.length); for (ClspClass cls : classes) { out.writeInt(cls.getAccFlags()); writeUnsignedByte(out, cls.getSource().ordinal()); String clsName = cls.getName(); writeString(out, clsName); names.put(clsName, cls); } for (ClspClass cls : classes) { writeArgTypesArray(out, cls.getParents(), names); writeArgTypesList(out, cls.getTypeParameters(), names); List methods = cls.getSortedMethodsList(); out.writeShort(methods.size()); for (ClspMethod method : methods) { writeMethod(out, method, names); } } int methodsCount = Stream.of(classes).mapToInt(c -> c.getMethodsMap().size()).sum(); LOG.info(""Classes: {}, methods: {}, file size: {} bytes"", classes.length, methodsCount, out.size()); } private static void writeMethod(DataOutputStream out, ClspMethod method, Map names) throws IOException { MethodInfo methodInfo = method.getMethodInfo(); writeString(out, methodInfo.getName()); writeArgTypesList(out, methodInfo.getArgumentsTypes(), names); writeArgType(out, methodInfo.getReturnType(), names); writeArgTypesList(out, method.containsGenericArgs() ? method.getArgTypes() : Collections.emptyList(), names); writeArgType(out, method.getReturnType(), names); writeArgTypesList(out, method.getTypeParameters(), names); out.writeInt(method.getRawAccessFlags()); writeArgTypesList(out, method.getThrows(), names); } private static void writeArgTypesList(DataOutputStream out, List list, Map names) throws IOException { int size = list.size(); writeUnsignedByte(out, size); if (size != 0) { for (ArgType type : list) { writeArgType(out, type, names); } } } private static void writeArgTypesArray(DataOutputStream out, @Nullable ArgType[] arr, Map names) throws IOException { if (arr == null) { out.writeByte(-1); return; } if (arr == OBJECT_ARGTYPE_ARRAY) { out.writeByte(-2); return; } int size = arr.length; out.writeByte(size); if (size != 0) { for (ArgType type : arr) { writeArgType(out, type, names); } } } private static void writeArgType(DataOutputStream out, ArgType argType, Map names) throws IOException { if (argType == null) { out.writeByte(-1); return; } if (argType.isPrimitive()) { out.writeByte(TypeEnum.PRIMITIVE.ordinal()); out.writeByte(argType.getPrimitiveType().getShortName().charAt(0)); } else if (argType.getOuterType() != null) { out.writeByte(TypeEnum.OUTER_GENERIC.ordinal()); writeArgType(out, argType.getOuterType(), names); writeArgType(out, argType.getInnerType(), names); } else if (argType.getWildcardType() != null) { out.writeByte(TypeEnum.WILDCARD.ordinal()); ArgType.WildcardBound bound = argType.getWildcardBound(); out.writeByte(bound.getNum()); if (bound != ArgType.WildcardBound.UNBOUND) { writeArgType(out, argType.getWildcardType(), names); } } else if (argType.isGeneric()) { out.writeByte(TypeEnum.GENERIC.ordinal()); out.writeInt(getCls(argType, names).getId()); writeArgTypesList(out, argType.getGenericTypes(), names); } else if (argType.isGenericType()) { out.writeByte(TypeEnum.GENERIC_TYPE_VARIABLE.ordinal()); writeString(out, argType.getObject()); writeArgTypesList(out, argType.getExtendTypes(), names); } else if (argType.isObject()) { out.writeByte(TypeEnum.OBJECT.ordinal()); out.writeInt(getCls(argType, names).getId()); } else if (argType.isArray()) { out.writeByte(TypeEnum.ARRAY.ordinal()); writeArgType(out, argType.getArrayElement(), names); } else { throw new JadxRuntimeException(""Cannot save type: "" + argType); } } private void load(InputStream input) throws IOException, DecodeException { try (DataInputStream in = new DataInputStream(new BufferedInputStream(input))) { byte[] header = new byte[JADX_CLS_SET_HEADER.length()]; int readHeaderLength = in.read(header); if (readHeaderLength != JADX_CLS_SET_HEADER.length() || !JADX_CLS_SET_HEADER.equals(new String(header, STRING_CHARSET))) { throw new DecodeException(""Wrong jadx class set header""); } int version = in.readByte(); if (version != VERSION) { throw new DecodeException(""Wrong jadx class set version, got: "" + version + "", expect: "" + VERSION); } androidApiLevel = in.readInt(); int clsCount = in.readInt(); classes = new ClspClass[clsCount]; for (int i = 0; i < clsCount; i++) { int accFlags = in.readInt(); ClspClassSource clsSource = readClsSource(in); String name = readString(in); classes[i] = new ClspClass(ArgType.object(name), i, accFlags, clsSource); } for (int i = 0; i < clsCount; i++) { ClspClass nClass = classes[i]; ClassInfo clsInfo = ClassInfo.fromType(root, nClass.getClsType()); nClass.setParents(readArgTypesArray(in)); nClass.setTypeParameters(readArgTypesList(in)); nClass.setMethods(readClsMethods(in, clsInfo)); } } } private static ClspClassSource readClsSource(DataInputStream in) throws IOException, DecodeException { int source = readUnsignedByte(in); ClspClassSource[] clspClassSources = ClspClassSource.values(); if (source < 0 || source > clspClassSources.length) { throw new DecodeException(""Wrong jadx source identifier: "" + source); } return clspClassSources[source]; } private List readClsMethods(DataInputStream in, ClassInfo clsInfo) throws IOException { int mCount = in.readShort(); List methods = new ArrayList<>(mCount); for (int j = 0; j < mCount; j++) { methods.add(readMethod(in, clsInfo)); } return methods; } private ClspMethod readMethod(DataInputStream in, ClassInfo clsInfo) throws IOException { String name = readString(in); List argTypes = readArgTypesList(in); ArgType retType = readArgType(in); List genericArgTypes = readArgTypesList(in); if (genericArgTypes.isEmpty() || Objects.equals(genericArgTypes, argTypes)) { genericArgTypes = argTypes; } ArgType genericRetType = readArgType(in); if (Objects.equals(genericRetType, retType)) { genericRetType = retType; } List typeParameters = readArgTypesList(in); int accFlags = in.readInt(); List throwList = readArgTypesList(in); MethodInfo methodInfo = MethodInfo.fromDetails(root, clsInfo, name, argTypes, retType); return new ClspMethod(methodInfo, genericArgTypes, genericRetType, typeParameters, throwList, accFlags); } private List readArgTypesList(DataInputStream in) throws IOException { int count = in.readByte(); if (count == 0) { return Collections.emptyList(); } List list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add(readArgType(in)); } return list; } @Nullable private ArgType[] readArgTypesArray(DataInputStream in) throws IOException { int count = in.readByte(); switch (count) { case -1: return null; case -2: return OBJECT_ARGTYPE_ARRAY; case 0: return EMPTY_ARGTYPE_ARRAY; default: ArgType[] arr = new ArgType[count]; for (int i = 0; i < count; i++) { arr[i] = readArgType(in); } return arr; } } private ArgType readArgType(DataInputStream in) throws IOException { int ordinal = in.readByte(); if (ordinal == -1) { return null; } switch (TypeEnum.values()[ordinal]) { case WILDCARD: ArgType.WildcardBound bound = ArgType.WildcardBound.getByNum(in.readByte()); if (bound == ArgType.WildcardBound.UNBOUND) { return ArgType.WILDCARD; } ArgType objType = readArgType(in); return ArgType.wildcard(objType, bound); case OUTER_GENERIC: ArgType outerType = readArgType(in); ArgType innerType = readArgType(in); return ArgType.outerGeneric(outerType, innerType); case GENERIC: ArgType clsType = classes[in.readInt()].getClsType(); return ArgType.generic(clsType, readArgTypesList(in)); case GENERIC_TYPE_VARIABLE: String typeVar = readString(in); List extendTypes = readArgTypesList(in); return ArgType.genericType(typeVar, extendTypes); case OBJECT: return classes[in.readInt()].getClsType(); case ARRAY: return ArgType.array(Objects.requireNonNull(readArgType(in))); case PRIMITIVE: char shortName = (char) in.readByte(); return ArgType.parse(shortName); default: throw new JadxRuntimeException(""Unsupported Arg Type: "" + ordinal); } } private static void writeString(DataOutputStream out, String name) throws IOException { byte[] bytes = name.getBytes(STRING_CHARSET); int len = bytes.length; if (len >= 0xFF) { throw new JadxRuntimeException(""String is too long: "" + name); } writeUnsignedByte(out, bytes.length); out.write(bytes); } private static String readString(DataInputStream in) throws IOException { int len = readUnsignedByte(in); return readString(in, len); } private static String readString(DataInputStream in, int len) throws IOException { byte[] bytes = new byte[len]; int count = in.read(bytes); while (count != len) { int res = in.read(bytes, count, len - count); if (res == -1) { throw new IOException(""String read error""); } else { count += res; } } return new String(bytes, STRING_CHARSET); } private static void writeUnsignedByte(DataOutputStream out, int value) throws IOException { if (value < 0 || value >= 0xFF) { throw new JadxRuntimeException(""Unsigned byte value is too big: "" + value); } out.writeByte(value); } private static int readUnsignedByte(DataInputStream in) throws IOException { return ((int) in.readByte()) & 0xFF; } public int getClassesCount() { return classes.length; } public void addToMap(Map nameMap) { for (ClspClass cls : classes) { nameMap.put(cls.getName(), cls); } } public int getAndroidApiLevel() { return androidApiLevel; } public void setAndroidApiLevel(int androidApiLevel) { this.androidApiLevel = androidApiLevel; } }",parents,java,jadx "package org.apache.dubbo.metadata.definition.builder; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.util.ClassUtils; import org.apache.dubbo.metadata.definition.util.JaketConfigurationUtils; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import static org.apache.dubbo.common.utils.ClassUtils.isSimpleType; public final class DefaultTypeBuilder { public static TypeDefinition build(Class clazz, Map, TypeDefinition> typeCache) { final String name = clazz.getName(); TypeDefinition td = new TypeDefinition(name); if (typeCache.containsKey(clazz)) { return typeCache.get(clazz); } if (!JaketConfigurationUtils.needAnalyzing(clazz)) { return td; } TypeDefinition ref = new TypeDefinition(name); ref.set$ref(name); typeCache.put(clazz, ref); if(!clazz.isPrimitive() && !isSimpleType(clazz)){ List fields = ClassUtils.getNonStaticFields(clazz); for (Field field : fields) { String [MASK] = field.getName(); Class fieldClass = field.getType(); Type fieldType = field.getGenericType(); TypeDefinition fieldTd = TypeDefinitionBuilder.build(fieldType, fieldClass, typeCache); td.getProperties().put([MASK], fieldTd); } } typeCache.put(clazz, td); return td; } private DefaultTypeBuilder() { } }",fieldName,java,incubator-dubbo "package com.badlogic.gdx.physics.bullet.softbody; public class SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Anchor_t { private transient long swigCPtr; protected SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Anchor_t (long cPtr, @SuppressWarnings(""unused"") boolean [MASK]) { swigCPtr = cPtr; } protected SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Anchor_t () { swigCPtr = 0; } protected static long getCPtr (SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Anchor_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } }",futureUse,java,libgdx "package com.badlogic.gdx.physics.bullet.dynamics; import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.physics.bullet.collision.*; public class btMultiBodyJacobianData extends BulletBase { private long [MASK]; protected btMultiBodyJacobianData (final String className, long cPtr, boolean cMemoryOwn) { super(className, cPtr, cMemoryOwn); [MASK] = cPtr; } public btMultiBodyJacobianData (long cPtr, boolean cMemoryOwn) { this(""btMultiBodyJacobianData"", cPtr, cMemoryOwn); construct(); } @Override protected void reset (long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset([MASK] = cPtr, cMemoryOwn); } public static long getCPtr (btMultiBodyJacobianData obj) { return (obj == null) ? 0 : obj.[MASK]; } @Override protected void finalize () throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete () { if ([MASK] != 0) { if (swigCMemOwn) { swigCMemOwn = false; DynamicsJNI.delete_btMultiBodyJacobianData([MASK]); } [MASK] = 0; } super.delete(); } public void setJacobians (btScalarArray value) { DynamicsJNI.btMultiBodyJacobianData_jacobians_set([MASK], this, btScalarArray.getCPtr(value), value); } public btScalarArray getJacobians () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_jacobians_get([MASK], this); return (cPtr == 0) ? null : new btScalarArray(cPtr, false); } public void setDeltaVelocitiesUnitImpulse (btScalarArray value) { DynamicsJNI.btMultiBodyJacobianData_deltaVelocitiesUnitImpulse_set([MASK], this, btScalarArray.getCPtr(value), value); } public btScalarArray getDeltaVelocitiesUnitImpulse () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_deltaVelocitiesUnitImpulse_get([MASK], this); return (cPtr == 0) ? null : new btScalarArray(cPtr, false); } public void setDeltaVelocities (btScalarArray value) { DynamicsJNI.btMultiBodyJacobianData_deltaVelocities_set([MASK], this, btScalarArray.getCPtr(value), value); } public btScalarArray getDeltaVelocities () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_deltaVelocities_get([MASK], this); return (cPtr == 0) ? null : new btScalarArray(cPtr, false); } public void setScratch_r (btScalarArray value) { DynamicsJNI.btMultiBodyJacobianData_scratch_r_set([MASK], this, btScalarArray.getCPtr(value), value); } public btScalarArray getScratch_r () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_scratch_r_get([MASK], this); return (cPtr == 0) ? null : new btScalarArray(cPtr, false); } public void setScratch_v (btVector3Array value) { DynamicsJNI.btMultiBodyJacobianData_scratch_v_set([MASK], this, btVector3Array.getCPtr(value), value); } public btVector3Array getScratch_v () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_scratch_v_get([MASK], this); return (cPtr == 0) ? null : new btVector3Array(cPtr, false); } public void setScratch_m (SWIGTYPE_p_btAlignedObjectArrayT_btMatrix3x3_t value) { DynamicsJNI.btMultiBodyJacobianData_scratch_m_set([MASK], this, SWIGTYPE_p_btAlignedObjectArrayT_btMatrix3x3_t.getCPtr(value)); } public SWIGTYPE_p_btAlignedObjectArrayT_btMatrix3x3_t getScratch_m () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_scratch_m_get([MASK], this); return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btMatrix3x3_t(cPtr, false); } public void setSolverBodyPool (SWIGTYPE_p_btAlignedObjectArrayT_btSolverBody_t value) { DynamicsJNI.btMultiBodyJacobianData_solverBodyPool_set([MASK], this, SWIGTYPE_p_btAlignedObjectArrayT_btSolverBody_t.getCPtr(value)); } public SWIGTYPE_p_btAlignedObjectArrayT_btSolverBody_t getSolverBodyPool () { long cPtr = DynamicsJNI.btMultiBodyJacobianData_solverBodyPool_get([MASK], this); return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btSolverBody_t(cPtr, false); } public void setFixedBodyId (int value) { DynamicsJNI.btMultiBodyJacobianData_fixedBodyId_set([MASK], this, value); } public int getFixedBodyId () { return DynamicsJNI.btMultiBodyJacobianData_fixedBodyId_get([MASK], this); } public btMultiBodyJacobianData () { this(DynamicsJNI.new_btMultiBodyJacobianData(), true); } }",swigCPtr,java,libgdx "package jadx.core.codegen.json.mapping; public class JsonFieldMapping { private String name; private String [MASK]; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlias() { return [MASK]; } public void setAlias(String [MASK]) { this.[MASK] = [MASK]; } }",alias,java,jadx "package io.netty5.handler.ssl.util; import io.netty5.util.internal.EmptyArrays; import org.jetbrains.annotations.TestOnly; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import java.security.KeyStore; import java.security.cert.X509Certificate; @TestOnly public final class InsecureTrustManagerFactory extends SimpleTrustManagerFactory { private static final Logger logger = LoggerFactory.getLogger(InsecureTrustManagerFactory.class); public static final TrustManagerFactory INSTANCE = new InsecureTrustManagerFactory(); private static final TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String s) { if (logger.isDebugEnabled()) { logger.debug(""Accepting a client certificate: "" + chain[0].getSubjectDN()); } } @Override public void checkServerTrusted(X509Certificate[] chain, String s) { if (logger.isDebugEnabled()) { logger.debug(""Accepting a server certificate: "" + chain[0].getSubjectDN()); } } @Override public X509Certificate[] getAcceptedIssuers() { return EmptyArrays.EMPTY_X509_CERTIFICATES; } }; private InsecureTrustManagerFactory() { } @Override protected void engineInit(KeyStore [MASK]) throws Exception { } @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws Exception { } @Override protected TrustManager[] engineGetTrustManagers() { return new TrustManager[] { tm }; } }",keyStore,java,netty "package io.netty5.util.concurrent; import java.util.concurrent.TimeUnit; import static java.util.Objects.requireNonNull; enum SystemTicker implements Ticker { INSTANCE; static final long START_TIME = System.nanoTime(); @Override public long initialNanoTime() { return START_TIME; } @Override public long nanoTime() { return System.nanoTime() - START_TIME; } @Override public void sleep(long [MASK], TimeUnit unit) throws InterruptedException { requireNonNull(unit, ""unit""); unit.sleep([MASK]); } }",delay,java,netty "package com.alibaba.[MASK].bvt.issue_2700; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2743 extends TestCase { public void test_0() throws Exception { String [MASK] = ""{\""info\"":{\""com.xxx.service.xxxServiceForOrder@queryGoodsV2(Long,Long,Long)\"":[{\""method\"":\""queryPrepayGoodsV2\""}]}}""; Object obj = JSONPath.extract([MASK], ""$['info']['com.xxx.service.xxxServiceForOrder@queryGoodsV2(Long,Long,Long)']""); assertEquals(""[{\""method\"":\""queryPrepayGoodsV2\""}]"", obj.toString()); } public void test_1() throws Exception { String [MASK] = ""[10,11,12,13,14,15,16,17,18,19,20]""; Object obj = JSONPath.extract([MASK], ""$[3,4]""); assertEquals(""[13,14]"", obj.toString()); } }",json,java,fastjson "package com.netflix.hystrix.contrib.javanica.test.common.cache; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult; import com.netflix.hystrix.contrib.javanica.exception.HystrixCachingException; import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest; import com.netflix.hystrix.contrib.javanica.test.common.domain.Profile; import com.netflix.hystrix.contrib.javanica.test.common.domain.User; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import org.junit.Before; import org.junit.Test; import javax.annotation.PostConstruct; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getLastExecutedCommand; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public abstract class BasicCacheTest extends BasicHystrixTest { private UserService userService; @Before public void setUp() throws Exception { userService = createUserService(); } protected abstract UserService createUserService(); @Test public void testGetSetGetUserCache_givenTwoCommands() { User user = userService.getUserById(""1""); HystrixInvokableInfo [MASK] = getLastExecutedCommand(); assertFalse([MASK].isResponseFromCache()); assertEquals(""1"", user.getId()); assertEquals(""name"", user.getName()); user = userService.getUserById(""1""); assertEquals(""1"", user.getId()); [MASK] = getLastExecutedCommand(); assertTrue([MASK].isResponseFromCache()); assertEquals(""name"", user.getName()); user = new User(""1"", ""new_name""); userService.update(user); user = userService.getUserById(""1""); [MASK] = getLastExecutedCommand(); assertFalse([MASK].isResponseFromCache()); assertEquals(""1"", user.getId()); assertEquals(""new_name"", user.getName()); resetContext(); user = userService.getUserById(""1""); [MASK] = getLastExecutedCommand(); assertEquals(""1"", user.getId()); assertFalse([MASK].isResponseFromCache()); } @Test public void testGetSetGetUserCache_givenGetUserByEmailAndUpdateProfile() { User user = userService.getUserByEmail(""email""); HystrixInvokableInfo [MASK] = getLastExecutedCommand(); assertFalse([MASK].isResponseFromCache()); assertEquals(""1"", user.getId()); assertEquals(""name"", user.getName()); assertEquals(""email"", user.getProfile().getEmail()); user = userService.getUserByEmail(""email""); assertEquals(""1"", user.getId()); [MASK] = getLastExecutedCommand(); assertTrue([MASK].isResponseFromCache()); assertEquals(""email"", user.getProfile().getEmail()); Profile profile = new Profile(); profile.setEmail(""new_email""); user.setProfile(profile); userService.updateProfile(user); user = userService.getUserByEmail(""new_email""); [MASK] = getLastExecutedCommand(); assertFalse([MASK].isResponseFromCache()); assertEquals(""1"", user.getId()); assertEquals(""name"", user.getName()); assertEquals(""new_email"", user.getProfile().getEmail()); resetContext(); user = userService.getUserByEmail(""new_email""); [MASK] = getLastExecutedCommand(); assertEquals(""1"", user.getId()); assertFalse([MASK].isResponseFromCache()); } @Test public void testGetSetGetUserCache_givenOneCommandAndOneMethodAnnotatedWithCacheRemove() { User user = userService.getUserById(""1""); HystrixInvokableInfo [MASK] = getLastExecutedCommand(); assertFalse([MASK].isResponseFromCache()); assertEquals(""1"", user.getId()); assertEquals(""name"", user.getName()); user = userService.getUserById(""1""); assertEquals(""1"", user.getId()); [MASK] = getLastExecutedCommand(); assertTrue([MASK].isResponseFromCache()); assertEquals(""name"", user.getName()); userService.updateName(""1"", ""new_name""); user = userService.getUserById(""1""); [MASK] = getLastExecutedCommand(); assertFalse([MASK].isResponseFromCache()); assertEquals(""1"", user.getId()); assertEquals(""new_name"", user.getName()); resetContext(); user = userService.getUserById(""1""); [MASK] = getLastExecutedCommand(); assertEquals(""1"", user.getId()); assertFalse([MASK].isResponseFromCache()); } @Test(expected = HystrixCachingException.class) public void testGetUser_givenWrongCacheKeyMethodReturnType_shouldThrowException() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { User user = userService.getUserByName(""name""); } finally { context.shutdown(); } } @Test(expected = HystrixCachingException.class) public void testGetUserByName_givenNonexistentCacheKeyMethod_shouldThrowException() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { User user = userService.getUser(); } finally { context.shutdown(); } } public static class UserService { private Map storage = new ConcurrentHashMap(); @PostConstruct public void init() { User user = new User(""1"", ""name""); Profile profile = new Profile(); profile.setEmail(""email""); user.setProfile(profile); storage.put(""1"", user); } @CacheResult @HystrixCommand public User getUserById(@CacheKey String id) { return storage.get(id); } @CacheResult(cacheKeyMethod = ""getUserByNameCacheKey"") @HystrixCommand public User getUserByName(String name) { return null; } private Long getUserByNameCacheKey() { return 0L; } @CacheResult(cacheKeyMethod = ""nonexistent"") @HystrixCommand public User getUser() { return null; } @CacheResult(cacheKeyMethod = ""getUserByEmailCacheKey"") @HystrixCommand public User getUserByEmail(final String email) { return Iterables.tryFind(storage.values(), new Predicate() { @Override public boolean apply(User input) { return input.getProfile().getEmail().equalsIgnoreCase(email); } }).orNull(); } private String getUserByEmailCacheKey(String email) { return email; } @CacheRemove(commandKey = ""getUserById"") @HystrixCommand public void update(@CacheKey(""id"") User user) { storage.put(user.getId(), user); } @CacheRemove(commandKey = ""getUserByEmail"") @HystrixCommand public void updateProfile(@CacheKey(""profile.email"") User user) { storage.get(user.getId()).setProfile(user.getProfile()); } @CacheRemove(commandKey = ""getUserById"") public void updateName(@CacheKey String id, String name) { storage.get(id).setName(name); } } }",getUserByIdCommand,java,Hystrix "package org.apache.dubbo.registry.client.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.Protocol; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import static java.lang.Boolean.TRUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_KEY; public class RestProtocolSubscribedURLsSynthesizer implements SubscribedURLsSynthesizer { @Override public boolean supports(URL subscribedURL) { return ""rest"".equals(subscribedURL.getProtocol()) || ""rest"".equals(subscribedURL.getParameter(PROTOCOL_KEY)); } @Override public List synthesize(URL subscribedURL, Collection serviceInstances) { String [MASK] = subscribedURL.getParameter(PROTOCOL_KEY); return serviceInstances.stream().map(serviceInstance -> { URLBuilder urlBuilder = new URLBuilder() .setProtocol([MASK]) .setHost(serviceInstance.getHost()) .setPort(serviceInstance.getPort()) .setPath(subscribedURL.getServiceInterface()) .addParameter(SIDE_KEY, PROVIDER) .addParameter(APPLICATION_KEY, serviceInstance.getServiceName()) .addParameter(REGISTER_KEY, TRUE.toString()); return urlBuilder.build(); }).collect(Collectors.toList()); } }",protocol,java,incubator-dubbo "package org.apache.dubbo.common.serialize.java; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static org.apache.dubbo.common.serialize.Constants.COMPACTED_JAVA_SERIALIZATION_ID; public class CompactedJavaSerialization implements Serialization { @Override public byte getContentTypeId() { return COMPACTED_JAVA_SERIALIZATION_ID; } @Override public String getContentType() { return ""x-application/compactedjava""; } @Override public ObjectOutput serialize(URL url, OutputStream [MASK]) throws IOException { return new JavaObjectOutput([MASK], true); } @Override public ObjectInput deserialize(URL url, InputStream is) throws IOException { return new JavaObjectInput(is, true); } }",out,java,incubator-dubbo "package io.netty5.handler.codec.http2; import io.netty5.buffer.Buffer; import io.netty5.buffer.BufferAllocator; import io.netty5.channel.ChannelHandlerContext; import io.netty5.handler.codec.http.DefaultFullHttpRequest; import io.netty5.handler.codec.http.FullHttpMessage; import io.netty5.handler.codec.http.FullHttpRequest; import io.netty5.handler.codec.http.FullHttpResponse; import io.netty5.handler.codec.http.HttpHeaderNames; import io.netty5.handler.codec.http.HttpStatusClass; import io.netty5.handler.codec.http.HttpUtil; import io.netty5.handler.codec.http.headers.HttpHeadersFactory; import io.netty5.handler.codec.http2.headers.Http2Headers; import io.netty5.util.internal.UnstableApi; import static io.netty5.handler.codec.http.HttpResponseStatus.OK; import static io.netty5.handler.codec.http2.Http2Error.INTERNAL_ERROR; import static io.netty5.handler.codec.http2.Http2Error.PROTOCOL_ERROR; import static io.netty5.handler.codec.http2.Http2Exception.connectionError; import static io.netty5.util.internal.ObjectUtil.checkPositive; import static java.util.Objects.requireNonNull; @UnstableApi public class InboundHttp2ToHttpAdapter extends Http2EventAdapter { private static final ImmediateSendDetector DEFAULT_SEND_DETECTOR = new ImmediateSendDetector() { @Override public boolean mustSendImmediately(FullHttpMessage msg) { if (msg instanceof FullHttpResponse) { return ((FullHttpResponse) msg).status().codeClass() == HttpStatusClass.INFORMATIONAL; } if (msg instanceof FullHttpRequest) { return msg.headers().contains(HttpHeaderNames.EXPECT); } return false; } @Override public FullHttpMessage copyIfNeeded(BufferAllocator allocator, FullHttpMessage msg) { if (msg instanceof FullHttpRequest) { final FullHttpRequest original = (FullHttpRequest) msg; FullHttpRequest copy = new DefaultFullHttpRequest(original.protocolVersion(), original.method(), original.uri(), allocator.allocate(0), original.headers(), original.trailingHeaders()); copy.headers().remove(HttpHeaderNames.EXPECT); return copy; } return null; } }; private final int maxContentLength; private final ImmediateSendDetector sendDetector; private final Http2Connection.PropertyKey messageKey; private final boolean propagateSettings; protected final Http2Connection connection; protected final HttpHeadersFactory headersFactory; protected final HttpHeadersFactory trailersFactory; protected InboundHttp2ToHttpAdapter( Http2Connection connection, int maxContentLength, boolean propagateSettings, HttpHeadersFactory headersFactory, HttpHeadersFactory trailersFactory) { requireNonNull(connection, ""connection""); this.connection = connection; this.maxContentLength = checkPositive(maxContentLength, ""maxContentLength""); this.propagateSettings = propagateSettings; this.headersFactory = headersFactory; this.trailersFactory = trailersFactory; sendDetector = DEFAULT_SEND_DETECTOR; messageKey = connection.newKey(); } protected final void removeMessage(Http2Stream stream, boolean release) { FullHttpMessage msg = stream.removeProperty(messageKey); if (release && msg != null) { msg.close(); } } protected final FullHttpMessage getMessage(Http2Stream stream) { return stream.getProperty(messageKey); } protected final void putMessage(Http2Stream stream, FullHttpMessage message) { FullHttpMessage previous = stream.setProperty(messageKey, message); if (previous != message && previous != null) { previous.close(); } } @Override public void onStreamRemoved(Http2Stream stream) { removeMessage(stream, true); } protected void fireChannelRead(ChannelHandlerContext ctx, FullHttpMessage msg, boolean release, Http2Stream stream) { removeMessage(stream, release); HttpUtil.setContentLength(msg, msg.payload().readableBytes()); ctx.fireChannelRead(msg); } protected FullHttpMessage newMessage( Http2Stream stream, Http2Headers headers, BufferAllocator alloc, HttpHeadersFactory headersFactory, HttpHeadersFactory trailersFactory) throws Http2Exception { if (connection.isServer()) { return HttpConversionUtil.toFullHttpRequest(stream.id(), headers, alloc, headersFactory, trailersFactory); } return HttpConversionUtil.toFullHttpResponse(stream.id(), headers, alloc, headersFactory, trailersFactory); } protected FullHttpMessage processHeadersBegin(ChannelHandlerContext ctx, Http2Stream stream, Http2Headers headers, boolean endOfStream, boolean allowAppend, boolean appendToTrailer) throws Http2Exception { FullHttpMessage msg = getMessage(stream); boolean release = true; if (msg == null) { msg = newMessage(stream, headers, ctx.bufferAllocator(), headersFactory, trailersFactory); } else if (allowAppend) { release = false; HttpConversionUtil.addHttp2ToHttpHeaders(stream.id(), headers, msg, appendToTrailer); } else { release = false; msg = null; } if (sendDetector.mustSendImmediately(msg)) { final FullHttpMessage copy = endOfStream ? null : sendDetector.copyIfNeeded(ctx.bufferAllocator(), msg); fireChannelRead(ctx, msg, release, stream); return copy; } return msg; } private void processHeadersEnd(ChannelHandlerContext ctx, Http2Stream stream, FullHttpMessage msg, boolean endOfStream) { if (endOfStream) { fireChannelRead(ctx, msg, getMessage(stream) != msg, stream); } else { putMessage(stream, msg); } } @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, Buffer data, int padding, boolean endOfStream) throws Http2Exception { Http2Stream stream = connection.stream(streamId); FullHttpMessage msg = getMessage(stream); if (msg == null) { throw connectionError(PROTOCOL_ERROR, ""Data Frame received for unknown stream id %d"", streamId); } Buffer content = msg.payload(); final int dataReadableBytes = data.readableBytes(); if (content.readableBytes() > maxContentLength - dataReadableBytes) { throw connectionError(INTERNAL_ERROR, ""Content length exceeded max of %d for stream id %d"", maxContentLength, streamId); } content.ensureWritable(dataReadableBytes); content.writeBytes(data); if (endOfStream) { fireChannelRead(ctx, msg, false, stream); } return dataReadableBytes + padding; } @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) throws Http2Exception { Http2Stream stream = connection.stream(streamId); FullHttpMessage msg = processHeadersBegin(ctx, stream, headers, endOfStream, true, true); if (msg != null) { processHeadersEnd(ctx, stream, msg, endOfStream); } } @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception { Http2Stream stream = connection.stream(streamId); FullHttpMessage msg = processHeadersBegin(ctx, stream, headers, endOfStream, true, true); if (msg != null) { if (streamDependency != Http2CodecUtil.CONNECTION_STREAM_ID) { msg.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), String.valueOf(streamDependency)); } msg.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), String.valueOf(weight)); processHeadersEnd(ctx, stream, msg, endOfStream); } } @Override public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long [MASK]) throws Http2Exception { Http2Stream stream = connection.stream(streamId); FullHttpMessage msg = getMessage(stream); if (msg != null) { onRstStreamRead(stream, msg); } ctx.fireChannelExceptionCaught(Http2Exception.streamError(streamId, Http2Error.valueOf([MASK]), ""HTTP/2 to HTTP layer caught stream reset"")); } @Override public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception { Http2Stream promisedStream = connection.stream(promisedStreamId); if (headers.status() == null) { headers.status(OK.codeAsText()); } FullHttpMessage msg = processHeadersBegin(ctx, promisedStream, headers, false, false, false); if (msg == null) { throw connectionError(PROTOCOL_ERROR, ""Push Promise Frame received for pre-existing stream id %d"", promisedStreamId); } msg.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_PROMISE_ID.text(), String.valueOf(streamId)); msg.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), String.valueOf(Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT)); processHeadersEnd(ctx, promisedStream, msg, false); } @Override public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception { if (propagateSettings) { ctx.fireChannelRead(settings); } } protected void onRstStreamRead(Http2Stream stream, FullHttpMessage msg) { removeMessage(stream, true); } private interface ImmediateSendDetector { boolean mustSendImmediately(FullHttpMessage msg); FullHttpMessage copyIfNeeded(BufferAllocator allocator, FullHttpMessage msg); } }",errorCode,java,netty "package com.alibaba.json.bvt.issue_1500; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.List; public class Issue1570_private extends TestCase { public void test_for_issue() throws Exception { Model [MASK] = new Model(); assertEquals(""{}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullBooleanAsFalse)); assertEquals(""{\""value\"":\""\""}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullStringAsEmpty)); } public void test_for_issue_int() throws Exception { ModelInt [MASK] = new ModelInt(); assertEquals(""{}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullBooleanAsFalse)); assertEquals(""{\""value\"":0}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullNumberAsZero)); } public void test_for_issue_long() throws Exception { ModelLong [MASK] = new ModelLong(); assertEquals(""{}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullBooleanAsFalse)); assertEquals(""{\""value\"":0}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullNumberAsZero)); } public void test_for_issue_bool() throws Exception { ModelBool [MASK] = new ModelBool(); assertEquals(""{}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullNumberAsZero)); assertEquals(""{\""value\"":false}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullBooleanAsFalse)); } public void test_for_issue_list() throws Exception { ModelList [MASK] = new ModelList(); assertEquals(""{}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullNumberAsZero)); assertEquals(""{\""value\"":[]}"", JSON.toJSONString([MASK], SerializerFeature.WriteNullListAsEmpty)); } private static class Model { public String value; } private static class ModelInt { public Integer value; } private static class ModelLong { public Long value; } private static class ModelBool { public Boolean value; } private static class ModelList { public List value; } }",model,java,fastjson "package jadx.gui.utils.fileswatcher; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.Utils; import static java.nio.file.LinkOption.NOFOLLOW_LINKS; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import static java.nio.file.StandardWatchEventKinds.OVERFLOW; public class FilesWatcher { private static final Logger LOG = LoggerFactory.getLogger(FilesWatcher.class); private final WatchService watcher = FileSystems.getDefault().newWatchService(); private final Map keys = new HashMap<>(); private final Map> [MASK] = new HashMap<>(); private final AtomicBoolean cancel = new AtomicBoolean(false); private final BiConsumer> listener; public FilesWatcher(List paths, BiConsumer> listener) throws IOException { this.listener = listener; for (Path path : paths) { if (Files.isDirectory(path, NOFOLLOW_LINKS)) { registerDirs(path); } else { Path parentDir = path.toAbsolutePath().getParent(); register(parentDir); [MASK].merge(parentDir, Collections.singleton(path), Utils::mergeSets); } } } public void cancel() { cancel.set(true); } @SuppressWarnings(""unchecked"") public void watch() { cancel.set(false); LOG.debug(""File watcher started for {} dirs"", keys.size()); while (!cancel.get()) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException e) { LOG.debug(""File watcher interrupted""); return; } Path dir = keys.get(key); if (dir == null) { LOG.warn(""Unknown directory key: {}"", key); continue; } for (WatchEvent event : key.pollEvents()) { if (cancel.get() || Thread.interrupted()) { return; } WatchEvent.Kind kind = event.kind(); if (kind == OVERFLOW) { continue; } Path fileName = ((WatchEvent) event).context(); Path path = dir.resolve(fileName); Set [MASK] = this.[MASK].get(dir); if ([MASK] == null || [MASK].contains(path)) { listener.accept(path, (WatchEvent.Kind) kind); } if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(path, NOFOLLOW_LINKS)) { registerDirs(path); } } catch (Exception e) { LOG.warn(""Failed to update directory watch: {}"", path, e); } } } boolean valid = key.reset(); if (!valid) { keys.remove(key); if (keys.isEmpty()) { LOG.debug(""File watcher stopped: all watch keys removed""); return; } } } } private void registerDirs(Path start) throws IOException { Files.walkFileTree(start, new SimpleFileVisitor() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { register(dir); return FileVisitResult.CONTINUE; } }); } private void register(Path dir) throws IOException { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); keys.put(key, dir); } }",files,java,jadx "package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.maps.tiled.TideMapLoader; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.OrthoCamController; import com.badlogic.gdx.utils.ScreenUtils; public class TideMapAssetManagerTest extends GdxTest { private TiledMap map; private TiledMapRenderer [MASK]; private OrthographicCamera camera; private OrthoCamController cameraController; private AssetManager assetManager; private BitmapFont font; private SpriteBatch batch; @Override public void create () { float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); camera = new OrthographicCamera(); camera.setToOrtho(false, (w / h) * 10, 10); camera.zoom = 2; camera.update(); cameraController = new OrthoCamController(camera); Gdx.input.setInputProcessor(cameraController); font = new BitmapFont(); batch = new SpriteBatch(); assetManager = new AssetManager(); assetManager.setLoader(TiledMap.class, new TideMapLoader(new InternalFileHandleResolver())); assetManager.load(""data/maps/tide/Map01.tide"", TiledMap.class); assetManager.finishLoading(); map = assetManager.get(""data/maps/tide/Map01.tide""); [MASK] = new OrthogonalTiledMapRenderer(map, 1f / 32f); } @Override public void render () { ScreenUtils.clear(0.55f, 0.55f, 0.55f, 1f); camera.update(); [MASK].setView(camera); [MASK].render(); batch.begin(); font.draw(batch, ""FPS: "" + Gdx.graphics.getFramesPerSecond(), 10, 20); batch.end(); } }",renderer,java,libgdx "package org.apache.dubbo.config.spring.util; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.spring.[MASK].factory.annotation.DubboConfigAliasPostProcessor; import org.apache.dubbo.config.spring.[MASK].factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.[MASK].factory.config.DubboConfigDefaultPropertyValueBeanPostProcessor; import org.apache.dubbo.config.spring.[MASK].factory.config.DubboConfigEarlyRegistrationPostProcessor; import org.apache.dubbo.config.spring.context.DubboApplicationListenerRegistrar; import org.apache.dubbo.config.spring.context.DubboBootstrapApplicationListener; import org.apache.dubbo.config.spring.context.DubboLifecycleComponentApplicationListener; import org.springframework.[MASK].BeansException; import org.springframework.[MASK].factory.BeanFactoryUtils; import org.springframework.[MASK].factory.BeanNotOfRequiredTypeException; import org.springframework.[MASK].factory.ListableBeanFactory; import org.springframework.[MASK].factory.NoSuchBeanDefinitionException; import org.springframework.[MASK].factory.NoUniqueBeanDefinitionException; import org.springframework.[MASK].factory.support.BeanDefinitionRegistry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.alibaba.spring.util.BeanRegistrar.registerInfrastructureBean; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.springframework.util.ObjectUtils.isEmpty; public abstract class DubboBeanUtils { private static final Logger logger = LoggerFactory.getLogger(DubboBeanUtils.class); public static void registerCommonBeans(BeanDefinitionRegistry registry) { registerInfrastructureBean(registry, ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); registerInfrastructureBean(registry, DubboConfigAliasPostProcessor.BEAN_NAME, DubboConfigAliasPostProcessor.class); registerInfrastructureBean(registry, DubboApplicationListenerRegistrar.BEAN_NAME, DubboApplicationListenerRegistrar.class); registerInfrastructureBean(registry, DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME, DubboConfigDefaultPropertyValueBeanPostProcessor.class); registerInfrastructureBean(registry, DubboConfigEarlyRegistrationPostProcessor.BEAN_NAME, DubboConfigEarlyRegistrationPostProcessor.class); } public static T getOptionalBean(ListableBeanFactory beanFactory, String beanName, Class beanType) throws BeansException { if (beanName == null) { return getOptionalBeanByType(beanFactory, beanType); } T bean = null; try { bean = beanFactory.getBean(beanName, beanType); } catch (NoSuchBeanDefinitionException e) { } catch (BeanNotOfRequiredTypeException e) { logger.warn(String.format(""bean type not match, name: %s, expected type: %s, actual type: %s"", beanName, beanType.getName(), e.getActualType().getName())); } return bean; } private static T getOptionalBeanByType(ListableBeanFactory beanFactory, Class beanType) { String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, beanType, true, false); if (beanNames == null || beanNames.length == 0) { return null; } else if (beanNames.length > 1) { throw new NoUniqueBeanDefinitionException(beanType, Arrays.asList(beanNames)); } return (T) beanFactory.getBean(beanNames[0]); } public static T getBean(ListableBeanFactory beanFactory, String beanName, Class beanType) throws BeansException { return beanFactory.getBean(beanName, beanType); } public static List getBeans(ListableBeanFactory beanFactory, String[] beanNames, Class beanType) throws BeansException { if (isEmpty(beanNames)) { return emptyList(); } List [MASK] = new ArrayList(beanNames.length); for (String beanName : beanNames) { T bean = getBean(beanFactory, beanName, beanType); if (bean != null) { [MASK].add(bean); } } return unmodifiableList([MASK]); } }",beans,java,incubator-dubbo "package com.badlogic.gdx.utils; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import static com.badlogic.gdx.utils.ObjectSet.tableSize; public class IntIntMap implements Iterable { public int size; int[] keyTable; int[] valueTable; int zeroValue; boolean hasZeroValue; private final float loadFactor; private int threshold; protected int [MASK]; protected int mask; private transient Entries entries1, entries2; private transient Values values1, values2; private transient Keys keys1, keys2; public IntIntMap () { this(51, 0.8f); } public IntIntMap (int initialCapacity) { this(initialCapacity, 0.8f); } public IntIntMap (int initialCapacity, float loadFactor) { if (loadFactor <= 0f || loadFactor >= 1f) throw new IllegalArgumentException(""loadFactor must be > 0 and < 1: "" + loadFactor); this.loadFactor = loadFactor; int tableSize = tableSize(initialCapacity, loadFactor); threshold = (int)(tableSize * loadFactor); mask = tableSize - 1; [MASK] = Long.numberOfLeadingZeros(mask); keyTable = new int[tableSize]; valueTable = new int[tableSize]; } public IntIntMap (IntIntMap map) { this((int)(map.keyTable.length * map.loadFactor), map.loadFactor); System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length); System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length); size = map.size; zeroValue = map.zeroValue; hasZeroValue = map.hasZeroValue; } protected int place (int item) { return (int)(item * 0x9E3779B97F4A7C15L >>> [MASK]); } private int locateKey (int key) { int[] keyTable = this.keyTable; for (int i = place(key);; i = i + 1 & mask) { int other = keyTable[i]; if (other == 0) return -(i + 1); if (other == key) return i; } } public void put (int key, int value) { if (key == 0) { zeroValue = value; if (!hasZeroValue) { hasZeroValue = true; size++; } return; } int i = locateKey(key); if (i >= 0) { valueTable[i] = value; return; } i = -(i + 1); keyTable[i] = key; valueTable[i] = value; if (++size >= threshold) resize(keyTable.length << 1); } public int put (int key, int value, int defaultValue) { if (key == 0) { int oldValue = zeroValue; zeroValue = value; if (!hasZeroValue) { hasZeroValue = true; size++; return defaultValue; } return oldValue; } int i = locateKey(key); if (i >= 0) { int oldValue = valueTable[i]; valueTable[i] = value; return oldValue; } i = -(i + 1); keyTable[i] = key; valueTable[i] = value; if (++size >= threshold) resize(keyTable.length << 1); return defaultValue; } public void putAll (IntIntMap map) { ensureCapacity(map.size); if (map.hasZeroValue) put(0, map.zeroValue); int[] keyTable = map.keyTable; int[] valueTable = map.valueTable; for (int i = 0, n = keyTable.length; i < n; i++) { int key = keyTable[i]; if (key != 0) put(key, valueTable[i]); } } private void putResize (int key, int value) { int[] keyTable = this.keyTable; for (int i = place(key);; i = (i + 1) & mask) { if (keyTable[i] == 0) { keyTable[i] = key; valueTable[i] = value; return; } } } public int get (int key, int defaultValue) { if (key == 0) return hasZeroValue ? zeroValue : defaultValue; int i = locateKey(key); return i >= 0 ? valueTable[i] : defaultValue; } public int getAndIncrement (int key, int defaultValue, int increment) { if (key == 0) { if (!hasZeroValue) { hasZeroValue = true; zeroValue = defaultValue + increment; size++; return defaultValue; } int oldValue = zeroValue; zeroValue += increment; return oldValue; } int i = locateKey(key); if (i >= 0) { int oldValue = valueTable[i]; valueTable[i] += increment; return oldValue; } i = -(i + 1); keyTable[i] = key; valueTable[i] = defaultValue + increment; if (++size >= threshold) resize(keyTable.length << 1); return defaultValue; } public int remove (int key, int defaultValue) { if (key == 0) { if (!hasZeroValue) return defaultValue; hasZeroValue = false; size--; return zeroValue; } int i = locateKey(key); if (i < 0) return defaultValue; int[] keyTable = this.keyTable; int[] valueTable = this.valueTable; int oldValue = valueTable[i], mask = this.mask, next = i + 1 & mask; while ((key = keyTable[next]) != 0) { int placement = place(key); if ((next - placement & mask) > (i - placement & mask)) { keyTable[i] = key; valueTable[i] = valueTable[next]; i = next; } next = next + 1 & mask; } keyTable[i] = 0; size--; return oldValue; } public boolean notEmpty () { return size > 0; } public boolean isEmpty () { return size == 0; } public void shrink (int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException(""maximumCapacity must be >= 0: "" + maximumCapacity); int tableSize = tableSize(maximumCapacity, loadFactor); if (keyTable.length > tableSize) resize(tableSize); } public void clear (int maximumCapacity) { int tableSize = tableSize(maximumCapacity, loadFactor); if (keyTable.length <= tableSize) { clear(); return; } size = 0; hasZeroValue = false; resize(tableSize); } public void clear () { if (size == 0) return; Arrays.fill(keyTable, 0); size = 0; hasZeroValue = false; } public boolean containsValue (int value) { if (hasZeroValue && zeroValue == value) return true; int[] keyTable = this.keyTable; int[] valueTable = this.valueTable; for (int i = valueTable.length - 1; i >= 0; i--) if (keyTable[i] != 0 && valueTable[i] == value) return true; return false; } public boolean containsKey (int key) { if (key == 0) return hasZeroValue; return locateKey(key) >= 0; } public int findKey (int value, int notFound) { if (hasZeroValue && zeroValue == value) return 0; int[] keyTable = this.keyTable; int[] valueTable = this.valueTable; for (int i = valueTable.length - 1; i >= 0; i--) { int key = keyTable[i]; if (key != 0 && valueTable[i] == value) return key; } return notFound; } public void ensureCapacity (int additionalCapacity) { int tableSize = tableSize(size + additionalCapacity, loadFactor); if (keyTable.length < tableSize) resize(tableSize); } private void resize (int newSize) { int oldCapacity = keyTable.length; threshold = (int)(newSize * loadFactor); mask = newSize - 1; [MASK] = Long.numberOfLeadingZeros(mask); int[] oldKeyTable = keyTable; int[] oldValueTable = valueTable; keyTable = new int[newSize]; valueTable = new int[newSize]; if (size > 0) { for (int i = 0; i < oldCapacity; i++) { int key = oldKeyTable[i]; if (key != 0) putResize(key, oldValueTable[i]); } } } public int hashCode () { int h = size; if (hasZeroValue) h += zeroValue; int[] keyTable = this.keyTable; int[] valueTable = this.valueTable; for (int i = 0, n = keyTable.length; i < n; i++) { int key = keyTable[i]; if (key != 0) h += key * 31 + valueTable[i]; } return h; } public boolean equals (Object obj) { if (obj == this) return true; if (!(obj instanceof IntIntMap)) return false; IntIntMap other = (IntIntMap)obj; if (other.size != size) return false; if (other.hasZeroValue != hasZeroValue) return false; if (hasZeroValue) { if (other.zeroValue != zeroValue) return false; } int[] keyTable = this.keyTable; int[] valueTable = this.valueTable; for (int i = 0, n = keyTable.length; i < n; i++) { int key = keyTable[i]; if (key != 0) { int otherValue = other.get(key, 0); if (otherValue == 0 && !other.containsKey(key)) return false; if (otherValue != valueTable[i]) return false; } } return true; } public String toString () { if (size == 0) return ""[]""; java.lang.StringBuilder buffer = new java.lang.StringBuilder(32); buffer.append('['); int[] keyTable = this.keyTable; int[] valueTable = this.valueTable; int i = keyTable.length; if (hasZeroValue) { buffer.append(""0=""); buffer.append(zeroValue); } else { while (i-- > 0) { int key = keyTable[i]; if (key == 0) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } } while (i-- > 0) { int key = keyTable[i]; if (key == 0) continue; buffer.append("", ""); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append(']'); return buffer.toString(); } public Iterator iterator () { return entries(); } public Entries entries () { if (Collections.allocateIterators) return new Entries(this); if (entries1 == null) { entries1 = new Entries(this); entries2 = new Entries(this); } if (!entries1.valid) { entries1.reset(); entries1.valid = true; entries2.valid = false; return entries1; } entries2.reset(); entries2.valid = true; entries1.valid = false; return entries2; } public Values values () { if (Collections.allocateIterators) return new Values(this); if (values1 == null) { values1 = new Values(this); values2 = new Values(this); } if (!values1.valid) { values1.reset(); values1.valid = true; values2.valid = false; return values1; } values2.reset(); values2.valid = true; values1.valid = false; return values2; } public Keys keys () { if (Collections.allocateIterators) return new Keys(this); if (keys1 == null) { keys1 = new Keys(this); keys2 = new Keys(this); } if (!keys1.valid) { keys1.reset(); keys1.valid = true; keys2.valid = false; return keys1; } keys2.reset(); keys2.valid = true; keys1.valid = false; return keys2; } static public class Entry { public int key; public int value; public String toString () { return key + ""="" + value; } } static private class MapIterator { static private final int INDEX_ILLEGAL = -2; static final int INDEX_ZERO = -1; public boolean hasNext; final IntIntMap map; int nextIndex, currentIndex; boolean valid = true; public MapIterator (IntIntMap map) { this.map = map; reset(); } public void reset () { currentIndex = INDEX_ILLEGAL; nextIndex = INDEX_ZERO; if (map.hasZeroValue) hasNext = true; else findNextIndex(); } void findNextIndex () { int[] keyTable = map.keyTable; for (int n = keyTable.length; ++nextIndex < n;) { if (keyTable[nextIndex] != 0) { hasNext = true; return; } } hasNext = false; } public void remove () { int i = currentIndex; if (i == INDEX_ZERO && map.hasZeroValue) { map.hasZeroValue = false; } else if (i < 0) { throw new IllegalStateException(""next must be called before remove.""); } else { int[] keyTable = map.keyTable; int[] valueTable = map.valueTable; int mask = map.mask, next = i + 1 & mask, key; while ((key = keyTable[next]) != 0) { int placement = map.place(key); if ((next - placement & mask) > (i - placement & mask)) { keyTable[i] = key; valueTable[i] = valueTable[next]; i = next; } next = next + 1 & mask; } keyTable[i] = 0; if (i != currentIndex) --nextIndex; } currentIndex = INDEX_ILLEGAL; map.size--; } } static public class Entries extends MapIterator implements Iterable, Iterator { private final Entry entry = new Entry(); public Entries (IntIntMap map) { super(map); } public Entry next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException(""#iterator() cannot be used nested.""); int[] keyTable = map.keyTable; if (nextIndex == INDEX_ZERO) { entry.key = 0; entry.value = map.zeroValue; } else { entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; } currentIndex = nextIndex; findNextIndex(); return entry; } public boolean hasNext () { if (!valid) throw new GdxRuntimeException(""#iterator() cannot be used nested.""); return hasNext; } public Iterator iterator () { return this; } } static public class Values extends MapIterator { public Values (IntIntMap map) { super(map); } public boolean hasNext () { if (!valid) throw new GdxRuntimeException(""#iterator() cannot be used nested.""); return hasNext; } public int next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException(""#iterator() cannot be used nested.""); int value = nextIndex == INDEX_ZERO ? map.zeroValue : map.valueTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return value; } public Values iterator () { return this; } public IntArray toArray () { IntArray array = new IntArray(true, map.size); while (hasNext) array.add(next()); return array; } public IntArray toArray (IntArray array) { while (hasNext) array.add(next()); return array; } } static public class Keys extends MapIterator { public Keys (IntIntMap map) { super(map); } public int next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException(""#iterator() cannot be used nested.""); int key = nextIndex == INDEX_ZERO ? 0 : map.keyTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return key; } public IntArray toArray () { IntArray array = new IntArray(true, map.size); while (hasNext) array.add(next()); return array; } public IntArray toArray (IntArray array) { while (hasNext) array.add(next()); return array; } } }",shift,java,libgdx "package com.facebook.imagepipeline.animated.base; import android.graphics.Bitmap; import com.facebook.common.references.CloseableReference; import com.facebook.imagepipeline.transformation.BitmapTransformation; import com.facebook.infer.annotation.Nullsafe; import java.util.List; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) public class AnimatedImageResultBuilder { private final AnimatedImage mImage; private @Nullable CloseableReference mPreviewBitmap; private @Nullable List> mDecodedFrames; private int mFrameForPreview; private @Nullable BitmapTransformation [MASK]; private @Nullable String mSource; AnimatedImageResultBuilder(AnimatedImage image) { mImage = image; } public AnimatedImage getImage() { return mImage; } public @Nullable CloseableReference getPreviewBitmap() { return CloseableReference.cloneOrNull(mPreviewBitmap); } public AnimatedImageResultBuilder setPreviewBitmap( @Nullable CloseableReference previewBitmap) { mPreviewBitmap = CloseableReference.cloneOrNull(previewBitmap); return this; } public int getFrameForPreview() { return mFrameForPreview; } public AnimatedImageResultBuilder setFrameForPreview(int frameForPreview) { mFrameForPreview = frameForPreview; return this; } public @Nullable List> getDecodedFrames() { return CloseableReference.cloneOrNull(mDecodedFrames); } @Nullable public String getSource() { return mSource; } public AnimatedImageResultBuilder setDecodedFrames( @Nullable List> decodedFrames) { mDecodedFrames = CloseableReference.cloneOrNull(decodedFrames); return this; } @Nullable public BitmapTransformation getBitmapTransformation() { return [MASK]; } public AnimatedImageResultBuilder setBitmapTransformation( @Nullable BitmapTransformation bitmapTransformation) { [MASK] = bitmapTransformation; return this; } public AnimatedImageResultBuilder setSource(@Nullable String source) { mSource = source; return this; } public AnimatedImageResult build() { try { return new AnimatedImageResult(this); } finally { CloseableReference.closeSafely(mPreviewBitmap); mPreviewBitmap = null; CloseableReference.closeSafely(mDecodedFrames); mDecodedFrames = null; } } }",mBitmapTransformation,java,fresco "package com.alibaba.[MASK].bvt.jdk8; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.Optional; public class OptionalTest4 extends TestCase { public void test_for_issue() throws Exception { JsonResult result = new JsonResult(); result.a = Optional.empty(); result.b = Optional.empty(); String [MASK] = JSON.toJSONString(result); System.out.println([MASK]); } public static class JsonResult { public Object a; public Optional b; } }",json,java,fastjson "package com.facebook.webpsupport; import android.annotation.SuppressLint; import android.content.[MASK].Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import com.facebook.common.internal.DoNotStrip; import com.facebook.common.webp.BitmapCreator; import com.facebook.common.webp.WebpBitmapFactory; import com.facebook.imagepipeline.nativecode.StaticWebpNativeLoader; import com.facebook.infer.annotation.Nullsafe; import java.io.BufferedInputStream; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.LOCAL) @DoNotStrip public class WebpBitmapFactoryImpl implements WebpBitmapFactory { private static final int HEADER_SIZE = 20; private static final int IN_TEMP_BUFFER_SIZE = 8 * 1024; private static WebpErrorLogger mWebpErrorLogger; private static BitmapCreator mBitmapCreator; @Override public void setBitmapCreator(final BitmapCreator bitmapCreator) { mBitmapCreator = bitmapCreator; } private static InputStream wrapToMarkSupportedStream(InputStream inputStream) { if (!inputStream.markSupported()) { inputStream = new BufferedInputStream(inputStream, HEADER_SIZE); } return inputStream; } private static @Nullable byte[] getWebpHeader( InputStream inputStream, @Nullable BitmapFactory.Options opts) { inputStream.mark(HEADER_SIZE); byte[] header; if (opts != null && opts.inTempStorage != null && opts.inTempStorage.length >= HEADER_SIZE) { header = opts.inTempStorage; } else { header = new byte[HEADER_SIZE]; } try { inputStream.read(header, 0, HEADER_SIZE); inputStream.reset(); } catch (IOException exp) { return null; } return header; } private static void setDensityFromOptions( @Nullable Bitmap outputBitmap, @Nullable BitmapFactory.Options opts) { if (outputBitmap == null || opts == null) { return; } final int density = opts.inDensity; if (density != 0) { outputBitmap.setDensity(density); final int targetDensity = opts.inTargetDensity; if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) { return; } if (opts.inScaled) { outputBitmap.setDensity(targetDensity); } } else if (opts.inBitmap != null) { outputBitmap.setDensity(DisplayMetrics.DENSITY_DEFAULT); } } @Override public void setWebpErrorLogger(WebpBitmapFactory.WebpErrorLogger webpErrorLogger) { mWebpErrorLogger = webpErrorLogger; } @Override @Nullable public Bitmap decodeFileDescriptor( FileDescriptor fd, @Nullable Rect outPadding, @Nullable BitmapFactory.Options opts) { return hookDecodeFileDescriptor(fd, outPadding, opts); } @Override @Nullable public Bitmap decodeStream( InputStream inputStream, @Nullable Rect outPadding, @Nullable BitmapFactory.Options opts) { return hookDecodeStream(inputStream, outPadding, opts); } @Override @Nullable public Bitmap decodeFile(String pathName, @Nullable BitmapFactory.Options opts) { return hookDecodeFile(pathName, opts); } @Override @Nullable public Bitmap decodeByteArray( byte[] array, int offset, int length, @Nullable BitmapFactory.Options opts) { return hookDecodeByteArray(array, offset, length, opts); } @DoNotStrip @Nullable public static Bitmap hookDecodeByteArray( byte[] array, int offset, int length, @Nullable BitmapFactory.Options opts) { StaticWebpNativeLoader.ensure(); Bitmap bitmap = originalDecodeByteArray(array, offset, length, opts); if (bitmap == null) { sendWebpErrorLog(""webp_direct_decode_array_failed_on_no_webp""); } return bitmap; } @DoNotStrip @Nullable private static Bitmap originalDecodeByteArray( byte[] array, int offset, int length, @Nullable BitmapFactory.Options opts) { return BitmapFactory.decodeByteArray(array, offset, length, opts); } @DoNotStrip @Nullable public static Bitmap hookDecodeByteArray(byte[] array, int offset, int length) { return hookDecodeByteArray(array, offset, length, null); } @DoNotStrip @Nullable private static Bitmap originalDecodeByteArray(byte[] array, int offset, int length) { return BitmapFactory.decodeByteArray(array, offset, length); } @DoNotStrip @Nullable public static Bitmap hookDecodeStream( InputStream inputStream, @Nullable Rect outPadding, @Nullable BitmapFactory.Options opts) { StaticWebpNativeLoader.ensure(); inputStream = wrapToMarkSupportedStream(inputStream); Bitmap bitmap; bitmap = originalDecodeStream(inputStream, outPadding, opts); if (bitmap == null) { sendWebpErrorLog(""webp_direct_decode_stream_failed_on_no_webp""); } return bitmap; } @DoNotStrip @Nullable private static Bitmap originalDecodeStream( InputStream inputStream, @Nullable Rect outPadding, @Nullable BitmapFactory.Options opts) { return BitmapFactory.decodeStream(inputStream, outPadding, opts); } @DoNotStrip @Nullable public static Bitmap hookDecodeStream(InputStream inputStream) { return hookDecodeStream(inputStream, null, null); } @Nullable @DoNotStrip private static Bitmap originalDecodeStream(InputStream inputStream) { return BitmapFactory.decodeStream(inputStream); } @DoNotStrip public static @Nullable Bitmap hookDecodeFile( String pathName, @Nullable BitmapFactory.Options opts) { Bitmap bitmap = null; try (InputStream stream = new FileInputStream(pathName)) { bitmap = hookDecodeStream(stream, null, opts); } catch (Exception e) { } return bitmap; } @DoNotStrip @Nullable public static Bitmap hookDecodeFile(String pathName) { return hookDecodeFile(pathName, null); } @DoNotStrip @Nullable public static Bitmap hookDecodeResourceStream( @Nullable Resources [MASK], @Nullable TypedValue value, InputStream is, @Nullable Rect pad, @Nullable BitmapFactory.Options opts) { if (opts == null) { opts = new BitmapFactory.Options(); } if (opts.inDensity == 0 && value != null) { final int density = value.density; if (density == TypedValue.DENSITY_DEFAULT) { opts.inDensity = DisplayMetrics.DENSITY_DEFAULT; } else if (density != TypedValue.DENSITY_NONE) { opts.inDensity = density; } } if (opts.inTargetDensity == 0 && [MASK] != null) { opts.inTargetDensity = [MASK].getDisplayMetrics().densityDpi; } return hookDecodeStream(is, pad, opts); } @DoNotStrip @Nullable private static Bitmap originalDecodeResourceStream( Resources [MASK], TypedValue value, InputStream is, Rect pad, BitmapFactory.Options opts) { return BitmapFactory.decodeResourceStream([MASK], value, is, pad, opts); } @DoNotStrip public static @Nullable Bitmap hookDecodeResource( Resources [MASK], int id, @Nullable BitmapFactory.Options opts) { Bitmap bm = null; TypedValue value = new TypedValue(); try (InputStream is = [MASK].openRawResource(id, value)) { bm = hookDecodeResourceStream([MASK], value, is, null, opts); } catch (Exception e) { } if (bm == null && opts != null && opts.inBitmap != null) { throw new IllegalArgumentException(""Problem decoding into existing bitmap""); } return bm; } @DoNotStrip @Nullable private static Bitmap originalDecodeResource(Resources [MASK], int id, BitmapFactory.Options opts) { return BitmapFactory.decodeResource([MASK], id, opts); } @DoNotStrip @Nullable public static Bitmap hookDecodeResource(Resources [MASK], int id) { return hookDecodeResource([MASK], id, null); } @DoNotStrip @Nullable private static Bitmap originalDecodeResource(Resources [MASK], int id) { return BitmapFactory.decodeResource([MASK], id); } @DoNotStrip private static boolean setOutDimensions( @Nullable BitmapFactory.Options options, int imageWidth, int imageHeight) { if (options != null && options.inJustDecodeBounds) { options.outWidth = imageWidth; options.outHeight = imageHeight; return true; } return false; } @DoNotStrip private static void setPaddingDefaultValues(@Nullable Rect padding) { if (padding != null) { padding.top = -1; padding.left = -1; padding.bottom = -1; padding.right = -1; } } @DoNotStrip private static void setBitmapSize( @Nullable BitmapFactory.Options options, int width, int height) { if (options != null) { options.outWidth = width; options.outHeight = height; } } @DoNotStrip @Nullable private static Bitmap originalDecodeFile(String pathName, @Nullable BitmapFactory.Options opts) { return BitmapFactory.decodeFile(pathName, opts); } @DoNotStrip @Nullable private static Bitmap originalDecodeFile(String pathName) { return BitmapFactory.decodeFile(pathName); } @DoNotStrip @Nullable public static Bitmap hookDecodeFileDescriptor( FileDescriptor fd, @Nullable Rect outPadding, @Nullable BitmapFactory.Options opts) { StaticWebpNativeLoader.ensure(); Bitmap bitmap; long originalSeekPosition = nativeSeek(fd, 0, false); if (originalSeekPosition != -1) { InputStream inputStream = wrapToMarkSupportedStream(new FileInputStream(fd)); try { byte[] header = getWebpHeader(inputStream, opts); nativeSeek(fd, originalSeekPosition, true); bitmap = originalDecodeFileDescriptor(fd, outPadding, opts); if (bitmap == null) { sendWebpErrorLog(""webp_direct_decode_fd_failed_on_no_webp""); } } finally { try { inputStream.close(); } catch (Throwable t) { } } } else { bitmap = hookDecodeStream(new FileInputStream(fd), outPadding, opts); setPaddingDefaultValues(outPadding); } return bitmap; } @DoNotStrip @Nullable private static Bitmap originalDecodeFileDescriptor( FileDescriptor fd, @Nullable Rect outPadding, @Nullable BitmapFactory.Options opts) { return BitmapFactory.decodeFileDescriptor(fd, outPadding, opts); } @DoNotStrip @Nullable public static Bitmap hookDecodeFileDescriptor(FileDescriptor fd) { return hookDecodeFileDescriptor(fd, null, null); } @DoNotStrip @Nullable private static Bitmap originalDecodeFileDescriptor(FileDescriptor fd) { return BitmapFactory.decodeFileDescriptor(fd); } private static void setWebpBitmapOptions( @Nullable Bitmap bitmap, @Nullable BitmapFactory.Options opts) { setDensityFromOptions(bitmap, opts); if (opts != null) { opts.outMimeType = ""image/webp""; } } @DoNotStrip @SuppressLint(""NewApi"") private static boolean shouldPremultiply(@Nullable BitmapFactory.Options options) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && options != null) { return options.inPremultiplied; } return true; } @DoNotStrip @Nullable private static Bitmap createBitmap( int width, int height, @Nullable BitmapFactory.Options options) { if (options != null && options.inBitmap != null && options.inBitmap.isMutable()) { return options.inBitmap; } return mBitmapCreator.createNakedBitmap(width, height, Bitmap.Config.ARGB_8888); } @DoNotStrip @Nullable private static native Bitmap nativeDecodeStream( InputStream is, @Nullable BitmapFactory.Options options, float scale, byte[] inTempStorage); @DoNotStrip @Nullable private static native Bitmap nativeDecodeByteArray( byte[] data, int offset, int length, @Nullable BitmapFactory.Options opts, float scale, byte[] inTempStorage); @DoNotStrip private static native long nativeSeek(FileDescriptor fd, long offset, boolean absolute); @DoNotStrip private static byte[] getInTempStorageFromOptions(@Nullable final BitmapFactory.Options options) { if (options != null && options.inTempStorage != null) { return options.inTempStorage; } else { return new byte[IN_TEMP_BUFFER_SIZE]; } } @DoNotStrip private static float getScaleFromOptions(@Nullable BitmapFactory.Options options) { float scale = 1.0f; if (options != null) { int sampleSize = options.inSampleSize; if (sampleSize > 1) { scale = 1.0f / (float) sampleSize; } if (options.inScaled) { int density = options.inDensity; int targetDensity = options.inTargetDensity; int screenDensity = options.inScreenDensity; if (density != 0 && targetDensity != 0 && density != screenDensity) { scale = targetDensity / (float) density; } } } return scale; } private static void sendWebpErrorLog(String message) { if (mWebpErrorLogger != null) { mWebpErrorLogger.onWebpErrorLog(message, ""decoding_failure""); } } }",res,java,fresco "package com.alibaba.dubbo.registry.support; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.Registry; import java.util.List; import java.util.stream.Collectors; @Deprecated public abstract class FailbackRegistry implements org.apache.dubbo.registry.Registry, Registry { private CompatibleFailbackRegistry failbackRegistry; public FailbackRegistry(URL url) { failbackRegistry = new CompatibleFailbackRegistry(url.getOriginalURL(), this); } public void removeFailedRegisteredTask(URL url) { failbackRegistry.removeFailedRegisteredTask(url.getOriginalURL()); } public void removeFailedUnregisteredTask(URL url) { failbackRegistry.removeFailedUnregisteredTask(url.getOriginalURL()); } public void removeFailedSubscribedTask(URL url, NotifyListener listener) { failbackRegistry.removeFailedSubscribedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) { failbackRegistry.removeFailedUnsubscribedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override public void register(URL url) { failbackRegistry.register(url.getOriginalURL()); } @Override public void unregister(URL url) { failbackRegistry.unregister(url.getOriginalURL()); } @Override public void subscribe(URL url, NotifyListener listener) { failbackRegistry.subscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { failbackRegistry.unsubscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } protected void notify(URL url, NotifyListener listener, List urls) { List [MASK] = urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); failbackRegistry.notify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), [MASK]); } protected void doNotify(URL url, NotifyListener listener, List urls) { List [MASK] = urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); failbackRegistry.doNotify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), [MASK]); } protected void recover() throws Exception { failbackRegistry.recover(); } @Override public List lookup(URL url) { return failbackRegistry.lookup(url.getOriginalURL()).stream().map(e -> new URL(e)).collect(Collectors.toList()); } @Override public URL getUrl() { return new URL(failbackRegistry.getUrl()); } @Override public void destroy() { failbackRegistry.destroy(); } public abstract void doRegister(URL url); public abstract void doUnregister(URL url); public abstract void doSubscribe(URL url, NotifyListener listener); public abstract void doUnsubscribe(URL url, NotifyListener listener); @Override public void register(org.apache.dubbo.common.URL url) { this.register(new URL(url)); } @Override public void unregister(org.apache.dubbo.common.URL url) { this.unregister(new URL(url)); } @Override public void subscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.subscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void unsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.unsubscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public List lookup(org.apache.dubbo.common.URL url) { return failbackRegistry.lookup(url); } static class CompatibleFailbackRegistry extends org.apache.dubbo.registry.support.FailbackRegistry { private FailbackRegistry compatibleFailbackRegistry; public CompatibleFailbackRegistry(org.apache.dubbo.common.URL url, FailbackRegistry compatibleFailbackRegistry) { super(url); this.compatibleFailbackRegistry = compatibleFailbackRegistry; } @Override public void doRegister(org.apache.dubbo.common.URL url) { this.compatibleFailbackRegistry.doRegister(new URL(url)); } @Override public void doUnregister(org.apache.dubbo.common.URL url) { this.compatibleFailbackRegistry.doUnregister(new URL(url)); } @Override public void doSubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.compatibleFailbackRegistry.doSubscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void doUnsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.compatibleFailbackRegistry.doUnsubscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void notify(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List urls) { super.notify(url, listener, urls); } @Override public void doNotify(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List urls) { super.doNotify(url, listener, urls); } @Override public boolean isAvailable() { return false; } @Override public void recover() throws Exception { super.recover(); } } }",urlResult,java,incubator-dubbo "package com.alibaba.json.bvt.writeAsArray; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class WriteAsArray_string_special extends TestCase { public void test_0() throws Exception { Model model = new Model(); model.name = ""a\\bc""; String text = JSON.toJSONString(model, SerializerFeature.BeanToArray); Assert.assertEquals(""[\""a\\\\bc\""]"", text); Model [MASK] = JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); Assert.assertEquals(model.name, [MASK].name); } public void test_1() throws Exception { Model model = new Model(); model.name = ""a\\bc\""""; String text = JSON.toJSONString(model, SerializerFeature.BeanToArray); Assert.assertEquals(""[\""a\\\\bc\\\""\""]"", text); Model [MASK] = JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); Assert.assertEquals(model.name, [MASK].name); } public static class Model { public String name; } }",model2,java,fastjson "package io.netty5.channel.uring; import io.netty5.bootstrap.Bootstrap; import io.netty5.bootstrap.ServerBootstrap; import io.netty5.channel.EventLoopGroup; import io.netty5.channel.nio.NioIoHandler; import io.netty5.testsuite.transport.TestsuitePermutation; import io.netty5.testsuite.transport.socket.SocketMultipleConnectTest; import org.junit.jupiter.api.BeforeAll; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assumptions.assumeTrue; public class IOUringSocketMultipleConnectTest extends SocketMultipleConnectTest { @BeforeAll public static void loadJNI() { assumeTrue(IOUring.isAvailable()); } @Override protected List> newFactories() { List> [MASK] = new ArrayList<>(); for (var comboFactory : IOUringSocketTestPermutation.INSTANCE.socket()) { EventLoopGroup group = comboFactory.newClientInstance().config().group(); if (group.isIoType(NioIoHandler.class) || group.isIoType(IOUringIoHandler.class)) { [MASK].add(comboFactory); } } return [MASK]; } }",factories,java,netty "package com.alibaba.json.bvt.serializer.date; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.junit.Assert; import java.util.Date; public class DateTest4 extends TestCase { public void test_date() throws Exception { assertNotNull( JSON.parseObject( ""{\""[MASK]\"":\""1970-01-01 00:00:00\""}"" , VO.class) .[MASK] ); assertNotNull( JSON.parseObject( ""{\""[MASK]\"":\""1970-01-01 00:00:00.000\""}"" , VO.class) .[MASK] ); assertNotNull( JSON.parseObject( ""{\""[MASK]\"":\""1960-01-01 00:00:00.000\""}"" , VO.class) .[MASK] ); } public static class VO { public Date [MASK]; } }",gmtCreate,java,fastjson "package io.netty5.handler.codec; import io.netty5.buffer.BufferUtil; import io.netty5.buffer.Buffer; import io.netty5.channel.ChannelHandlerContext; import java.nio.ByteOrder; import java.util.List; import static io.netty5.util.internal.ObjectUtil.checkPositiveOrZero; import static java.util.Objects.requireNonNull; public class LengthFieldPrepender extends MessageToMessageEncoder { private final ByteOrder byteOrder; private final int [MASK]; private final boolean lengthIncludesLengthFieldLength; private final int lengthAdjustment; public LengthFieldPrepender(int [MASK]) { this([MASK], false); } public LengthFieldPrepender(int [MASK], boolean lengthIncludesLengthFieldLength) { this([MASK], 0, lengthIncludesLengthFieldLength); } public LengthFieldPrepender(int [MASK], int lengthAdjustment) { this([MASK], lengthAdjustment, false); } public LengthFieldPrepender(int [MASK], int lengthAdjustment, boolean lengthIncludesLengthFieldLength) { this(ByteOrder.BIG_ENDIAN, [MASK], lengthAdjustment, lengthIncludesLengthFieldLength); } public LengthFieldPrepender( ByteOrder byteOrder, int [MASK], int lengthAdjustment, boolean lengthIncludesLengthFieldLength) { requireNonNull(byteOrder, ""byteOrder""); this.byteOrder = byteOrder; this.[MASK] = [MASK]; this.lengthIncludesLengthFieldLength = lengthIncludesLengthFieldLength; this.lengthAdjustment = lengthAdjustment; } @Override public boolean isSharable() { return true; } @Override protected void encode(ChannelHandlerContext ctx, Buffer buffer, List out) throws Exception { int length = buffer.readableBytes() + lengthAdjustment; if (lengthIncludesLengthFieldLength) { length += [MASK]; } checkPositiveOrZero(length, ""length""); out.add(getLengthFieldBuffer(ctx, length, [MASK], byteOrder)); out.add(buffer.split()); } protected Buffer getLengthFieldBuffer( ChannelHandlerContext ctx, int length, int [MASK], ByteOrder byteOrder) { final boolean reverseBytes = byteOrder == ByteOrder.LITTLE_ENDIAN; switch ([MASK]) { case 1: if (length >= 256) { throw new IllegalArgumentException(""length does not fit into a byte: "" + length); } return ctx.bufferAllocator().allocate([MASK]).writeByte((byte) length); case 2: if (length >= 65536) { throw new IllegalArgumentException(""length does not fit into a short integer: "" + length); } return ctx.bufferAllocator().allocate([MASK]) .writeShort(reverseBytes ? Short.reverseBytes((short) length) : (short) length); case 3: if (length >= 16777216) { throw new IllegalArgumentException(""length does not fit into a medium integer: "" + length); } return ctx.bufferAllocator().allocate([MASK]) .writeMedium(reverseBytes ? BufferUtil.reverseMedium(length) : length); case 4: return ctx.bufferAllocator().allocate([MASK]) .writeInt(reverseBytes ? Integer.reverseBytes(length) : length); case 8: return ctx.bufferAllocator().allocate([MASK]) .writeLong(reverseBytes ? Long.reverseBytes(length) : length); default: throw new EncoderException( ""unsupported [MASK]: "" + [MASK] + "" (expected: 1, 2, 3, 4, or 8)""); } } }",lengthFieldLength,java,netty "package org.apache.dubbo.config.event.listener; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.event.DubboServiceDestroyedEvent; import org.apache.dubbo.config.event.ServiceConfigExportedEvent; import org.apache.dubbo.event.Event; import org.apache.dubbo.event.GenericEventListener; import static java.lang.String.format; public class LoggingEventListener extends GenericEventListener { private static final String NAME = ""Dubbo Service""; private final Logger logger = LoggerFactory.getLogger(getClass()); public void onEvent(DubboServiceDestroyedEvent event) { if (logger.isInfoEnabled()) { logger.info(NAME + "" has been destroyed.""); } } private void debug(String [MASK], Object... args) { if (logger.isDebugEnabled()) { logger.debug(format([MASK], args)); } } }",pattern,java,incubator-dubbo "package jadx.plugins.input.java.data.attributes.types; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.attributes.types.MethodParametersAttr; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class JavaMethodParametersAttr extends MethodParametersAttr implements IJavaAttribute { public JavaMethodParametersAttr(List list) { super(list); } public static IJavaAttributeReader reader() { return (clsData, reader) -> { ConstPoolReader constPool = clsData.getConstPoolReader(); int count = reader.readU1(); List params = new ArrayList<>(count); for (int i = 0; i < count; i++) { String name = constPool.getUtf8(reader.readU2()); int [MASK] = reader.readU2(); params.add(new Info([MASK], name)); } return new JavaMethodParametersAttr(params); }; } }",accessFlags,java,jadx "package com.badlogic.gdx.math; import java.io.Serializable; import com.badlogic.gdx.utils.GdxRuntimeException; public final class Affine2 implements Serializable { private static final long serialVersionUID = 1524569123485049187L; public float m00 = 1, m01 = 0, m02 = 0; public float m10 = 0, m11 = 1, m12 = 0; public Affine2 () { } public Affine2 (Affine2 other) { set(other); } public Affine2 idt () { m00 = 1; m01 = 0; m02 = 0; m10 = 0; m11 = 1; m12 = 0; return this; } public Affine2 set (Affine2 other) { m00 = other.m00; m01 = other.m01; m02 = other.m02; m10 = other.m10; m11 = other.m11; m12 = other.m12; return this; } public Affine2 set (Matrix3 matrix) { float[] other = matrix.val; m00 = other[Matrix3.M00]; m01 = other[Matrix3.M01]; m02 = other[Matrix3.M02]; m10 = other[Matrix3.M10]; m11 = other[Matrix3.M11]; m12 = other[Matrix3.M12]; return this; } public Affine2 set (Matrix4 matrix) { float[] other = matrix.val; m00 = other[Matrix4.M00]; m01 = other[Matrix4.M01]; m02 = other[Matrix4.M03]; m10 = other[Matrix4.M10]; m11 = other[Matrix4.M11]; m12 = other[Matrix4.M13]; return this; } public Affine2 setToTranslation (float x, float y) { m00 = 1; m01 = 0; m02 = x; m10 = 0; m11 = 1; m12 = y; return this; } public Affine2 setToTranslation (Vector2 trn) { return setToTranslation(trn.x, trn.y); } public Affine2 setToScaling (float scaleX, float scaleY) { m00 = scaleX; m01 = 0; m02 = 0; m10 = 0; m11 = scaleY; m12 = 0; return this; } public Affine2 setToScaling (Vector2 scale) { return setToScaling(scale.x, scale.y); } public Affine2 setToRotation (float degrees) { float cos = MathUtils.cosDeg(degrees); float sin = MathUtils.sinDeg(degrees); m00 = cos; m01 = -sin; m02 = 0; m10 = sin; m11 = cos; m12 = 0; return this; } public Affine2 setToRotationRad (float radians) { float cos = MathUtils.cos(radians); float sin = MathUtils.sin(radians); m00 = cos; m01 = -sin; m02 = 0; m10 = sin; m11 = cos; m12 = 0; return this; } public Affine2 setToRotation (float cos, float sin) { m00 = cos; m01 = -sin; m02 = 0; m10 = sin; m11 = cos; m12 = 0; return this; } public Affine2 setToShearing (float shearX, float shearY) { m00 = 1; m01 = shearX; m02 = 0; m10 = shearY; m11 = 1; m12 = 0; return this; } public Affine2 setToShearing (Vector2 shear) { return setToShearing(shear.x, shear.y); } public Affine2 setToTrnRotScl (float x, float y, float degrees, float scaleX, float scaleY) { m02 = x; m12 = y; if (degrees == 0) { m00 = scaleX; m01 = 0; m10 = 0; m11 = scaleY; } else { float sin = MathUtils.sinDeg(degrees); float cos = MathUtils.cosDeg(degrees); m00 = cos * scaleX; m01 = -sin * scaleY; m10 = sin * scaleX; m11 = cos * scaleY; } return this; } public Affine2 setToTrnRotScl (Vector2 trn, float degrees, Vector2 scale) { return setToTrnRotScl(trn.x, trn.y, degrees, scale.x, scale.y); } public Affine2 setToTrnRotRadScl (float x, float y, float radians, float scaleX, float scaleY) { m02 = x; m12 = y; if (radians == 0) { m00 = scaleX; m01 = 0; m10 = 0; m11 = scaleY; } else { float sin = MathUtils.sin(radians); float cos = MathUtils.cos(radians); m00 = cos * scaleX; m01 = -sin * scaleY; m10 = sin * scaleX; m11 = cos * scaleY; } return this; } public Affine2 setToTrnRotRadScl (Vector2 trn, float radians, Vector2 scale) { return setToTrnRotRadScl(trn.x, trn.y, radians, scale.x, scale.y); } public Affine2 setToTrnScl (float x, float y, float scaleX, float scaleY) { m00 = scaleX; m01 = 0; m02 = x; m10 = 0; m11 = scaleY; m12 = y; return this; } public Affine2 setToTrnScl (Vector2 trn, Vector2 scale) { return setToTrnScl(trn.x, trn.y, scale.x, scale.y); } public Affine2 setToProduct (Affine2 l, Affine2 r) { m00 = l.m00 * r.m00 + l.m01 * r.m10; m01 = l.m00 * r.m01 + l.m01 * r.m11; m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02; m10 = l.m10 * r.m00 + l.m11 * r.m10; m11 = l.m10 * r.m01 + l.m11 * r.m11; m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12; return this; } public Affine2 inv () { float det = det(); if (det == 0) throw new GdxRuntimeException(""Can't invert a singular affine matrix""); float invDet = 1.0f / det; float tmp00 = m11; float tmp01 = -m01; float tmp02 = m01 * m12 - m11 * m02; float tmp10 = -m10; float [MASK] = m00; float tmp12 = m10 * m02 - m00 * m12; m00 = invDet * tmp00; m01 = invDet * tmp01; m02 = invDet * tmp02; m10 = invDet * tmp10; m11 = invDet * [MASK]; m12 = invDet * tmp12; return this; } public Affine2 mul (Affine2 other) { float tmp00 = m00 * other.m00 + m01 * other.m10; float tmp01 = m00 * other.m01 + m01 * other.m11; float tmp02 = m00 * other.m02 + m01 * other.m12 + m02; float tmp10 = m10 * other.m00 + m11 * other.m10; float [MASK] = m10 * other.m01 + m11 * other.m11; float tmp12 = m10 * other.m02 + m11 * other.m12 + m12; m00 = tmp00; m01 = tmp01; m02 = tmp02; m10 = tmp10; m11 = [MASK]; m12 = tmp12; return this; } public Affine2 preMul (Affine2 other) { float tmp00 = other.m00 * m00 + other.m01 * m10; float tmp01 = other.m00 * m01 + other.m01 * m11; float tmp02 = other.m00 * m02 + other.m01 * m12 + other.m02; float tmp10 = other.m10 * m00 + other.m11 * m10; float [MASK] = other.m10 * m01 + other.m11 * m11; float tmp12 = other.m10 * m02 + other.m11 * m12 + other.m12; m00 = tmp00; m01 = tmp01; m02 = tmp02; m10 = tmp10; m11 = [MASK]; m12 = tmp12; return this; } public Affine2 translate (float x, float y) { m02 += m00 * x + m01 * y; m12 += m10 * x + m11 * y; return this; } public Affine2 translate (Vector2 trn) { return translate(trn.x, trn.y); } public Affine2 preTranslate (float x, float y) { m02 += x; m12 += y; return this; } public Affine2 preTranslate (Vector2 trn) { return preTranslate(trn.x, trn.y); } public Affine2 scale (float scaleX, float scaleY) { m00 *= scaleX; m01 *= scaleY; m10 *= scaleX; m11 *= scaleY; return this; } public Affine2 scale (Vector2 scale) { return scale(scale.x, scale.y); } public Affine2 preScale (float scaleX, float scaleY) { m00 *= scaleX; m01 *= scaleX; m02 *= scaleX; m10 *= scaleY; m11 *= scaleY; m12 *= scaleY; return this; } public Affine2 preScale (Vector2 scale) { return preScale(scale.x, scale.y); } public Affine2 rotate (float degrees) { if (degrees == 0) return this; float cos = MathUtils.cosDeg(degrees); float sin = MathUtils.sinDeg(degrees); float tmp00 = m00 * cos + m01 * sin; float tmp01 = m00 * -sin + m01 * cos; float tmp10 = m10 * cos + m11 * sin; float [MASK] = m10 * -sin + m11 * cos; m00 = tmp00; m01 = tmp01; m10 = tmp10; m11 = [MASK]; return this; } public Affine2 rotateRad (float radians) { if (radians == 0) return this; float cos = MathUtils.cos(radians); float sin = MathUtils.sin(radians); float tmp00 = m00 * cos + m01 * sin; float tmp01 = m00 * -sin + m01 * cos; float tmp10 = m10 * cos + m11 * sin; float [MASK] = m10 * -sin + m11 * cos; m00 = tmp00; m01 = tmp01; m10 = tmp10; m11 = [MASK]; return this; } public Affine2 preRotate (float degrees) { if (degrees == 0) return this; float cos = MathUtils.cosDeg(degrees); float sin = MathUtils.sinDeg(degrees); float tmp00 = cos * m00 - sin * m10; float tmp01 = cos * m01 - sin * m11; float tmp02 = cos * m02 - sin * m12; float tmp10 = sin * m00 + cos * m10; float [MASK] = sin * m01 + cos * m11; float tmp12 = sin * m02 + cos * m12; m00 = tmp00; m01 = tmp01; m02 = tmp02; m10 = tmp10; m11 = [MASK]; m12 = tmp12; return this; } public Affine2 preRotateRad (float radians) { if (radians == 0) return this; float cos = MathUtils.cos(radians); float sin = MathUtils.sin(radians); float tmp00 = cos * m00 - sin * m10; float tmp01 = cos * m01 - sin * m11; float tmp02 = cos * m02 - sin * m12; float tmp10 = sin * m00 + cos * m10; float [MASK] = sin * m01 + cos * m11; float tmp12 = sin * m02 + cos * m12; m00 = tmp00; m01 = tmp01; m02 = tmp02; m10 = tmp10; m11 = [MASK]; m12 = tmp12; return this; } public Affine2 shear (float shearX, float shearY) { float tmp0 = m00 + shearY * m01; float tmp1 = m01 + shearX * m00; m00 = tmp0; m01 = tmp1; tmp0 = m10 + shearY * m11; tmp1 = m11 + shearX * m10; m10 = tmp0; m11 = tmp1; return this; } public Affine2 shear (Vector2 shear) { return shear(shear.x, shear.y); } public Affine2 preShear (float shearX, float shearY) { float tmp00 = m00 + shearX * m10; float tmp01 = m01 + shearX * m11; float tmp02 = m02 + shearX * m12; float tmp10 = m10 + shearY * m00; float [MASK] = m11 + shearY * m01; float tmp12 = m12 + shearY * m02; m00 = tmp00; m01 = tmp01; m02 = tmp02; m10 = tmp10; m11 = [MASK]; m12 = tmp12; return this; } public Affine2 preShear (Vector2 shear) { return preShear(shear.x, shear.y); } public float det () { return m00 * m11 - m01 * m10; } public Vector2 getTranslation (Vector2 position) { position.x = m02; position.y = m12; return position; } public boolean isTranslation () { return (m00 == 1 && m11 == 1 && m01 == 0 && m10 == 0); } public boolean isIdt () { return (m00 == 1 && m02 == 0 && m12 == 0 && m11 == 1 && m01 == 0 && m10 == 0); } public void applyTo (Vector2 point) { float x = point.x; float y = point.y; point.x = m00 * x + m01 * y + m02; point.y = m10 * x + m11 * y + m12; } @Override public String toString () { return ""["" + m00 + ""|"" + m01 + ""|"" + m02 + ""]\n["" + m10 + ""|"" + m11 + ""|"" + m12 + ""]\n[0.0|0.0|0.1]""; } }",tmp11,java,libgdx "package jadx.gui.utils; import java.io.IOException; import java.io.InputStream; import org.jetbrains.annotations.Nullable; public class IOUtils { @Nullable public static byte[] readNBytes(InputStream inputStream, int len) throws IOException { byte[] payload = new byte[len]; int readSize = 0; while (true) { int read = inputStream.read(payload, readSize, len - readSize); if (read == -1) { return null; } readSize += read; if (readSize == len) { return payload; } } } public static int read(InputStream inputStream, byte[] buf) throws IOException { return read(inputStream, buf, 0, buf.length); } public static int read(InputStream inputStream, byte[] buf, int [MASK], int len) throws IOException { int remainingBytes = len; while (remainingBytes > 0) { int start = len - remainingBytes; int bytesRead = inputStream.read(buf, [MASK] + start, remainingBytes); if (bytesRead == -1) { break; } remainingBytes -= bytesRead; } return len - remainingBytes; } }",off,java,jadx "package jadx.core.dex.attributes; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.utils.Utils; public class AttrList implements IJadxAttribute { private final IJadxAttrType> [MASK]; private final List list = new ArrayList<>(); public AttrList(IJadxAttrType> [MASK]) { this.[MASK] = [MASK]; } public List getList() { return list; } @Override public IJadxAttrType> getAttrType() { return [MASK]; } @Override public String toString() { return Utils.listToString(list, "", ""); } }",type,java,jadx "package com.alibaba.json.bvt.issue_1300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; import java.util.Map; import java.util.TreeMap; public class Issue1371 extends TestCase { private enum Rooms{ A, B, C, D ,E ; } public void testFastjsonEnum(){ Map [MASK] = new TreeMap(); [MASK].put(Rooms.C, Rooms.D); [MASK].put(Rooms.E, Rooms.A); Assert.assertEquals(JSON.toJSONString([MASK], SerializerFeature.WriteNonStringKeyAsString), ""{\""C\"":\""D\"",\""E\"":\""A\""}""); } }",enumMap,java,fastjson "package com.badlogic.gdx.physics.box2d.joints; import org.jbox2d.common.Vec2; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; public class MotorJoint extends Joint { org.jbox2d.dynamics.joints.MotorJoint joint; private final Vector2 linearOffset = new Vector2(); private final Vec2 tmp = new Vec2(); public MotorJoint (World world, org.jbox2d.dynamics.joints.MotorJoint joint) { super(world, joint); this.joint = joint; } public Vector2 getLinearOffset () { joint.getLinearOffset(tmp); return linearOffset.set(tmp.x, tmp.y); } public void setLinearOffset (Vector2 linearOffset) { joint.setLinearOffset(tmp.set(linearOffset.x, linearOffset.y)); } public float getAngularOffset () { return joint.getAngularOffset(); } public void setAngularOffset (float angularOffset) { joint.setAngularOffset(angularOffset); } public float getMaxForce () { return joint.getMaxForce(); } public void setMaxForce (float maxForce) { joint.setMaxForce(maxForce); } public float getMaxTorque () { return joint.getMaxTorque(); } public void setMaxTorque (float [MASK]) { joint.setMaxTorque([MASK]); } public float getCorrectionFactor () { return joint.getCorrectionFactor(); } public void setCorrectionFactor (float correctionFactor) { joint.setCorrectionFactor(correctionFactor); } }",maxTorque,java,libgdx "package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; public class WriteClassNameTest extends TestCase { public void test_writeClassName() throws Exception { Entity object = new Entity(); object.setId(123); object.setName(""jobs""); object.setAverage(3.21F); SerializeConfig config = new SerializeConfig(); config.setAsmEnable(false); String [MASK] = JSON.toJSONString(object, config, SerializerFeature.WriteClassName); System.out.println([MASK]); } public static class Entity { private int id; private String name; private float average; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getAverage() { return average; } public void setAverage(float average) { this.average = average; } } }",text,java,fastjson "package io.netty5.handler.codec.http2; import io.netty5.util.internal.UnstableApi; @UnstableApi public abstract class AbstractHttp2StreamFrame implements Http2StreamFrame { private Http2FrameStream stream; @Override public AbstractHttp2StreamFrame stream(Http2FrameStream stream) { this.stream = stream; return this; } @Override public Http2FrameStream stream() { return stream; } @Override public boolean equals(Object o) { if (!(o instanceof Http2StreamFrame)) { return false; } Http2StreamFrame [MASK] = (Http2StreamFrame) o; return stream == [MASK].stream() || stream != null && stream.equals([MASK].stream()); } @Override public int hashCode() { Http2FrameStream stream = this.stream; if (stream == null) { return super.hashCode(); } return stream.hashCode(); } }",other,java,netty "package io.netty5.handler.codec.http2; import io.netty5.bootstrap.Bootstrap; import io.netty5.bootstrap.ServerBootstrap; import io.netty5.buffer.Buffer; import io.netty5.channel.Channel; import io.netty5.channel.ChannelFutureListeners; import io.netty5.channel.ChannelHandler; import io.netty5.channel.ChannelHandlerAdapter; import io.netty5.channel.ChannelHandlerContext; import io.netty5.channel.ChannelInitializer; import io.netty5.channel.ChannelOption; import io.netty5.channel.ChannelPipeline; import io.netty5.channel.EventLoopGroup; import io.netty5.channel.MultithreadEventLoopGroup; import io.netty5.channel.SimpleChannelInboundHandler; import io.netty5.channel.local.LocalAddress; import io.netty5.channel.local.LocalChannel; import io.netty5.channel.local.LocalIoHandler; import io.netty5.channel.local.LocalServerChannel; import io.netty5.channel.nio.NioIoHandler; import io.netty5.channel.socket.nio.NioServerSocketChannel; import io.netty5.channel.socket.nio.NioSocketChannel; import io.netty5.handler.codec.http.DefaultFullHttpRequest; import io.netty5.handler.codec.http.DefaultFullHttpResponse; import io.netty5.handler.codec.http.FullHttpRequest; import io.netty5.handler.codec.http.FullHttpResponse; import io.netty5.handler.codec.http.HttpMethod; import io.netty5.handler.codec.http.HttpObjectAggregator; import io.netty5.handler.codec.http.HttpResponseStatus; import io.netty5.handler.codec.http.HttpVersion; import io.netty5.handler.codec.http2.headers.Http2Headers; import io.netty5.handler.ssl.ApplicationProtocolConfig; import io.netty5.handler.ssl.ApplicationProtocolNames; import io.netty5.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty5.handler.ssl.ClientAuth; import io.netty5.handler.ssl.OpenSsl; import io.netty5.handler.ssl.SslContext; import io.netty5.handler.ssl.SslContextBuilder; import io.netty5.handler.ssl.SslHandshakeCompletionEvent; import io.netty5.handler.ssl.SslProvider; import io.netty5.handler.ssl.SupportedCipherSuiteFilter; import io.netty5.handler.ssl.util.InsecureTrustManagerFactory; import io.netty5.pkitesting.CertificateBuilder; import io.netty5.pkitesting.X509Bundle; import io.netty5.util.NetUtil; import io.netty5.util.Resource; import io.netty5.util.concurrent.Future; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLException; import javax.net.ssl.X509TrustManager; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static io.netty5.handler.codec.http2.Http2TestUtil.bb; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; public class Http2MultiplexTransportTest { private static final Logger LOGGER = LoggerFactory.getLogger(Http2MultiplexTransportTest.class); private static final ChannelHandler DISCARD_HANDLER = new ChannelHandlerAdapter() { @Override public boolean isSharable() { return true; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { Resource.dispose(msg); } @Override public void channelInboundEvent(ChannelHandlerContext ctx, Object evt) { Resource.dispose(evt); } }; private EventLoopGroup eventLoopGroup; private Channel clientChannel; private Channel serverChannel; private Channel serverConnectedChannel; private static final class MultiplexInboundStream implements ChannelHandler { Future responseFuture; final AtomicInteger handleInactivatedFlushed; final AtomicInteger [MASK]; final CountDownLatch latchHandlerInactive; static final String LARGE_STRING = generateLargeString(10240); MultiplexInboundStream(AtomicInteger handleInactivatedFlushed, AtomicInteger [MASK], CountDownLatch latchHandlerInactive) { this.handleInactivatedFlushed = handleInactivatedFlushed; this.[MASK] = [MASK]; this.latchHandlerInactive = latchHandlerInactive; } @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) { Buffer response = ctx.bufferAllocator().copyOf(LARGE_STRING, StandardCharsets.US_ASCII); responseFuture = ctx.writeAndFlush(new DefaultHttp2DataFrame(response.send(), true)); } Resource.dispose(msg); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (responseFuture.isSuccess()) { handleInactivatedFlushed.incrementAndGet(); } else { [MASK].incrementAndGet(); } latchHandlerInactive.countDown(); ctx.fireChannelInactive(); } private static String generateLargeString(int sizeInBytes) { return ""X"".repeat(Math.max(0, sizeInBytes)); } } @BeforeEach public void setup() { eventLoopGroup = new MultithreadEventLoopGroup(NioIoHandler.newFactory()); } @AfterEach public void teardown() { if (clientChannel != null) { clientChannel.close(); } if (serverChannel != null) { serverChannel.close(); } if (serverConnectedChannel != null) { serverConnectedChannel.close(); } eventLoopGroup.shutdownGracefully(0, 0, MILLISECONDS); } @Disabled(""This started failing when Http2MultiplexCodecBuilder was removed"") @Test @Timeout(value = 10000, unit = MILLISECONDS) public void asyncSettingsAckWithMultiplexHandler() throws Exception { asyncSettingsAck0(new Http2FrameCodecBuilder(true).build(), new Http2MultiplexHandler(DISCARD_HANDLER)); } private void asyncSettingsAck0(final Http2FrameCodec codec, final ChannelHandler multiplexer) throws Exception { final CountDownLatch serverAckOneLatch = new CountDownLatch(1); final CountDownLatch serverAckAllLatch = new CountDownLatch(2); final CountDownLatch clientSettingsLatch = new CountDownLatch(2); final CountDownLatch serverConnectedChannelLatch = new CountDownLatch(1); final AtomicReference serverConnectedChannelRef = new AtomicReference(); ServerBootstrap sb = new ServerBootstrap(); sb.group(eventLoopGroup); sb.channel(NioServerSocketChannel.class); sb.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(codec); if (multiplexer != null) { ch.pipeline().addLast(multiplexer); } ch.pipeline().addLast(new ChannelHandler() { @Override public void channelActive(ChannelHandlerContext ctx) { serverConnectedChannelRef.set(ctx.channel()); serverConnectedChannelLatch.countDown(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2SettingsAckFrame) { serverAckOneLatch.countDown(); serverAckAllLatch.countDown(); } Resource.dispose(msg); } }); } }); serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).asStage().get(); Bootstrap bs = new Bootstrap(); bs.group(eventLoopGroup); bs.channel(NioSocketChannel.class); bs.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(Http2FrameCodecBuilder .forClient().autoAckSettingsFrame(false).build()); ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER, new ChannelHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2SettingsFrame) { clientSettingsLatch.countDown(); } Resource.dispose(msg); } })); } }); clientChannel = bs.connect(serverChannel.localAddress()).asStage().get(); serverConnectedChannelLatch.await(); serverConnectedChannel = serverConnectedChannelRef.get(); serverConnectedChannel.writeAndFlush(new DefaultHttp2SettingsFrame(new Http2Settings() .maxConcurrentStreams(10))).asStage().sync(); clientSettingsLatch.await(); assertFalse(serverAckOneLatch.await(300, MILLISECONDS)); clientChannel.writeAndFlush(Http2SettingsAckFrame.INSTANCE).asStage().sync(); clientChannel.writeAndFlush(Http2SettingsAckFrame.INSTANCE).asStage().sync(); serverAckAllLatch.await(); } @Test @Timeout(value = 5000L, unit = MILLISECONDS) public void testFlushNotDiscarded() throws Exception { final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); try { ServerBootstrap sb = new ServerBootstrap(); sb.group(eventLoopGroup); sb.channel(NioServerSocketChannel.class); sb.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(new Http2FrameCodecBuilder(true).build()); ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelHandler() { @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) { executorService.schedule(() -> { ctx.writeAndFlush(new DefaultHttp2HeadersFrame( Http2Headers.newHeaders(), false)).addListener(future -> { ctx.write(new DefaultHttp2DataFrame( bb(""Hello World"").send(), true)); ctx.channel().executor().execute(ctx::flush); }); }, 500, MILLISECONDS); } Resource.dispose(msg); } })); } }); serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).asStage().get(); final CountDownLatch latch = new CountDownLatch(1); Bootstrap bs = new Bootstrap(); bs.group(eventLoopGroup); bs.channel(NioSocketChannel.class); bs.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(new Http2FrameCodecBuilder(false).build()); ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER)); } }); clientChannel = bs.connect(serverChannel.localAddress()).asStage().get(); Http2StreamChannelBootstrap h2Bootstrap = new Http2StreamChannelBootstrap(clientChannel); h2Bootstrap.handler(new ChannelHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) { latch.countDown(); } Resource.dispose(msg); } }); Http2StreamChannel streamChannel = h2Bootstrap.open().asStage().get(); streamChannel.writeAndFlush(new DefaultHttp2HeadersFrame(Http2Headers.newHeaders(), true)).asStage().sync(); latch.await(); } finally { executorService.shutdown(); } } @Test @Timeout(value = 10000L, unit = MILLISECONDS) public void testSSLExceptionOpenSslTLSv12() throws Exception { testSslException(SslProvider.OPENSSL, false); } @Test @Timeout(value = 10000L, unit = MILLISECONDS) public void testSSLExceptionOpenSslTLSv13() throws Exception { testSslException(SslProvider.OPENSSL, true); } @Disabled(""JDK SSLEngine does not produce an alert"") @Test @Timeout(value = 10000L, unit = MILLISECONDS) public void testSSLExceptionJDKTLSv12() throws Exception { testSslException(SslProvider.JDK, false); } @Disabled(""JDK SSLEngine does not produce an alert"") @Test @Timeout(value = 10000L, unit = MILLISECONDS) public void testSSLExceptionJDKTLSv13() throws Exception { testSslException(SslProvider.JDK, true); } private void testSslException(SslProvider provider, final boolean tlsv13) throws Exception { assumeTrue(SslProvider.isAlpnSupported(provider)); if (tlsv13) { assumeTrue(SslProvider.isTlsv13Supported(provider)); } final String protocol = tlsv13 ? ""TLSv1.3"" : ""TLSv1.2""; X509Bundle cert = new CertificateBuilder() .subject(""cn=localhost"") .setIsCertificateAuthority(true) .buildSelfSigned(); final SslContext sslCtx = SslContextBuilder.forServer(cert.getKeyPair().getPrivate(), cert.getCertificatePath()) .trustManager(new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateExpiredException(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateExpiredException(); } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }).sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .protocols(protocol) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)).clientAuth(ClientAuth.REQUIRE) .build(); ServerBootstrap sb = new ServerBootstrap(); sb.group(eventLoopGroup); sb.channel(NioServerSocketChannel.class); sb.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(sslCtx.newHandler(ch.bufferAllocator())); ch.pipeline().addLast(new Http2FrameCodecBuilder(true).build()); ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER)); } }); serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).asStage().get(); final SslContext clientCtx = SslContextBuilder.forClient() .keyManager(cert.toKeyManagerFactory()) .sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .protocols(protocol) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); final CountDownLatch latch = new CountDownLatch(2); final AtomicReference errorRef = new AtomicReference(); Bootstrap bs = new Bootstrap(); bs.group(eventLoopGroup); bs.channel(NioSocketChannel.class); bs.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientCtx.newHandler(ch.bufferAllocator())); ch.pipeline().addLast(new Http2FrameCodecBuilder(false).build()); ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER)); ch.pipeline().addLast(new ChannelHandler() { @Override public void channelInboundEvent(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeCompletionEvent = (SslHandshakeCompletionEvent) evt; if (handshakeCompletionEvent.isSuccess()) { if (!tlsv13) { errorRef.set(new AssertionError(""TLSv1.3 expected"")); } Http2StreamChannelBootstrap h2Bootstrap = new Http2StreamChannelBootstrap(ctx.channel()); h2Bootstrap.handler(new ChannelHandler() { @Override public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause.getCause() instanceof SSLException) { latch.countDown(); } else { LOGGER.debug(""Got unexpected exception in h2Boostrap handler"", cause); } } @Override public void channelInactive(ChannelHandlerContext ctx) { latch.countDown(); } }); h2Bootstrap.open().addListener(future -> { if (future.isSuccess()) { future.getNow().writeAndFlush(new DefaultHttp2HeadersFrame( Http2Headers.newHeaders(), false)); } }); } else if (handshakeCompletionEvent.cause() instanceof SSLException) { if (tlsv13) { errorRef.set(new AssertionError(""TLSv1.2 expected"")); } latch.countDown(); latch.countDown(); } else { LOGGER.debug( ""Got unexpected handshake completion event in client bootstrap handler: {}"", handshakeCompletionEvent); } } else { LOGGER.debug(""Got unexpected user event in client bootstrap handler: {}"", evt); } } }); } }); clientChannel = bs.connect(serverChannel.localAddress()).asStage().get(); latch.await(); AssertionError error = errorRef.get(); if (error != null) { throw error; } } @Test @DisabledOnOs(value = OS.WINDOWS, disabledReason = ""See: https: @Timeout(value = 5000L, unit = MILLISECONDS) public void testFireChannelReadAfterHandshakeSuccess_JDK() throws Exception { assumeTrue(SslProvider.isAlpnSupported(SslProvider.JDK)); testFireChannelReadAfterHandshakeSuccess(SslProvider.JDK); } @Disabled(""This fails atm... needs investigation"") @Test @DisabledOnOs(value = OS.WINDOWS, disabledReason = ""See: https: @Timeout(value = 5000L, unit = MILLISECONDS) public void testFireChannelReadAfterHandshakeSuccess_OPENSSL() throws Exception { assumeTrue(OpenSsl.isAvailable()); assumeTrue(SslProvider.isAlpnSupported(SslProvider.OPENSSL)); testFireChannelReadAfterHandshakeSuccess(SslProvider.OPENSSL); } private void testFireChannelReadAfterHandshakeSuccess(SslProvider provider) throws Exception { X509Bundle cert = new CertificateBuilder() .subject(""cn=localhost"") .setIsCertificateAuthority(true) .buildSelfSigned(); final SslContext serverCtx = SslContextBuilder.forServer(cert.getKeyPair().getPrivate(), cert.getCertificatePath()) .sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); ServerBootstrap sb = new ServerBootstrap(); sb.group(eventLoopGroup); sb.channel(NioServerSocketChannel.class); sb.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(serverCtx.newHandler(ch.bufferAllocator())); ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { ctx.pipeline().addLast(new Http2FrameCodecBuilder(true).build()); ctx.pipeline().addLast(new Http2MultiplexHandler(new ChannelHandler() { @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) { ctx.writeAndFlush(new DefaultHttp2HeadersFrame( Http2Headers.newHeaders(), false)) .addListener(future -> { ctx.writeAndFlush(new DefaultHttp2DataFrame( bb(""Hello World"").send(), true)); }); } Resource.dispose(msg); } })); } }); } }); serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).asStage().get(); final SslContext clientCtx = SslContextBuilder.forClient() .sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); final CountDownLatch latch = new CountDownLatch(1); Bootstrap bs = new Bootstrap(); bs.group(eventLoopGroup); bs.channel(NioSocketChannel.class); bs.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(clientCtx.newHandler(ch.bufferAllocator())); ch.pipeline().addLast(new Http2FrameCodecBuilder(false).build()); ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER)); ch.pipeline().addLast(new ChannelHandler() { @Override public void channelInboundEvent(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeCompletionEvent = (SslHandshakeCompletionEvent) evt; if (handshakeCompletionEvent.isSuccess()) { Http2StreamChannelBootstrap h2Bootstrap = new Http2StreamChannelBootstrap(ctx.channel()); h2Bootstrap.handler(new ChannelHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) { latch.countDown(); } Resource.dispose(msg); } }); h2Bootstrap.open().addListener(future -> { if (future.isSuccess()) { future.getNow().writeAndFlush(new DefaultHttp2HeadersFrame( Http2Headers.newHeaders(), true)); } }); } } } }); } }); clientChannel = bs.connect(serverChannel.localAddress()).asStage().get(); latch.await(); } @Test @Timeout(value = 120000L, unit = MILLISECONDS) public void streamHandlerInactivatedResponseFlushed() throws Exception { EventLoopGroup serverEventLoopGroup = null; EventLoopGroup clientEventLoopGroup = null; try { serverEventLoopGroup = new MultithreadEventLoopGroup(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, ""serverloop""); } }, NioIoHandler.newFactory()); clientEventLoopGroup = new MultithreadEventLoopGroup(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, ""clientloop""); } }, NioIoHandler.newFactory()); final int streams = 10; final CountDownLatch latchClientResponses = new CountDownLatch(streams); final CountDownLatch latchHandlerInactive = new CountDownLatch(streams); final AtomicInteger handlerInactivatedFlushed = new AtomicInteger(); final AtomicInteger [MASK] = new AtomicInteger(); final ServerBootstrap sb = new ServerBootstrap(); sb.group(serverEventLoopGroup); sb.channel(NioServerSocketChannel.class); sb.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.setOption(ChannelOption.SO_SNDBUF, 1); ch.pipeline().addLast(new Http2FrameCodecBuilder(true).build()); ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().remove(this); ch.pipeline().addLast(new MultiplexInboundStream(handlerInactivatedFlushed, [MASK], latchHandlerInactive)); } })); } }); serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).asStage().get(); final Bootstrap bs = new Bootstrap(); bs.group(clientEventLoopGroup); bs.channel(NioSocketChannel.class); bs.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(new Http2FrameCodecBuilder(false).build()); ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER)); } }); clientChannel = bs.connect(serverChannel.localAddress()).asStage().get(); final Http2StreamChannelBootstrap h2Bootstrap = new Http2StreamChannelBootstrap(clientChannel); h2Bootstrap.handler(new ChannelHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) { latchClientResponses.countDown(); } Resource.dispose(msg); } @Override public boolean isSharable() { return true; } }); List> streamFutures = new ArrayList<>(); for (int i = 0; i < streams; i ++) { Http2StreamChannel stream = h2Bootstrap.open().asStage().get(); streamFutures.add(stream.writeAndFlush(new DefaultHttp2HeadersFrame(Http2Headers.newHeaders(), true))); } for (int i = 0; i < streams; i ++) { streamFutures.get(i).asStage().sync(); } assertTrue(latchHandlerInactive.await(120000, MILLISECONDS)); assertTrue(latchClientResponses.await(120000, MILLISECONDS)); assertEquals(0, [MASK].get()); assertEquals(streams, handlerInactivatedFlushed.get()); } finally { if (serverEventLoopGroup != null) { serverEventLoopGroup.shutdownGracefully(0, 0, MILLISECONDS); } if (clientEventLoopGroup != null) { clientEventLoopGroup.shutdownGracefully(0, 0, MILLISECONDS); } } } @Test public void testServerCloseShouldNotSendResetIfClientSentEOS() throws Exception { EventLoopGroup group = null; Channel serverChannel = null; Channel clientChannel = null; Channel clientStreamChannel = null; try { final CountDownLatch clientReceivedResponseLatch = new CountDownLatch(1); final CountDownLatch resetFrameLatch = new CountDownLatch(1); group = new MultithreadEventLoopGroup(LocalIoHandler.newFactory()); LocalAddress serverAddress = new LocalAddress(getClass().getName()); ServerBootstrap sb = new ServerBootstrap() .channel(LocalServerChannel.class) .group(group) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(Http2FrameCodecBuilder.forServer().build()); pipeline.addLast(new Http2FrameIgnore(Http2SettingsFrame.class)); pipeline.addLast(new Http2FrameIgnore(Http2SettingsAckFrame.class)); pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer() { @Override protected void initChannel(Http2StreamChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new Http2StreamFrameToHttpObjectCodec(true)); pipeline.addLast(new HttpObjectAggregator<>(16384)); pipeline.addLast(new SimpleChannelInboundHandler() { @Override protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest msg) { ctx.writeAndFlush( new DefaultFullHttpResponse( msg.protocolVersion(), HttpResponseStatus.OK, ctx.bufferAllocator().copyOf( ""hello"", StandardCharsets.US_ASCII))) .addListener(ctx, ChannelFutureListeners.CLOSE); } }); } })); } }); serverChannel = sb.bind(serverAddress).asStage().get(); Bootstrap cb = new Bootstrap() .channel(LocalChannel.class) .group(group) .handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(Http2FrameCodecBuilder.forClient().build()); pipeline.addLast(new Http2FrameIgnore<>(Http2SettingsFrame.class)); pipeline.addLast(new Http2FrameIgnore<>(Http2SettingsAckFrame.class)); pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer() { @Override protected void initChannel(Http2StreamChannel ch) { } })); } }); clientChannel = cb.connect(serverAddress).asStage().get(); clientStreamChannel = new Http2StreamChannelBootstrap(clientChannel) .handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new Http2StreamFrameToHttpObjectCodec(false)); pipeline.addLast(new HttpObjectAggregator<>(16384)); pipeline.addLast(new SimpleChannelInboundHandler() { @Override protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) { clientReceivedResponseLatch.countDown(); } }); } }) .open().asStage().get(); clientStreamChannel.writeAndFlush( new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""/test/"", clientStreamChannel.bufferAllocator().allocate(0))).asStage().get(); assertTrue(clientReceivedResponseLatch.await(3, SECONDS)); assertFalse(resetFrameLatch.await(1, SECONDS)); } finally { if (clientStreamChannel != null) { clientStreamChannel.close().asStage().get(); } if (clientChannel != null) { clientChannel.close().asStage().get(); } if (serverChannel != null) { serverChannel.close().asStage().get(); } if (group != null) { group.shutdownGracefully(0, 3, SECONDS); } } } private static final class Http2FrameIgnore extends SimpleChannelInboundHandler { Http2FrameIgnore(Class inboundMessageType) { super(inboundMessageType); } @Override protected void messageReceived(ChannelHandlerContext ctx, T msg) { } } }",handleInactivatedNotFlushed,java,netty "package org.apache.dubbo.config; import com.alibaba.dubbo.config.ProtocolConfig; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class ProtocolConfigTest { @Test public void testName() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setName(""name""); Map parameters = new HashMap(); ProtocolConfig.appendParameters(parameters, [MASK]); assertThat([MASK].getName(), equalTo(""name"")); assertThat([MASK].getId(), equalTo(""name"")); assertThat(parameters.isEmpty(), is(true)); } @Test public void testHost() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setHost(""host""); Map parameters = new HashMap(); ProtocolConfig.appendParameters(parameters, [MASK]); assertThat([MASK].getHost(), equalTo(""host"")); assertThat(parameters.isEmpty(), is(true)); } @Test public void testPort() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setPort(8080); Map parameters = new HashMap(); ProtocolConfig.appendParameters(parameters, [MASK]); assertThat([MASK].getPort(), equalTo(8080)); assertThat(parameters.isEmpty(), is(true)); } @Test public void testPath() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setContextpath(""context-path""); Map parameters = new HashMap(); ProtocolConfig.appendParameters(parameters, [MASK]); assertThat([MASK].getPath(), equalTo(""context-path"")); assertThat([MASK].getContextpath(), equalTo(""context-path"")); assertThat(parameters.isEmpty(), is(true)); [MASK].setPath(""path""); assertThat([MASK].getPath(), equalTo(""path"")); assertThat([MASK].getContextpath(), equalTo(""path"")); } @Test public void testThreads() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setThreads(10); assertThat([MASK].getThreads(), is(10)); } @Test public void testIothreads() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setIothreads(10); assertThat([MASK].getIothreads(), is(10)); } @Test public void testQueues() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setQueues(10); assertThat([MASK].getQueues(), is(10)); } @Test public void testAccepts() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setAccepts(10); assertThat([MASK].getAccepts(), is(10)); } @Test public void testAccesslog() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setAccesslog(""access.log""); assertThat([MASK].getAccesslog(), equalTo(""access.log"")); } @Test public void testRegister() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setRegister(true); assertThat([MASK].isRegister(), is(true)); } @Test public void testParameters() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setParameters(Collections.singletonMap(""k1"", ""v1"")); assertThat([MASK].getParameters(), hasEntry(""k1"", ""v1"")); } @Test public void testDefault() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setDefault(true); assertThat([MASK].isDefault(), is(true)); } @Test public void testKeepAlive() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setKeepAlive(true); assertThat([MASK].getKeepAlive(), is(true)); } @Test public void testOptimizer() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setOptimizer(""optimizer""); assertThat([MASK].getOptimizer(), equalTo(""optimizer"")); } @Test public void testExtension() throws Exception { ProtocolConfig [MASK] = new ProtocolConfig(); [MASK].setExtension(""extension""); assertThat([MASK].getExtension(), equalTo(""extension"")); } }",protocol,java,incubator-dubbo "package jadx.core.dex.instructions.args; import org.jetbrains.annotations.Nullable; import jadx.core.codegen.TypeGen; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; public final class LiteralArg extends InsnArg { public static LiteralArg make(long value, ArgType type) { return new LiteralArg(value, type); } public static LiteralArg makeWithFixedType(long value, ArgType type) { return new LiteralArg(value, fixLiteralType(value, type)); } private static ArgType fixLiteralType(long value, ArgType type) { if (value == 0 || type.isTypeKnown() || type.contains(PrimitiveType.LONG) || type.contains(PrimitiveType.DOUBLE)) { return type; } if (value == 1) { return ArgType.NARROW_NUMBERS; } return ArgType.NARROW_NUMBERS_NO_BOOL; } public static LiteralArg litFalse() { return new LiteralArg(0, ArgType.BOOLEAN); } public static LiteralArg litTrue() { return new LiteralArg(1, ArgType.BOOLEAN); } private final long literal; private LiteralArg(long value, ArgType type) { if (value != 0 && type.isObject()) { throw new JadxRuntimeException(""Wrong literal type: "" + type + "" for value: "" + value); } this.literal = value; this.type = type; } public long getLiteral() { return literal; } @Override public void setType(ArgType type) { super.setType(type); } @Override public boolean isLiteral() { return true; } @Override public boolean isZeroLiteral() { return literal == 0; } public boolean isInteger() { switch (type.getPrimitiveType()) { case INT: case BYTE: case CHAR: case SHORT: case LONG: return true; default: return false; } } public boolean isNegative() { if (isInteger()) { return literal < 0; } if (type == ArgType.FLOAT) { float val = Float.intBitsToFloat(((int) literal)); return val < 0 && Float.isFinite(val); } if (type == ArgType.DOUBLE) { double val = Double.longBitsToDouble(literal); return val < 0 && Double.isFinite(val); } return false; } @Nullable public LiteralArg negate() { long [MASK]; if (isInteger()) { [MASK] = -literal; } else if (type == ArgType.FLOAT) { float val = Float.intBitsToFloat(((int) literal)); [MASK] = Float.floatToIntBits(-val); } else if (type == ArgType.DOUBLE) { double val = Double.longBitsToDouble(literal); [MASK] = Double.doubleToLongBits(-val); } else { return null; } return new LiteralArg([MASK], type); } @Override public InsnArg duplicate() { return copyCommonParams(new LiteralArg(literal, type)); } @Override public int hashCode() { return (int) (literal ^ literal >>> 32) + 31 * getType().hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LiteralArg that = (LiteralArg) o; return literal == that.literal && getType().equals(that.getType()); } @Override public String toShortString() { return Long.toString(literal); } @Override public String toString() { try { String value = TypeGen.literalToString(literal, getType(), StringUtils.getInstance(), true, false); if (getType().equals(ArgType.BOOLEAN) && (value.equals(""true"") || value.equals(""false""))) { return value; } return '(' + value + ' ' + type + ')'; } catch (JadxRuntimeException ex) { return ""("" + literal + ' ' + type + ')'; } } }",neg,java,jadx "package java.nio; final class ReadWriteIntArrayBuffer extends IntArrayBuffer { static ReadWriteIntArrayBuffer copy (IntArrayBuffer other, int markOfOther) { ReadWriteIntArrayBuffer buf = new ReadWriteIntArrayBuffer(other.[MASK](), other.backingArray, other.offset); buf.limit = other.limit(); buf.position = other.position(); buf.mark = markOfOther; return buf; } ReadWriteIntArrayBuffer (int[] array) { super(array); } ReadWriteIntArrayBuffer (int [MASK]) { super([MASK]); } ReadWriteIntArrayBuffer (int [MASK], int[] backingArray, int arrayOffset) { super([MASK], backingArray, arrayOffset); } public IntBuffer asReadOnlyBuffer () { return ReadOnlyIntArrayBuffer.copy(this, mark); } public IntBuffer compact () { System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); position = limit - position; limit = [MASK]; mark = UNSET_MARK; return this; } public IntBuffer duplicate () { return copy(this, mark); } public boolean isReadOnly () { return false; } protected int[] protectedArray () { return backingArray; } protected int protectedArrayOffset () { return offset; } protected boolean protectedHasArray () { return true; } public IntBuffer put (int c) { if (position == limit) { throw new BufferOverflowException(); } backingArray[offset + position++] = c; return this; } public IntBuffer put (int index, int c) { if (index < 0 || index >= limit) { throw new IndexOutOfBoundsException(); } backingArray[offset + index] = c; return this; } public IntBuffer put (int[] src, int off, int len) { int length = src.length; if (off < 0 || len < 0 || (long)off + (long)len > length) { throw new IndexOutOfBoundsException(); } if (len > remaining()) { throw new BufferOverflowException(); } System.arraycopy(src, off, backingArray, offset + position, len); position += len; return this; } public IntBuffer slice () { return new ReadWriteIntArrayBuffer(remaining(), backingArray, offset + position); } }",capacity,java,libgdx "package io.netty5.channel.embedded; import io.netty5.channel.ChannelId; final class EmbeddedChannelId implements ChannelId { private static final long [MASK] = -251711922203466130L; static final ChannelId INSTANCE = new EmbeddedChannelId(); private EmbeddedChannelId() { } @Override public String asShortText() { return toString(); } @Override public String asLongText() { return toString(); } @Override public int compareTo(final ChannelId o) { if (o instanceof EmbeddedChannelId) { return 0; } return asLongText().compareTo(o.asLongText()); } @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { return obj instanceof EmbeddedChannelId; } @Override public String toString() { return ""embedded""; } }",serialVersionUID,java,netty "package org.apache.dubbo.rpc.[MASK].dubbo.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.[MASK].dubbo.DubboProtocol; import java.util.List; public class ProtocolUtils { public static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private static Protocol [MASK] = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); public static T refer(Class type, String url) { return refer(type, URL.valueOf(url)); } public static T refer(Class type, URL url) { return proxy.getProxy([MASK].refer(type, url)); } public static Invoker referInvoker(Class type, URL url) { return (Invoker) [MASK].refer(type, url); } public static Exporter export(T instance, Class type, String url) { return export(instance, type, URL.valueOf(url)); } public static Exporter export(T instance, Class type, URL url) { return [MASK].export(proxy.getInvoker(instance, type, url)); } public static void closeAll() { DubboProtocol.getDubboProtocol().destroy(); List servers = DubboProtocol.getDubboProtocol().getServers(); for (ProtocolServer server : servers) { server.close(); } } }",protocol,java,incubator-dubbo "package org.apache.dubbo.config.spring.schema; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.AbstractServiceConfig; import org.apache.dubbo.config.ArgumentConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.ServiceBean; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.core.env.Environment; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static org.apache.dubbo.common.constants.CommonConstants.HIDDEN_KEY_PREFIX; public class DubboBeanDefinitionParser implements BeanDefinitionParser { private static final Logger logger = LoggerFactory.getLogger(DubboBeanDefinitionParser.class); private static final Pattern GROUP_AND_VERSION = Pattern.compile(""^[\\-.0-9_a-zA-Z]+(\\:[\\-.0-9_a-zA-Z]+)?$""); private static final String ONRETURN = ""onreturn""; private static final String ONTHROW = ""onthrow""; private static final String ONINVOKE = ""oninvoke""; private static final String METHOD = ""Method""; private final Class beanClass; private final boolean required; public DubboBeanDefinitionParser(Class beanClass, boolean required) { this.beanClass = beanClass; this.required = required; } @SuppressWarnings(""unchecked"") private static RootBeanDefinition parse(Element element, ParserContext parserContext, Class beanClass, boolean required) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClass(beanClass); beanDefinition.setLazyInit(false); String id = resolveAttribute(element, ""id"", parserContext); if (StringUtils.isEmpty(id) && required) { String generatedBeanName = resolveAttribute(element, ""name"", parserContext); if (StringUtils.isEmpty(generatedBeanName)) { if (ProtocolConfig.class.equals(beanClass)) { generatedBeanName = ""dubbo""; } else { generatedBeanName = resolveAttribute(element, ""interface"", parserContext); } } if (StringUtils.isEmpty(generatedBeanName)) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while (parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter++); } } if (StringUtils.isNotEmpty(id)) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException(""Duplicate spring bean id "" + id); } parserContext.getRegistry().registerBeanDefinition(id, beanDefinition); beanDefinition.getPropertyValues().addPropertyValue(""id"", id); } if (ProtocolConfig.class.equals(beanClass)) { for (String name : parserContext.getRegistry().getBeanDefinitionNames()) { BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name); PropertyValue property = definition.getPropertyValues().getPropertyValue(""protocol""); if (property != null) { Object value = property.getValue(); if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) { definition.getPropertyValues().addPropertyValue(""protocol"", new RuntimeBeanReference(id)); } } } } else if (ServiceBean.class.equals(beanClass)) { String className = resolveAttribute(element, ""class"", parserContext); if (StringUtils.isNotEmpty(className)) { RootBeanDefinition classDefinition = new RootBeanDefinition(); classDefinition.setBeanClass(ReflectUtils.forName(className)); classDefinition.setLazyInit(false); parseProperties(element.getChildNodes(), classDefinition, parserContext); beanDefinition.getPropertyValues().addPropertyValue(""ref"", new BeanDefinitionHolder(classDefinition, id + ""Impl"")); } } else if (ProviderConfig.class.equals(beanClass)) { parseNested(element, parserContext, ServiceBean.class, true, ""service"", ""provider"", id, beanDefinition); } else if (ConsumerConfig.class.equals(beanClass)) { parseNested(element, parserContext, ReferenceBean.class, false, ""reference"", ""consumer"", id, beanDefinition); } Set props = new HashSet<>(); ManagedMap parameters = null; for (Method setter : beanClass.getMethods()) { String name = setter.getName(); if (name.length() > 3 && name.startsWith(""set"") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) { Class type = setter.getParameterTypes()[0]; String beanProperty = name.substring(3, 4).toLowerCase() + name.substring(4); String property = StringUtils.camelToSplitName(beanProperty, ""-""); props.add(property); Method getter = null; try { getter = beanClass.getMethod(""get"" + name.substring(3), new Class[0]); } catch (NoSuchMethodException e) { try { getter = beanClass.getMethod(""is"" + name.substring(3), new Class[0]); } catch (NoSuchMethodException e2) { } } if (getter == null || !Modifier.isPublic(getter.getModifiers()) || !type.equals(getter.getReturnType())) { continue; } if (""parameters"".equals(property)) { parameters = parseParameters(element.getChildNodes(), beanDefinition, parserContext); } else if (""methods"".equals(property)) { parseMethods(id, element.getChildNodes(), beanDefinition, parserContext); } else if (""arguments"".equals(property)) { parseArguments(id, element.getChildNodes(), beanDefinition, parserContext); } else { String value = resolveAttribute(element, property, parserContext); if (value != null) { value = value.trim(); if (value.length() > 0) { if (""registry"".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); beanDefinition.getPropertyValues().addPropertyValue(beanProperty, registryConfig); } else if (""provider"".equals(property) || ""registry"".equals(property) || (""protocol"".equals(property) && AbstractServiceConfig.class.isAssignableFrom(beanClass))) { beanDefinition.getPropertyValues().addPropertyValue(beanProperty + ""Ids"", value); } else { Object reference; if (isPrimitive(type)) { if (""async"".equals(property) && ""false"".equals(value) || ""timeout"".equals(property) && ""0"".equals(value) || ""delay"".equals(property) && ""0"".equals(value) || ""version"".equals(property) && ""0.0.0"".equals(value) || ""stat"".equals(property) && ""-1"".equals(value) || ""reliable"".equals(property) && ""false"".equals(value)) { value = null; } reference = value; } else if (ONRETURN.equals(property) || ONTHROW.equals(property) || ONINVOKE.equals(property)) { int index = value.lastIndexOf("".""); String ref = value.substring(0, index); String method = value.substring(index + 1); reference = new RuntimeBeanReference(ref); beanDefinition.getPropertyValues().addPropertyValue(property + METHOD, method); } else { if (""ref"".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); if (!refBean.isSingleton()) { throw new IllegalStateException(""The exported service ref "" + value + "" must be singleton! Please set the "" + value + "" bean scope to singleton, eg: ""); } } reference = new RuntimeBeanReference(value); } beanDefinition.getPropertyValues().addPropertyValue(beanProperty, reference); } } } } } } NamedNodeMap attributes = element.getAttributes(); int len = attributes.getLength(); for (int i = 0; i < len; i++) { Node node = attributes.item(i); String name = node.getLocalName(); if (!props.contains(name)) { if (parameters == null) { parameters = new ManagedMap(); } String value = node.getNodeValue(); parameters.put(name, new TypedStringValue(value, String.class)); } } if (parameters != null) { beanDefinition.getPropertyValues().addPropertyValue(""parameters"", parameters); } return beanDefinition; } private static boolean isPrimitive(Class cls) { return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class || cls == Character.class || cls == Short.class || cls == Integer.class || cls == Long.class || cls == Float.class || cls == Double.class || cls == String.class || cls == Date.class || cls == Class.class; } private static void parseNested(Element element, ParserContext parserContext, Class beanClass, boolean required, String tag, String property, String ref, BeanDefinition beanDefinition) { NodeList nodeList = element.getChildNodes(); if (nodeList == null) { return; } boolean first = true; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (!(node instanceof Element)) { continue; } if (tag.equals(node.getNodeName()) || tag.equals(node.getLocalName())) { if (first) { first = false; String isDefault = resolveAttribute(element, ""default"", parserContext); if (StringUtils.isEmpty(isDefault)) { beanDefinition.getPropertyValues().addPropertyValue(""default"", ""false""); } } BeanDefinition subDefinition = parse((Element) node, parserContext, beanClass, required); if (subDefinition != null && StringUtils.isNotEmpty(ref)) { subDefinition.getPropertyValues().addPropertyValue(property, new RuntimeBeanReference(ref)); } } } } private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return; } for (int i = 0; i < nodeList.getLength(); i++) { if (!(nodeList.item(i) instanceof Element)) { continue; } Element element = (Element) nodeList.item(i); if (""property"".equals(element.getNodeName()) || ""property"".equals(element.getLocalName())) { String name = resolveAttribute(element, ""name"", parserContext); if (StringUtils.isNotEmpty(name)) { String value = resolveAttribute(element, ""value"", parserContext); String ref = resolveAttribute(element, ""ref"", parserContext); if (StringUtils.isNotEmpty(value)) { beanDefinition.getPropertyValues().addPropertyValue(name, value); } else if (StringUtils.isNotEmpty(ref)) { beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref)); } else { throw new UnsupportedOperationException(""Unsupported sub tag, Only supported or ""); } } } } } @SuppressWarnings(""unchecked"") private static ManagedMap parseParameters(NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return null; } ManagedMap parameters = null; for (int i = 0; i < nodeList.getLength(); i++) { if (!(nodeList.item(i) instanceof Element)) { continue; } Element element = (Element) nodeList.item(i); if (""parameter"".equals(element.getNodeName()) || ""parameter"".equals(element.getLocalName())) { if (parameters == null) { parameters = new ManagedMap(); } String key = resolveAttribute(element, ""key"", parserContext); String value = resolveAttribute(element, ""value"", parserContext); boolean hide = ""true"".equals(resolveAttribute(element, ""hide"", parserContext)); if (hide) { key = HIDDEN_KEY_PREFIX + key; } parameters.put(key, new TypedStringValue(value, String.class)); } } return parameters; } @SuppressWarnings(""unchecked"") private static void parseMethods(String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return; } ManagedList methods = null; for (int i = 0; i < nodeList.getLength(); i++) { if (!(nodeList.item(i) instanceof Element)) { continue; } Element element = (Element) nodeList.item(i); if (""method"".equals(element.getNodeName()) || ""method"".equals(element.getLocalName())) { String methodName = resolveAttribute(element, ""name"", parserContext); if (StringUtils.isEmpty(methodName)) { throw new IllegalStateException("" name attribute == null""); } if (methods == null) { methods = new ManagedList(); } RootBeanDefinition methodBeanDefinition = parse(element, parserContext, MethodConfig.class, false); String beanName = id + ""."" + methodName; if (!hasPropertyValue(methodBeanDefinition, ""id"")) { addPropertyValue(methodBeanDefinition, ""id"", beanName); } BeanDefinitionHolder methodBeanDefinitionHolder = new BeanDefinitionHolder( methodBeanDefinition, beanName); methods.add(methodBeanDefinitionHolder); } } if (methods != null) { beanDefinition.getPropertyValues().addPropertyValue(""methods"", methods); } } private static boolean hasPropertyValue(AbstractBeanDefinition beanDefinition, String [MASK]) { return beanDefinition.getPropertyValues().contains([MASK]); } private static void addPropertyValue(AbstractBeanDefinition beanDefinition, String [MASK], String propertyValue) { if (StringUtils.isBlank([MASK]) || StringUtils.isBlank(propertyValue)) { return; } beanDefinition.getPropertyValues().addPropertyValue([MASK], propertyValue); } @SuppressWarnings(""unchecked"") private static void parseArguments(String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return; } ManagedList arguments = null; for (int i = 0; i < nodeList.getLength(); i++) { if (!(nodeList.item(i) instanceof Element)) { continue; } Element element = (Element) nodeList.item(i); if (""argument"".equals(element.getNodeName()) || ""argument"".equals(element.getLocalName())) { String argumentIndex = resolveAttribute(element, ""index"", parserContext); if (arguments == null) { arguments = new ManagedList(); } BeanDefinition argumentBeanDefinition = parse(element, parserContext, ArgumentConfig.class, false); String name = id + ""."" + argumentIndex; BeanDefinitionHolder argumentBeanDefinitionHolder = new BeanDefinitionHolder( argumentBeanDefinition, name); arguments.add(argumentBeanDefinitionHolder); } } if (arguments != null) { beanDefinition.getPropertyValues().addPropertyValue(""arguments"", arguments); } } @Override public BeanDefinition parse(Element element, ParserContext parserContext) { return parse(element, parserContext, beanClass, required); } private static String resolveAttribute(Element element, String attributeName, ParserContext parserContext) { String attributeValue = element.getAttribute(attributeName); Environment environment = parserContext.getReaderContext().getEnvironment(); return environment.resolvePlaceholders(attributeValue); } }",propertyName,java,incubator-dubbo "package com.badlogic.gdx.physics.box2d.joints; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; public class PrismaticJoint extends Joint { private final float[] tmp = new float[2]; private final Vector2 localAnchorA = new Vector2(); private final Vector2 localAnchorB = new Vector2(); private final Vector2 localAxisA = new Vector2(); public PrismaticJoint (World world, long addr) { super(world, addr); } public Vector2 getLocalAnchorA () { jniGetLocalAnchorA(addr, tmp); localAnchorA.set(tmp[0], tmp[1]); return localAnchorA; } private native void jniGetLocalAnchorA (long addr, float[] anchor); public Vector2 getLocalAnchorB () { jniGetLocalAnchorB(addr, tmp); localAnchorB.set(tmp[0], tmp[1]); return localAnchorB; } private native void jniGetLocalAnchorB (long addr, float[] anchor); public Vector2 getLocalAxisA () { jniGetLocalAxisA(addr, tmp); localAxisA.set(tmp[0], tmp[1]); return localAxisA; } private native void jniGetLocalAxisA (long addr, float[] anchor); public float getJointTranslation () { return jniGetJointTranslation(addr); } private native float jniGetJointTranslation (long addr); public float getJointSpeed () { return jniGetJointSpeed(addr); } private native float jniGetJointSpeed (long addr); public boolean isLimitEnabled () { return jniIsLimitEnabled(addr); } private native boolean jniIsLimitEnabled (long addr); public void enableLimit (boolean flag) { jniEnableLimit(addr, flag); } private native void jniEnableLimit (long addr, boolean flag); public float getLowerLimit () { return jniGetLowerLimit(addr); } private native float jniGetLowerLimit (long addr); public float getUpperLimit () { return jniGetUpperLimit(addr); } private native float jniGetUpperLimit (long addr); public void setLimits (float lower, float upper) { jniSetLimits(addr, lower, upper); } private native void jniSetLimits (long addr, float lower, float upper); public boolean isMotorEnabled () { return jniIsMotorEnabled(addr); } private native boolean jniIsMotorEnabled (long addr); public void enableMotor (boolean flag) { jniEnableMotor(addr, flag); } private native void jniEnableMotor (long addr, boolean flag); public void setMotorSpeed (float speed) { jniSetMotorSpeed(addr, speed); } private native void jniSetMotorSpeed (long addr, float speed); public float getMotorSpeed () { return jniGetMotorSpeed(addr); } private native float jniGetMotorSpeed (long addr); public void setMaxMotorForce (float [MASK]) { jniSetMaxMotorForce(addr, [MASK]); } private native void jniSetMaxMotorForce (long addr, float [MASK]); public float getMotorForce (float invDt) { return jniGetMotorForce(addr, invDt); } private native float jniGetMotorForce (long addr, float invDt); public float getMaxMotorForce () { return jniGetMaxMotorForce(addr); } private native float jniGetMaxMotorForce (long addr); public float getReferenceAngle () { return jniGetReferenceAngle(addr); } private native float jniGetReferenceAngle (long addr); }",force,java,libgdx "package com.badlogic.gdx.graphics.g3d.utils; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.ArrowShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.BoxShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.CapsuleShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.ConeShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.CylinderShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.EllipseShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.PatchShapeBuilder; import com.badlogic.gdx.graphics.g3d.utils.shapebuilders.SphereShapeBuilder; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix3; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.FloatArray; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.IntIntMap; import com.badlogic.gdx.utils.ShortArray; public class MeshBuilder implements MeshPartBuilder { public static final int MAX_VERTICES = 1 << 16; public static final int MAX_INDEX = MAX_VERTICES - 1; private final static ShortArray tmpIndices = new ShortArray(); private final static FloatArray tmpVertices = new FloatArray(); private final VertexInfo vertTmp1 = new VertexInfo(); private final VertexInfo vertTmp2 = new VertexInfo(); private final VertexInfo vertTmp3 = new VertexInfo(); private final VertexInfo vertTmp4 = new VertexInfo(); private final Color tempC1 = new Color(); private VertexAttributes attributes; private FloatArray vertices = new FloatArray(); private ShortArray indices = new ShortArray(); private int stride; private int vindex; private int istart; private int posOffset; private int posSize; private int norOffset; private int biNorOffset; private int tangentOffset; private int colOffset; private int colSize; private int cpOffset; private int uvOffset; private MeshPart part; private Array parts = new Array(); private final Color color = new Color(Color.WHITE); private boolean hasColor = false; private int primitiveType; private float uOffset = 0f, uScale = 1f, vOffset = 0f, vScale = 1f; private boolean hasUVTransform = false; private float[] vertex; private boolean vertexTransformationEnabled = false; private final Matrix4 positionTransform = new Matrix4(); private final Matrix3 normalTransform = new Matrix3(); private final BoundingBox bounds = new BoundingBox(); public static VertexAttributes createAttributes (long usage) { final Array attrs = new Array(); if ((usage & Usage.Position) == Usage.Position) attrs.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); if ((usage & Usage.ColorUnpacked) == Usage.ColorUnpacked) attrs.add(new VertexAttribute(Usage.ColorUnpacked, 4, ShaderProgram.COLOR_ATTRIBUTE)); if ((usage & Usage.ColorPacked) == Usage.ColorPacked) attrs.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE)); if ((usage & Usage.Normal) == Usage.Normal) attrs.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); if ((usage & Usage.TextureCoordinates) == Usage.TextureCoordinates) attrs.add(new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + ""0"")); final VertexAttribute attributes[] = new VertexAttribute[attrs.size]; for (int i = 0; i < attributes.length; i++) attributes[i] = attrs.get(i); return new VertexAttributes(attributes); } public void begin (final long attributes) { begin(createAttributes(attributes), -1); } public void begin (final VertexAttributes attributes) { begin(attributes, -1); } public void begin (final long attributes, int primitiveType) { begin(createAttributes(attributes), primitiveType); } public void begin (final VertexAttributes attributes, int primitiveType) { if (this.attributes != null) throw new RuntimeException(""Call end() first""); this.attributes = attributes; this.vertices.clear(); this.indices.clear(); this.parts.clear(); this.vindex = 0; this.lastIndex = -1; this.istart = 0; this.part = null; this.stride = attributes.vertexSize / 4; if (this.vertex == null || this.vertex.length < stride) this.vertex = new float[stride]; VertexAttribute a = attributes.findByUsage(Usage.Position); if (a == null) throw new GdxRuntimeException(""Cannot build mesh without position attribute""); posOffset = a.offset / 4; posSize = a.numComponents; a = attributes.findByUsage(Usage.Normal); norOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.BiNormal); biNorOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.Tangent); tangentOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.ColorUnpacked); colOffset = a == null ? -1 : a.offset / 4; colSize = a == null ? 0 : a.numComponents; a = attributes.findByUsage(Usage.ColorPacked); cpOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.TextureCoordinates); uvOffset = a == null ? -1 : a.offset / 4; setColor(null); setVertexTransform(null); setUVRange(null); this.primitiveType = primitiveType; bounds.inf(); } private void endpart () { if (part != null) { bounds.getCenter(part.center); bounds.getDimensions(part.halfExtents).scl(0.5f); part.radius = part.halfExtents.len(); bounds.inf(); part.offset = istart; part.size = indices.size - istart; istart = indices.size; part = null; } } public MeshPart part (final String id, int primitiveType) { return part(id, primitiveType, new MeshPart()); } public MeshPart part (final String id, final int primitiveType, MeshPart meshPart) { if (this.attributes == null) throw new RuntimeException(""Call begin() first""); endpart(); part = meshPart; part.id = id; this.primitiveType = part.primitiveType = primitiveType; parts.add(part); setColor(null); setVertexTransform(null); setUVRange(null); return part; } public Mesh end (Mesh mesh) { endpart(); if (attributes == null) throw new GdxRuntimeException(""Call begin() first""); if (!attributes.equals(mesh.getVertexAttributes())) throw new GdxRuntimeException(""Mesh attributes don't match""); if ((mesh.getMaxVertices() * stride) < vertices.size) throw new GdxRuntimeException( ""Mesh can't hold enough vertices: "" + mesh.getMaxVertices() + "" * "" + stride + "" < "" + vertices.size); if (mesh.getMaxIndices() < indices.size) throw new GdxRuntimeException(""Mesh can't hold enough indices: "" + mesh.getMaxIndices() + "" < "" + indices.size); mesh.setVertices(vertices.items, 0, vertices.size); mesh.setIndices(indices.items, 0, indices.size); for (MeshPart p : parts) p.mesh = mesh; parts.clear(); attributes = null; vertices.clear(); indices.clear(); return mesh; } public Mesh end () { return end(new Mesh(true, Math.min(vertices.size / stride, MAX_VERTICES), indices.size, attributes)); } public void clear () { this.vertices.clear(); this.indices.clear(); this.parts.clear(); this.vindex = 0; this.lastIndex = -1; this.istart = 0; this.part = null; } public int getFloatsPerVertex () { return stride; } public int getNumVertices () { return vertices.size / stride; } public void getVertices (float[] out, int destOffset) { if (attributes == null) throw new GdxRuntimeException(""Must be called in between #begin and #end""); if ((destOffset < 0) || (destOffset > out.length - vertices.size)) throw new GdxRuntimeException(""Array too small or offset out of range""); System.arraycopy(vertices.items, 0, out, destOffset, vertices.size); } protected float[] getVertices () { return vertices.items; } public int getNumIndices () { return indices.size; } public void getIndices (short[] out, int destOffset) { if (attributes == null) throw new GdxRuntimeException(""Must be called in between #begin and #end""); if ((destOffset < 0) || (destOffset > out.length - indices.size)) throw new GdxRuntimeException(""Array too small or offset out of range""); System.arraycopy(indices.items, 0, out, destOffset, indices.size); } protected short[] getIndices () { return indices.items; } @Override public VertexAttributes getAttributes () { return attributes; } @Override public MeshPart getMeshPart () { return part; } @Override public int getPrimitiveType () { return primitiveType; } @Override public void setColor (float r, float g, float b, float a) { color.set(r, g, b, a); hasColor = !color.equals(Color.WHITE); } @Override public void setColor (final Color color) { this.color.set(!(hasColor = (color != null)) ? Color.WHITE : color); } @Override public void setUVRange (float u1, float v1, float u2, float v2) { uOffset = u1; vOffset = v1; uScale = u2 - u1; vScale = v2 - v1; hasUVTransform = !(MathUtils.isZero(u1) && MathUtils.isZero(v1) && MathUtils.isEqual(u2, 1f) && MathUtils.isEqual(v2, 1f)); } @Override public void setUVRange (TextureRegion region) { if (region == null) { hasUVTransform = false; uOffset = vOffset = 0f; uScale = vScale = 1f; } else { hasUVTransform = true; setUVRange(region.getU(), region.getV(), region.getU2(), region.getV2()); } } @Override public Matrix4 getVertexTransform (Matrix4 out) { return out.set(positionTransform); } @Override public void setVertexTransform (Matrix4 transform) { vertexTransformationEnabled = transform != null; if (vertexTransformationEnabled) { positionTransform.set(transform); normalTransform.set(transform).inv().transpose(); } else { positionTransform.idt(); normalTransform.idt(); } } @Override public boolean isVertexTransformationEnabled () { return vertexTransformationEnabled; } @Override public void setVertexTransformationEnabled (boolean enabled) { vertexTransformationEnabled = enabled; } @Override public void ensureVertices (int numVertices) { vertices.ensureCapacity(stride * numVertices); } @Override public void ensureIndices (int numIndices) { indices.ensureCapacity(numIndices); } @Override public void ensureCapacity (int numVertices, int numIndices) { ensureVertices(numVertices); ensureIndices(numIndices); } @Override public void ensureTriangleIndices (int numTriangles) { if (primitiveType == GL20.GL_LINES) ensureIndices(6 * numTriangles); else if (primitiveType == GL20.GL_TRIANGLES || primitiveType == GL20.GL_POINTS) ensureIndices(3 * numTriangles); else throw new GdxRuntimeException(""Incorrect primtive type""); } @Deprecated public void ensureTriangles (int numVertices, int numTriangles) { ensureVertices(numVertices); ensureTriangleIndices(numTriangles); } @Deprecated public void ensureTriangles (int numTriangles) { ensureVertices(3 * numTriangles); ensureTriangleIndices(numTriangles); } @Override public void ensureRectangleIndices (int numRectangles) { if (primitiveType == GL20.GL_POINTS) ensureIndices(4 * numRectangles); else if (primitiveType == GL20.GL_LINES) ensureIndices(8 * numRectangles); else ensureIndices(6 * numRectangles); } @Deprecated public void ensureRectangles (int numVertices, int numRectangles) { ensureVertices(numVertices); ensureRectangleIndices(numRectangles); } @Deprecated public void ensureRectangles (int numRectangles) { ensureVertices(4 * numRectangles); ensureRectangleIndices(numRectangles); } private int lastIndex = -1; @Override public int lastIndex () { return lastIndex; } private final static Vector3 vTmp = new Vector3(); private final static void transformPosition (final float[] values, final int offset, final int size, Matrix4 transform) { if (size > 2) { vTmp.set(values[offset], values[offset + 1], values[offset + 2]).mul(transform); values[offset] = vTmp.x; values[offset + 1] = vTmp.y; values[offset + 2] = vTmp.z; } else if (size > 1) { vTmp.set(values[offset], values[offset + 1], 0).mul(transform); values[offset] = vTmp.x; values[offset + 1] = vTmp.y; } else values[offset] = vTmp.set(values[offset], 0, 0).mul(transform).x; } private final static void transformNormal (final float[] values, final int offset, final int size, Matrix3 transform) { if (size > 2) { vTmp.set(values[offset], values[offset + 1], values[offset + 2]).mul(transform).nor(); values[offset] = vTmp.x; values[offset + 1] = vTmp.y; values[offset + 2] = vTmp.z; } else if (size > 1) { vTmp.set(values[offset], values[offset + 1], 0).mul(transform).nor(); values[offset] = vTmp.x; values[offset + 1] = vTmp.y; } else values[offset] = vTmp.set(values[offset], 0, 0).mul(transform).nor().x; } private final void addVertex (final float[] values, final int offset) { final int o = vertices.size; vertices.addAll(values, offset, stride); lastIndex = vindex++; if (vertexTransformationEnabled) { transformPosition(vertices.items, o + posOffset, posSize, positionTransform); if (norOffset >= 0) transformNormal(vertices.items, o + norOffset, 3, normalTransform); if (biNorOffset >= 0) transformNormal(vertices.items, o + biNorOffset, 3, normalTransform); if (tangentOffset >= 0) transformNormal(vertices.items, o + tangentOffset, 3, normalTransform); } final float x = vertices.items[o + posOffset]; final float y = (posSize > 1) ? vertices.items[o + posOffset + 1] : 0f; final float z = (posSize > 2) ? vertices.items[o + posOffset + 2] : 0f; bounds.ext(x, y, z); if (hasColor) { if (colOffset >= 0) { vertices.items[o + colOffset] *= color.r; vertices.items[o + colOffset + 1] *= color.g; vertices.items[o + colOffset + 2] *= color.b; if (colSize > 3) vertices.items[o + colOffset + 3] *= color.a; } else if (cpOffset >= 0) { Color.abgr8888ToColor(tempC1, vertices.items[o + cpOffset]); vertices.items[o + cpOffset] = tempC1.mul(color).toFloatBits(); } } if (hasUVTransform && uvOffset >= 0) { vertices.items[o + uvOffset] = uOffset + uScale * vertices.items[o + uvOffset]; vertices.items[o + uvOffset + 1] = vOffset + vScale * vertices.items[o + uvOffset + 1]; } } private final Vector3 tmpNormal = new Vector3(); @Override public short vertex (Vector3 pos, Vector3 nor, Color col, Vector2 uv) { if (vindex > MAX_INDEX) throw new GdxRuntimeException(""Too many vertices used""); vertex[posOffset] = pos.x; if (posSize > 1) vertex[posOffset + 1] = pos.y; if (posSize > 2) vertex[posOffset + 2] = pos.z; if (norOffset >= 0) { if (nor == null) nor = tmpNormal.set(pos).nor(); vertex[norOffset] = nor.x; vertex[norOffset + 1] = nor.y; vertex[norOffset + 2] = nor.z; } if (colOffset >= 0) { if (col == null) col = Color.WHITE; vertex[colOffset] = col.r; vertex[colOffset + 1] = col.g; vertex[colOffset + 2] = col.b; if (colSize > 3) vertex[colOffset + 3] = col.a; } else if (cpOffset > 0) { if (col == null) col = Color.WHITE; vertex[cpOffset] = col.toFloatBits(); } if (uv != null && uvOffset >= 0) { vertex[uvOffset] = uv.x; vertex[uvOffset + 1] = uv.y; } addVertex(vertex, 0); return (short)lastIndex; } @Override public short vertex (final float... values) { final int n = values.length - stride; for (int i = 0; i <= n; i += stride) addVertex(values, i); return (short)lastIndex; } @Override public short vertex (final VertexInfo info) { return vertex(info.hasPosition ? info.position : null, info.hasNormal ? info.normal : null, info.hasColor ? info.color : null, info.hasUV ? info.uv : null); } @Override public void index (final short value) { indices.add(value); } @Override public void index (final short value1, final short value2) { ensureIndices(2); indices.add(value1); indices.add(value2); } @Override public void index (final short value1, final short value2, final short value3) { ensureIndices(3); indices.add(value1); indices.add(value2); indices.add(value3); } @Override public void index (final short value1, final short value2, final short value3, final short value4) { ensureIndices(4); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); } @Override public void index (short value1, short value2, short value3, short value4, short value5, short value6) { ensureIndices(6); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); indices.add(value5); indices.add(value6); } @Override public void index (short value1, short value2, short value3, short value4, short value5, short value6, short value7, short value8) { ensureIndices(8); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); indices.add(value5); indices.add(value6); indices.add(value7); indices.add(value8); } @Override public void line (short index1, short index2) { if (primitiveType != GL20.GL_LINES) throw new GdxRuntimeException(""Incorrect primitive type""); index(index1, index2); } @Override public void line (VertexInfo p1, VertexInfo p2) { ensureVertices(2); line(vertex(p1), vertex(p2)); } @Override public void line (Vector3 p1, Vector3 p2) { line(vertTmp1.set(p1, null, null, null), vertTmp2.set(p2, null, null, null)); } @Override public void line (float x1, float y1, float z1, float x2, float y2, float z2) { line(vertTmp1.set(null, null, null, null).setPos(x1, y1, z1), vertTmp2.set(null, null, null, null).setPos(x2, y2, z2)); } @Override public void line (Vector3 p1, Color c1, Vector3 p2, Color c2) { line(vertTmp1.set(p1, null, c1, null), vertTmp2.set(p2, null, c2, null)); } @Override public void triangle (short index1, short index2, short index3) { if (primitiveType == GL20.GL_TRIANGLES || primitiveType == GL20.GL_POINTS) { index(index1, index2, index3); } else if (primitiveType == GL20.GL_LINES) { index(index1, index2, index2, index3, index3, index1); } else throw new GdxRuntimeException(""Incorrect primitive type""); } @Override public void triangle (VertexInfo p1, VertexInfo p2, VertexInfo p3) { ensureVertices(3); triangle(vertex(p1), vertex(p2), vertex(p3)); } @Override public void triangle (Vector3 p1, Vector3 p2, Vector3 p3) { triangle(vertTmp1.set(p1, null, null, null), vertTmp2.set(p2, null, null, null), vertTmp3.set(p3, null, null, null)); } @Override public void triangle (Vector3 p1, Color c1, Vector3 p2, Color c2, Vector3 p3, Color c3) { triangle(vertTmp1.set(p1, null, c1, null), vertTmp2.set(p2, null, c2, null), vertTmp3.set(p3, null, c3, null)); } @Override public void rect (short corner00, short [MASK], short corner11, short corner01) { if (primitiveType == GL20.GL_TRIANGLES) { index(corner00, [MASK], corner11, corner11, corner01, corner00); } else if (primitiveType == GL20.GL_LINES) { index(corner00, [MASK], [MASK], corner11, corner11, corner01, corner01, corner00); } else if (primitiveType == GL20.GL_POINTS) { index(corner00, [MASK], corner11, corner01); } else throw new GdxRuntimeException(""Incorrect primitive type""); } @Override public void rect (VertexInfo corner00, VertexInfo [MASK], VertexInfo corner11, VertexInfo corner01) { ensureVertices(4); rect(vertex(corner00), vertex([MASK]), vertex(corner11), vertex(corner01)); } @Override public void rect (Vector3 corner00, Vector3 [MASK], Vector3 corner11, Vector3 corner01, Vector3 normal) { rect(vertTmp1.set(corner00, normal, null, null).setUV(0f, 1f), vertTmp2.set([MASK], normal, null, null).setUV(1f, 1f), vertTmp3.set(corner11, normal, null, null).setUV(1f, 0f), vertTmp4.set(corner01, normal, null, null).setUV(0f, 0f)); } @Override public void rect (float x00, float y00, float z00, float x10, float y10, float z10, float x11, float y11, float z11, float x01, float y01, float z01, float normalX, float normalY, float normalZ) { rect(vertTmp1.set(null, null, null, null).setPos(x00, y00, z00).setNor(normalX, normalY, normalZ).setUV(0f, 1f), vertTmp2.set(null, null, null, null).setPos(x10, y10, z10).setNor(normalX, normalY, normalZ).setUV(1f, 1f), vertTmp3.set(null, null, null, null).setPos(x11, y11, z11).setNor(normalX, normalY, normalZ).setUV(1f, 0f), vertTmp4.set(null, null, null, null).setPos(x01, y01, z01).setNor(normalX, normalY, normalZ).setUV(0f, 0f)); } @Override public void addMesh (Mesh mesh) { addMesh(mesh, 0, mesh.getNumIndices()); } @Override public void addMesh (MeshPart meshpart) { if (meshpart.primitiveType != primitiveType) throw new GdxRuntimeException(""Primitive type doesn't match""); addMesh(meshpart.mesh, meshpart.offset, meshpart.size); } @Override public void addMesh (Mesh mesh, int indexOffset, int numIndices) { if (!attributes.equals(mesh.getVertexAttributes())) throw new GdxRuntimeException(""Vertex attributes do not match""); if (numIndices <= 0) return; int numFloats = mesh.getNumVertices() * stride; tmpVertices.clear(); tmpVertices.ensureCapacity(numFloats); tmpVertices.size = numFloats; mesh.getVertices(tmpVertices.items); tmpIndices.clear(); tmpIndices.ensureCapacity(numIndices); tmpIndices.size = numIndices; mesh.getIndices(indexOffset, numIndices, tmpIndices.items, 0); addMesh(tmpVertices.items, tmpIndices.items, 0, numIndices); } private static IntIntMap indicesMap = null; @Override public void addMesh (float[] vertices, short[] indices, int indexOffset, int numIndices) { if (indicesMap == null) indicesMap = new IntIntMap(numIndices); else { indicesMap.clear(); indicesMap.ensureCapacity(numIndices); } ensureIndices(numIndices); final int numVertices = vertices.length / stride; ensureVertices(numVertices < numIndices ? numVertices : numIndices); for (int i = 0; i < numIndices; i++) { final int sidx = indices[indexOffset + i] & 0xFFFF; int didx = indicesMap.get(sidx, -1); if (didx < 0) { addVertex(vertices, sidx * stride); indicesMap.put(sidx, didx = lastIndex); } index((short)didx); } } @Override public void addMesh (float[] vertices, short[] indices) { final int offset = lastIndex + 1; final int numVertices = vertices.length / stride; ensureVertices(numVertices); for (int v = 0; v < vertices.length; v += stride) addVertex(vertices, v); ensureIndices(indices.length); for (int i = 0; i < indices.length; ++i) index((short)((indices[i] & 0xFFFF) + offset)); } @Override @Deprecated public void patch (VertexInfo corner00, VertexInfo [MASK], VertexInfo corner11, VertexInfo corner01, int divisionsU, int divisionsV) { PatchShapeBuilder.build(this, corner00, [MASK], corner11, corner01, divisionsU, divisionsV); } @Override @Deprecated public void patch (Vector3 corner00, Vector3 [MASK], Vector3 corner11, Vector3 corner01, Vector3 normal, int divisionsU, int divisionsV) { PatchShapeBuilder.build(this, corner00, [MASK], corner11, corner01, normal, divisionsU, divisionsV); } @Override @Deprecated public void patch (float x00, float y00, float z00, float x10, float y10, float z10, float x11, float y11, float z11, float x01, float y01, float z01, float normalX, float normalY, float normalZ, int divisionsU, int divisionsV) { PatchShapeBuilder.build(this, x00, y00, z00, x10, y10, z10, x11, y11, z11, x01, y01, z01, normalX, normalY, normalZ, divisionsU, divisionsV); } @Override @Deprecated public void box (VertexInfo corner000, VertexInfo corner010, VertexInfo corner100, VertexInfo corner110, VertexInfo corner001, VertexInfo corner011, VertexInfo corner101, VertexInfo corner111) { BoxShapeBuilder.build(this, corner000, corner010, corner100, corner110, corner001, corner011, corner101, corner111); } @Override @Deprecated public void box (Vector3 corner000, Vector3 corner010, Vector3 corner100, Vector3 corner110, Vector3 corner001, Vector3 corner011, Vector3 corner101, Vector3 corner111) { BoxShapeBuilder.build(this, corner000, corner010, corner100, corner110, corner001, corner011, corner101, corner111); } @Override @Deprecated public void box (Matrix4 transform) { BoxShapeBuilder.build(this, transform); } @Override @Deprecated public void box (float width, float height, float depth) { BoxShapeBuilder.build(this, width, height, depth); } @Override @Deprecated public void box (float x, float y, float z, float width, float height, float depth) { BoxShapeBuilder.build(this, x, y, z, width, height, depth); } @Override @Deprecated public void circle (float radius, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ) { EllipseShapeBuilder.build(this, radius, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ); } @Override @Deprecated public void circle (float radius, int divisions, final Vector3 center, final Vector3 normal) { EllipseShapeBuilder.build(this, radius, divisions, center, normal); } @Override @Deprecated public void circle (float radius, int divisions, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal) { EllipseShapeBuilder.build(this, radius, divisions, center, normal, tangent, binormal); } @Override @Deprecated public void circle (float radius, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ) { EllipseShapeBuilder.build(this, radius, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ); } @Override @Deprecated public void circle (float radius, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, radius, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, angleFrom, angleTo); } @Override @Deprecated public void circle (float radius, int divisions, final Vector3 center, final Vector3 normal, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, radius, divisions, center, normal, angleFrom, angleTo); } @Override @Deprecated public void circle (float radius, int divisions, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal, float angleFrom, float angleTo) { circle(radius, divisions, center.x, center.y, center.z, normal.x, normal.y, normal.z, tangent.x, tangent.y, tangent.z, binormal.x, binormal.y, binormal.z, angleFrom, angleTo); } @Override @Deprecated public void circle (float radius, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, radius, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, angleFrom, angleTo); } @Override @Deprecated public void ellipse (float width, float height, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ) { EllipseShapeBuilder.build(this, width, height, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ); } @Override @Deprecated public void ellipse (float width, float height, int divisions, final Vector3 center, final Vector3 normal) { EllipseShapeBuilder.build(this, width, height, divisions, center, normal); } @Override @Deprecated public void ellipse (float width, float height, int divisions, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal) { EllipseShapeBuilder.build(this, width, height, divisions, center, normal, tangent, binormal); } @Override @Deprecated public void ellipse (float width, float height, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ) { EllipseShapeBuilder.build(this, width, height, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ); } @Override @Deprecated public void ellipse (float width, float height, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, width, height, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, angleFrom, angleTo); } @Override @Deprecated public void ellipse (float width, float height, int divisions, final Vector3 center, final Vector3 normal, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, width, height, divisions, center, normal, angleFrom, angleTo); } @Override @Deprecated public void ellipse (float width, float height, int divisions, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, width, height, divisions, center, normal, tangent, binormal, angleFrom, angleTo); } @Override @Deprecated public void ellipse (float width, float height, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, width, height, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, angleFrom, angleTo); } @Override @Deprecated public void ellipse (float width, float height, float innerWidth, float innerHeight, int divisions, Vector3 center, Vector3 normal) { EllipseShapeBuilder.build(this, width, height, innerWidth, innerHeight, divisions, center, normal); } @Override @Deprecated public void ellipse (float width, float height, float innerWidth, float innerHeight, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ) { EllipseShapeBuilder.build(this, width, height, innerWidth, innerHeight, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ); } @Override @Deprecated public void ellipse (float width, float height, float innerWidth, float innerHeight, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, width, height, innerWidth, innerHeight, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, angleFrom, angleTo); } @Override @Deprecated public void ellipse (float width, float height, float innerWidth, float innerHeight, int divisions, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, float angleFrom, float angleTo) { EllipseShapeBuilder.build(this, width, height, innerWidth, innerHeight, divisions, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, angleFrom, angleTo); } @Override @Deprecated public void cylinder (float width, float height, float depth, int divisions) { CylinderShapeBuilder.build(this, width, height, depth, divisions); } @Override @Deprecated public void cylinder (float width, float height, float depth, int divisions, float angleFrom, float angleTo) { CylinderShapeBuilder.build(this, width, height, depth, divisions, angleFrom, angleTo); } @Override @Deprecated public void cylinder (float width, float height, float depth, int divisions, float angleFrom, float angleTo, boolean close) { CylinderShapeBuilder.build(this, width, height, depth, divisions, angleFrom, angleTo, close); } @Override @Deprecated public void cone (float width, float height, float depth, int divisions) { cone(width, height, depth, divisions, 0, 360); } @Override @Deprecated public void cone (float width, float height, float depth, int divisions, float angleFrom, float angleTo) { ConeShapeBuilder.build(this, width, height, depth, divisions, angleFrom, angleTo); } @Override @Deprecated public void sphere (float width, float height, float depth, int divisionsU, int divisionsV) { SphereShapeBuilder.build(this, width, height, depth, divisionsU, divisionsV); } @Override @Deprecated public void sphere (final Matrix4 transform, float width, float height, float depth, int divisionsU, int divisionsV) { SphereShapeBuilder.build(this, transform, width, height, depth, divisionsU, divisionsV); } @Override @Deprecated public void sphere (float width, float height, float depth, int divisionsU, int divisionsV, float angleUFrom, float angleUTo, float angleVFrom, float angleVTo) { SphereShapeBuilder.build(this, width, height, depth, divisionsU, divisionsV, angleUFrom, angleUTo, angleVFrom, angleVTo); } @Override @Deprecated public void sphere (final Matrix4 transform, float width, float height, float depth, int divisionsU, int divisionsV, float angleUFrom, float angleUTo, float angleVFrom, float angleVTo) { SphereShapeBuilder.build(this, transform, width, height, depth, divisionsU, divisionsV, angleUFrom, angleUTo, angleVFrom, angleVTo); } @Override @Deprecated public void capsule (float radius, float height, int divisions) { CapsuleShapeBuilder.build(this, radius, height, divisions); } @Override @Deprecated public void arrow (float x1, float y1, float z1, float x2, float y2, float z2, float capLength, float stemThickness, int divisions) { ArrowShapeBuilder.build(this, x1, y1, z1, x2, y2, z2, capLength, stemThickness, divisions); } }",corner10,java,libgdx "package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_byte extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String [MASK] = JSON.toJSONString(v); V0 v1 = JSON.parseObject([MASK], V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private byte i = 12; public byte getI() { return i; } public void setI(byte i) { this.i = i; } } }",text,java,fastjson "package org.apache.dubbo.metadata.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.junit.jupiter.api.Test; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.Set; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private PrimitiveTypeDefinitionBuilder builder; private VariableElement zField; private VariableElement bField; private VariableElement cField; private VariableElement sField; private VariableElement iField; private VariableElement lField; private VariableElement fField; private VariableElement dField; @Override protected void addCompiledClasses(Set> classesToBeCompiled) { classesToBeCompiled.add(PrimitiveTypeModel.class); } @Override protected void beforeEach() { builder = new PrimitiveTypeDefinitionBuilder(); TypeElement testType = getType(PrimitiveTypeModel.class); zField = findField( testType, ""z""); bField = findField( testType, ""b""); cField = findField( testType, ""c""); sField = findField( testType, ""s""); iField = findField( testType, ""i""); lField = findField( testType, ""l""); fField = findField( testType, ""f""); dField = findField( testType, ""d""); assertEquals(""boolean"", zField.asType().toString()); assertEquals(""byte"", bField.asType().toString()); assertEquals(""char"", cField.asType().toString()); assertEquals(""short"", sField.asType().toString()); assertEquals(""int"", iField.asType().toString()); assertEquals(""long"", lField.asType().toString()); assertEquals(""float"", fField.asType().toString()); assertEquals(""double"", dField.asType().toString()); } @Test public void testAccept() { assertTrue(builder.accept(processingEnv, zField.asType())); assertTrue(builder.accept(processingEnv, bField.asType())); assertTrue(builder.accept(processingEnv, cField.asType())); assertTrue(builder.accept(processingEnv, sField.asType())); assertTrue(builder.accept(processingEnv, iField.asType())); assertTrue(builder.accept(processingEnv, lField.asType())); assertTrue(builder.accept(processingEnv, fField.asType())); assertTrue(builder.accept(processingEnv, dField.asType())); } @Test public void testBuild() { buildAndAssertTypeDefinition(processingEnv, zField, builder); buildAndAssertTypeDefinition(processingEnv, bField, builder); buildAndAssertTypeDefinition(processingEnv, cField, builder); buildAndAssertTypeDefinition(processingEnv, sField, builder); buildAndAssertTypeDefinition(processingEnv, iField, builder); buildAndAssertTypeDefinition(processingEnv, lField, builder); buildAndAssertTypeDefinition(processingEnv, zField, builder); buildAndAssertTypeDefinition(processingEnv, fField, builder); buildAndAssertTypeDefinition(processingEnv, dField, builder); } static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, TypeDefinitionBuilder builder) { TypeDefinition [MASK] = TypeDefinitionBuilder.build(processingEnv, field); assertBasicTypeDefinition([MASK], field.asType().toString(), builder); } static void assertBasicTypeDefinition(TypeDefinition [MASK], String type, TypeDefinitionBuilder builder) { assertEquals(type, [MASK].getType()); assertTrue([MASK].getProperties().isEmpty()); assertTrue([MASK].getItems().isEmpty()); assertTrue([MASK].getEnums().isEmpty()); assertNull([MASK].getId()); } }",typeDefinition,java,incubator-dubbo "package com.alibaba.json.bvt.parser.deser.array; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class FieldIntArrayTest_private extends TestCase { public void test_intArray() throws Exception { Model [MASK] = JSON.parseObject(""{\""value\"":[1,2,3]}"", Model.class); assertNotNull([MASK].value); assertEquals(3, [MASK].value.length); assertEquals(1, [MASK].value[0]); assertEquals(2, [MASK].value[1]); assertEquals(3, [MASK].value[2]); } private static class Model { public int[] value; } }",model,java,fastjson "package com.netflix.hystrix.metric.sample; import com.netflix.hystrix.HystrixThreadPoolMetrics; public class HystrixThreadPoolUtilization { private final int currentActiveCount; private final int currentCorePoolSize; private final int [MASK]; private final int currentQueueSize; public HystrixThreadPoolUtilization(int currentActiveCount, int currentCorePoolSize, int [MASK], int currentQueueSize) { this.currentActiveCount = currentActiveCount; this.currentCorePoolSize = currentCorePoolSize; this.[MASK] = [MASK]; this.currentQueueSize = currentQueueSize; } public static HystrixThreadPoolUtilization sample(HystrixThreadPoolMetrics threadPoolMetrics) { return new HystrixThreadPoolUtilization( threadPoolMetrics.getCurrentActiveCount().intValue(), threadPoolMetrics.getCurrentCorePoolSize().intValue(), threadPoolMetrics.getCurrentPoolSize().intValue(), threadPoolMetrics.getCurrentQueueSize().intValue() ); } public int getCurrentActiveCount() { return currentActiveCount; } public int getCurrentCorePoolSize() { return currentCorePoolSize; } public int getCurrentPoolSize() { return [MASK]; } public int getCurrentQueueSize() { return currentQueueSize; } }",currentPoolSize,java,Hystrix "package org.apache.dubbo.remoting.transport.mina; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; public class MinaHandler extends IoHandlerAdapter { private final URL url; private final ChannelHandler handler; public MinaHandler(URL url, ChannelHandler handler) { if (url == null) { throw new IllegalArgumentException(""url == null""); } if (handler == null) { throw new IllegalArgumentException(""handler == null""); } this.url = url; this.handler = handler; } @Override public void sessionOpened(IoSession session) throws Exception { MinaChannel [MASK] = MinaChannel.getOrAddChannel(session, url, handler); try { handler.connected([MASK]); } finally { MinaChannel.removeChannelIfDisconnected(session); } } @Override public void sessionClosed(IoSession session) throws Exception { MinaChannel [MASK] = MinaChannel.getOrAddChannel(session, url, handler); try { handler.disconnected([MASK]); } finally { MinaChannel.removeChannelIfDisconnected(session); } } @Override public void messageReceived(IoSession session, Object message) throws Exception { MinaChannel [MASK] = MinaChannel.getOrAddChannel(session, url, handler); try { handler.received([MASK], message); } finally { MinaChannel.removeChannelIfDisconnected(session); } } @Override public void messageSent(IoSession session, Object message) throws Exception { MinaChannel [MASK] = MinaChannel.getOrAddChannel(session, url, handler); try { handler.sent([MASK], message); } finally { MinaChannel.removeChannelIfDisconnected(session); } } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { MinaChannel [MASK] = MinaChannel.getOrAddChannel(session, url, handler); try { handler.caught([MASK], cause); } finally { MinaChannel.removeChannelIfDisconnected(session); } } }",channel,java,incubator-dubbo "package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Invoker; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @Disabled public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { private void assertStrictWRRResult(int loop, Map resultMap) { int invokeCount = 0; for (InvokeResult invokeResult : resultMap.values()) { int count = (int) invokeResult.getCount().get(); Assertions.assertTrue( Math.abs(invokeResult.getExpected(loop) - count) < 10, ""delta with expected count should < 10""); invokeCount += count; } Assertions.assertEquals(invokeCount, loop, ""select failed!""); } @Test public void testRoundRobinLoadBalanceSelect() { int runs = 10000; Map counter = getInvokeCounter(runs, RoundRobinLoadBalance.NAME); for (Map.Entry entry : counter.entrySet()) { Long count = entry.getValue().get(); Assertions.assertTrue(Math.abs(count - runs / (0f + invokers.size())) < 1f, ""abs diff should < 1""); } } @Test public void testSelectByWeight() { final Map [MASK] = new HashMap(); final AtomicBoolean shouldBegin = new AtomicBoolean(false); final int runs = 10000; List threads = new ArrayList(); int threadNum = 10; for (int i = 0; i < threadNum; i++) { threads.add(new Thread(() -> { while (!shouldBegin.get()) { try { Thread.sleep(5); } catch (InterruptedException e) { } } Map resultMap = getWeightedInvokeResult(runs, RoundRobinLoadBalance.NAME); synchronized ([MASK]) { for (Entry entry : resultMap.entrySet()) { if (![MASK].containsKey(entry.getKey())) { [MASK].put(entry.getKey(), entry.getValue()); } else { [MASK].get(entry.getKey()).getCount().addAndGet(entry.getValue().getCount().get()); } } } })); } for (Thread thread : threads) { thread.start(); } shouldBegin.set(true); for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { } } assertStrictWRRResult(runs * threadNum, [MASK]); } @Test public void testNodeCacheShouldNotRecycle() { int loop = 10000; weightInvokers.add(weightInvokerTmp); try { Map resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME); Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); weightInvokers.remove(weightInvokerTmp); resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); Assertions.assertNotEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); } finally { weightInvokers.remove(weightInvokerTmp); } } @Test public void testNodeCacheShouldRecycle() { { Field recycleTimeField = null; try { recycleTimeField = RoundRobinLoadBalance.class.getDeclaredField(""RECYCLE_PERIOD""); ReflectUtils.makeAccessible(recycleTimeField); recycleTimeField.setInt(RoundRobinLoadBalance.class, 10); } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException | SecurityException e) { Assertions.assertTrue(true, ""getField failed""); } } int loop = 10000; weightInvokers.add(weightInvokerTmp); try { Map resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME); Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); weightInvokers.remove(weightInvokerTmp); resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); } finally { weightInvokers.remove(weightInvokerTmp); } } }",totalMap,java,incubator-dubbo "package io.netty5.channel; import io.netty5.buffer.Buffer; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; public interface ChannelPipeline extends ChannelInboundInvoker, ChannelOutboundInvoker, Iterable> { ChannelPipeline addFirst(String name, ChannelHandler handler); ChannelPipeline addLast(String name, ChannelHandler handler); ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler); ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler); ChannelPipeline addFirst(ChannelHandler... handlers); ChannelPipeline addLast(ChannelHandler... handlers); default ChannelPipeline remove(ChannelHandler handler) { if (removeIfExists(handler) == null) { throw new NoSuchElementException(); } return this; } default ChannelHandler remove(String name) { ChannelHandler handler = removeIfExists(name); if (handler == null) { throw new NoSuchElementException(); } return handler; } default T remove(Class handlerType) { T handler = removeIfExists(handlerType); if (handler == null) { throw new NoSuchElementException(); } return handler; } T removeIfExists(String name); T removeIfExists(Class handlerType); T removeIfExists(ChannelHandler handler); ChannelHandler removeFirst(); ChannelHandler removeLast(); ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler); ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler); T replace(Class oldHandlerType, String newName, ChannelHandler newHandler); default ChannelHandler first() { ChannelHandlerContext [MASK] = firstContext(); return [MASK] == null ? null : [MASK].handler(); } ChannelHandlerContext firstContext(); default ChannelHandler last() { ChannelHandlerContext [MASK] = lastContext(); return [MASK] == null ? null : [MASK].handler(); } ChannelHandlerContext lastContext(); default boolean isEmpty() { return lastContext() == null; } ChannelHandler get(String name); T get(Class handlerType); ChannelHandlerContext context(ChannelHandler handler); ChannelHandlerContext context(String name); ChannelHandlerContext context(Class handlerType); Channel channel(); default List names() { return new ArrayList<>(toMap().keySet()); } Map toMap(); @Override ChannelPipeline fireChannelRegistered(); @Override ChannelPipeline fireChannelUnregistered(); @Override ChannelPipeline fireChannelActive(); @Override ChannelPipeline fireChannelInactive(); @Override ChannelPipeline fireChannelShutdown(ChannelShutdownDirection direction); @Override ChannelPipeline fireChannelExceptionCaught(Throwable cause); @Override ChannelPipeline fireChannelInboundEvent(Object event); @Override ChannelPipeline fireChannelRead(Object msg); @Override ChannelPipeline fireChannelReadComplete(); @Override ChannelPipeline fireChannelWritabilityChanged(); @Override ChannelPipeline flush(); @Override ChannelPipeline read(ReadBufferAllocator readBufferAllocator); @Override ChannelPipeline read(); long pendingOutboundBytes(); }",ctx,java,netty "package org.apache.dubbo.remoting.codec; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.codec.ExchangeCodec; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; public class ExchangeCodecTest extends TelnetCodecTest { private static final short MAGIC = (short) 0xdabb; private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; Serialization serialization = getSerialization(Constants.DEFAULT_REMOTING_SERIALIZATION); private static Serialization getSerialization(String name) { Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); return serialization; } private Object decode(byte[] request) throws IOException { ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); AbstractMockChannel channel = getServerSideChannel(url); Object obj = codec.decode(channel, buffer); return obj; } private byte[] getRequestBytes(Object obj, byte[] header) throws IOException { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(url, bos); out.writeObject(obj); out.flushBuffer(); bos.flush(); bos.close(); byte[] data = bos.toByteArray(); byte[] len = Bytes.int2bytes(data.length); System.arraycopy(len, 0, header, 12, 4); byte[] request = join(header, data); return request; } private byte[] getReadonlyEventRequestBytes(Object obj, byte[] header) throws IOException { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(url, bos); out.writeObject(obj); out.flushBuffer(); bos.flush(); bos.close(); byte[] data = bos.toByteArray(); System.arraycopy(data, 0, header, 12, data.length); byte[] request = join(header, data); return request; } private byte[] assemblyDataProtocol(byte[] header) { Person request = new Person(); byte[] newbuf = join(header, objectToByte(request)); return newbuf; } @BeforeEach public void setUp() throws Exception { codec = new ExchangeCodec(); } @Test public void test_Decode_Error_MagicNum() throws IOException { HashMap inputBytes = new HashMap(); inputBytes.put(new byte[]{0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); inputBytes.put(new byte[]{MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); inputBytes.put(new byte[]{0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); for (Map.Entry entry: inputBytes.entrySet()) { testDecode_assertEquals(assemblyDataProtocol(entry.getKey()), entry.getValue()); } } @Test public void test_Decode_Error_Length() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x02, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Channel channel = getServerSideChannel(url); byte[] baddata = new byte[]{1, 2}; ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata)); Response obj = (Response) codec.decode(channel, buffer); Assertions.assertEquals(person, obj.getResult()); Assertions.assertEquals(request.length, buffer.readerIndex()); future.cancel(); } @Test public void test_Decode_Error_Response_Object() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x02, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); byte[] badbytes = new byte[]{-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); Response obj = (Response) decode(request); Assertions.assertEquals(90, obj.getStatus()); } @Test public void testInvalidSerializaitonId() throws Exception { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte)0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Object obj = decode(header); Assertions.assertTrue(obj instanceof Request); Request request = (Request) obj; Assertions.assertTrue(request.isBroken()); Assertions.assertTrue(request.getData() instanceof IOException); header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte)0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; obj = decode(header); Assertions.assertTrue(obj instanceof Response); Response response = (Response) obj; Assertions.assertEquals(response.getStatus(), Response.CLIENT_ERROR); Assertions.assertTrue(response.getErrorMessage().contains(""IOException"")); } @Test public void test_Decode_Check_Payload() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; byte[] request = assemblyDataProtocol(header); try { Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); Object obj = codec.decode(channel, buffer); Assertions.assertTrue(obj instanceof Response); Assertions.assertTrue(((Response) obj).getErrorMessage().startsWith( ""Data length too large: "" + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); } catch (IOException expected) { Assertions.assertTrue(expected.getMessage().startsWith(""Data length too large: "" + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); } } @Test public void test_Decode_Header_Need_Readmore() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test public void test_Decode_Body_Need_Readmore() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test public void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException { byte[] header = new byte[]{0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header); Object obj = codec.decode(channel, buffer); Assertions.assertEquals(TelnetCodec.DecodeResult.NEED_MORE_INPUT, obj); Assertions.assertEquals(2, buffer.readerIndex()); } @Test public void test_Decode_Return_Response_Person() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Response obj = (Response) decode(request); Assertions.assertEquals(20, obj.getStatus()); Assertions.assertEquals(person, obj.getResult()); System.out.println(obj); future.cancel(); } @Test public void test_Decode_Return_Response_Error() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 2, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String [MASK] = ""encode request data error ""; byte[] request = getRequestBytes([MASK], header); Response obj = (Response) decode(request); Assertions.assertEquals(90, obj.getStatus()); Assertions.assertEquals([MASK], obj.getErrorMessage()); } @Test public void test_Decode_Return_Request_Event_Object() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xe2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); System.setProperty(""deserialization.event.size"", ""100""); Request obj = (Request) decode(request); Assertions.assertEquals(person, obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertTrue(obj.isEvent()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); System.clearProperty(""deserialization.event.size""); } @Test public void test_Decode_Return_Request_Event_String() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xe2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String event = READONLY_EVENT; byte[] request = getRequestBytes(event, header); Request obj = (Request) decode(request); Assertions.assertEquals(event, obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertTrue(obj.isEvent()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @Test public void test_Decode_Return_Request_Heartbeat_Object() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xe2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; byte[] request = getRequestBytes(null, header); Request obj = (Request) decode(request); Assertions.assertNull(obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertTrue(obj.isHeartbeat()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @Test public void test_Decode_Return_Request_Object() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xc2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Request obj = (Request) decode(request); Assertions.assertEquals(person, obj.getData()); Assertions.assertTrue(obj.isTwoWay()); Assertions.assertFalse(obj.isHeartbeat()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @Test public void test_Decode_Error_Request_Object() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xe2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); byte[] badbytes = new byte[]{-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); Request obj = (Request) decode(request); Assertions.assertTrue(obj.isBroken()); Assertions.assertTrue(obj.getData() instanceof Throwable); } @Test public void test_Header_Response_NoSerializationFlag() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0x02, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Response obj = (Response) decode(request); Assertions.assertEquals(20, obj.getStatus()); Assertions.assertEquals(person, obj.getResult()); System.out.println(obj); future.cancel(); } @Test public void test_Header_Response_Heartbeat() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x02, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Response obj = (Response) decode(request); Assertions.assertEquals(20, obj.getStatus()); Assertions.assertEquals(person, obj.getResult()); System.out.println(obj); future.cancel(); } @Test public void test_Encode_Request() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(2014); Channel channel = getCliendSideChannel(url); Request request = new Request(); Person person = new Person(); request.setData(person); codec.encode(channel, encodeBuffer, request); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Request obj = (Request) codec.decode(channel, decodeBuffer); Assertions.assertEquals(request.isBroken(), obj.isBroken()); Assertions.assertEquals(request.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(request.isTwoWay(), obj.isTwoWay()); Assertions.assertEquals(person, obj.getData()); } @Test public void test_Encode_Response() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(1001), 100000, null); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getCliendSideChannel(url); Response response = new Response(); response.setHeartbeat(true); response.setId(1001L); response.setStatus((byte) 20); response.setVersion(""11""); Person person = new Person(); response.setResult(person); codec.encode(channel, encodeBuffer, response); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Response obj = (Response) codec.decode(channel, decodeBuffer); Assertions.assertEquals(response.getId(), obj.getId()); Assertions.assertEquals(response.getStatus(), obj.getStatus()); Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(person, obj.getResult()); future.cancel(); } @Test public void test_Encode_Error_Response() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getCliendSideChannel(url); Response response = new Response(); response.setHeartbeat(true); response.setId(1001L); response.setStatus((byte) 10); response.setVersion(""11""); String badString = ""bad""; response.setErrorMessage(badString); Person person = new Person(); response.setResult(person); codec.encode(channel, encodeBuffer, response); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Response obj = (Response) codec.decode(channel, decodeBuffer); Assertions.assertEquals(response.getId(), obj.getId()); Assertions.assertEquals(response.getStatus(), obj.getStatus()); Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(badString, obj.getErrorMessage()); Assertions.assertNull(obj.getResult()); } @Test public void testMessageLengthGreaterThanMessageActualLength() throws Exception { Channel channel = getCliendSideChannel(url); Request request = new Request(1L); request.setVersion(Version.getProtocolVersion()); Date date = new Date(); request.setData(date); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); codec.encode(channel, encodeBuffer, request); byte[] bytes = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(bytes); int len = Bytes.bytes2int(bytes, 12); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); out.write(bytes, 0, 12); int padding = 512; out.write(Bytes.int2bytes(len + padding)); out.write(bytes, 16, bytes.length - 16); for (int i = 0; i < padding; i++) { out.write(1); } out.write(bytes); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray()); Request decodedRequest = (Request) codec.decode(channel, decodeBuffer); Assertions.assertEquals(date, decodedRequest.getData()); Assertions.assertEquals(bytes.length + padding, decodeBuffer.readerIndex()); decodedRequest = (Request) codec.decode(channel, decodeBuffer); Assertions.assertEquals(date, decodedRequest.getData()); } @Test public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Request request = new Request(1L); request.setData(""hello""); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512); AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); try { codec.encode(channel, encodeBuffer, request); Assertions.fail(); } catch (IOException e) { Assertions.assertTrue(e.getMessage().startsWith(""Data length too large: "" + 6)); } Response response = new Response(1L); response.setResult(""hello""); encodeBuffer = ChannelBuffers.dynamicBuffer(512); channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); codec.encode(channel, encodeBuffer, response); Assertions.assertTrue(channel.getReceivedMessage() instanceof Response); Response receiveMessage = (Response) channel.getReceivedMessage(); Assertions.assertEquals(Response.SERIALIZATION_ERROR, receiveMessage.getStatus()); Assertions.assertTrue(receiveMessage.getErrorMessage().contains(""Data length too large: "")); } }",errorString,java,incubator-dubbo "package io.netty5.handler.codec.http2; import io.netty5.handler.codec.http2.Http2TestUtil.TestStreamByteDistributorStreamState; import io.netty5.util.collection.IntObjectHashMap; import io.netty5.util.collection.IntObjectMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; import org.mockito.verification.VerificationMode; import static io.netty5.handler.codec.http2.Http2CodecUtil.DEFAULT_MIN_ALLOCATION_CHUNK; import static io.netty5.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class UniformStreamByteDistributorTest { private static final int CHUNK_SIZE = DEFAULT_MIN_ALLOCATION_CHUNK; private static final int STREAM_A = 1; private static final int STREAM_B = 3; private static final int STREAM_C = 5; private static final int STREAM_D = 7; private Http2Connection connection; private UniformStreamByteDistributor distributor; private IntObjectMap stateMap; @Mock private StreamByteDistributor.Writer writer; @BeforeEach public void setup() throws Http2Exception { MockitoAnnotations.initMocks(this); stateMap = new IntObjectHashMap(); connection = new DefaultHttp2Connection(false); distributor = new UniformStreamByteDistributor(connection); resetWriter(); connection.local().createStream(STREAM_A, false); connection.local().createStream(STREAM_B, false); Http2Stream [MASK] = connection.local().createStream(STREAM_C, false); Http2Stream streamD = connection.local().createStream(STREAM_D, false); setPriority([MASK].id(), STREAM_A, DEFAULT_PRIORITY_WEIGHT, false); setPriority(streamD.id(), STREAM_A, DEFAULT_PRIORITY_WEIGHT, false); } private Answer writeAnswer() { return in -> { Http2Stream stream = in.getArgument(0); int numBytes = in.getArgument(1); TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); state.pendingBytes -= numBytes; state.hasFrame = state.pendingBytes > 0; distributor.updateStreamableBytes(state); return null; }; } private void resetWriter() { reset(writer); doAnswer(writeAnswer()).when(writer).write(any(Http2Stream.class), anyInt()); } @Test public void bytesUnassignedAfterProcessing() throws Http2Exception { initState(STREAM_A, 1, true); initState(STREAM_B, 2, true); initState(STREAM_C, 3, true); initState(STREAM_D, 4, true); assertFalse(write(10)); verifyWrite(STREAM_A, 1); verifyWrite(STREAM_B, 2); verifyWrite(STREAM_C, 3); verifyWrite(STREAM_D, 4); verifyNoMoreInteractions(writer); assertFalse(write(10)); verifyNoMoreInteractions(writer); } @Test public void connectionErrorForWriterException() throws Http2Exception { initState(STREAM_A, 1, true); initState(STREAM_B, 2, true); initState(STREAM_C, 3, true); initState(STREAM_D, 4, true); Exception fakeException = new RuntimeException(""Fake exception""); doThrow(fakeException).when(writer).write(same(stream(STREAM_C)), eq(3)); Http2Exception e = assertThrows(Http2Exception.class, new Executable() { @Override public void execute() throws Throwable { write(10); } }); assertFalse(Http2Exception.isStreamError(e)); assertEquals(Http2Error.INTERNAL_ERROR, e.error()); assertSame(fakeException, e.getCause()); verifyWrite(atMost(1), STREAM_A, 1); verifyWrite(atMost(1), STREAM_B, 2); verifyWrite(STREAM_C, 3); verifyWrite(atMost(1), STREAM_D, 4); doNothing().when(writer).write(same(stream(STREAM_C)), eq(3)); write(10); verifyWrite(STREAM_A, 1); verifyWrite(STREAM_B, 2); verifyWrite(STREAM_C, 3); verifyWrite(STREAM_D, 4); } @Test public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { setPriority(STREAM_A, 0, (short) 50, false); setPriority(STREAM_B, 0, (short) 200, false); setPriority(STREAM_C, STREAM_A, (short) 100, false); setPriority(STREAM_D, STREAM_A, (short) 100, false); initState(STREAM_A, CHUNK_SIZE, true); initState(STREAM_B, CHUNK_SIZE, true); initState(STREAM_C, CHUNK_SIZE, true); initState(STREAM_D, CHUNK_SIZE, true); int written = 3 * CHUNK_SIZE; assertTrue(write(written)); assertEquals(CHUNK_SIZE, captureWrite(STREAM_A)); assertEquals(CHUNK_SIZE, captureWrite(STREAM_B)); assertEquals(CHUNK_SIZE, captureWrite(STREAM_C)); verifyNoMoreInteractions(writer); resetWriter(); assertFalse(write(CHUNK_SIZE)); assertEquals(CHUNK_SIZE, captureWrite(STREAM_D)); verifyNoMoreInteractions(writer); } @Test public void streamWithMoreDataShouldBeEnqueuedAfterWrite() throws Http2Exception { initState(STREAM_A, 2 * CHUNK_SIZE, true); assertTrue(write(CHUNK_SIZE)); assertEquals(CHUNK_SIZE, captureWrite(STREAM_A)); verifyNoMoreInteractions(writer); resetWriter(); assertFalse(write(CHUNK_SIZE)); assertEquals(CHUNK_SIZE, captureWrite(STREAM_A)); verifyNoMoreInteractions(writer); } @Test public void emptyFrameAtHeadIsWritten() throws Http2Exception { initState(STREAM_A, 10, true); initState(STREAM_B, 0, true); initState(STREAM_C, 0, true); initState(STREAM_D, 10, true); assertTrue(write(10)); verifyWrite(STREAM_A, 10); verifyWrite(STREAM_B, 0); verifyWrite(STREAM_C, 0); verifyNoMoreInteractions(writer); } @Test public void streamWindowExhaustedDoesNotWrite() throws Http2Exception { initState(STREAM_A, 0, true, false); initState(STREAM_B, 0, true); initState(STREAM_C, 0, true); initState(STREAM_D, 0, true, false); assertFalse(write(10)); verifyWrite(STREAM_B, 0); verifyWrite(STREAM_C, 0); verifyNoMoreInteractions(writer); } @Test public void streamWindowLargerThanIntDoesNotInfiniteLoop() throws Http2Exception { initState(STREAM_A, Integer.MAX_VALUE + 1L, true, true); assertTrue(write(Integer.MAX_VALUE)); verifyWrite(STREAM_A, Integer.MAX_VALUE); assertFalse(write(1)); verifyWrite(STREAM_A, 1); } private Http2Stream stream(int streamId) { return connection.stream(streamId); } private void initState(final int streamId, final long streamableBytes, final boolean hasFrame) { initState(streamId, streamableBytes, hasFrame, hasFrame); } private void initState(final int streamId, final long pendingBytes, final boolean hasFrame, final boolean isWriteAllowed) { final Http2Stream stream = stream(streamId); TestStreamByteDistributorStreamState state = new TestStreamByteDistributorStreamState(stream, pendingBytes, hasFrame, isWriteAllowed); stateMap.put(streamId, state); distributor.updateStreamableBytes(state); } private void setPriority(int streamId, int parent, int weight, boolean exclusive) { distributor.updateDependencyTree(streamId, parent, (short) weight, exclusive); } private boolean write(int numBytes) throws Http2Exception { return distributor.distribute(numBytes, writer); } private void verifyWrite(int streamId, int numBytes) { verify(writer).write(same(stream(streamId)), eq(numBytes)); } private void verifyWrite(VerificationMode mode, int streamId, int numBytes) { verify(writer, mode).write(same(stream(streamId)), eq(numBytes)); } private int captureWrite(int streamId) { ArgumentCaptor captor = ArgumentCaptor.forClass(Integer.class); verify(writer).write(same(stream(streamId)), captor.capture()); return captor.getValue(); } }",streamC,java,netty "package com.derbysoft.spitfire.fastjson.dto; import java.util.Date; public class DateRangeDTO extends AbstractDTO{ private Date start; private Date [MASK]; public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Date getEnd() { return [MASK]; } public void setEnd(Date [MASK]) { this.[MASK] = [MASK]; } }",end,java,fastjson "package com.alibaba.fastjson.deserializer.issues569.parser; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.ParseContext; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ContextObjectDeserializer; import com.alibaba.fastjson.parser.deserializer.DefaultFieldDeserializer; import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; import com.alibaba.fastjson.util.FieldInfo; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Map; public class DefaultFieldDeserializerBug569 extends DefaultFieldDeserializer { public DefaultFieldDeserializerBug569(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { super(mapping, clazz, fieldInfo); } @Override public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { if (fieldValueDeserilizer == null) { getFieldValueDeserilizer(parser.getConfig()); } Type fieldType = fieldInfo.fieldType; if (objectType instanceof ParameterizedType) { ParseContext objContext = parser.getContext(); objContext.type = objectType; fieldType = FieldInfo.getFieldType(this.clazz, objectType, fieldType); } Object value; if (fieldValueDeserilizer instanceof JavaBeanDeserializer) { JavaBeanDeserializer javaBeanDeser = (JavaBeanDeserializer) fieldValueDeserilizer; value = javaBeanDeser.deserialze(parser, fieldType, fieldInfo.name, fieldInfo.parserFeatures); } else { if (this.fieldInfo.format != null && fieldValueDeserilizer instanceof ContextObjectDeserializer) { value = ((ContextObjectDeserializer) fieldValueDeserilizer) .deserialze(parser, fieldType, fieldInfo.name, fieldInfo.format, fieldInfo.parserFeatures); } else { value = fieldValueDeserilizer.deserialze(parser, fieldType, fieldInfo.name); } } if (parser.getResolveStatus() == DefaultJSONParser.NeedToResolve) { DefaultJSONParser.ResolveTask [MASK] = parser.getLastResolveTask(); [MASK].fieldDeserializer = this; [MASK].ownerContext = parser.getContext(); parser.setResolveStatus(DefaultJSONParser.NONE); } else { if (object == null) { fieldValues.put(fieldInfo.name, value); } else { setValue(object, value); } } } }",task,java,fastjson "package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.common.BitMatrix; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; public final class Code128Writer extends OneDimensionalCodeWriter { private static final int CODE_START_A = 103; private static final int CODE_START_B = 104; private static final int CODE_START_C = 105; private static final int CODE_CODE_A = 101; private static final int CODE_CODE_B = 100; private static final int CODE_CODE_C = 99; private static final int CODE_STOP = 106; private static final char ESCAPE_FNC_1 = '\u00f1'; private static final char ESCAPE_FNC_2 = '\u00f2'; private static final char ESCAPE_FNC_3 = '\u00f3'; private static final char ESCAPE_FNC_4 = '\u00f4'; private static final int CODE_FNC_1 = 102; private static final int CODE_FNC_2 = 97; private static final int CODE_FNC_3 = 96; private static final int CODE_FNC_4_A = 101; private static final int CODE_FNC_4_B = 100; private enum CType { UNCODABLE, ONE_DIGIT, TWO_DIGITS, FNC_1 } @Override protected Collection getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.CODE_128); } @Override public boolean[] encode(String contents) { return encode(contents, null); } @Override public boolean[] encode(String contents, Map hints) { int forcedCodeSet = check(contents, hints); boolean hasCompactionHint = hints != null && hints.containsKey(EncodeHintType.CODE128_COMPACT) && Boolean.parseBoolean(hints.get(EncodeHintType.CODE128_COMPACT).toString()); return hasCompactionHint ? new MinimalEncoder().encode(contents) : encodeFast(contents, forcedCodeSet); } private static int check(String contents, Map hints) { int forcedCodeSet = -1; if (hints != null && hints.containsKey(EncodeHintType.FORCE_CODE_SET)) { String codeSetHint = hints.get(EncodeHintType.FORCE_CODE_SET).toString(); switch (codeSetHint) { case ""A"": forcedCodeSet = CODE_CODE_A; break; case ""B"": forcedCodeSet = CODE_CODE_B; break; case ""C"": forcedCodeSet = CODE_CODE_C; break; default: throw new IllegalArgumentException(""Unsupported code set hint: "" + codeSetHint); } } int length = contents.length(); for (int i = 0; i < length; i++) { char c = contents.charAt(i); switch (c) { case ESCAPE_FNC_1: case ESCAPE_FNC_2: case ESCAPE_FNC_3: case ESCAPE_FNC_4: break; default: if (c > 127) { throw new IllegalArgumentException(""Bad character in input: ASCII value="" + (int) c); } } switch (forcedCodeSet) { case CODE_CODE_A: if (c > 95 && c <= 127) { throw new IllegalArgumentException(""Bad character in input for forced code set A: ASCII value="" + (int) c); } break; case CODE_CODE_B: if (c < 32) { throw new IllegalArgumentException(""Bad character in input for forced code set B: ASCII value="" + (int) c); } break; case CODE_CODE_C: if (c < 48 || (c > 57 && c <= 127) || c == ESCAPE_FNC_2 || c == ESCAPE_FNC_3 || c == ESCAPE_FNC_4) { throw new IllegalArgumentException(""Bad character in input for forced code set C: ASCII value="" + (int) c); } break; } } return forcedCodeSet; } private static boolean[] encodeFast(String contents, int forcedCodeSet) { int length = contents.length(); Collection patterns = new ArrayList<>(); int checkSum = 0; int checkWeight = 1; int codeSet = 0; int position = 0; while (position < length) { int newCodeSet; if (forcedCodeSet == -1) { newCodeSet = chooseCode(contents, position, codeSet); } else { newCodeSet = forcedCodeSet; } int patternIndex; if (newCodeSet == codeSet) { switch (contents.charAt(position)) { case ESCAPE_FNC_1: patternIndex = CODE_FNC_1; break; case ESCAPE_FNC_2: patternIndex = CODE_FNC_2; break; case ESCAPE_FNC_3: patternIndex = CODE_FNC_3; break; case ESCAPE_FNC_4: if (codeSet == CODE_CODE_A) { patternIndex = CODE_FNC_4_A; } else { patternIndex = CODE_FNC_4_B; } break; default: switch (codeSet) { case CODE_CODE_A: patternIndex = contents.charAt(position) - ' '; if (patternIndex < 0) { patternIndex += '`'; } break; case CODE_CODE_B: patternIndex = contents.charAt(position) - ' '; break; default: if (position + 1 == length) { throw new IllegalArgumentException(""Bad number of characters for digit only encoding.""); } patternIndex = Integer.parseInt(contents.substring(position, position + 2)); position++; break; } } position++; } else { if (codeSet == 0) { switch (newCodeSet) { case CODE_CODE_A: patternIndex = CODE_START_A; break; case CODE_CODE_B: patternIndex = CODE_START_B; break; default: patternIndex = CODE_START_C; break; } } else { patternIndex = newCodeSet; } codeSet = newCodeSet; } patterns.add(Code128Reader.CODE_PATTERNS[patternIndex]); checkSum += patternIndex * checkWeight; if (position != 0) { checkWeight++; } } return produceResult(patterns, checkSum); } static boolean[] produceResult(Collection patterns, int checkSum) { checkSum %= 103; if (checkSum < 0) { throw new IllegalArgumentException(""Unable to compute a valid input checksum""); } patterns.add(Code128Reader.CODE_PATTERNS[checkSum]); patterns.add(Code128Reader.CODE_PATTERNS[CODE_STOP]); int codeWidth = 0; for (int[] pattern : patterns) { for (int width : pattern) { codeWidth += width; } } boolean[] result = new boolean[codeWidth]; int pos = 0; for (int[] pattern : patterns) { pos += appendPattern(result, pos, pattern, true); } return result; } private static CType findCType(CharSequence value, int start) { int last = value.length(); if (start >= last) { return CType.UNCODABLE; } char c = value.charAt(start); if (c == ESCAPE_FNC_1) { return CType.FNC_1; } if (c < '0' || c > '9') { return CType.UNCODABLE; } if (start + 1 >= last) { return CType.ONE_DIGIT; } c = value.charAt(start + 1); if (c < '0' || c > '9') { return CType.ONE_DIGIT; } return CType.TWO_DIGITS; } private static int chooseCode(CharSequence value, int start, int oldCode) { CType lookahead = findCType(value, start); if (lookahead == CType.ONE_DIGIT) { if (oldCode == CODE_CODE_A) { return CODE_CODE_A; } return CODE_CODE_B; } if (lookahead == CType.UNCODABLE) { if (start < value.length()) { char c = value.charAt(start); if (c < ' ' || (oldCode == CODE_CODE_A && (c < '`' || (c >= ESCAPE_FNC_1 && c <= ESCAPE_FNC_4)))) { return CODE_CODE_A; } } return CODE_CODE_B; } if (oldCode == CODE_CODE_A && lookahead == CType.FNC_1) { return CODE_CODE_A; } if (oldCode == CODE_CODE_C) { return CODE_CODE_C; } if (oldCode == CODE_CODE_B) { if (lookahead == CType.FNC_1) { return CODE_CODE_B; } lookahead = findCType(value, start + 2); if (lookahead == CType.UNCODABLE || lookahead == CType.ONE_DIGIT) { return CODE_CODE_B; } if (lookahead == CType.FNC_1) { lookahead = findCType(value, start + 3); if (lookahead == CType.TWO_DIGITS) { return CODE_CODE_C; } else { return CODE_CODE_B; } } int index = start + 4; while ((lookahead = findCType(value, index)) == CType.TWO_DIGITS) { index += 2; } if (lookahead == CType.ONE_DIGIT) { return CODE_CODE_B; } return CODE_CODE_C; } if (lookahead == CType.FNC_1) { lookahead = findCType(value, start + 1); } if (lookahead == CType.TWO_DIGITS) { return CODE_CODE_C; } return CODE_CODE_B; } private static final class MinimalEncoder { private enum Charset { A, B, C, NONE } private enum Latch { A, B, C, SHIFT, NONE } static final String A = "" !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\u0000\u0001\u0002"" + ""\u0003\u0004\u0005\u0006\u0007\u0008\u0009\n\u000B\u000C\r\u000E\u000F\u0010\u0011"" + ""\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F"" + ""\u00FF""; static final String B = "" !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqr"" + ""stuvwxyz{|}~\u007F\u00FF""; private static final int CODE_SHIFT = 98; private int[][] memoizedCost; private Latch[][] minPath; private boolean[] encode(String contents) { memoizedCost = new int[4][contents.length()]; minPath = new Latch[4][contents.length()]; encode(contents, Charset.NONE, 0); Collection patterns = new ArrayList<>(); int[] checkSum = new int[] {0}; int[] checkWeight = new int[] {1}; int length = contents.length(); Charset charset = Charset.NONE; for (int i = 0; i < length; i++) { Latch latch = minPath[charset.ordinal()][i]; switch (latch) { case A: charset = Charset.A; addPattern(patterns, i == 0 ? CODE_START_A : CODE_CODE_A, checkSum, checkWeight, i); break; case B: charset = Charset.B; addPattern(patterns, i == 0 ? CODE_START_B : CODE_CODE_B, checkSum, checkWeight, i); break; case C: charset = Charset.C; addPattern(patterns, i == 0 ? CODE_START_C : CODE_CODE_C, checkSum, checkWeight, i); break; case SHIFT: addPattern(patterns, CODE_SHIFT, checkSum, checkWeight, i); break; } if (charset == Charset.C) { if (contents.charAt(i) == ESCAPE_FNC_1) { addPattern(patterns, CODE_FNC_1, checkSum, checkWeight, i); } else { addPattern(patterns, Integer.parseInt(contents.substring(i, i + 2)), checkSum, checkWeight, i); assert i + 1 < length; if (i + 1 < length) { i++; } } } else { int patternIndex; switch (contents.charAt(i)) { case ESCAPE_FNC_1: patternIndex = CODE_FNC_1; break; case ESCAPE_FNC_2: patternIndex = CODE_FNC_2; break; case ESCAPE_FNC_3: patternIndex = CODE_FNC_3; break; case ESCAPE_FNC_4: if (charset == Charset.A && latch != Latch.SHIFT || charset == Charset.B && latch == Latch.SHIFT) { patternIndex = CODE_FNC_4_A; } else { patternIndex = CODE_FNC_4_B; } break; default: patternIndex = contents.charAt(i) - ' '; } if ((charset == Charset.A && latch != Latch.SHIFT || charset == Charset.B && latch == Latch.SHIFT) && patternIndex < 0) { patternIndex += '`'; } addPattern(patterns, patternIndex, checkSum, checkWeight, i); } } memoizedCost = null; minPath = null; return produceResult(patterns, checkSum[0]); } private static void addPattern(Collection patterns, int patternIndex, int[] checkSum, int[] checkWeight, int position) { patterns.add(Code128Reader.CODE_PATTERNS[patternIndex]); if (position != 0) { checkWeight[0]++; } checkSum[0] += patternIndex * checkWeight[0]; } private static boolean isDigit(char c) { return c >= '0' && c <= '9'; } private boolean canEncode(CharSequence contents, Charset charset,int position) { char c = contents.charAt(position); switch (charset) { case A: return c == ESCAPE_FNC_1 || c == ESCAPE_FNC_2 || c == ESCAPE_FNC_3 || c == ESCAPE_FNC_4 || A.indexOf(c) >= 0; case B: return c == ESCAPE_FNC_1 || c == ESCAPE_FNC_2 || c == ESCAPE_FNC_3 || c == ESCAPE_FNC_4 || B.indexOf(c) >= 0; case C: return c == ESCAPE_FNC_1 || (position + 1 < contents.length() && isDigit(c) && isDigit(contents.charAt(position + 1))); default: return false; } } private int encode(CharSequence contents, Charset charset, int position) { assert position < contents.length(); int mCost = memoizedCost[charset.ordinal()][position]; if (mCost > 0) { return mCost; } int minCost = Integer.MAX_VALUE; Latch minLatch = Latch.NONE; boolean atEnd = position + 1 >= contents.length(); Charset[] sets = new Charset[] { Charset.A, Charset.B }; for (int i = 0; i <= 1; i++) { if (canEncode(contents, sets[i], position)) { int cost = 1; Latch latch = Latch.NONE; if (charset != sets[i]) { cost++; latch = Latch.valueOf(sets[i].toString()); } if (!atEnd) { cost += encode(contents, sets[i], position + 1); } if (cost < minCost) { minCost = cost; minLatch = latch; } cost = 1; if (charset == sets[(i + 1) % 2]) { cost++; latch = Latch.SHIFT; if (!atEnd) { cost += encode(contents, charset, position + 1); } if (cost < minCost) { minCost = cost; minLatch = latch; } } } } if (canEncode(contents, Charset.C, position)) { int cost = 1; Latch latch = Latch.NONE; if (charset != Charset.C) { cost++; latch = Latch.C; } int [MASK] = contents.charAt(position) == ESCAPE_FNC_1 ? 1 : 2; if (position + [MASK] < contents.length()) { cost += encode(contents, Charset.C, position + [MASK]); } if (cost < minCost) { minCost = cost; minLatch = latch; } } if (minCost == Integer.MAX_VALUE) { throw new IllegalArgumentException(""Bad character in input: ASCII value="" + (int) contents.charAt(position)); } memoizedCost[charset.ordinal()][position] = minCost; minPath[charset.ordinal()][position] = minLatch; return minCost; } } }",advance,java,zxing "package io.netty5.handler.codec.http; import io.netty5.handler.codec.compression.Brotli; import io.netty5.handler.codec.compression.BrotliCompressor; import io.netty5.handler.codec.compression.BrotliOptions; import io.netty5.handler.codec.compression.CompressionOptions; import io.netty5.handler.codec.compression.Compressor; import io.netty5.handler.codec.compression.DeflateOptions; import io.netty5.handler.codec.compression.GzipOptions; import io.netty5.handler.codec.compression.StandardCompressionOptions; import io.netty5.handler.codec.compression.ZlibCompressor; import io.netty5.handler.codec.compression.ZlibWrapper; import io.netty5.handler.codec.compression.Zstd; import io.netty5.handler.codec.compression.ZstdCompressor; import io.netty5.handler.codec.compression.ZstdOptions; import io.netty5.handler.codec.compression.SnappyCompressor; import io.netty5.handler.codec.compression.SnappyOptions; import io.netty5.util.internal.ObjectUtil; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; public class HttpContentCompressor extends HttpContentEncoder { private final boolean supportsCompressionOptions; private final BrotliOptions brotliOptions; private final GzipOptions gzipOptions; private final DeflateOptions deflateOptions; private final ZstdOptions zstdOptions; private final SnappyOptions snappyOptions; private final int compressionLevel; private final int contentSizeThreshold; private final Map> factories; public HttpContentCompressor() { this(6); } @Deprecated public HttpContentCompressor(int compressionLevel) { this(compressionLevel, 0); } @Deprecated public HttpContentCompressor(int compressionLevel, int contentSizeThreshold) { this.compressionLevel = ObjectUtil.checkInRange(compressionLevel, 0, 9, ""compressionLevel""); this.contentSizeThreshold = ObjectUtil.checkPositiveOrZero(contentSizeThreshold, ""contentSizeThreshold""); this.brotliOptions = null; this.gzipOptions = null; this.deflateOptions = null; this.zstdOptions = null; this.snappyOptions = null; this.factories = null; this.supportsCompressionOptions = false; } public HttpContentCompressor(CompressionOptions... compressionOptions) { this(0, compressionOptions); } public HttpContentCompressor(int contentSizeThreshold, CompressionOptions... compressionOptions) { this.contentSizeThreshold = ObjectUtil.checkPositiveOrZero(contentSizeThreshold, ""contentSizeThreshold""); BrotliOptions brotliOptions = null; GzipOptions gzipOptions = null; DeflateOptions deflateOptions = null; ZstdOptions zstdOptions = null; SnappyOptions snappyOptions = null; if (compressionOptions == null || compressionOptions.length == 0) { brotliOptions = Brotli.isAvailable() ? StandardCompressionOptions.brotli() : null; gzipOptions = StandardCompressionOptions.gzip(); deflateOptions = StandardCompressionOptions.deflate(); zstdOptions = Zstd.isAvailable() ? StandardCompressionOptions.zstd() : null; snappyOptions = StandardCompressionOptions.snappy(); } else { ObjectUtil.deepCheckNotNull(""compressionOptions"", compressionOptions); for (CompressionOptions compressionOption : compressionOptions) { if (Brotli.isAvailable() && compressionOption instanceof BrotliOptions) { brotliOptions = (BrotliOptions) compressionOption; } else if (compressionOption instanceof GzipOptions) { gzipOptions = (GzipOptions) compressionOption; } else if (compressionOption instanceof DeflateOptions) { deflateOptions = (DeflateOptions) compressionOption; } else if (compressionOption instanceof ZstdOptions) { zstdOptions = (ZstdOptions) compressionOption; } else if (compressionOption instanceof SnappyOptions) { snappyOptions = (SnappyOptions) compressionOption; } else { throw new IllegalArgumentException(""Unsupported "" + CompressionOptions.class.getSimpleName() + "": "" + compressionOption); } } } this.gzipOptions = gzipOptions; this.deflateOptions = deflateOptions; this.brotliOptions = brotliOptions; this.zstdOptions = zstdOptions; this.snappyOptions = snappyOptions; factories = new HashMap<>(); if (this.gzipOptions != null) { factories.put(""gzip"", ZlibCompressor.newFactory( ZlibWrapper.GZIP, gzipOptions.compressionLevel())); } if (this.deflateOptions != null) { factories.put(""deflate"", ZlibCompressor.newFactory( ZlibWrapper.ZLIB, deflateOptions.compressionLevel())); } if (this.snappyOptions != null) { this.factories.put(""snappy"", SnappyCompressor.newFactory()); } if (Brotli.isAvailable() && this.brotliOptions != null) { factories.put(""br"", BrotliCompressor.newFactory(brotliOptions.parameters())); } if (this.zstdOptions != null) { factories.put(""zstd"", ZstdCompressor.newFactory(zstdOptions.compressionLevel(), zstdOptions.blockSize(), zstdOptions.maxEncodeSize())); } compressionLevel = -1; supportsCompressionOptions = true; } @Override protected Result beginEncode(HttpResponse [MASK], String acceptEncoding) { if (contentSizeThreshold > 0) { if ([MASK] instanceof HttpContent && ((HttpContent) [MASK]).payload().readableBytes() < contentSizeThreshold) { return null; } } CharSequence contentEncoding = [MASK].headers().get(HttpHeaderNames.CONTENT_ENCODING); if (contentEncoding != null) { return null; } if (supportsCompressionOptions) { String targetContentEncoding = determineEncoding(acceptEncoding); if (targetContentEncoding == null) { return null; } Supplier compressorFactory = factories.get(targetContentEncoding); if (compressorFactory == null) { throw new Error(); } return new Result(targetContentEncoding, compressorFactory.get()); } else { ZlibWrapper wrapper = determineWrapper(acceptEncoding); if (wrapper == null) { return null; } String targetContentEncoding; switch (wrapper) { case GZIP: targetContentEncoding = ""gzip""; break; case ZLIB: targetContentEncoding = ""deflate""; break; default: throw new Error(); } return new Result( targetContentEncoding, ZlibCompressor.newFactory(wrapper, compressionLevel).get()); } } @SuppressWarnings(""FloatingPointEquality"") protected String determineEncoding(String acceptEncoding) { float starQ = -1.0f; float brQ = -1.0f; float zstdQ = -1.0f; float snappyQ = -1.0f; float gzipQ = -1.0f; float deflateQ = -1.0f; for (String encoding : acceptEncoding.split("","")) { float q = 1.0f; int equalsPos = encoding.indexOf('='); if (equalsPos != -1) { try { q = Float.parseFloat(encoding.substring(equalsPos + 1)); } catch (NumberFormatException e) { q = 0.0f; } } if (encoding.contains(""*"")) { starQ = q; } else if (encoding.contains(""br"") && q > brQ) { brQ = q; } else if (encoding.contains(""zstd"") && q > zstdQ) { zstdQ = q; } else if (encoding.contains(""snappy"") && q > snappyQ) { snappyQ = q; } else if (encoding.contains(""gzip"") && q > gzipQ) { gzipQ = q; } else if (encoding.contains(""deflate"") && q > deflateQ) { deflateQ = q; } } if (brQ > 0.0f || zstdQ > 0.0f || snappyQ > 0.0f || gzipQ > 0.0f || deflateQ > 0.0f) { if (brQ != -1.0f && brQ >= zstdQ && this.brotliOptions != null) { return ""br""; } else if (zstdQ != -1.0f && zstdQ >= snappyQ && this.zstdOptions != null) { return ""zstd""; } else if (snappyQ != -1.0f && snappyQ >= gzipQ && this.snappyOptions != null) { return ""snappy""; } else if (gzipQ != -1.0f && gzipQ >= deflateQ && this.gzipOptions != null) { return ""gzip""; } else if (deflateQ != -1.0f && deflateOptions != null) { return ""deflate""; } } if (starQ > 0.0f) { if (brQ == -1.0f && brotliOptions != null) { return ""br""; } if (zstdQ == -1.0f && zstdOptions != null) { return ""zstd""; } if (snappyQ == -1.0f && this.snappyOptions != null) { return ""snappy""; } if (gzipQ == -1.0f && this.gzipOptions != null) { return ""gzip""; } if (deflateQ == -1.0f && deflateOptions != null) { return ""deflate""; } } return null; } @Deprecated @SuppressWarnings(""FloatingPointEquality"") protected ZlibWrapper determineWrapper(String acceptEncoding) { float starQ = -1.0f; float gzipQ = -1.0f; float deflateQ = -1.0f; for (String encoding : acceptEncoding.split("","")) { float q = 1.0f; int equalsPos = encoding.indexOf('='); if (equalsPos != -1) { try { q = Float.parseFloat(encoding.substring(equalsPos + 1)); } catch (NumberFormatException e) { q = 0.0f; } } if (encoding.contains(""*"")) { starQ = q; } else if (encoding.contains(""gzip"") && q > gzipQ) { gzipQ = q; } else if (encoding.contains(""deflate"") && q > deflateQ) { deflateQ = q; } } if (gzipQ > 0.0f || deflateQ > 0.0f) { if (gzipQ >= deflateQ) { return ZlibWrapper.GZIP; } else { return ZlibWrapper.ZLIB; } } if (starQ > 0.0f) { if (gzipQ == -1.0f) { return ZlibWrapper.GZIP; } if (deflateQ == -1.0f) { return ZlibWrapper.ZLIB; } } return null; } }",httpResponse,java,netty "package io.netty5.buffer.pool; import java.util.concurrent.ConcurrentHashMap; abstract class SizeClasses implements SizeClassesMetric { private static final ConcurrentHashMap CACHE = new ConcurrentHashMap<>(); static final int LOG2_QUANTUM = 4; private static final int LOG2_SIZE_CLASS_GROUP = 2; private static final int LOG2_MAX_LOOKUP_SIZE = 12; private static final int LOG2GROUP_IDX = 1; private static final int LOG2DELTA_IDX = 2; private static final int NDELTA_IDX = 3; private static final int PAGESIZE_IDX = 4; private static final int SUBPAGE_IDX = 5; private static final int LOG2_DELTA_LOOKUP_IDX = 6; private static final byte no = 0, yes = 1; protected SizeClasses(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; SizeClassValue value = CACHE.computeIfAbsent( new SizeClassKey(pageSize, pageShifts, chunkSize, directMemoryCacheAlignment), key -> new SizeClassValue(key, directMemoryCacheAlignment)); nSizes = value.nSizes; nSubpages = value.nSubpages; nPSizes = value.nPSizes; smallMaxSizeIdx = value.smallMaxSizeIdx; lookupMaxSize = value.lookupMaxSize; pageIdx2sizeTab = value.pageIdx2sizeTab; sizeIdx2sizeTab = value.sizeIdx2sizeTab; size2idxTab = value.size2idxTab; } protected final int pageSize; protected final int pageShifts; protected final int chunkSize; protected final int directMemoryCacheAlignment; final int nSizes; final int nSubpages; final int nPSizes; final int smallMaxSizeIdx; private final int lookupMaxSize; private final int[] pageIdx2sizeTab; private final int[] sizeIdx2sizeTab; private final int[] size2idxTab; @Override public int sizeIdx2size(int sizeIdx) { return sizeIdx2sizeTab[sizeIdx]; } @Override public int sizeIdx2sizeCompute(int sizeIdx) { int group = sizeIdx >> LOG2_SIZE_CLASS_GROUP; int mod = sizeIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int groupSize = group == 0? 0 : 1 << LOG2_QUANTUM + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int lgDelta = shift + LOG2_QUANTUM - 1; int modSize = mod + 1 << lgDelta; return groupSize + modSize; } @Override public long pageIdx2size(int pageIdx) { return pageIdx2sizeTab[pageIdx]; } @Override public long pageIdx2sizeCompute(int pageIdx) { int group = pageIdx >> LOG2_SIZE_CLASS_GROUP; int mod = pageIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; long groupSize = group == 0? 0 : 1L << pageShifts + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int log2Delta = shift + pageShifts - 1; int modSize = mod + 1 << log2Delta; return groupSize + modSize; } @Override public int size2SizeIdx(int size) { if (size == 0) { return 0; } if (size > chunkSize) { return nSizes; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { return size2idxTab[size - 1 >> LOG2_QUANTUM]; } int x = PoolThreadCache.log2((size << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? 0 : x - (LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = size - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; return group + mod; } @Override public int pages2pageIdx(int pages) { return pages2pageIdxCompute(pages, false); } @Override public int pages2pageIdxFloor(int pages) { return pages2pageIdxCompute(pages, true); } private int pages2pageIdxCompute(int pages, boolean floor) { int pageSize = pages << pageShifts; if (pageSize > chunkSize) { return nPSizes; } int x = PoolThreadCache.log2((pageSize << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + pageShifts ? 0 : x - (LOG2_SIZE_CLASS_GROUP + pageShifts); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + pageShifts + 1? pageShifts : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = pageSize - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int pageIdx = group + mod; if (floor && pageIdx2sizeTab[pageIdx] > pages << pageShifts) { pageIdx--; } return pageIdx; } private static int alignSizeIfNeeded(int size, int alignment) { if (alignment <= 0) { return size; } int [MASK] = size & alignment - 1; return [MASK] == 0? size : size + alignment - [MASK]; } @Override public int normalizeSize(int size) { if (size == 0) { return sizeIdx2sizeTab[0]; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { int ret = sizeIdx2sizeTab[size2idxTab[size - 1 >> LOG2_QUANTUM]]; assert ret == normalizeSizeCompute(size); return ret; } return normalizeSizeCompute(size); } private static int normalizeSizeCompute(int size) { int x = PoolThreadCache.log2((size << 1) - 1); int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int [MASK] = 1 << log2Delta; int delta_mask = [MASK] - 1; return size + delta_mask & ~delta_mask; } private static final class SizeClassKey { final int pageSize; final int pageShifts; final int chunkSize; final int directMemoryCacheAlignment; private SizeClassKey(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SizeClassKey that = (SizeClassKey) o; if (pageSize != that.pageSize) { return false; } if (pageShifts != that.pageShifts) { return false; } if (chunkSize != that.chunkSize) { return false; } return directMemoryCacheAlignment == that.directMemoryCacheAlignment; } @Override public int hashCode() { int result = pageSize; result = 31 * result + pageShifts; result = 31 * result + chunkSize; result = 31 * result + directMemoryCacheAlignment; return result; } } private static final class SizeClassValue { final SizeClassKey key; final int nSizes; final int nSubpages; final int nPSizes; final int smallMaxSizeIdx; final int lookupMaxSize; final int[] pageIdx2sizeTab; final int[] sizeIdx2sizeTab; final int[] size2idxTab; SizeClassValue(SizeClassKey key, int directMemoryCacheAlignment) { this.key = key; int group = PoolThreadCache.log2(key.chunkSize) - LOG2_SIZE_CLASS_GROUP + 1 - LOG2_QUANTUM; short[][] sizeClasses = new short[group << LOG2_SIZE_CLASS_GROUP][7]; int normalMaxSize = -1; int nSizes = 0; int size = 0; int log2Group = LOG2_QUANTUM; int log2Delta = LOG2_QUANTUM; int ndeltaLimit = 1 << LOG2_SIZE_CLASS_GROUP; for (int nDelta = 0; nDelta < ndeltaLimit; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, key); sizeClasses[nSizes] = sizeClass; size = sizeOf(sizeClass, directMemoryCacheAlignment); } log2Group += LOG2_SIZE_CLASS_GROUP; for (; size < key.chunkSize; log2Group++, log2Delta++) { for (int nDelta = 1; nDelta <= ndeltaLimit && size < key.chunkSize; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, key); sizeClasses[nSizes] = sizeClass; size = normalMaxSize = sizeOf(sizeClass, directMemoryCacheAlignment); } } assert key.chunkSize == normalMaxSize; int smallMaxSizeIdx = 0; int lookupMaxSize = 0; int nPSizes = 0; int nSubpages = 0; for (int idx = 0; idx < nSizes; idx++) { short[] sz = sizeClasses[idx]; if (sz[PAGESIZE_IDX] == yes) { nPSizes++; } if (sz[SUBPAGE_IDX] == yes) { nSubpages++; smallMaxSizeIdx = idx; } if (sz[LOG2_DELTA_LOOKUP_IDX] != no) { lookupMaxSize = sizeOf(sz, directMemoryCacheAlignment); } } this.smallMaxSizeIdx = smallMaxSizeIdx; this.lookupMaxSize = lookupMaxSize; this.nPSizes = nPSizes; this.nSubpages = nSubpages; this.nSizes = nSizes; sizeIdx2sizeTab = newIdx2SizeTab(sizeClasses, nSizes, directMemoryCacheAlignment); pageIdx2sizeTab = newPageIdx2sizeTab(sizeClasses, nSizes, nPSizes, directMemoryCacheAlignment); size2idxTab = newSize2idxTab(lookupMaxSize, sizeClasses); } private static short[] newSizeClass(int index, int log2Group, int log2Delta, int nDelta, SizeClassKey key) { short isMultiPageSize; if (log2Delta >= key.pageShifts) { isMultiPageSize = yes; } else { int pageSize = 1 << key.pageShifts; int size = (1 << log2Group) + (1 << log2Delta) * nDelta; isMultiPageSize = size == size / pageSize * pageSize? yes : no; } int log2Ndelta = nDelta == 0? 0 : PoolThreadCache.log2(nDelta); byte remove = 1 << log2Ndelta < nDelta? yes : no; int log2Size = log2Delta + log2Ndelta == log2Group? log2Group + 1 : log2Group; if (log2Size == log2Group) { remove = yes; } short isSubpage = log2Size < key.pageShifts + LOG2_SIZE_CLASS_GROUP? yes : no; int log2DeltaLookup = log2Size < LOG2_MAX_LOOKUP_SIZE || log2Size == LOG2_MAX_LOOKUP_SIZE && remove == no ? log2Delta : no; return new short[] { (short) index, (short) log2Group, (short) log2Delta, (short) nDelta, isMultiPageSize, isSubpage, (short) log2DeltaLookup }; } private static int[] newIdx2SizeTab(short[][] sizeClasses, int nSizes, int directMemoryCacheAlignment) { int[] sizeIdx2sizeTab = new int[nSizes]; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; sizeIdx2sizeTab[i] = sizeOf(sizeClass, directMemoryCacheAlignment); } return sizeIdx2sizeTab; } private static int calculateSize(int log2Group, int nDelta, int log2Delta) { return (1 << log2Group) + (nDelta << log2Delta); } private static int sizeOf(short[] sizeClass, int directMemoryCacheAlignment) { int log2Group = sizeClass[LOG2GROUP_IDX]; int log2Delta = sizeClass[LOG2DELTA_IDX]; int nDelta = sizeClass[NDELTA_IDX]; int size = calculateSize(log2Group, nDelta, log2Delta); return alignSizeIfNeeded(size, directMemoryCacheAlignment); } private static int[] newPageIdx2sizeTab(short[][] sizeClasses, int nSizes, int nPSizes, int directMemoryCacheAlignment) { int[] pageIdx2sizeTab = new int[nPSizes]; int pageIdx = 0; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; if (sizeClass[PAGESIZE_IDX] == yes) { pageIdx2sizeTab[pageIdx++] = sizeOf(sizeClass, directMemoryCacheAlignment); } } return pageIdx2sizeTab; } private static int[] newSize2idxTab(int lookupMaxSize, short[][] sizeClasses) { int[] size2idxTab = new int[lookupMaxSize >> LOG2_QUANTUM]; int idx = 0; int size = 0; for (int i = 0; size <= lookupMaxSize; i++) { int log2Delta = sizeClasses[i][LOG2DELTA_IDX]; int times = 1 << log2Delta - LOG2_QUANTUM; while (size <= lookupMaxSize && times-- > 0) { size2idxTab[idx++] = i; size = idx + 1 << LOG2_QUANTUM; } } return size2idxTab; } } }",delta,java,netty "package com.alibaba.json.bvt.serializer; import java.util.TimeZone; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TimeZoneTest extends TestCase { public void test_timezone() throws Exception { TimeZone tz1 = TimeZone.getDefault(); String [MASK] = JSON.toJSONString(tz1); Assert.assertEquals(JSON.toJSONString(tz1.getID()), [MASK]); TimeZone tz2 = JSON.parseObject([MASK], TimeZone.class); Assert.assertEquals(tz1.getID(), tz2.getID()); } }",text,java,fastjson "package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3470 extends TestCase { public void test_for_issue() throws Exception { String str = JSON.toJSONString(new Privacy().setPassword(""test"")); assertEquals(""{\""__password\"":\""test\""}"", str); } public static class Privacy { private String [MASK]; private String password; public Privacy() { super(); } public String getPhone() { return [MASK]; } public Privacy setPhone(String [MASK]) { this.[MASK] = [MASK]; return this; } public String get__password() { return password; } public Privacy setPassword(String password) { this.password = password; return this; } } }",phone,java,fastjson