text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```kotlin package com.blankj.utilcode.pkg.feature.bus import android.content.Context import android.content.Intent import androidx.annotation.Keep import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.BusUtils import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ThreadUtils import kotlin.random.Random /** * ``` * author: Blankj * blog : path_to_url * time : 2019/03/12 * desc : demo about BusUtils * ``` */ class BusActivity : CommonActivity() { private val titleItem: CommonItemTitle = CommonItemTitle("", true); @BusUtils.Bus(tag = TAG_BASIC_TYPE) fun test(param: Int) { titleItem.title = param.toString() } @BusUtils.Bus(tag = TAG_BUS, priority = 5) fun test(param: String) { titleItem.title = param } @BusUtils.Bus(tag = TAG_BUS, priority = 1) fun testSameTag(param: String) { if (titleItem.title.toString() == TAG_BUS) { titleItem.title = "${titleItem.title} * 2" } } @BusUtils.Bus(tag = TAG_STICKY_BUS, sticky = true) fun testSticky(callback: Callback) { titleItem.title = callback.call() } @BusUtils.Bus(tag = TAG_IO, threadMode = BusUtils.ThreadMode.IO) fun testIo() { val currentThread = Thread.currentThread().toString() ThreadUtils.runOnUiThread(Runnable { titleItem.title = currentThread }) } companion object { const val TAG_BASIC_TYPE = "tag_basic_type" const val TAG_BUS = "tag_bus" const val TAG_STICKY_BUS = "tag_sticky_bus" const val TAG_IO = "tag_io" fun start(context: Context) { val starter = Intent(context, BusActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_bus } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( titleItem, CommonItemClick(R.string.bus_register) { BusUtils.register(this) }, CommonItemClick(R.string.bus_unregister) { BusUtils.unregister(this) }, CommonItemClick(R.string.bus_post) { BusUtils.post(TAG_BUS, TAG_BUS) }, CommonItemClick(R.string.bus_post_basic_type) { BusUtils.post(TAG_BASIC_TYPE, Random(System.currentTimeMillis()).nextInt()) }, CommonItemClick(R.string.bus_post_sticky) { BusUtils.postSticky(TAG_STICKY_BUS, object : Callback { override fun call(): String { return TAG_STICKY_BUS } }) }, CommonItemClick(R.string.bus_post_to_io_thread) { BusUtils.post(TAG_IO) }, CommonItemClick(R.string.bus_remove_sticky) { BusUtils.removeSticky(TAG_STICKY_BUS) }, CommonItemClick(R.string.bus_start_compare, true) { BusCompareActivity.start(this) } ) } override fun onDestroy() { super.onDestroy() BusUtils.removeSticky(TAG_STICKY_BUS) BusUtils.unregister(this) } } @Keep interface Callback { fun call(): String } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/bus/BusActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
750
```kotlin package com.blankj.utilcode.pkg.feature.bus import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.BusUtils import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ThreadUtils import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import java.util.* import java.util.concurrent.CopyOnWriteArrayList /** * ``` * author: Blankj * blog : path_to_url * time : 2019/07/14 * desc : demo about BusUtils * ``` */ class BusCompareActivity : CommonActivity() { private val titleItem: CommonItemTitle = CommonItemTitle("", true) companion object { fun start(context: Context) { val starter = Intent(context, BusCompareActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_bus } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( titleItem, CommonItemClick(R.string.bus_compare_register_10000_times) { compareRegister10000Times() }, CommonItemClick(R.string.bus_compare_post_to_1_subscriber_1000000_times) { comparePostTo1Subscriber1000000Times() }, CommonItemClick(R.string.bus_compare_post_to_100_subscriber_100000_times) { comparePostTo100Subscribers100000Times() }, CommonItemClick(R.string.bus_compare_unregister_10000_times) { compareUnregister10000Times() } ) } override fun onDestroy() { super.onDestroy() ThreadUtils.cancel(ThreadUtils.getCpuPool()) } /** * 10000 10 */ private fun compareRegister10000Times() { val eventBusTests = CopyOnWriteArrayList<BusEvent>() val busUtilsTests = CopyOnWriteArrayList<BusEvent>() compareWithEventBus("Register 10000 times.", 10, 10000, object : CompareCallback { override fun runEventBus() { val test = BusEvent() EventBus.getDefault().register(test) eventBusTests.add(test) } override fun runBusUtils() { val test = BusEvent() BusUtils.register(test) busUtilsTests.add(test) } override fun restState() { for (test in eventBusTests) { EventBus.getDefault().unregister(test) } eventBusTests.clear() for (test in busUtilsTests) { BusUtils.unregister(test) } busUtilsTests.clear() } }, object : OnFinishCallback { override fun onFinish() { for (test in eventBusTests) { EventBus.getDefault().unregister(test) } eventBusTests.clear() for (test in busUtilsTests) { BusUtils.unregister(test) } busUtilsTests.clear() } }) } /** * 1 * 1000000 10 */ private fun comparePostTo1Subscriber1000000Times() { comparePostTemplate("Post to 1 subscriber 1000000 times.", 1, 1000000) } /** * 100 * 100000 10 */ private fun comparePostTo100Subscribers100000Times() { comparePostTemplate("Post to 100 subscribers 100000 times.", 100, 100000) } private fun comparePostTemplate(name: String, subscribeNum: Int, postTimes: Int) { val tests = java.util.ArrayList<BusEvent>() for (i in 0 until subscribeNum) { val test = BusEvent() EventBus.getDefault().register(test) BusUtils.register(test) tests.add(test) } compareWithEventBus(name, 10, postTimes, object : CompareCallback { override fun runEventBus() { EventBus.getDefault().post("EventBus") } override fun runBusUtils() { BusUtils.post("busUtilsFun", "BusUtils") } override fun restState() { } }, object : OnFinishCallback { override fun onFinish() { for (test in tests) { EventBus.getDefault().unregister(test) BusUtils.unregister(test) } } }) } /** * 10000 10 */ private fun compareUnregister10000Times() { showLoading() ThreadUtils.executeBySingle(object : ThreadUtils.SimpleTask<List<BusEvent>>() { override fun doInBackground(): List<BusEvent> { val tests = ArrayList<BusEvent>() for (i in 0..9999) { val test = BusEvent() EventBus.getDefault().register(test) BusUtils.register(test) tests.add(test) } return tests } override fun onSuccess(tests: List<BusEvent>) { compareWithEventBus("Unregister 10000 times.", 10, 1, object : CompareCallback { override fun runEventBus() { for (test in tests) { EventBus.getDefault().unregister(test) } } override fun runBusUtils() { for (test in tests) { BusUtils.unregister(test) } } override fun restState() { for (test in tests) { EventBus.getDefault().register(test) BusUtils.register(test) } } }, object : OnFinishCallback { override fun onFinish() { for (test in tests) { EventBus.getDefault().unregister(test) BusUtils.unregister(test) } } }) } }) } /** * @param name * @param sampleSize * @param times * @param callback * @param onFinishCallback */ private fun compareWithEventBus(name: String, sampleSize: Int, times: Int, callback: CompareCallback, onFinishCallback: OnFinishCallback) { showLoading() ThreadUtils.executeByCpu(object : ThreadUtils.Task<String>() { override fun doInBackground(): String { val dur = Array(2) { LongArray(sampleSize) } for (i in 0 until sampleSize) { var cur = System.currentTimeMillis() for (j in 0 until times) { callback.runEventBus() } dur[0][i] = System.currentTimeMillis() - cur cur = System.currentTimeMillis() for (j in 0 until times) { callback.runBusUtils() } dur[1][i] = System.currentTimeMillis() - cur callback.restState() } var eventBusAverageTime: Long = 0 var busUtilsAverageTime: Long = 0 for (i in 0 until sampleSize) { eventBusAverageTime += dur[0][i] busUtilsAverageTime += dur[1][i] } return name + "\nEventBusCostTime: " + eventBusAverageTime / sampleSize + "\nBusUtilsCostTime: " + busUtilsAverageTime / sampleSize; } override fun onSuccess(result: String?) { onFinishCallback.onFinish() dismissLoading() titleItem?.title = result } override fun onCancel() { onFinishCallback.onFinish() dismissLoading() } override fun onFail(t: Throwable?) { onFinishCallback.onFinish() dismissLoading() } }) } } interface CompareCallback { fun runEventBus() fun runBusUtils() fun restState() } interface OnFinishCallback { fun onFinish() } class BusEvent { @Subscribe fun eventBusFun(param: String) { } @BusUtils.Bus(tag = "busUtilsFun") fun busUtilsFun(param: String) { } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/bus/BusCompareActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,720
```kotlin package com.blankj.utilcode.pkg.feature.screen import android.content.Context import android.content.Intent import android.os.Build import android.widget.ImageView import android.widget.TextView import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemSwitch import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.helper.DialogHelper import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2019/01/29 * desc : demo about RomUtils * ``` */ class ScreenActivity : CommonActivity() { companion object { fun start(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PermissionUtils.requestWriteSettings(object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, ScreenActivity::class.java) context.startActivity(starter) } override fun onDenied() { ToastUtils.showLong("No permission of write settings.") } }) } else { val starter = Intent(context, ScreenActivity::class.java) context.startActivity(starter) } } } override fun bindTitleRes(): Int { return R.string.demo_screen } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("getScreenWidth", ScreenUtils.getScreenWidth().toString()), CommonItemTitle("getScreenHeight", ScreenUtils.getScreenHeight().toString()), CommonItemTitle("getAppScreenWidth", ScreenUtils.getAppScreenWidth().toString()), CommonItemTitle("getAppScreenHeight", ScreenUtils.getAppScreenHeight().toString()), CommonItemTitle("getScreenDensity", ScreenUtils.getScreenDensity().toString()), CommonItemTitle("getScreenDensityDpi", ScreenUtils.getScreenDensityDpi().toString()), CommonItemTitle("getScreenRotation", ScreenUtils.getScreenRotation(this).toString()), CommonItemTitle("isScreenLock", ScreenUtils.isScreenLock().toString()), CommonItemTitle("getSleepDuration", ScreenUtils.getSleepDuration().toString()), CommonItemSwitch( "isFullScreen", { ScreenUtils.isFullScreen(this) }, { if (it) { ScreenUtils.setFullScreen(this) BarUtils.setStatusBarVisibility(this, false) } else { ScreenUtils.setNonFullScreen(this) BarUtils.setStatusBarVisibility(this, true) } } ), CommonItemSwitch( "isLandscape", { ScreenUtils.isLandscape() }, { if (it) { ScreenUtils.setLandscape(this) } else { ScreenUtils.setPortrait(this) } } ), CommonItemClick(R.string.screen_screenshot) { val iv :ImageView = ImageView(this) iv.setImageResource(R.mipmap.ic_launcher) val tv: TextView = TextView(this) tv.setText("wowowowwowo") DialogHelper.showScreenshotDialog(ImageUtils.view2Bitmap(tv)) // DialogHelper.showScreenshotDialog(ScreenUtils.screenShot(this)) } ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/screen/ScreenActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
678
```kotlin package com.blankj.utilcode.pkg.feature.language import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemSwitch import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.LanguageUtils import com.blankj.utilcode.util.SPStaticUtils import com.blankj.utilcode.util.StringUtils import java.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2018/12/29 * desc : demo about VibrateUtils * ``` */ class LanguageActivity : CommonActivity() { companion object { const val SP_KEY_IS_RELAUNCH_APP = "SP_KEY_IS_RELAUNCH_APP" fun start(context: Context) { val starter = Intent(context, LanguageActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_language } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("isAppliedLanguage", LanguageUtils.isAppliedLanguage().toString()), CommonItemTitle("isAppliedLanguage(SIMPLIFIED_CHINESE)", LanguageUtils.isAppliedLanguage(Locale.SIMPLIFIED_CHINESE).toString()), CommonItemTitle("getAppliedLanguage", (LanguageUtils.getAppliedLanguage() ?: "null").toString()), CommonItemTitle("getActivityContextLanguage", LanguageUtils.getContextLanguage(this).toString()), CommonItemTitle("getAppContextLanguage", LanguageUtils.getAppContextLanguage().toString()), CommonItemTitle("getSystemLanguage", LanguageUtils.getSystemLanguage().toString()), CommonItemSwitch( StringUtils.getString(R.string.language_relaunch_app), { isRelaunchApp() }, { SPStaticUtils.put(SP_KEY_IS_RELAUNCH_APP, it) } ), CommonItemClick(R.string.language_apply_simple_chinese) { LanguageUtils.applyLanguage(Locale.SIMPLIFIED_CHINESE, isRelaunchApp()) }, CommonItemClick(R.string.language_apply_american) { LanguageUtils.applyLanguage(Locale.US, isRelaunchApp()) }, CommonItemClick(R.string.language_apply_english) { LanguageUtils.applyLanguage(Locale.ENGLISH, isRelaunchApp()) }, CommonItemClick(R.string.language_apply_arabic) { LanguageUtils.applyLanguage(Locale("ar"), isRelaunchApp()) }, CommonItemClick(R.string.language_apply_system) { LanguageUtils.applySystemLanguage(isRelaunchApp()) } ) } private fun isRelaunchApp() = SPStaticUtils.getBoolean(SP_KEY_IS_RELAUNCH_APP) } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/language/LanguageActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
591
```kotlin package com.blankj.utilcode.pkg.feature.activity import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.core.app.ActivityCompat import android.view.View import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.ColorUtils import kotlinx.android.synthetic.main.activity_sub_activity.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about ActivityUtils * ``` */ class SubActivityActivity : CommonActivity() { override fun bindLayout(): Int { return R.layout.activity_sub_activity } override fun bindTitleRes(): Int { return R.string.demo_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) contentView?.setBackgroundColor(ColorUtils.getRandomColor(false)) activityViewSharedElement.setOnClickListener { val result = Intent() result.putExtra("data", "data") this@SubActivityActivity.setResult(Activity.RESULT_OK, result) this@SubActivityActivity.finish() } } override fun onBackPressed() { super.onBackPressed() ActivityCompat.finishAfterTransition(this) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/activity/SubActivityActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
262
```kotlin package com.blankj.utilcode.pkg.feature.snackbar import android.content.Context import android.content.Intent import android.graphics.Color import android.text.SpannableStringBuilder import android.view.ViewGroup import android.widget.TextView import androidx.annotation.StringRes import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.SnackbarUtils import com.blankj.utilcode.util.SpanUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/17 * desc : demo about SnackbarUtils * ``` */ class SnackbarActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, SnackbarActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_snackbar } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.snackbar_short) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_short)) .setMessageColor(Color.WHITE) .setBgResource(R.drawable.snackbar_custom_bg) .show() }, CommonItemClick(R.string.snackbar_short_top) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_short_top)) .setMessageColor(Color.WHITE) .setBgResource(R.drawable.snackbar_custom_bg) .show(true) }, CommonItemClick(R.string.snackbar_short_with_action) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_short_with_action)) .setMessageColor(Color.WHITE) .setBgResource(R.drawable.snackbar_custom_bg) .setAction(getString(R.string.snackbar_click), Color.YELLOW) { ToastUtils.showShort(getString(R.string.snackbar_click)) } .show() }, CommonItemClick(R.string.snackbar_short_with_action_top) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_short_with_action_top)) .setMessageColor(Color.WHITE) .setBgResource(R.drawable.snackbar_custom_bg) .setAction(getString(R.string.snackbar_click), Color.YELLOW) { ToastUtils.showShort(getString(R.string.snackbar_click)) } .show(true) }, CommonItemClick(R.string.snackbar_long) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_long)) .setMessageColor(Color.WHITE) .setDuration(SnackbarUtils.LENGTH_LONG) .setBgResource(R.drawable.snackbar_custom_bg) .show() }, CommonItemClick(R.string.snackbar_long_with_action) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_long_with_action)) .setMessageColor(Color.WHITE) .setBgResource(R.drawable.snackbar_custom_bg) .setDuration(SnackbarUtils.LENGTH_LONG) .setAction(getString(R.string.snackbar_click), Color.YELLOW) { ToastUtils.showShort(getString(R.string.snackbar_click)) } .show() }, CommonItemClick(R.string.snackbar_indefinite) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_indefinite)) .setMessageColor(Color.WHITE) .setDuration(SnackbarUtils.LENGTH_INDEFINITE) .setBgResource(R.drawable.snackbar_custom_bg) .show() }, CommonItemClick(R.string.snackbar_indefinite_with_action) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_indefinite_with_action)) .setMessageColor(Color.WHITE) .setDuration(SnackbarUtils.LENGTH_INDEFINITE) .setBgResource(R.drawable.snackbar_custom_bg) .setAction(getString(R.string.snackbar_click), Color.YELLOW) { ToastUtils.showShort(getString(R.string.snackbar_click)) } .show() }, CommonItemClick(R.string.snackbar_add_view) { val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) SnackbarUtils.with(mContentView) .setBgColor(Color.TRANSPARENT) .setDuration(SnackbarUtils.LENGTH_INDEFINITE) .show() SnackbarUtils.addView(R.layout.snackbar_custom, params) }, CommonItemClick(R.string.snackbar_add_view_with_action) { val params: ViewGroup.LayoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) SnackbarUtils.with(mContentView) .setBgColor(Color.TRANSPARENT) .setDuration(SnackbarUtils.LENGTH_INDEFINITE) .show() SnackbarUtils.addView(R.layout.snackbar_custom, params) val snackbarView = SnackbarUtils.getView() if (snackbarView != null) { val tvSnackbarCustom = snackbarView.findViewById<TextView>(R.id.snackbarCustomTv) tvSnackbarCustom.setText(R.string.snackbar_click_to_dismiss) snackbarView.setOnClickListener { SnackbarUtils.dismiss() } } }, CommonItemClick(R.string.snackbar_success) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_success)) .showSuccess() }, CommonItemClick(R.string.snackbar_warning) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_warning)) .showWarning() }, CommonItemClick(R.string.snackbar_error) { SnackbarUtils.with(mContentView) .setMessage(getMsg(R.string.snackbar_error)) .showError() }, CommonItemClick(R.string.snackbar_dismiss) { SnackbarUtils.dismiss() } ) } private fun getMsg(@StringRes resId: Int): SpannableStringBuilder { return SpanUtils() .appendImage(R.mipmap.ic_launcher, SpanUtils.ALIGN_CENTER) .appendSpace(32) .append(getString(resId)).setFontSize(24, true) .create() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/snackbar/SnackbarActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,278
```kotlin package com.blankj.utilcode.pkg.feature.volume import android.content.Context import android.content.Intent import android.media.AudioManager import android.widget.SeekBar import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemSeekBar import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.VolumeUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2018/12/29 * desc : demo about VibrateUtils * ``` */ class VolumeActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, VolumeActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_volume } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( getItemSeekBar("Voice Call", AudioManager.STREAM_VOICE_CALL), getItemSeekBar("System", AudioManager.STREAM_SYSTEM), getItemSeekBar("Music", AudioManager.STREAM_MUSIC), getItemSeekBar("Ring", AudioManager.STREAM_RING), getItemSeekBar("Alarm", AudioManager.STREAM_ALARM), getItemSeekBar("Notification", AudioManager.STREAM_NOTIFICATION), getItemSeekBar("Dtmf", AudioManager.STREAM_DTMF) ) } private fun getItemSeekBar(title: CharSequence, streamType: Int): CommonItemSeekBar { return CommonItemSeekBar(title, VolumeUtils.getMaxVolume(streamType), object : CommonItemSeekBar.ProgressListener() { override fun getCurValue(): Int { return VolumeUtils.getVolume(streamType) } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { VolumeUtils.setVolume(streamType, progress, AudioManager.FLAG_SHOW_UI) } }) } override fun onResume() { super.onResume() itemsView.updateItems(bindItems()) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/volume/VolumeActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
427
```kotlin package com.blankj.utilcode.pkg.feature.adaptScreen import android.content.Context import android.content.Intent import android.content.res.Resources import android.os.Bundle import android.view.View import android.view.WindowManager import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.AdaptScreenUtils class AdaptCloseActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, AdaptCloseActivity::class.java) context.startActivity(starter) } } override fun bindLayout(): Int { return R.layout.adaptscreen_close_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } override fun getResources(): Resources { return AdaptScreenUtils.closeAdapt(super.getResources()) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/adaptScreen/AdaptCloseActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
194
```kotlin package com.blankj.utilcode.pkg.feature.adaptScreen import android.content.Context import android.content.Intent import android.content.res.Resources import android.os.Bundle import android.view.View import android.view.WindowManager import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.AdaptScreenUtils import com.blankj.utilcode.util.BarUtils import com.blankj.utilcode.util.LogUtils class AdaptHeightActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, AdaptHeightActivity::class.java) context.startActivity(starter) } } override fun bindLayout(): Int { return R.layout.adaptscreen_height_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } override fun onResume() { super.onResume() LogUtils.e(BarUtils.getStatusBarHeight()) } override fun getResources(): Resources { return AdaptScreenUtils.adaptHeight(super.getResources(), 1920) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/adaptScreen/AdaptHeightActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
241
```kotlin package com.blankj.utilcode.pkg.feature.activity import android.content.Context import android.content.Intent import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.widget.ImageView import androidx.core.app.ActivityOptionsCompat import com.blankj.base.rv.ItemViewHolder import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemImage import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.feature.CoreUtilActivity import com.blankj.utilcode.util.ActivityUtils import com.blankj.utilcode.util.AppUtils import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.StringUtils import java.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about ActivityUtils * ``` */ class ActivityActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ActivityActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_activity } override fun bindItems(): List<CommonItem<*>> { val elementItem = ActivityItem() val intent = Intent(this, SubActivityActivity::class.java) val intents = arrayOfNulls<Intent>(2) intents[0] = intent intents[1] = Intent(this, SubActivityActivity::class.java) return CollectionUtils.newArrayList( elementItem, CommonItemTitle("isActivityExists(${SubActivityActivity::class.java.name})", ActivityUtils.isActivityExists(AppUtils.getAppPackageName(), SubActivityActivity::class.java.name).toString()), CommonItemTitle("getLauncherActivity", ActivityUtils.getLauncherActivity(AppUtils.getAppPackageName())), CommonItemTitle("getMainActivities", ActivityUtils.getMainActivities().toString()), CommonItemTitle("getActivityList", CollectionUtils.collect(ActivityUtils.getActivityList()) { input -> input.javaClass.simpleName }.toString()), CommonItemTitle("getTopActivity", ActivityUtils.getTopActivity().toString()), CommonItemTitle("isActivityExistsInStack", ActivityUtils.isActivityExistsInStack(CoreUtilActivity::class.java).toString()), CommonItemImage("getActivityIcon") { it.setImageDrawable(ActivityUtils.getActivityIcon(ActivityActivity::class.java)) }, CommonItemImage("getActivityLogo") { it.setImageDrawable(ActivityUtils.getActivityLogo(ActivityActivity::class.java)) }, CommonItemClick(R.string.activity_clz, true) { ActivityUtils.startActivity(SubActivityActivity::class.java) }, CommonItemClick(R.string.activity_clz_opt, true) { ActivityUtils.startActivity(SubActivityActivity::class.java, getOption(elementItem)) }, CommonItemClick(R.string.activity_clz_anim, true) { ActivityUtils.startActivity(SubActivityActivity::class.java, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_act_clz, true) { ActivityUtils.startActivity(this, SubActivityActivity::class.java) }, CommonItemClick(R.string.activity_act_clz_shared_element, true) { ActivityUtils.startActivity(this, SubActivityActivity::class.java, elementItem.element) }, CommonItemClick(R.string.activity_act_clz_anim, true) { ActivityUtils.startActivity(this, SubActivityActivity::class.java, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_pkg_cls, true) { ActivityUtils.startActivity(this.packageName, SubActivityActivity::class.java.name) }, CommonItemClick(R.string.activity_pkg_cls_opt, true) { ActivityUtils.startActivity(this.packageName, SubActivityActivity::class.java.name, getOption(elementItem)) }, CommonItemClick(R.string.activity_pkg_cls_anim, true) { ActivityUtils.startActivity(this.packageName, SubActivityActivity::class.java.name, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_act_pkg_cls, true) { ActivityUtils.startActivity(this, this.packageName, SubActivityActivity::class.java.name) }, CommonItemClick(R.string.activity_act_pkg_cls_opt, true) { ActivityUtils.startActivity(this, this.packageName, SubActivityActivity::class.java.name, getOption(elementItem)) }, CommonItemClick(R.string.activity_act_pkg_cls_shared_element, true) { ActivityUtils.startActivity(this, this.packageName, SubActivityActivity::class.java.name, elementItem.element) }, CommonItemClick(R.string.activity_act_pkg_cls_anim, true) { ActivityUtils.startActivity(this, this.packageName, SubActivityActivity::class.java.name, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_intent, true) { ActivityUtils.startActivity(this, intent) }, CommonItemClick(R.string.activity_intent_opt, true) { ActivityUtils.startActivity(this, intent, getOption(elementItem)) }, CommonItemClick(R.string.activity_intent_shared_element, true) { ActivityUtils.startActivity(this, intent, elementItem.element) }, CommonItemClick(R.string.activity_intent_anim, true) { ActivityUtils.startActivity(this, intent, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_intents, true) { ActivityUtils.startActivities(intents) }, CommonItemClick(R.string.activity_intents_opt, true) { ActivityUtils.startActivities(intents, getOption(elementItem)) }, CommonItemClick(R.string.activity_intents_anim, true) { ActivityUtils.startActivities(intents, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_act_intents, true) { ActivityUtils.startActivities(this, intents, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_act_intents_opt, true) { ActivityUtils.startActivities(this, intents, getOption(elementItem)) }, CommonItemClick(R.string.activity_act_intents_anim, true) { ActivityUtils.startActivities(this, intents, R.anim.fade_in_1000, R.anim.fade_out_1000) }, CommonItemClick(R.string.activity_start_home_activity, true) { ActivityUtils.startHomeActivity() }, CommonItemClick(R.string.activity_start_launcher_activity, true) { ActivityUtils.startLauncherActivity() }, CommonItemClick(R.string.activity_finish_activity, false) { ActivityUtils.finishActivity(CoreUtilActivity::class.java) }, CommonItemClick(R.string.activity_finish_to_activity, true) { ActivityUtils.finishToActivity(CoreUtilActivity::class.java, false, true) }, CommonItemClick(R.string.activity_finish_all_activities_except_newest, true) { ActivityUtils.finishAllActivitiesExceptNewest() }, CommonItemClick(R.string.activity_finish_all_activities, true) { ActivityUtils.finishAllActivities() } ) } private fun getOption(activityItem: ActivityItem): Bundle? { when (Random().nextInt(5)) { 0 -> return ActivityOptionsCompat.makeCustomAnimation(this, R.anim.slide_right_in_1000, R.anim.slide_left_out_1000) .toBundle() 1 -> return ActivityOptionsCompat.makeScaleUpAnimation(activityItem.element, activityItem.element.width / 2, activityItem.element.height / 2, 0, 0) .toBundle() 2 -> return ActivityOptionsCompat.makeThumbnailScaleUpAnimation(activityItem.element, (activityItem.element.drawable as BitmapDrawable).bitmap, 0, 0) .toBundle() 3 -> return ActivityOptionsCompat.makeSceneTransitionAnimation(this, activityItem.element, StringUtils.getString(R.string.activity_shared_element)) .toBundle() else -> return ActivityOptionsCompat.makeClipRevealAnimation(activityItem.element, activityItem.element.width / 2, activityItem.element.height / 2, 0, 0) .toBundle() } } } class ActivityItem : CommonItem<ActivityItem> { lateinit var element: ImageView; constructor() : super(R.layout.activity_item_shared_element_activity) override fun bind(holder: ItemViewHolder, position: Int) { super.bind(holder, position) element = holder.findViewById(R.id.activityViewSharedElement) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/activity/ActivityActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,792
```kotlin package com.blankj.utilcode.pkg.feature.adaptScreen import android.content.Context import android.content.Intent import android.content.res.Resources import android.graphics.Color import android.os.Bundle import android.view.View import android.view.WindowManager import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.AdaptScreenUtils import kotlinx.android.synthetic.main.adaptscreen_width_activity.* class AdaptWidthActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, AdaptWidthActivity::class.java) context.startActivity(starter) } } override fun bindLayout(): Int { return R.layout.adaptscreen_width_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) adaptScreenWidthWebView.setBackgroundColor(Color.parseColor("#f0d26d")) } override fun getResources(): Resources { return AdaptScreenUtils.adaptWidth(super.getResources(), 1080) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/adaptScreen/AdaptWidthActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
229
```kotlin package com.blankj.utilcode.pkg.feature.adaptScreen import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils class AdaptScreenActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, AdaptScreenActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_adapt_screen } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.adaptScreen_adapt_width, true) { AdaptWidthActivity.start(this) }, CommonItemClick(R.string.adaptScreen_adapt_height, true) { AdaptHeightActivity.start(this) }, CommonItemClick(R.string.adaptScreen_adapt_close, true) { AdaptCloseActivity.start(this) } ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/adaptScreen/AdaptScreenActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
230
```kotlin package com.blankj.utilcode.pkg.feature.rom import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.RomUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2019/01/29 * desc : demo about RomUtils * ``` */ class RomActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, RomActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_rom } override fun bindItems(): MutableList<CommonItem<*>> { val romInfo = RomUtils.getRomInfo() return CollectionUtils.newArrayList( CommonItemTitle("Rom Name", romInfo.name), CommonItemTitle("Rom Version", romInfo.version) ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/rom/RomActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
241
```kotlin package com.blankj.utilcode.pkg.feature.clipboard import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemSwitch import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.ClipboardUtils import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2020/09/11 * desc : demo about ClipboardUtils * ``` */ class ClipboardActivity : CommonActivity() { private var index: Int = 0 private var isAddListener: Boolean = false private var listener = { ToastUtils.showShort(ClipboardUtils.getText()) } companion object { fun start(context: Context) { val starter = Intent(context, ClipboardActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_clipboard } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("getText", ClipboardUtils.getText()), CommonItemTitle("getLabel", ClipboardUtils.getLabel()), CommonItemClick("copyText: value{$index}").setOnItemClickListener { _, _, _ -> ClipboardUtils.copyText("value{${index++}}") itemsView.updateItems(bindItems()) }, CommonItemClick("clear").setOnItemClickListener { _, _, _ -> ClipboardUtils.clear() itemsView.updateItems(bindItems()) }, CommonItemSwitch("clipChangeListener", { isAddListener }, { isAddListener = it if (isAddListener) { ClipboardUtils.addChangedListener(listener) } else { ClipboardUtils.removeChangedListener(listener) } }) ) } override fun onResume() { super.onResume() itemsView.updateItems(bindItems()) } override fun onDestroy() { super.onDestroy() if (isAddListener) { ClipboardUtils.removeChangedListener(listener) } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/clipboard/ClipboardActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
475
```kotlin package com.blankj.utilcode.pkg.feature.clean import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CleanUtils import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.SDCardUtils import com.blankj.utilcode.util.SnackbarUtils import java.io.File /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/29 * desc : demo about CleanUtils * ``` */ class CleanActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, CleanActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_clean } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList<CommonItem<*>>().apply { add(CommonItemClick(R.string.clean_internal_cache) { showSnackbar(CleanUtils.cleanInternalCache(), cacheDir.path) }) add(CommonItemClick(R.string.clean_internal_files) { showSnackbar(CleanUtils.cleanInternalFiles(), filesDir.path) }) add(CommonItemClick(R.string.clean_internal_databases) { showSnackbar(CleanUtils.cleanInternalDbs(), filesDir.parent + File.separator + "databases") }) add(CommonItemClick(R.string.clean_internal_sp) { showSnackbar(CleanUtils.cleanInternalSp(), filesDir.parent + File.separator + "shared_prefs") }) if (SDCardUtils.isSDCardEnableByEnvironment()) { add(CommonItemClick(R.string.clean_external_cache) { showSnackbar(CleanUtils.cleanExternalCache(), externalCacheDir?.absolutePath) }) } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { add(CommonItemClick(R.string.clean_app_user_data) { CleanUtils.cleanAppUserData() }) } } } private fun showSnackbar(isSuccess: Boolean, path: String?) { SnackbarUtils.with(mContentView) .setDuration(SnackbarUtils.LENGTH_LONG) .apply { if (isSuccess) { setMessage("clean \"$path\" dir successful.") showSuccess() } else { setMessage("clean \"$path\" dir failed.") showError() } } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/clean/CleanActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
534
```kotlin package com.blankj.utilcode.pkg.feature.network import android.content.Context import android.content.Intent import android.net.wifi.ScanResult import android.net.wifi.WifiManager import android.os.Bundle import android.view.View import com.blankj.common.activity.CommonActivity import com.blankj.common.helper.PermissionHelper import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemSwitch import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about NetworkUtils * ``` */ class NetworkActivity : CommonActivity(), NetworkUtils.OnNetworkStatusChangedListener { companion object { fun start(context: Context) { PermissionHelper.request(context, object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, NetworkActivity::class.java) context.startActivity(starter) } override fun onDenied() { } }, PermissionConstants.LOCATION) } } private lateinit var itemsTask: ThreadUtils.SimpleTask<List<CommonItem<*>>> private lateinit var wifiScanResultItem: CommonItemTitle private val consumer = Utils.Consumer<NetworkUtils.WifiScanResults> { t -> wifiScanResultItem.setContent(scanResults2String(t.filterResults)) wifiScanResultItem.update() } override fun bindTitleRes(): Int { return R.string.demo_network } private fun getItemsTask(): ThreadUtils.SimpleTask<List<CommonItem<*>>> { itemsTask = object : ThreadUtils.SimpleTask<List<CommonItem<*>>>() { override fun doInBackground(): List<CommonItem<*>> { return bindItems() } override fun onSuccess(result: List<CommonItem<*>>) { dismissLoading() itemsView.updateItems(result) } } return itemsTask } override fun bindItems(): List<CommonItem<*>> { if (ThreadUtils.isMainThread()) return arrayListOf() wifiScanResultItem = CommonItemTitle("getWifiScanResult", scanResults2String(NetworkUtils.getWifiScanResult().filterResults)) return CollectionUtils.newArrayList( CommonItemTitle("isConnected", NetworkUtils.isConnected().toString()), CommonItemTitle("getMobileDataEnabled", NetworkUtils.getMobileDataEnabled().toString()), CommonItemTitle("isMobileData", NetworkUtils.isMobileData().toString()), CommonItemTitle("is4G", NetworkUtils.is4G().toString()), CommonItemTitle("is5G", NetworkUtils.is5G().toString()), CommonItemTitle("isWifiConnected", NetworkUtils.isWifiConnected().toString()), CommonItemTitle("getNetworkOperatorName", NetworkUtils.getNetworkOperatorName()), CommonItemTitle("getNetworkTypeName", NetworkUtils.getNetworkType().toString()), CommonItemTitle("getBroadcastIpAddress", NetworkUtils.getBroadcastIpAddress()), CommonItemTitle("getIpAddressByWifi", NetworkUtils.getIpAddressByWifi()), CommonItemTitle("getGatewayByWifi", NetworkUtils.getGatewayByWifi()), CommonItemTitle("getNetMaskByWifi", NetworkUtils.getNetMaskByWifi()), CommonItemTitle("getServerAddressByWifi", NetworkUtils.getServerAddressByWifi()), CommonItemTitle("getSSID", NetworkUtils.getSSID()), CommonItemTitle("getIPv4Address", NetworkUtils.getIPAddress(true)), CommonItemTitle("getIPv6Address", NetworkUtils.getIPAddress(false)), CommonItemTitle("isWifiAvailable", NetworkUtils.isWifiAvailable().toString()), CommonItemTitle("isAvailable", NetworkUtils.isAvailable().toString()), CommonItemTitle("getBaiduDomainAddress", NetworkUtils.getDomainAddress("baidu.com")), wifiScanResultItem, CommonItemSwitch( R.string.network_wifi_enabled, { val wifiEnabled = NetworkUtils.getWifiEnabled() if (wifiEnabled) { NetworkUtils.addOnWifiChangedConsumer(consumer) } else { NetworkUtils.removeOnWifiChangedConsumer(consumer) } wifiEnabled }, { NetworkUtils.setWifiEnabled(it) ThreadUtils.executeByIo(getItemsTask()) } ), CommonItemClick(R.string.network_open_wireless_settings) { NetworkUtils.openWirelessSettings() } ) } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) NetworkUtils.registerNetworkStatusChangedListener(this) updateItems() } override fun onDisconnected() { ToastUtils.showLong("onDisconnected") updateItems() } override fun onConnected(networkType: NetworkUtils.NetworkType) { ToastUtils.showLong("onConnected: ${networkType.name}") updateItems() } private fun updateItems() { showLoading() ThreadUtils.executeByIo(getItemsTask()) } override fun onDestroy() { super.onDestroy() ThreadUtils.cancel(itemsTask) NetworkUtils.unregisterNetworkStatusChangedListener(this) NetworkUtils.removeOnWifiChangedConsumer(consumer) } private fun scanResults2String(results: List<ScanResult>): String { val sb: StringBuilder = StringBuilder() for (result in results) { sb.append(String.format("${result.SSID}, Level: ${WifiManager.calculateSignalLevel(result.level, 4)}\n")) } return sb.toString() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/network/NetworkActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,167
```kotlin package com.blankj.utilcode.pkg.feature.flashlight import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.helper.PermissionHelper import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemSwitch import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2018/04/27 * desc : demo about FlashlightUtils * ``` */ class FlashlightActivity : CommonActivity() { companion object { fun start(context: Context) { if (!FlashlightUtils.isFlashlightEnable()) { ToastUtils.showLong("Didn't support flashlight.") return } PermissionHelper.request(context, object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, FlashlightActivity::class.java) context.startActivity(starter) } override fun onDenied() { LogUtils.e("permission denied") } }, PermissionConstants.CAMERA) } } override fun bindTitleRes(): Int { return R.string.demo_flashlight } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList<CommonItem<*>>().apply { add(CommonItemTitle("isFlashlightEnable", FlashlightUtils.isFlashlightEnable().toString())) if (FlashlightUtils.isFlashlightEnable()) { add(CommonItemSwitch( R.string.flashlight_status, { FlashlightUtils.isFlashlightOn() }, { FlashlightUtils.setFlashlightStatus(it) } )) } } } override fun onDestroy() { FlashlightUtils.destroy() super.onDestroy() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/flashlight/FlashlightActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
398
```kotlin package com.blankj.utilcode.pkg.feature.api import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.feature.api.other.export.OtherModuleApi import com.blankj.utilcode.util.ApiUtils import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2019/03/12 * desc : demo about ApiUtils * ``` */ class ApiActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ApiActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_api } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.api_invoke_with_params) { ApiUtils.getApi(OtherModuleApi::class.java)?.invokeWithParams(OtherModuleApi.ApiBean("params")) }, CommonItemClick(R.string.api_invoke_with_return_value) { ToastUtils.showShort(ApiUtils.getApi(OtherModuleApi::class.java)?.invokeWithReturnValue()?.name) } ); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/ApiActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
303
```java package com.blankj.utilcode.pkg.feature.api.other.export; import com.blankj.utilcode.util.ApiUtils; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/07/10 * desc : demo about ApiUtils * </pre> */ public abstract class OtherModuleApi extends ApiUtils.BaseApi { public abstract void invokeWithParams(ApiBean bean); public abstract ApiBean invokeWithReturnValue(); public static class ApiBean { public String name; public ApiBean(String name) { this.name = name; } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/other/export/OtherModuleApi.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
135
```java package com.blankj.utilcode.pkg.feature.api.other.pkg; import com.blankj.utilcode.pkg.feature.api.other.export.OtherModuleApi; import com.blankj.utilcode.util.ApiUtils; import com.blankj.utilcode.util.ToastUtils; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/07/10 * desc : demo about ApiUtils * </pre> */ @ApiUtils.Api public class OtherPkgApiImpl extends OtherModuleApi { @Override public void invokeWithParams(ApiBean bean) { ToastUtils.showShort(bean.name); } @Override public ApiBean invokeWithReturnValue() { String value = "value"; return new ApiBean(value); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/other/pkg/OtherPkgApiImpl.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
168
```kotlin package com.blankj.utilcode.pkg.feature.metaData import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.MetaDataUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2018/05/15 * desc : demo about MetaDataUtils * ``` */ class MetaDataActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, MetaDataActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_meta_data } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("getMetaDataInApp", MetaDataUtils.getMetaDataInApp("app_meta_data")), CommonItemTitle("getMetaDataInActivity", MetaDataUtils.getMetaDataInActivity(this, "activity_meta_data").substring(1)) ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/metaData/MetaDataActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
260
```kotlin package com.blankj.utilcode.pkg.feature.brightness import android.content.Context import android.content.Intent import android.os.Build import android.widget.SeekBar import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemSeekBar import com.blankj.common.item.CommonItemSwitch import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2018/02/08 * desc : demo about BrightnessUtils * ``` */ class BrightnessActivity : CommonActivity() { companion object { fun start(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PermissionUtils.requestWriteSettings(object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, BrightnessActivity::class.java) context.startActivity(starter) } override fun onDenied() { ToastUtils.showLong("No permission of write settings.") } }) } else { val starter = Intent(context, BrightnessActivity::class.java) context.startActivity(starter) } } } override fun bindTitleRes(): Int { return R.string.demo_brightness } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemSeekBar("getBrightness", 255, object : CommonItemSeekBar.ProgressListener() { override fun getCurValue(): Int { return BrightnessUtils.getBrightness() } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { BrightnessUtils.setBrightness(progress) } }), CommonItemSeekBar("getWindowBrightness", 255, object : CommonItemSeekBar.ProgressListener() { override fun getCurValue(): Int { return BrightnessUtils.getWindowBrightness(window) } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { BrightnessUtils.setWindowBrightness(window, progress) } }), CommonItemSwitch( R.string.brightness_auto_brightness, { BrightnessUtils.isAutoBrightnessEnabled() }, { BrightnessUtils.setAutoBrightnessEnabled(it) } ) ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/brightness/BrightnessActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
491
```kotlin package com.blankj.utilcode.pkg.feature.file import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.Config.CACHE_PATH import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.FileUtils import com.blankj.utilcode.util.PathUtils import com.blankj.utilcode.util.SnackbarUtils import java.io.File /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/29 * desc : demo about FileUtils * ``` */ class FileActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, FileActivity::class.java) context.startActivity(starter) } val TEST_FILE_PATH: String = CACHE_PATH + "test_file.txt" } override fun bindTitleRes(): Int { return R.string.demo_file } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("isFileExists: " + PathUtils.getInternalAppFilesPath(), "" + FileUtils.isFileExists(PathUtils.getInternalAppFilesPath())), CommonItemTitle("isFileExists: " + PathUtils.getExternalAppFilesPath(), "" + FileUtils.isFileExists(PathUtils.getExternalAppFilesPath())), CommonItemTitle("isFileExists: " + PathUtils.getExternalStoragePath(), "" + FileUtils.isFileExists(PathUtils.getExternalStoragePath())), CommonItemTitle("isFileExists: " + PathUtils.getDownloadCachePath(), "" + FileUtils.isFileExists(PathUtils.getDownloadCachePath())), CommonItemTitle("isFileExists: " + PathUtils.getExternalDownloadsPath(), "" + FileUtils.isFileExists(PathUtils.getExternalDownloadsPath())), CommonItemTitle("isFileExists: " + PathUtils.getInternalAppFilesPath(), "" + FileUtils.isFileExists(File(PathUtils.getInternalAppFilesPath()))), CommonItemTitle("isFileExists: " + PathUtils.getExternalAppFilesPath(), "" + FileUtils.isFileExists(File(PathUtils.getExternalAppFilesPath()))), CommonItemTitle("isFileExists: " + PathUtils.getExternalStoragePath(), "" + FileUtils.isFileExists(File(PathUtils.getExternalStoragePath()))), CommonItemTitle("isFileExists: " + PathUtils.getDownloadCachePath(), "" + FileUtils.isFileExists(File(PathUtils.getDownloadCachePath()))), CommonItemTitle("isFileExists: " + PathUtils.getExternalDownloadsPath(), "" + FileUtils.isFileExists(File(PathUtils.getExternalDownloadsPath()))) ) } override fun onDestroy() { super.onDestroy() SnackbarUtils.dismiss() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/file/FileActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
576
```kotlin package com.blankj.utilcode.pkg.feature.device import android.content.Context import android.content.Intent import android.os.Build import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.DeviceUtils import java.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/27 * desc : demo about DeviceUtils * ``` */ class DeviceActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, DeviceActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_device } override fun bindItems(): List<CommonItem<*>> { return arrayListOf<CommonItem<*>>().apply { add(CommonItemTitle("isRoot", DeviceUtils.isDeviceRooted().toString())) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { add(CommonItemTitle("isAdbEnabled", DeviceUtils.isAdbEnabled().toString())) } add(CommonItemTitle("getSDKVersionName", DeviceUtils.getSDKVersionName())) add(CommonItemTitle("getSDKVersionCode", DeviceUtils.getSDKVersionCode().toString())) add(CommonItemTitle("getAndroidID", DeviceUtils.getAndroidID())) add(CommonItemTitle("getMacAddress", DeviceUtils.getMacAddress())) add(CommonItemTitle("getManufacturer", DeviceUtils.getManufacturer())) add(CommonItemTitle("getModel", DeviceUtils.getModel())) add(CommonItemTitle("getABIs", Arrays.asList(*DeviceUtils.getABIs()).toString())) add(CommonItemTitle("isTablet", DeviceUtils.isTablet().toString())) add(CommonItemTitle("isEmulator", DeviceUtils.isEmulator().toString())) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { add(CommonItemTitle("isDevelopmentSettingsEnabled", DeviceUtils.isDevelopmentSettingsEnabled().toString())) } add(CommonItemTitle("getUniqueDeviceId", DeviceUtils.getUniqueDeviceId("util"))) add(CommonItemTitle("isSameDevice", DeviceUtils.isSameDevice(DeviceUtils.getUniqueDeviceId()).toString())) } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/device/DeviceActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
509
```kotlin package com.blankj.utilcode.pkg.feature.permission import android.Manifest.permission import android.content.Context import android.content.Intent import android.os.Build import com.blankj.common.activity.CommonActivity import com.blankj.common.helper.PermissionHelper import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemSwitch import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2018/01/01 * desc : demo about PermissionUtils * ``` */ class PermissionActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, PermissionActivity::class.java) context.startActivity(starter) } } private val permissions: String init { val permissionList = PermissionUtils.getPermissions() if (permissionList.isEmpty()) { permissions = "" } else { val sb = StringBuilder() for (permission in permissionList) { sb.append("\n").append(permission.substring(permission.lastIndexOf('.') + 1)) } permissions = sb.deleteCharAt(0).toString() } } override fun bindTitleRes(): Int { return R.string.demo_permission } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList<CommonItem<*>>().apply { add(CommonItemTitle("Permissions", permissions)) add(CommonItemClick(R.string.permission_open_app_settings, true) { PermissionUtils.launchAppDetailsSettings() }) add(CommonItemSwitch( R.string.permission_calendar_status, { PermissionUtils.isGranted(PermissionConstants.CALENDAR) }, { requestCalendar() } )) add(CommonItemSwitch( R.string.permission_record_audio_status, { PermissionUtils.isGranted(PermissionConstants.MICROPHONE) }, { requestRecordAudio() } )) add(CommonItemSwitch( R.string.permission_calendar_and_record_audio_status, { PermissionUtils.isGranted(PermissionConstants.CALENDAR, PermissionConstants.MICROPHONE) }, { requestCalendarAndRecordAudio() } )) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { add(CommonItemSwitch( R.string.permission_write_settings_status, { PermissionUtils.isGrantedWriteSettings() }, { requestWriteSettings() } )) add(CommonItemSwitch( R.string.permission_write_settings_status, { PermissionUtils.isGrantedDrawOverlays() }, { requestDrawOverlays() } )) } } } private fun requestCalendar() { PermissionUtils.permissionGroup(PermissionConstants.CALENDAR) .rationale { activity, shouldRequest -> PermissionHelper.showRationaleDialog(activity, shouldRequest) } .callback(object : PermissionUtils.FullCallback { override fun onGranted(permissionsGranted: List<String>) { LogUtils.d(permissionsGranted) showSnackbar(true, "Calendar is granted") itemsView.updateItems(bindItems()) } override fun onDenied(permissionsDeniedForever: List<String>, permissionsDenied: List<String>) { LogUtils.d(permissionsDeniedForever, permissionsDenied) if (permissionsDeniedForever.isNotEmpty()) { showSnackbar(false, "Calendar is denied forever") } else { showSnackbar(false, "Calendar is denied") } itemsView.updateItems(bindItems()) } }) .theme { activity -> ScreenUtils.setFullScreen(activity) } .request() } private fun requestRecordAudio() { PermissionUtils.permissionGroup(PermissionConstants.MICROPHONE) .rationale { activity, shouldRequest -> PermissionHelper.showRationaleDialog(activity, shouldRequest) } .callback(object : PermissionUtils.FullCallback { override fun onGranted(permissionsGranted: List<String>) { LogUtils.d(permissionsGranted) showSnackbar(true, "Microphone is granted") itemsView.updateItems(bindItems()) } override fun onDenied(permissionsDeniedForever: List<String>, permissionsDenied: List<String>) { LogUtils.d(permissionsDeniedForever, permissionsDenied) if (permissionsDeniedForever.isNotEmpty()) { showSnackbar(false, "Microphone is denied forever") } else { showSnackbar(false, "Microphone is denied") } itemsView.updateItems(bindItems()) } }) .request() } private fun requestCalendarAndRecordAudio() { PermissionUtils.permission(permission.READ_CALENDAR, permission.RECORD_AUDIO) .explain { activity, denied, shouldRequest -> PermissionHelper.showExplainDialog(activity, denied, shouldRequest) } .callback { isAllGranted, granted, deniedForever, denied -> LogUtils.d(granted, deniedForever, denied) itemsView.updateItems(bindItems()) if (isAllGranted) { showSnackbar(true, "Calendar and Microphone are granted") return@callback } if (deniedForever.isNotEmpty()) { showSnackbar(false, "Calendar or Microphone is denied forever") } else { showSnackbar(false, "Calendar or Microphone is denied") } } .request() } private fun requestWriteSettings() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PermissionUtils.requestWriteSettings(object : PermissionUtils.SimpleCallback { override fun onGranted() { showSnackbar(true, "Write Settings is granted") itemsView.updateItems(bindItems()) } override fun onDenied() { showSnackbar(false, "Write Settings is denied") itemsView.updateItems(bindItems()) } }) } } private fun requestDrawOverlays() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PermissionUtils.requestDrawOverlays(object : PermissionUtils.SimpleCallback { override fun onGranted() { showSnackbar(true, "Draw Overlays is granted") itemsView.updateItems(bindItems()) } override fun onDenied() { showSnackbar(false, "Draw Overlays is denied") itemsView.updateItems(bindItems()) } }) } } private fun showSnackbar(isSuccess: Boolean, msg: String) { SnackbarUtils.with(mContentView) .setDuration(SnackbarUtils.LENGTH_LONG) .setMessage(msg) .apply { if (isSuccess) { showSuccess() } else { showError() } } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/permission/PermissionActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,372
```kotlin package com.blankj.utilcode.pkg.feature.process import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ProcessUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about ProcessUtils * ``` */ class ProcessActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ProcessActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_process } override fun bindItems(): MutableList<CommonItem<*>> { val set = ProcessUtils.getAllBackgroundProcesses() return CollectionUtils.newArrayList( CommonItemTitle("getForegroundProcessName", ProcessUtils.getForegroundProcessName()!!), CommonItemTitle("getAllBackgroundProcesses -> ${set.size}", getSetItems(set)), CommonItemTitle("isMainProcess", ProcessUtils.isMainProcess().toString()), CommonItemTitle("getCurrentProcessName", ProcessUtils.getCurrentProcessName()), CommonItemClick(R.string.process_kill_all_background).setOnItemClickListener { _, item, _ -> val bgSet = ProcessUtils.getAllBackgroundProcesses() val killedSet = ProcessUtils.killAllBackgroundProcesses() itemsView.updateItems( CollectionUtils.newArrayList( CommonItemTitle("getForegroundProcessName", ProcessUtils.getForegroundProcessName()), CommonItemTitle("getAllBackgroundProcesses -> ${bgSet.size}", getSetItems(bgSet)), CommonItemTitle("killAllBackgroundProcesses -> ${killedSet.size}", getSetItems(killedSet)), CommonItemTitle("isMainProcess", ProcessUtils.isMainProcess().toString()), CommonItemTitle("getCurrentProcessName", ProcessUtils.getCurrentProcessName()), item ) ) } ) } private fun getSetItems(set: Set<String>): String { val iterator = set.iterator() val sb = StringBuilder() while (iterator.hasNext()) { sb.append("\n").append(iterator.next()) } return if (sb.isNotEmpty()) sb.deleteCharAt(0).toString() else "" } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/process/ProcessActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
512
```kotlin package com.blankj.utilcode.pkg.feature.shadow import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.View import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.ShadowUtils import com.blankj.utilcode.util.ShadowUtils.Config import com.blankj.utilcode.util.SizeUtils import kotlinx.android.synthetic.main.shadow_activity.* /** * ``` * author: Blankj * blog : path_to_url * time : 2019/10/22 * desc : demo about ShadowUtils * ``` */ class ShadowActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ShadowActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_shadow } override fun bindLayout(): Int { return R.layout.shadow_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) ShadowUtils.apply(shadowRectView, Config().setShadowColor(0x44000000, 0x55000000)) ShadowUtils.apply(shadowRoundRectView, Config().setShadowColor(0x44000000, 0x55000000).setShadowRadius( SizeUtils.dp2px(16f).toFloat())) ShadowUtils.apply(shadowCircleView, Config().setCircle().setShadowColor(0x44000000, 0x55000000)) ShadowUtils.apply(shadowRectView1, Config().setShadowColor(0x44000000, 0x55000000)) ShadowUtils.apply(shadowRoundRectView1, Config().setShadowColor(0x44000000, 0x55000000).setShadowRadius( SizeUtils.dp2px(16f).toFloat())) ShadowUtils.apply(shadowCircleView1, Config().setCircle().setShadowColor(0x44000000, 0x55000000)) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/shadow/ShadowActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
449
```kotlin package com.blankj.utilcode.pkg.feature.phone import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.helper.PermissionHelper import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.PermissionUtils import com.blankj.utilcode.util.PhoneUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about PhoneUtils * ``` */ class PhoneActivity : CommonActivity() { companion object { fun start(context: Context) { PermissionHelper.request(context, object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, PhoneActivity::class.java) context.startActivity(starter) } override fun onDenied() { } }, PermissionConstants.PHONE) } } override fun bindTitleRes(): Int { return R.string.demo_phone } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("isPhone", PhoneUtils.isPhone().toString()), CommonItemTitle("getDeviceId", PhoneUtils.getDeviceId()), CommonItemTitle("getSerial", PhoneUtils.getSerial()), CommonItemTitle("getIMEI", PhoneUtils.getIMEI()), CommonItemTitle("getMEID", PhoneUtils.getMEID()), CommonItemTitle("getIMSI", PhoneUtils.getIMSI()), CommonItemTitle("getPhoneType", PhoneUtils.getPhoneType().toString()), CommonItemTitle("isSimCardReady", PhoneUtils.isSimCardReady().toString()), CommonItemTitle("getSimOperatorName", PhoneUtils.getSimOperatorName()), CommonItemTitle("getSimOperatorByMnc", PhoneUtils.getSimOperatorByMnc()), CommonItemClick(R.string.phone_dial) { PhoneUtils.dial("*10000#haha") }, CommonItemClick(R.string.phone_call) { PhoneUtils.call("*10000#haha") }, CommonItemClick(R.string.phone_send_sms) { PhoneUtils.sendSms("10000", "sendSms") } ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/phone/PhoneActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
510
```kotlin package com.blankj.utilcode.pkg.feature.vibrate import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.VibrateUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2018/12/29 * desc : demo about VibrateUtils * ``` */ class VibrateActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, VibrateActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_vibrate } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.vibrate_1000ms) { VibrateUtils.vibrate(1000) }, CommonItemClick(R.string.vibrate_custom) { VibrateUtils.vibrate(longArrayOf(0, 1000, 1000, 2000, 2000, 1000), 1) }, CommonItemClick(R.string.vibrate_background) { backHome() mContentView.postDelayed({ // VibrateUtils.vibrate(1000) -- can not vibrate in background VibrateUtils.vibrateCompat(longArrayOf(0, 1000, 1000, 2000, 2000, 1000), 1) // VibrateUtils.vibrateCompat(1000) }, 1000) }, CommonItemClick(R.string.vibrate_cancel) { VibrateUtils.cancel() } ) } override fun onDestroy() { super.onDestroy() VibrateUtils.cancel() } private fun backHome() { val intent = Intent(Intent.ACTION_MAIN).apply { addCategory(Intent.CATEGORY_HOME) } startActivity(intent) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/vibrate/VibrateActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
444
```kotlin package com.blankj.utilcode.pkg.feature.fragment import android.content.Context import android.content.Intent import android.os.Bundle import android.os.PersistableBundle import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.fragment.app.Fragment import android.view.View import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.FragmentUtils import kotlinx.android.synthetic.main.fragment_activity.* /** * ``` * author: Blankj * blog : path_to_url * time : 17/02/01 * desc : demo about FragmentUtils * ``` */ class FragmentActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, FragmentActivity::class.java) context.startActivity(starter) } } private val mFragments = arrayListOf<androidx.fragment.app.Fragment>() private var curIndex: Int = 0 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.fragmentNavigation0 -> { showCurrentFragment(0) return@OnNavigationItemSelectedListener true } R.id.fragmentNavigation1 -> { showCurrentFragment(1) return@OnNavigationItemSelectedListener true } R.id.fragmentNavigation2 -> { showCurrentFragment(2) return@OnNavigationItemSelectedListener true } else -> false } } override fun bindLayout(): Int { return R.layout.fragment_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) if (savedInstanceState != null) { curIndex = savedInstanceState.getInt("curIndex") } fragmentNav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) mFragments.add(RootFragment.newInstance()) mFragments.add(RootFragment.newInstance()) mFragments.add(RootFragment.newInstance()) FragmentUtils.add( supportFragmentManager, mFragments, R.id.fragmentContainer, arrayOf("RootFragment0", "RootFragment1", "RootFragment2"), curIndex ) } override fun onBackPressed() { if (!FragmentUtils.dispatchBackPress(mFragments[curIndex])) { super.onBackPressed() } } private fun showCurrentFragment(index: Int) { curIndex = index FragmentUtils.showHide(index, mFragments) } override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) { super.onSaveInstanceState(outState, outPersistentState) outState.putInt("curIndex", curIndex) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/fragment/FragmentActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
551
```kotlin package com.blankj.utilcode.pkg.feature.fragment import android.os.Bundle import android.view.View import com.blankj.common.fragment.CommonFragment import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.BarUtils import com.blankj.utilcode.util.ColorUtils import com.blankj.utilcode.util.FragmentUtils import kotlinx.android.synthetic.main.fragment_root.* /** * ``` * author: Blankj * blog : path_to_url * time : 17/02/02 * desc : demo about FragmentUtils * ``` */ class RootFragment : CommonFragment(), FragmentUtils.OnBackClickListener { companion object { fun newInstance(): RootFragment { val args = Bundle() val fragment = RootFragment() fragment.arguments = args return fragment } } override fun bindLayout(): Int { return R.layout.fragment_root } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) BarUtils.setStatusBarColor(rootFragmentFakeStatusBar, ColorUtils.getColor(R.color.colorPrimary)) FragmentUtils.add( childFragmentManager, ContainerFragment.newInstance(), R.id.rootFragmentContainer ) } override fun onBackClick(): Boolean { if (FragmentUtils.dispatchBackPress(childFragmentManager)) return true return if (childFragmentManager.backStackEntryCount == 0) { false } else { childFragmentManager.popBackStack() true } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/fragment/RootFragment.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
309
```kotlin package com.blankj.utilcode.pkg.feature.fragment import android.os.Bundle import android.view.View import androidx.fragment.app.FragmentManager import com.blankj.common.fragment.CommonFragment import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.helper.DialogHelper import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ColorUtils import com.blankj.utilcode.util.FragmentUtils import com.blankj.utilcode.util.SpanUtils /** * ``` * author: Blankj * blog : path_to_url * time : 17/02/02 * desc : demo about FragmentUtils * ``` */ class ChildFragment : CommonFragment() { companion object { fun newInstance(): ChildFragment { val args = Bundle() val fragment = ChildFragment() fragment.arguments = args return fragment } } private lateinit var fm: FragmentManager private val mBgColor = ColorUtils.getRandomColor(false) override fun bindLayout(): Int { return R.layout.fragment_child } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) FragmentUtils.setBackgroundColor(this, mBgColor) fm = fragmentManager!! setCommonItems(findViewById(R.id.commonItemRv), getItems()) } private fun getItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList<CommonItem<*>>( CommonItemClick(R.string.fragment_show_stack) { DialogHelper.showFragmentDialog( SpanUtils().appendLine("top: " + FragmentUtils.getSimpleName(FragmentUtils.getTop(fm))) .appendLine("topInStack: " + FragmentUtils.getSimpleName(FragmentUtils.getTopInStack(fm))) .appendLine("topShow: " + FragmentUtils.getSimpleName(FragmentUtils.getTopShow(fm))) .appendLine("topShowInStack: " + FragmentUtils.getSimpleName(FragmentUtils.getTopShowInStack(fm))) .appendLine() .appendLine("---all of fragments---") .appendLine(FragmentUtils.getAllFragments(fm).toString()) .appendLine("----------------------") .appendLine() .appendLine("---stack top---") .appendLine(FragmentUtils.getAllFragmentsInStack(fm).toString()) .appendLine("---stack bottom---") .create() ) }, CommonItemClick(R.string.fragment_pop) { FragmentUtils.pop(fm) }, CommonItemClick(R.string.fragment_remove) { FragmentUtils.remove(this) }, SharedElementItem() ).apply { for (ci: CommonItem<*> in this) { ci.backgroundColor = mBgColor } } } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/fragment/ChildFragment.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
577
```kotlin package com.blankj.utilcode.pkg.feature.keyboard import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.helper.DialogHelper import com.blankj.utilcode.util.* import kotlinx.android.synthetic.main.keyboard_activity.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/27 * desc : demo about KeyboardUtils * ``` */ class KeyboardActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, KeyboardActivity::class.java) context.startActivity(starter) } } private var titleItem: CommonItemTitle = CommonItemTitle("", true) override fun bindTitleRes(): Int { return R.string.demo_keyboard } override fun bindLayout(): Int { return R.layout.keyboard_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) KeyboardUtils.fixAndroidBug5497(this) setCommonItems(findViewById(R.id.commonItemRv), getItems()) KeyboardUtils.registerSoftInputChangedListener(this) { height -> titleItem.title = "isSoftInputVisible: " + KeyboardUtils.isSoftInputVisible(this@KeyboardActivity) + "\nkeyboardHeight: $height" if (height > 0) { keyboardEt.requestFocus() } } } private fun getItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( titleItem, CommonItemClick(R.string.keyboard_hide_soft_input) { KeyboardUtils.hideSoftInput(this) }, CommonItemClick(R.string.keyboard_show_soft_input) { KeyboardUtils.showSoftInput(this) }, CommonItemClick(R.string.keyboard_toggle_soft_input) { KeyboardUtils.toggleSoftInput() }, CommonItemClick(R.string.keyboard_show_dialog) { keyboardEt.clearFocus() DialogHelper.showKeyboardDialog(this) } ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/keyboard/KeyboardActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
468
```kotlin package com.blankj.utilcode.pkg.feature.fragment import android.os.Build import android.os.Bundle import android.transition.* import android.view.View import android.widget.ImageView import androidx.annotation.RequiresApi import androidx.fragment.app.FragmentManager import com.blankj.base.rv.ItemViewHolder import com.blankj.common.fragment.CommonFragment import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.helper.DialogHelper import com.blankj.utilcode.util.* import java.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 17/02/02 * desc : demo about FragmentUtils * ``` */ class ContainerFragment : CommonFragment(), FragmentUtils.OnBackClickListener { companion object { fun newInstance(): ContainerFragment { val args = Bundle() val fragment = ContainerFragment() fragment.arguments = args return fragment } } private lateinit var fm: FragmentManager private val mBgColor = ColorUtils.getRandomColor(false) override fun bindLayout(): Int { return R.layout.fragment_container } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) mContentView.setBackgroundColor(mBgColor) fm = fragmentManager!! setCommonItems(findViewById(R.id.commonItemRv), getItems()) } private fun getItems(): ArrayList<CommonItem<*>>? { val item = SharedElementItem() return CollectionUtils.newArrayList<CommonItem<*>>( CommonItemClick(R.string.fragment_show_stack) { DialogHelper.showFragmentDialog( SpanUtils().appendLine("top: " + FragmentUtils.getSimpleName(FragmentUtils.getTop(fm))) .appendLine("topInStack: " + FragmentUtils.getSimpleName(FragmentUtils.getTopInStack(fm))) .appendLine("topShow: " + FragmentUtils.getSimpleName(FragmentUtils.getTopShow(fm))) .appendLine("topShowInStack: " + FragmentUtils.getSimpleName(FragmentUtils.getTopShowInStack(fm))) .appendLine() .appendLine("---all of fragments---") .appendLine(FragmentUtils.getAllFragments(fm).toString()) .appendLine("----------------------") .appendLine() .appendLine("---stack top---") .appendLine(FragmentUtils.getAllFragmentsInStack(fm).toString()) .appendLine("---stack bottom---") .create() ) }, CommonItemClick(R.string.fragment_add_child) { FragmentUtils.add( fm, ChildFragment.newInstance(), id ) }, CommonItemClick(R.string.fragment_add_child_stack) { FragmentUtils.add( fm, ChildFragment.newInstance(), id, false, true ) }, CommonItemClick(R.string.fragment_add_hide) { FragmentUtils.add( fm, ChildFragment.newInstance(), id, true ) }, CommonItemClick(R.string.fragment_add_hide_stack) { FragmentUtils.add( fm, ChildFragment.newInstance(), id, true, true ) }, CommonItemClick(R.string.fragment_add_demo1_show) { FragmentUtils.add( fm, addSharedElement(ChildFragment.newInstance()), id, false, false ) }, CommonItemClick(R.string.fragment_pop_to_root) { FragmentUtils.popTo( fm, ChildFragment::class.java, true ) }, CommonItemClick(R.string.fragment_hide_demo0_show_demo1) { val fragment1 = FragmentUtils.findFragment(fm, ChildFragment::class.java) if (fragment1 != null) { FragmentUtils.showHide(this, fragment1) } else { ToastUtils.showLong("please add demo1 first!") } }, CommonItemClick(R.string.fragment_replace) { FragmentUtils.replace( fm, addSharedElement(ChildFragment.newInstance()), id, true, item.element ) }, item ).apply { for (ci: CommonItem<*> in this) { ci.backgroundColor = mBgColor } } } private fun addSharedElement(fragment: androidx.fragment.app.Fragment): androidx.fragment.app.Fragment { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fragment.sharedElementEnterTransition = DetailTransition() fragment.enterTransition = Fade() fragment.sharedElementReturnTransition = DetailTransition() } return fragment } override fun onBackClick(): Boolean { return false } } class SharedElementItem : CommonItem<SharedElementItem> { lateinit var element: ImageView; constructor() : super(R.layout.fragment_item_shared_element) override fun bind(holder: ItemViewHolder, position: Int) { super.bind(holder, position) element = holder.findViewById(R.id.fragmentRootSharedElementIv) } } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) class DetailTransition() : TransitionSet() { init { ordering = ORDERING_TOGETHER addTransition(ChangeBounds()).addTransition(ChangeTransform()).addTransition(ChangeImageTransform()) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/fragment/ContainerFragment.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,088
```kotlin package com.blankj.utilcode.pkg.feature.spStatic import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.SPStaticUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2018/01/08 * desc : demo about SPUtils * ``` */ class SPStaticActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, SPStaticActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_spStatic } override fun bindItems(): MutableList<CommonItem<*>> { val itemTitle = CommonItemTitle(sp2String(), true) return CollectionUtils.newArrayList( itemTitle, CommonItemClick(R.string.sp_put_string) { SPStaticUtils.put("STRING", "string") itemTitle.title = sp2String() }, CommonItemClick(R.string.sp_put_int) { SPStaticUtils.put("INT", 21) itemTitle.title = sp2String() }, CommonItemClick(R.string.sp_put_long) { SPStaticUtils.put("LONG", java.lang.Long.MAX_VALUE) itemTitle.title = sp2String() }, CommonItemClick(R.string.sp_put_float) { SPStaticUtils.put("FLOAT", Math.PI.toFloat()) itemTitle.title = sp2String() }, CommonItemClick(R.string.sp_put_boolean) { SPStaticUtils.put("BOOLEAN", true) itemTitle.title = sp2String() }, CommonItemClick(R.string.sp_put_string_set) { SPStaticUtils.put("SET", setOf("1", "2")) itemTitle.title = sp2String() }, CommonItemClick(R.string.sp_clear) { SPStaticUtils.clear() itemTitle.title = sp2String() } ) } private fun sp2String(): String { val sb = StringBuilder() val map = SPStaticUtils.getAll() if (map.isEmpty()) return "" for ((key, value) in map) { sb.append("\n") .append(key) .append(": ") .append(value) } return sb.deleteCharAt(0).toString() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/spStatic/SPStaticActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
542
```kotlin package com.blankj.utilcode.pkg.feature.reflect import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ReflectUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2018/01/29 * desc : demo about ReflectUtils * ``` */ class ReflectActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ReflectActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_reflect } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("source value", TestPrivateStaticFinal.STR), CommonItemTitle("reflect get", ReflectUtils.reflect(TestPrivateStaticFinal::class.java).field("STR").get<String>()), CommonItemTitle("after reflect get", ReflectUtils.reflect(TestPrivateStaticFinal::class.java).field("STR", "reflect success").field("STR").get<String>()), CommonItemTitle("source value", TestPrivateStaticFinal.STR) ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/reflect/ReflectActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
299
```java package com.blankj.utilcode.pkg.feature.reflect; import androidx.annotation.Keep; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/09 * desc : * </pre> */ @Keep public class TestPrivateStaticFinal { public static final String STR = "str"; } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/reflect/TestPrivateStaticFinal.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
82
```kotlin package com.blankj.utilcode.pkg.feature.uiMessage import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.UiMessageUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2020/04/14 * desc : demo about UiMessageUtils * ``` */ class UiMessageActivity : CommonActivity(), UiMessageUtils.UiMessageCallback { private val titleItem: CommonItemTitle = CommonItemTitle("", true); private var sendContent: String = "" companion object { fun start(context: Context) { val starter = Intent(context, UiMessageActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_uiMessage } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( titleItem, CommonItemClick(R.string.uiMessage_add_listener_id) { UiMessageUtils.getInstance().addListener(R.id.utilCodeUiMessageAddListenerId, this) }, CommonItemClick(R.string.uiMessage_remove_all_id) { UiMessageUtils.getInstance().removeListeners(R.id.utilCodeUiMessageAddListenerId) }, CommonItemClick(R.string.uiMessage_add_listener) { UiMessageUtils.getInstance().addListener(this) }, CommonItemClick(R.string.uiMessage_remove_listener) { UiMessageUtils.getInstance().removeListener(this) }, CommonItemClick(R.string.uiMessage_send) { sendContent = "send: UiMessageActivity#${UiMessageActivity.hashCode()}" titleItem.title = "" UiMessageUtils.getInstance().send(R.id.utilCodeUiMessageAddListenerId, UiMessageActivity) } ) } override fun handleMessage(localMessage: UiMessageUtils.UiMessage) { if (localMessage.id == R.id.utilCodeUiMessageAddListenerId) { var content: String = sendContent content += "\nreceive: UiMessageActivity#${localMessage.getObject().hashCode()}" titleItem.title = if (titleItem.title.toString().isEmpty()) { content } else { titleItem.title.toString() + "\n" + content } } } override fun onDestroy() { super.onDestroy() UiMessageUtils.getInstance().removeListeners(R.id.utilCodeUiMessageAddListenerId) UiMessageUtils.getInstance().removeListener(this) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/uiMessage/UiMessageActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
560
```kotlin package com.blankj.utilcode.pkg.feature.messenger import android.content.Context import android.content.Intent import android.os.Bundle import com.blankj.common.activity.CommonActivity import com.blankj.common.activity.CommonActivityItemsView import com.blankj.common.activity.CommonActivityTitleView import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.MessengerUtils import com.blankj.utilcode.util.SnackbarUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2019/03/12 * desc : demo about MessengerUtils * ``` */ class MessengerRemoteActivity : CommonActivity() { companion object { const val MESSENGER_KEY = "MessengerRemoteActivity" fun start(context: Context) { val starter = Intent(context, MessengerRemoteActivity::class.java) context.startActivity(starter) } val BUNDLE = Bundle() init { BUNDLE.putString(MESSENGER_KEY, "MessengerRemoteActivity") } } override fun bindTitleRes(): Int { return R.string.demo_messenger } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.messenger_register_remote_client) { MessengerUtils.register() }, CommonItemClick(R.string.messenger_unregister_remote_client) { MessengerUtils.unregister() }, CommonItemClick(R.string.messenger_post_to_self_client) { MessengerUtils.post(MESSENGER_KEY, BUNDLE) }, CommonItemClick(R.string.messenger_post_to_main_server) { MessengerUtils.post(MessengerActivity.MESSENGER_KEY, MessengerActivity.BUNDLE) } ) } override fun doBusiness() { MessengerUtils.subscribe(MESSENGER_KEY) { data -> SnackbarUtils.with(mContentView) .setMessage(data.getString(MESSENGER_KEY) ?: "") .setDuration(SnackbarUtils.LENGTH_INDEFINITE) .show() } } override fun onDestroy() { super.onDestroy() MessengerUtils.unsubscribe(MESSENGER_KEY) MessengerUtils.unregister() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/messenger/MessengerRemoteActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
481
```kotlin package com.blankj.utilcode.pkg.feature.messenger import android.content.Context import android.content.Intent import android.os.Bundle import com.blankj.common.activity.CommonActivity import com.blankj.common.activity.CommonActivityItemsView import com.blankj.common.activity.CommonActivityTitleView import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.MessengerUtils import com.blankj.utilcode.util.SnackbarUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2019/03/12 * desc : demo about MessengerUtils * ``` */ class MessengerActivity : CommonActivity() { companion object { const val MESSENGER_KEY = "MessengerActivity" fun start(context: Context) { val starter = Intent(context, MessengerActivity::class.java) context.startActivity(starter) MessengerUtils.register() } val BUNDLE = Bundle() init { BUNDLE.putString(MESSENGER_KEY, "MessengerActivity") } } override fun bindTitleRes(): Int { return R.string.demo_messenger } override fun bindItems(): List<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.messenger_post_to_main_server) { MessengerUtils.post(MESSENGER_KEY, BUNDLE) }, CommonItemClick(R.string.messenger_start_remote) { MessengerRemoteActivity.start(this) } ) } override fun doBusiness() { MessengerUtils.subscribe(MESSENGER_KEY) { data -> SnackbarUtils.with(mContentView) .setMessage(data.getString(MESSENGER_KEY) ?: "") .setDuration(SnackbarUtils.LENGTH_INDEFINITE) .show() } } override fun onDestroy() { super.onDestroy() MessengerUtils.unregister() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/messenger/MessengerActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
429
```kotlin package com.blankj.utilcode.pkg.feature.span import android.animation.ValueAnimator import android.content.Context import android.content.Intent import android.graphics.* import android.os.Bundle import android.text.Layout import android.text.SpannableStringBuilder import android.text.TextPaint import android.text.style.CharacterStyle import android.text.style.ClickableSpan import android.text.style.UpdateAppearance import android.view.View import android.view.animation.LinearInterpolator import androidx.annotation.ColorInt import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.SpanUtils import com.blankj.utilcode.util.ToastUtils import kotlinx.android.synthetic.main.span_activity.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/27 * desc : demo about SpanUtils * ``` */ class SpanActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, SpanActivity::class.java) context.startActivity(starter) } } private lateinit var mSpanUtils: SpanUtils private lateinit var animSsb: SpannableStringBuilder private var lineHeight: Int = 0 private var textSize: Float = 0f private lateinit var valueAnimator: ValueAnimator private lateinit var mShader: Shader private var mShaderWidth: Float = 0f private lateinit var matrix: Matrix private lateinit var mBlurMaskFilterSpan: BlurMaskFilterSpan private lateinit var mShadowSpan: ShadowSpan private lateinit var mForegroundAlphaColorSpan: ForegroundAlphaColorSpan private lateinit var mForegroundAlphaColorSpanGroup: ForegroundAlphaColorSpanGroup private lateinit var mPrinterString: String private var density: Float = 0f override fun bindTitleRes(): Int { return R.string.demo_span } override fun bindLayout(): Int { return R.layout.span_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) val clickableSpan = object : ClickableSpan() { override fun onClick(widget: View) { ToastUtils.showShort("") } override fun updateDrawState(ds: TextPaint) { ds.color = Color.BLUE ds.isUnderlineText = false } } lineHeight = spanAboutTv.lineHeight textSize = spanAboutTv.textSize density = resources.displayMetrics.density SpanUtils.with(spanAboutTv) .appendLine("SpanUtils").setBackgroundColor(Color.LTGRAY).setBold().setForegroundColor(Color.YELLOW).setHorizontalAlign(Layout.Alignment.ALIGN_CENTER) .appendLine("").setForegroundColor(Color.GREEN) // .appendLine("").setForegroundColor(Color.RED).setBackgroundColor(Color.LTGRAY).setFontSize(10).setLineHeight(280, SpanUtils.ALIGN_BOTTOM) .appendLine("").setBackgroundColor(Color.LTGRAY) .appendLine("").setLineHeight(2 * lineHeight, SpanUtils.ALIGN_CENTER).setBackgroundColor(Color.LTGRAY) .appendLine("").setLineHeight(2 * lineHeight, SpanUtils.ALIGN_BOTTOM).setBackgroundColor(Color.GREEN) .appendLine("").setLeadingMargin(textSize.toInt() * 2, 10).setBackgroundColor(Color.GREEN) .appendLine("").setQuoteColor(Color.GREEN, 10, 10).setBackgroundColor(Color.LTGRAY) .appendLine("").setBullet(Color.GREEN, 20, 10).setBackgroundColor(Color.LTGRAY).setBackgroundColor(Color.GREEN) .appendLine("32dp ").setFontSize(32, true) .appendLine("2 ").setFontProportion(2f) .appendLine(" 2 ").setFontXProportion(1.5f) .appendLine("").setStrikethrough() .appendLine("").setUnderline() .append("").appendLine("").setSuperscript() .append("").appendLine("").setSubscript() .appendLine("").setBold() .appendLine("").setItalic() .appendLine("").setBoldItalic() .appendLine("monospace ").setFontFamily("monospace") .appendLine("").setTypeface(Typeface.createFromAsset(assets, "fonts/dnmbhs.ttf")) .appendLine("").setHorizontalAlign(Layout.Alignment.ALIGN_OPPOSITE) .appendLine("").setHorizontalAlign(Layout.Alignment.ALIGN_CENTER) .appendLine("").setHorizontalAlign(Layout.Alignment.ALIGN_NORMAL) .append("").appendLine("").setClickSpan(clickableSpan) .append("").appendLine("Url").setUrl("path_to_url") .append("").appendLine("").setBlur(3f, BlurMaskFilter.Blur.NORMAL) .appendLine("").setShader(LinearGradient(0f, 0f, 64f * density * 4f, 0f, resources.getIntArray(R.array.rainbow), null, Shader.TileMode.REPEAT)).setFontSize(64, true) .appendLine("").setFontSize(64, true).setShader(BitmapShader(BitmapFactory.decodeResource(resources, R.drawable.span_cheetah), Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)) .appendLine("").setFontSize(64, true).setBackgroundColor(Color.BLACK).setShadow(24f, 8f, 8f, Color.WHITE) .append("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_TOP) .append("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_CENTER) .append("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_BASELINE) .append("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_BOTTOM) .appendLine("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP) .append("").setBackgroundColor(Color.LTGRAY) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP) .append("").setBackgroundColor(Color.LTGRAY) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP) .appendLine("").setBackgroundColor(Color.LTGRAY) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER) .append("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER) .append("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER) .appendLine("").setBackgroundColor(Color.GREEN) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM) .append("").setBackgroundColor(Color.LTGRAY) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM) .append("").setBackgroundColor(Color.LTGRAY) .appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM) .appendLine("").setBackgroundColor(Color.LTGRAY) .append("").appendSpace(30, Color.LTGRAY).appendSpace(50, Color.GREEN).appendSpace(100).appendSpace(30, Color.LTGRAY).appendSpace(50, Color.GREEN) .create() // initAnimSpan(); // startAnim(); } private fun initAnimSpan() { mShaderWidth = 64f * density * 4f mShader = LinearGradient(0f, 0f, mShaderWidth, 0f, resources.getIntArray(R.array.rainbow), null, Shader.TileMode.REPEAT) matrix = Matrix() mBlurMaskFilterSpan = BlurMaskFilterSpan(25f) mShadowSpan = ShadowSpan(8f, 8f, 8f, Color.WHITE) mForegroundAlphaColorSpan = ForegroundAlphaColorSpan(Color.TRANSPARENT) mForegroundAlphaColorSpanGroup = ForegroundAlphaColorSpanGroup(0f) mPrinterString = "..." mSpanUtils = SpanUtils() .appendLine("").setFontSize(64, true).setShader(mShader) .appendLine("").setFontSize(64, true).setSpans(mBlurMaskFilterSpan) .appendLine("").setFontSize(64, true).setBackgroundColor(Color.BLACK).setSpans(mShadowSpan) .appendLine("").setFontSize(64, true).setSpans(mForegroundAlphaColorSpan) var i = 0 val len = mPrinterString.length while (i < len) { val span = ForegroundAlphaColorSpan(Color.TRANSPARENT) mSpanUtils.append(mPrinterString.substring(i, i + 1)).setSpans(span) mForegroundAlphaColorSpanGroup.addSpan(span) ++i } animSsb = mSpanUtils.create() } private fun startAnim() { valueAnimator = ValueAnimator.ofFloat(0f, 1f) valueAnimator.addUpdateListener { animation -> // shader matrix.reset() matrix.setTranslate(animation.animatedValue as Float * mShaderWidth, 0f) mShader.setLocalMatrix(matrix) // blur mBlurMaskFilterSpan.radius = 25 * (1.00001f - animation.animatedValue as Float) // shadow mShadowSpan.dx = 16 * (0.5f - animation.animatedValue as Float) mShadowSpan.dy = 16 * (0.5f - animation.animatedValue as Float) // alpha mForegroundAlphaColorSpan.setAlpha((255 * animation.animatedValue as Float).toInt()) // printer mForegroundAlphaColorSpanGroup.alpha = animation.animatedValue as Float // showMsg spanAboutAnimTv.text = animSsb } valueAnimator.interpolator = LinearInterpolator() valueAnimator.duration = (600 * 3).toLong() valueAnimator.repeatCount = ValueAnimator.INFINITE valueAnimator.start() } override fun doBusiness() {} override fun onDebouncingClick(view: View) {} // override fun onDestroy() { // if (valueAnimator.isRunning) { // valueAnimator.cancel() // } // super.onDestroy() // } } class BlurMaskFilterSpan(private var mRadius: Float) : CharacterStyle(), UpdateAppearance { private var mFilter: MaskFilter? = null var radius: Float get() = mRadius set(radius) { mRadius = radius mFilter = BlurMaskFilter(mRadius, BlurMaskFilter.Blur.NORMAL) } override fun updateDrawState(ds: TextPaint) { ds.maskFilter = mFilter } } class ForegroundAlphaColorSpan(@param:ColorInt private var mColor: Int) : CharacterStyle(), UpdateAppearance { fun setAlpha(alpha: Int) { mColor = Color.argb(alpha, Color.red(mColor), Color.green(mColor), Color.blue(mColor)) } override fun updateDrawState(ds: TextPaint) { ds.color = mColor } } class ForegroundAlphaColorSpanGroup(private val mAlpha: Float) { private val mSpans: ArrayList<ForegroundAlphaColorSpan> = ArrayList() var alpha: Float get() = mAlpha set(alpha) { val size = mSpans.size var total = 1.0f * size.toFloat() * alpha for (index in 0 until size) { val span = mSpans[index] if (total >= 1.0f) { span.setAlpha(255) total -= 1.0f } else { span.setAlpha((total * 255).toInt()) total = 0.0f } } } fun addSpan(span: ForegroundAlphaColorSpan) { span.setAlpha((mAlpha * 255).toInt()) mSpans.add(span) } } class ShadowSpan(private val radius: Float, var dx: Float, var dy: Float, private val shadowColor: Int) : CharacterStyle(), UpdateAppearance { override fun updateDrawState(tp: TextPaint) { tp.setShadowLayer(radius, dx, dy, shadowColor) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/span/SpanActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
2,584
```kotlin package com.blankj.utilcode.pkg.feature.image import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.os.Build import android.os.Bundle import android.view.View import com.blankj.common.activity.CommonActivity import com.blankj.common.helper.PermissionHelper import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemImage import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.pkg.Config import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* import java.io.File import java.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/26 * desc : demo about ImageUtils * ``` */ class ImageActivity : CommonActivity() { private val savePath = Config.CACHE_PATH + "lena.jpg" private val titleItem: CommonItemTitle = CommonItemTitle("isImage: $savePath", ""); companion object { fun start(context: Context) { PermissionHelper.request(context, object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, ImageActivity::class.java) context.startActivity(starter) } override fun onDenied() { } }, PermissionConstants.STORAGE) } } private val bgTask: ThreadUtils.SimpleTask<List<CommonItem<*>>> = object : ThreadUtils.SimpleTask<List<CommonItem<*>>>() { override fun doInBackground(): List<CommonItem<*>> { return bindItems() } override fun onSuccess(result: List<CommonItem<*>>) { dismissLoading() itemsView.updateItems(result) } } override fun bindTitleRes(): Int { return R.string.demo_image } override fun bindItems(): ArrayList<CommonItem<*>> { if (ThreadUtils.isMainThread()) return arrayListOf() val src = ImageUtils.getBitmap(R.drawable.image_lena) val round = ImageUtils.getBitmap(R.drawable.common_avatar_round) val watermark = ImageUtils.getBitmap(R.mipmap.ic_launcher) val width = src.width val height = src.height titleItem.setContent(ImageUtils.isImage(savePath).toString()) return CollectionUtils.newArrayList<CommonItem<*>>().apply { add(titleItem) add(CommonItemClick("Save to $savePath") { ThreadUtils.executeBySingle(object : ThreadUtils.SimpleTask<Boolean>() { override fun doInBackground(): Boolean { return ImageUtils.save(src, savePath, Bitmap.CompressFormat.JPEG) } override fun onSuccess(result: Boolean) { titleItem.setContent(ImageUtils.isImage(savePath).toString()) titleItem.update() SnackbarUtils.with(mContentView) .setDuration(SnackbarUtils.LENGTH_LONG) .apply { if (result) { setMessage("save successful.") .showSuccess(true) } else { setMessage("save failed.") .showError(true) } } } }) }) add(CommonItemClick("Save to Album") { ThreadUtils.executeBySingle(object : ThreadUtils.SimpleTask<File?>() { override fun doInBackground(): File? { return ImageUtils.save2Album(src, Bitmap.CompressFormat.JPEG) } override fun onSuccess(result: File?) { SnackbarUtils.with(mContentView) .setDuration(SnackbarUtils.LENGTH_LONG) .apply { if (result != null) { setMessage("save successful.") .showSuccess(true) } else { setMessage("save failed.") .showError(true) } } } }) }) add(CommonItemImage(R.string.image_src) { it.setImageBitmap(src) }) add(CommonItemImage(R.string.image_add_color) { it.setImageBitmap(ImageUtils.drawColor(src, Color.parseColor("#8000FF00"))) }) add(CommonItemImage(R.string.image_scale) { it.setImageBitmap(ImageUtils.scale(src, width / 2, height / 2)) }) add(CommonItemImage(R.string.image_clip) { it.setImageBitmap(ImageUtils.clip(src, 0, 0, width / 2, height / 2)) }) add(CommonItemImage(R.string.image_skew) { it.setImageBitmap(ImageUtils.skew(src, 0.2f, 0.1f)) }) add(CommonItemImage(R.string.image_rotate) { it.setImageBitmap(ImageUtils.rotate(src, 90, (width / 2).toFloat(), (height / 2).toFloat())) }) add(CommonItemImage(R.string.image_to_round) { it.setImageBitmap(ImageUtils.toRound(src)) }) add(CommonItemImage(R.string.image_to_round_border) { it.setImageBitmap(ImageUtils.toRound(src, 16, Color.GREEN)) }) add(CommonItemImage(R.string.image_to_round_corner) { it.setImageBitmap(ImageUtils.toRoundCorner(src, 80f)) }) add(CommonItemImage(R.string.image_to_round_corner_border) { it.setImageBitmap(ImageUtils.toRoundCorner(src, 80f, 16f, Color.GREEN)) }) add(CommonItemImage(R.string.image_to_round_corner_border) { it.setImageBitmap(ImageUtils.toRoundCorner(src, floatArrayOf(0f, 0f, 80f, 80f, 0f, 0f, 80f, 80f), 16f, Color.GREEN)) }) add(CommonItemImage(R.string.image_add_corner_border) { it.setImageBitmap(ImageUtils.addCornerBorder(src, 16f, Color.GREEN, 80f)) }) add(CommonItemImage(R.string.image_add_corner_border) { it.setImageBitmap(ImageUtils.addCornerBorder(src, 16f, Color.GREEN, floatArrayOf(0f, 0f, 80f, 80f, 0f, 0f, 80f, 80f))) }) add(CommonItemImage(R.string.image_add_circle_border) { it.setImageBitmap(ImageUtils.addCircleBorder(src, 16f, Color.GREEN)) }) add(CommonItemImage(R.string.image_add_reflection) { it.setImageBitmap(ImageUtils.addReflection(src, 80)) }) add(CommonItemImage(R.string.image_add_text_watermark) { it.setImageBitmap(ImageUtils.addTextWatermark(src, "blankj", 40, Color.GREEN, 0f, 0f)) }) add(CommonItemImage(R.string.image_add_image_watermark) { it.setImageBitmap(ImageUtils.addImageWatermark(src, watermark, 0, 0, 0x88)) }) add(CommonItemImage(R.string.image_to_gray) { it.setImageBitmap(ImageUtils.toGray(src)) }) add(CommonItemImage(R.string.image_fast_blur) { it.setImageBitmap(ImageUtils.fastBlur(src, 0.1f, 5f)) }) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { add(CommonItemImage(R.string.image_render_script_blur) { it.setImageBitmap(ImageUtils.renderScriptBlur(src, 10f)) }) } add(CommonItemImage(R.string.image_stack_blur) { it.setImageBitmap(ImageUtils.stackBlur(src, 10)) }) add(CommonItemImage(R.string.image_compress_by_scale) { it.setImageBitmap(ImageUtils.compressByScale(src, 0.5f, 0.5f)) }) add(CommonItemImage(R.string.image_compress_by_sample_size) { it.setImageBitmap(ImageUtils.compressBySampleSize(src, 2)) }) } } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) showLoading() ThreadUtils.executeByIo(bgTask) } override fun onDestroy() { super.onDestroy() ThreadUtils.cancel(bgTask) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/image/ImageActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,651
```kotlin package com.blankj.utilcode.pkg.feature.app import android.app.Activity import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.helper.PermissionHelper import com.blankj.common.item.* import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.pkg.Config import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about AppUtils * ``` */ class AppActivity : CommonActivity(), Utils.OnAppStatusChangedListener { var isRegisterAppStatusChangedListener: Boolean = false companion object { fun start(context: Context) { PermissionHelper.request(context, object : PermissionUtils.SimpleCallback { override fun onGranted() { val starter = Intent(context, AppActivity::class.java) context.startActivity(starter) } override fun onDenied() { } }, PermissionConstants.STORAGE) } } private val listener = object : OnReleasedListener { override fun onReleased() { return AppUtils.installApp(Config.TEST_APK_PATH) } } override fun bindTitleRes(): Int { return R.string.demo_app } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) LogUtils.e(requestCode, resultCode) } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemSwitch( "registerAppStatusChangedListener", { isRegisterAppStatusChangedListener }, { isRegisterAppStatusChangedListener = it if (it) { AppUtils.registerAppStatusChangedListener(this) } else { AppUtils.unregisterAppStatusChangedListener(this) } }), CommonItemTitle("isAppRoot", AppUtils.isAppRoot().toString()), CommonItemTitle("isAppDebug", AppUtils.isAppDebug().toString()), CommonItemTitle("isAppSystem", AppUtils.isAppSystem().toString()), CommonItemTitle( "isAppForeground", AppUtils.isAppForeground(AppUtils.getAppPackageName()).toString() ), CommonItemTitle( "isAppRunning", AppUtils.isAppRunning(AppUtils.getAppPackageName()).toString() ), CommonItemImage("getAppIcon") { it.setImageDrawable(AppUtils.getAppIcon()) }, CommonItemTitle("getAppPackageName", AppUtils.getAppPackageName()), CommonItemTitle("getAppName", AppUtils.getAppName()), CommonItemTitle("getAppPath", AppUtils.getAppPath()), CommonItemTitle("getAppVersionName", AppUtils.getAppVersionName()), CommonItemTitle("getAppVersionCode", AppUtils.getAppVersionCode().toString()), CommonItemTitle("getAppMinSdkVersion", AppUtils.getAppMinSdkVersion().toString()), CommonItemTitle("getAppTargetSdkVersion", AppUtils.getAppTargetSdkVersion().toString()), CommonItemTitle("getAppSignaturesSHA1", AppUtils.getAppSignaturesSHA1().toString()), CommonItemTitle("getAppSignaturesSHA256", AppUtils.getAppSignaturesSHA256().toString()), CommonItemTitle("getAppSignaturesMD5", AppUtils.getAppSignaturesMD5().toString()), CommonItemTitle("getAppUid", AppUtils.getAppUid().toString()), CommonItemTitle("getApkInfo", AppUtils.getApkInfo(AppUtils.getAppPath()).toString()), CommonItemClick(R.string.app_install) { if (AppUtils.isAppInstalled(Config.TEST_PKG)) { ToastUtils.showShort(R.string.app_install_tips) } else { if (!FileUtils.isFileExists(Config.TEST_APK_PATH)) { ReleaseInstallApkTask(listener).execute() } else { listener.onReleased() } } }, CommonItemClick(R.string.app_uninstall) { if (AppUtils.isAppInstalled(Config.TEST_PKG)) { AppUtils.uninstallApp(Config.TEST_PKG) } else { ToastUtils.showShort(R.string.app_uninstall_tips) } }, CommonItemClick(R.string.app_launch) { AppUtils.launchApp(this.packageName) }, CommonItemClick(R.string.app_relaunch) { AppUtils.relaunchApp() }, CommonItemClick(R.string.app_launch_details_settings, true) { AppUtils.launchAppDetailsSettings() }, CommonItemClick(R.string.app_exit) { AppUtils.exitApp() } ) } override fun onForeground(activity: Activity) { ToastUtils.showShort("onForeground\n${activity.javaClass.simpleName}") } override fun onBackground(activity: Activity) { ToastUtils.showShort("onBackground\n${activity.javaClass.simpleName}") } override fun onDestroy() { super.onDestroy() if (isRegisterAppStatusChangedListener) { AppUtils.unregisterAppStatusChangedListener(this) } } } class ReleaseInstallApkTask(private val mListener: OnReleasedListener) : ThreadUtils.SimpleTask<Unit>() { override fun doInBackground() { ResourceUtils.copyFileFromAssets("test_install", Config.TEST_APK_PATH) } override fun onSuccess(result: Unit) { mListener.onReleased() } fun execute() { ThreadUtils.executeByIo(this) } } interface OnReleasedListener { fun onReleased() } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/app/AppActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,144
```kotlin package com.blankj.utilcode.pkg.feature.sdcard import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ConvertUtils import com.blankj.utilcode.util.SDCardUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/27 * desc : demo about SDCardUtils * ``` */ class SDCardActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, SDCardActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_sdcard } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("isSDCardEnableByEnvironment", SDCardUtils.isSDCardEnableByEnvironment().toString()), CommonItemTitle("getSDCardPathByEnvironment", SDCardUtils.getSDCardPathByEnvironment()), CommonItemTitle("getSDCardInfo", SDCardUtils.getSDCardInfo().toString()), CommonItemTitle("getMountedSDCardPath", SDCardUtils.getMountedSDCardPath().toString()), CommonItemTitle("getExternalTotalSize", ConvertUtils.byte2FitMemorySize(SDCardUtils.getExternalTotalSize(), 2)), CommonItemTitle("getExternalAvailableSize", ConvertUtils.byte2FitMemorySize(SDCardUtils.getExternalAvailableSize(), 2)), CommonItemTitle("getInternalTotalSize", ConvertUtils.byte2FitMemorySize(SDCardUtils.getInternalTotalSize(), 2)), CommonItemTitle("getInternalAvailableSize", ConvertUtils.byte2FitMemorySize(SDCardUtils.getInternalAvailableSize(), 2)) ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/sdcard/SDCardActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
430
```kotlin package com.blankj.utilcode.pkg.feature.path import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.PathUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/13 * desc : demo about PathUtils * ``` */ class PathActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, PathActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_path } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("getRootPath", PathUtils.getRootPath()), CommonItemTitle("getDataPath", PathUtils.getDataPath()), CommonItemTitle("getDownloadCachePath", PathUtils.getDownloadCachePath()), CommonItemTitle("getInternalAppDataPath", PathUtils.getInternalAppDataPath()), CommonItemTitle("getInternalAppCodeCacheDir", PathUtils.getInternalAppCodeCacheDir()), CommonItemTitle("getInternalAppCachePath", PathUtils.getInternalAppCachePath()), CommonItemTitle("getInternalAppDbsPath", PathUtils.getInternalAppDbsPath()), CommonItemTitle("getInternalAppDbPath", PathUtils.getInternalAppDbPath("demo")), CommonItemTitle("getInternalAppFilesPath", PathUtils.getInternalAppFilesPath()), CommonItemTitle("getInternalAppSpPath", PathUtils.getInternalAppSpPath()), CommonItemTitle("getInternalAppNoBackupFilesPath", PathUtils.getInternalAppNoBackupFilesPath()), CommonItemTitle("getExternalStoragePath", PathUtils.getExternalStoragePath()), CommonItemTitle("getExternalMusicPath", PathUtils.getExternalMusicPath()), CommonItemTitle("getExternalPodcastsPath", PathUtils.getExternalPodcastsPath()), CommonItemTitle("getExternalRingtonesPath", PathUtils.getExternalRingtonesPath()), CommonItemTitle("getExternalAlarmsPath", PathUtils.getExternalAlarmsPath()), CommonItemTitle("getExternalNotificationsPath", PathUtils.getExternalNotificationsPath()), CommonItemTitle("getExternalPicturesPath", PathUtils.getExternalPicturesPath()), CommonItemTitle("getExternalMoviesPath", PathUtils.getExternalMoviesPath()), CommonItemTitle("getExternalDownloadsPath", PathUtils.getExternalDownloadsPath()), CommonItemTitle("getExternalDcimPath", PathUtils.getExternalDcimPath()), CommonItemTitle("getExternalDocumentsPath", PathUtils.getExternalDocumentsPath()), CommonItemTitle("getExternalAppDataPath", PathUtils.getExternalAppDataPath()), CommonItemTitle("getExternalAppCachePath", PathUtils.getExternalAppCachePath()), CommonItemTitle("getExternalAppFilesPath", PathUtils.getExternalAppFilesPath()), CommonItemTitle("getExternalAppMusicPath", PathUtils.getExternalAppMusicPath()), CommonItemTitle("getExternalAppPodcastsPath", PathUtils.getExternalAppPodcastsPath()), CommonItemTitle("getExternalAppRingtonesPath", PathUtils.getExternalAppRingtonesPath()), CommonItemTitle("getExternalAppAlarmsPath", PathUtils.getExternalAppAlarmsPath()), CommonItemTitle("getExternalAppNotificationsPath", PathUtils.getExternalAppNotificationsPath()), CommonItemTitle("getExternalAppPicturesPath", PathUtils.getExternalAppPicturesPath()), CommonItemTitle("getExternalAppMoviesPath", PathUtils.getExternalAppMoviesPath()), CommonItemTitle("getExternalAppDownloadPath", PathUtils.getExternalAppDownloadPath()), CommonItemTitle("getExternalAppDcimPath", PathUtils.getExternalAppDcimPath()), CommonItemTitle("getExternalAppDocumentsPath", PathUtils.getExternalAppDocumentsPath()), CommonItemTitle("getExternalAppObbPath", PathUtils.getExternalAppObbPath()) ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/path/PathActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
865
```kotlin package com.blankj.utilcode.pkg.feature.toast import android.widget.TextView import androidx.annotation.StringRes import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.StringUtils import com.blankj.utilcode.util.ToastUtils import com.blankj.utilcode.util.ViewUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2017/08/31 * desc : demo about ToastUtils * ``` */ object CustomToast { fun showShort(text: CharSequence) { show(text, false) } fun showShort(@StringRes resId: Int) { show(StringUtils.getString(resId), false) } fun showShort(@StringRes resId: Int, vararg args: Any) { show(StringUtils.getString(resId, args), false) } fun showShort(format: String, vararg args: Any) { show(StringUtils.format(format, args), false) } fun showLong(text: CharSequence) { show(text, true) } fun showLong(@StringRes resId: Int) { show(StringUtils.getString(resId), true) } fun showLong(@StringRes resId: Int, vararg args: Any) { show(StringUtils.getString(resId, args), true) } fun showLong(format: String, vararg args: Any) { show(StringUtils.format(format, args), true) } private fun show(text: CharSequence, isLong: Boolean) { val textView = ViewUtils.layoutId2View(R.layout.toast_custom) as TextView textView.text = text ToastUtils.make().setDurationIsLong(isLong).show(textView) } fun cancel() { ToastUtils.cancel() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/toast/CustomToast.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
374
```kotlin package com.blankj.utilcode.pkg.feature.toast import android.content.Context import android.content.Intent import android.graphics.Color import android.view.Gravity import androidx.core.content.ContextCompat import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.R import com.blankj.utilcode.pkg.helper.DialogHelper import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ColorUtils import com.blankj.utilcode.util.SpanUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/09/29 * desc : demo about ToastUtils * ``` */ class ToastActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ToastActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_toast } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick(R.string.toast_show_short) { Thread(Runnable { ToastUtils.showShort(R.string.toast_short) }).start() }, CommonItemClick(R.string.toast_show_long) { Thread(Runnable { ToastUtils.showLong(R.string.toast_long) }).start() }, CommonItemClick(R.string.toast_show_null) { ToastUtils.showLong(null) }, CommonItemClick(R.string.toast_show_empty) { ToastUtils.showLong("") }, CommonItemClick(R.string.toast_show_span) { ToastUtils.showLong( SpanUtils() .appendImage(R.mipmap.ic_launcher, SpanUtils.ALIGN_CENTER) .appendSpace(32) .append(getString(R.string.toast_span)).setFontSize(24, true) .create() ) }, CommonItemClick(R.string.toast_show_long_string) { ToastUtils.showLong(R.string.toast_long_string) }, CommonItemClick(R.string.toast_show_green_font) { ToastUtils.make().setTextColor(Color.GREEN).setDurationIsLong(true).show(R.string.toast_green_font) }, CommonItemClick(R.string.toast_show_bg_color) { ToastUtils.make().setBgColor(ColorUtils.getColor(R.color.colorAccent)).show(R.string.toast_bg_color) }, CommonItemClick(R.string.toast_show_bg_resource) { ToastUtils.make().setBgResource(R.drawable.toast_round_rect).show(R.string.toast_custom_bg) }, CommonItemClick(R.string.toast_show_left_icon) { ToastUtils.make().setLeftIcon(R.mipmap.ic_launcher).show(R.string.toast_show_left_icon) }, CommonItemClick(R.string.toast_show_dark_mode) { ToastUtils.make().setTopIcon(R.mipmap.ic_launcher).setMode(ToastUtils.MODE.DARK).show(R.string.toast_show_dark_mode) }, CommonItemClick(R.string.toast_show_middle) { ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(R.string.toast_middle) }, CommonItemClick(R.string.toast_show_top) { ToastUtils.make().setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 0).show(R.string.toast_top) }, CommonItemClick(R.string.toast_show_custom_view) { Thread(Runnable { CustomToast.showLong(R.string.toast_custom_view) }).start() }, CommonItemClick(R.string.toast_cancel) { ToastUtils.cancel() }, CommonItemClick(R.string.toast_show_toast_dialog) { DialogHelper.showToastDialog() }, CommonItemClick(R.string.toast_show_toast_when_start_activity) { ToastUtils.showLong(R.string.toast_show_toast_when_start_activity) start(this) } ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/toast/ToastActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
792
```java package com.blankj.utilcode.pkg.feature.mvp; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.blankj.common.activity.CommonActivity; import com.blankj.utilcode.pkg.R; import androidx.annotation.Nullable; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/09 * desc : * </pre> */ public class MvpActivity extends CommonActivity { public static void start(Context context) { Intent starter = new Intent(context, MvpActivity.class); context.startActivity(starter); } @Override public int bindTitleRes() { return R.string.demo_mvp; } @Override public int bindLayout() { return R.layout.mvp_activity; } @Override public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) { super.initView(savedInstanceState, contentView); new MvpView(this).addPresenter(new MvpPresenter()); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpActivity.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
223
```kotlin package com.blankj.utilcode.pkg.feature.notification import android.app.PendingIntent import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.NotificationUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2019/10/22 * desc : demo about NotificationUtils * ``` */ class NotificationActivity : CommonActivity() { private var id: Int = 0 private var cancelId: Int = 0 companion object { fun start(context: Context) { val starter = Intent(context, NotificationActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_notification } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemTitle("areNotificationsEnabled", NotificationUtils.areNotificationsEnabled().toString()), CommonItemClick(R.string.notification_notify) { NotificationUtils.notify(id++) { param -> intent.putExtra("id", id); param.setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("title") .setContentText("content text: $id") .setContentIntent(PendingIntent.getActivity(mActivity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true) null } }, CommonItemClick(R.string.notification_cancel) { if (cancelId < id) { NotificationUtils.cancel(cancelId++) } else { ToastUtils.showShort("No notification.") } }, CommonItemClick(R.string.notification_cancel_all) { NotificationUtils.cancelAll() cancelId = id; }, CommonItemClick(R.string.notification_show) { NotificationUtils.setNotificationBarVisibility(true) } ) } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/notification/NotificationActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
442
```java package com.blankj.utilcode.pkg.feature.mvp; import com.blankj.utilcode.util.Utils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/26 * desc : * </pre> */ public interface MvpMvp { interface View { void setLoadingVisible(boolean visible); void showMsg(CharSequence msg); } interface Presenter { void updateMsg(); } interface Model { void requestUpdateMsg(final Utils.Consumer<String> consumer); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpMvp.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
121
```java package com.blankj.utilcode.pkg.feature.mvp; import com.blankj.base.mvp.BaseModel; import com.blankj.utilcode.util.ThreadUtils; import com.blankj.utilcode.util.Utils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/26 * desc : * </pre> */ public class MvpModel extends BaseModel implements MvpMvp.Model { private int index; @Override public void onCreate() { index = 0; } @Override public void requestUpdateMsg(final Utils.Consumer<String> consumer) { ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<String>() { @Override public String doInBackground() throws Throwable { Thread.sleep(2000); return "msg: " + index++; } @Override public void onSuccess(String result) { consumer.accept(result); } }); } @Override public void onDestroy() { super.onDestroy(); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpModel.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
222
```java package com.blankj.utilcode.pkg.feature.mvp; import android.text.Layout; import android.view.View; import android.widget.TextView; import com.blankj.base.mvp.BaseView; import com.blankj.utilcode.pkg.R; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.SizeUtils; import com.blankj.utilcode.util.ThreadUtils; import com.blankj.utilcode.util.ToastUtils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/26 * desc : * </pre> */ public class MvpView extends BaseView<MvpView> implements MvpMvp.View { private TextView mvpTv; private TextView mvpMeasureWidthTv; private int i = 0; public MvpView(MvpActivity activity) { super(activity); mvpTv = activity.findViewById(R.id.mvpUpdateTv); ClickUtils.applyPressedBgDark(mvpTv); mvpTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getPresenter(MvpPresenter.class).updateMsg(); } }); mvpMeasureWidthTv = activity.findViewById(R.id.mvpMeasureWidthTv); measure(); } private void measure() { ThreadUtils.runOnUiThreadDelayed(new Runnable() { @Override public void run() { float textWidth = Layout.getDesiredWidth(mvpMeasureWidthTv.getText(), mvpMeasureWidthTv.getPaint()) + SizeUtils.dp2px(16); float textWidth2 = mvpMeasureWidthTv.getPaint().measureText(mvpMeasureWidthTv.getText().toString()) + SizeUtils.dp2px(16); LogUtils.i(mvpMeasureWidthTv.getWidth(), textWidth, textWidth2); mvpMeasureWidthTv.setText(mvpMeasureWidthTv.getText().toString() + i); measure(); } }, 1000); } @Override public void setLoadingVisible(boolean visible) { final MvpActivity activity = getActivity(); if (visible) { activity.showLoading(new Runnable() { @Override public void run() { activity.finish(); } }); } else { activity.dismissLoading(); } } @Override public void showMsg(CharSequence msg) { ToastUtils.showLong(msg); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
514
```java package com.blankj.utilcode.pkg.feature.mvp; import com.blankj.base.mvp.BasePresenter; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.Utils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/26 * desc : * </pre> */ public class MvpPresenter extends BasePresenter<MvpView> implements MvpMvp.Presenter { @Override public void onBindView() { } @Override public void updateMsg() { getView().setLoadingVisible(true); getModel(MvpModel.class).requestUpdateMsg(new Utils.Consumer<String>() { @Override public void accept(String s) { if (isAlive()) { getView().showMsg(s); getView().setLoadingVisible(false); } else { LogUtils.iTag(MvpView.TAG, "destroyed"); } } }); } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpPresenter.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
213
```kotlin package com.blankj.utilcode.pkg.feature.intent import android.content.Context import android.content.Intent import android.graphics.Bitmap import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.utilcode.pkg.Config import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.* import java.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2020/05/29 * desc : demo about IntentUtils * ``` */ class IntentActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, IntentActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_intent } override fun bindItems(): MutableList<CommonItem<*>> { return CollectionUtils.newArrayList( CommonItemClick("LaunchApp") { startActivity(IntentUtils.getLaunchAppIntent(packageName)) }, CommonItemClick("LaunchAppDetailsSettings") { startActivityForResult(IntentUtils.getLaunchAppDetailsSettingsIntent(packageName), 1) }, CommonItemClick("ShareText") { startActivity(IntentUtils.getShareTextIntent("share content")) }, CommonItemClick("ShareImage") { startActivity(IntentUtils.getShareImageIntent(getShareImagePath()[0])); }, CommonItemClick("ShareTextImage") { startActivity(IntentUtils.getShareTextImageIntent("share content", getShareImagePath()[0])); }, CommonItemClick("ShareImages") { startActivity(IntentUtils.getShareImageIntent(getShareImagePath())); }, CommonItemClick("ShareTextImages") { startActivity(IntentUtils.getShareTextImageIntent("share content", getShareImagePath())); } ) } private fun getShareImagePath(): LinkedList<String> { val shareImagePath0 = Config.CACHE_PATH + "share.jpg" if (!FileUtils.isFile(shareImagePath0)) { ImageUtils.save(ImageUtils.getBitmap(R.drawable.image_lena), shareImagePath0, Bitmap.CompressFormat.JPEG) } val shareImagePath1 = Config.CACHE_PATH + "cheetah.jpg" if (!FileUtils.isFile(shareImagePath1)) { ImageUtils.save(ImageUtils.getBitmap(R.drawable.span_cheetah), shareImagePath1, Bitmap.CompressFormat.JPEG) } return CollectionUtils.newLinkedList(shareImagePath0, shareImagePath1) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) LogUtils.d("onActivityResult() called with: requestCode = $requestCode, resultCode = $resultCode, data = $data") } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/intent/IntentActivity.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
577
```kotlin package com.blankj.utilcode.pkg.helper import android.content.Context import android.content.DialogInterface import android.graphics.Bitmap import android.graphics.drawable.ColorDrawable import android.text.method.ScrollingMovementMethod import android.view.Gravity import android.view.View import android.view.Window import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.FragmentActivity import com.blankj.base.dialog.BaseDialogFragment import com.blankj.base.dialog.DialogLayoutCallback import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.ActivityUtils import com.blankj.utilcode.util.KeyboardUtils import com.blankj.utilcode.util.ScreenUtils import com.blankj.utilcode.util.ToastUtils /** * ``` * author: Blankj * blog : path_to_url * time : 2018/01/10 * desc : helper about dialog * ``` */ object DialogHelper { fun showKeyboardDialog(context: Context) { BaseDialogFragment().init(context, object : DialogLayoutCallback { override fun bindTheme(): Int { return View.NO_ID } override fun bindLayout(): Int { return R.layout.keyboard_dialog } override fun initView(dialog: BaseDialogFragment, contentView: View) { dialog.dialog.setCanceledOnTouchOutside(false) val keyboardDialogEt = contentView.findViewById<EditText>(R.id.keyboardDialogEt) val listener = View.OnClickListener { v -> when (v.id) { R.id.keyboardDialogHideSoftInputBtn -> KeyboardUtils.hideSoftInput(keyboardDialogEt) R.id.keyboardDialogShowSoftInputBtn -> KeyboardUtils.showSoftInput(keyboardDialogEt) R.id.keyboardDialogToggleSoftInputBtn -> KeyboardUtils.toggleSoftInput() R.id.keyboardDialogCloseBtn -> { KeyboardUtils.hideSoftInput(keyboardDialogEt) dialog.dismiss() } } } contentView.findViewById<View>(R.id.keyboardDialogHideSoftInputBtn).setOnClickListener(listener) contentView.findViewById<View>(R.id.keyboardDialogShowSoftInputBtn).setOnClickListener(listener) contentView.findViewById<View>(R.id.keyboardDialogToggleSoftInputBtn).setOnClickListener(listener) contentView.findViewById<View>(R.id.keyboardDialogCloseBtn).setOnClickListener(listener) dialog.dialog.setOnShowListener(DialogInterface.OnShowListener { KeyboardUtils.fixAndroidBug5497(dialog.dialog.window!!) KeyboardUtils.showSoftInput() }) } override fun setWindowStyle(window: Window) { window.setBackgroundDrawable(ColorDrawable(0)) val attributes = window.attributes attributes.gravity = Gravity.BOTTOM attributes.width = ScreenUtils.getAppScreenWidth() attributes.height = ScreenUtils.getAppScreenHeight() * 2 / 5 attributes.windowAnimations = R.style.BottomDialogAnimation window.attributes = attributes } override fun onCancel(dialog: BaseDialogFragment) {} override fun onDismiss(dialog: BaseDialogFragment) {} }).show() } fun showFragmentDialog(info: CharSequence) { val topActivity = ActivityUtils.getTopActivity() ?: return BaseDialogFragment().init(topActivity as FragmentActivity, object : DialogLayoutCallback { override fun bindTheme(): Int { return R.style.CommonContentDialogStyle } override fun bindLayout(): Int { return R.layout.fragment_dialog } override fun initView(dialog: BaseDialogFragment, contentView: View) { val aboutTv = contentView.findViewById<TextView>(R.id.fragmentDialogAboutTv) aboutTv.movementMethod = ScrollingMovementMethod.getInstance() aboutTv.text = info } override fun setWindowStyle(window: Window) {} override fun onCancel(dialog: BaseDialogFragment) {} override fun onDismiss(dialog: BaseDialogFragment) {} }).show() } fun showScreenshotDialog(screenshot: Bitmap) { val topActivity = ActivityUtils.getTopActivity() ?: return BaseDialogFragment().init(topActivity as FragmentActivity, object : DialogLayoutCallback { override fun bindTheme(): Int { return R.style.CommonContentDialogStyle } override fun bindLayout(): Int { return R.layout.screen_dialog } override fun initView(dialog: BaseDialogFragment, contentView: View) { contentView.findViewById<ImageView>(R.id.screenDialogScreenshotIv) .setImageBitmap(screenshot) } override fun setWindowStyle(window: Window) {} override fun onCancel(dialog: BaseDialogFragment) {} override fun onDismiss(dialog: BaseDialogFragment) {} }).show() } fun showToastDialog() { val topActivity = ActivityUtils.getTopActivity() ?: return BaseDialogFragment().init(topActivity as FragmentActivity, object : DialogLayoutCallback { override fun bindTheme(): Int { return R.style.CommonContentDialogStyle } override fun bindLayout(): Int { return R.layout.toast_dialog } override fun initView(dialog: BaseDialogFragment, contentView: View) { contentView.findViewById<Button>(R.id.toastDialogShowShortToastBtn) .setOnClickListener { ToastUtils.showShort("Short") } } override fun setWindowStyle(window: Window) {} override fun onCancel(dialog: BaseDialogFragment) {} override fun onDismiss(dialog: BaseDialogFragment) {} }).show() } } ```
/content/code_sandbox/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/helper/DialogHelper.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,091
```kotlin package com.blankj.utilcode.app import com.blankj.common.CommonApplication import com.blankj.utilcode.util.Utils /** * ``` * author: Blankj * blog : path_to_url * time : 2016/10/12 * desc : app about utils * ``` */ class UtilCodeApp : CommonApplication() { companion object { lateinit var instance: UtilCodeApp private set } override fun onCreate() { Utils.init(this) super.onCreate() instance = this // BusUtils.register("com.blankj.androidutilcode") } } ```
/content/code_sandbox/feature/utilcode/app/src/main/java/com/blankj/utilcode/app/UtilCodeApp.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
130
```java package com.blankj.launcher.app; import com.blankj.common.CommonApplication; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/10/12 * desc : * </pre> */ public class LauncherApp extends CommonApplication { private static LauncherApp sInstance; public static LauncherApp getInstance() { return sInstance; } @Override public void onCreate() { super.onCreate(); sInstance = this; } } ```
/content/code_sandbox/feature/launcher/app/src/main/java/com/blankj/launcher/app/LauncherApp.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
115
```groovy package com.blankj.plugin.readme class ReadmeExtension { File readmeFile File readmeCnFile } ```
/content/code_sandbox/buildSrc/src/main/java/com/blankj/plugin/readme/ReadmeExtension.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
27
```groovy package com.blankj.plugin.readme import org.gradle.api.Plugin import org.gradle.api.Project class ReadmeSubPlugin implements Plugin<Project> { @Override void apply(Project project) { project.extensions.create('readme', ReadmeExtension) project.task('readmeTask') { doLast { println "readmeTask start..." def ext = project['readme'] as ReadmeExtension def readmeCN = ext.readmeCnFile def readmeEng = ext.readmeFile readmeOfSubUtil2Eng(readmeCN, readmeEng) println "readmeTask finished." } } } static def readmeOfSubUtil2Eng(File readmeCN, File readmeEng) { FormatUtils.format(readmeCN) def lines = readmeCN.readLines("UTF-8"), sb = new StringBuilder("## How to use" + FormatUtils.LINE_SEP + FormatUtils.LINE_SEP + "You should copy the following classes which you want to use in your project." + FormatUtils.LINE_SEP), i = 3, size = lines.size() for (; i < size; ++i) { String line = lines.get(i) if (line.contains("* ###")) { String utilsName = line.substring(line.indexOf("[") + 1, line.indexOf("Utils")) sb.append("* ### About ").append(utilsName).append(line.substring(line.indexOf(" -> "))) } else if (line.contains(": ") && !line.contains("[")) { sb.append(line.substring(0, line.indexOf(':')).trim()) } else { sb.append(line) } sb.append(FormatUtils.LINE_SEP) } readmeEng.write(sb.toString(), "UTF-8") } } ```
/content/code_sandbox/buildSrc/src/main/java/com/blankj/plugin/readme/ReadmeSubPlugin.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
373
```groovy package com.blankj.plugin.readme import org.gradle.api.Plugin import org.gradle.api.Project class ReadmeCorePlugin implements Plugin<Project> { @Override void apply(Project project) { project.extensions.create('readme', ReadmeExtension) project.task('readmeTask') { doLast { println "readmeTask start..." def ext = project['readme'] as ReadmeExtension def readmeCN = ext.readmeCnFile def readmeEng = ext.readmeFile readmeOfUtilCode2Eng(readmeCN, readmeEng) println "readmeTask finished." } } } static def readmeOfUtilCode2Eng(File readmeCN, File readmeEng) { FormatUtils.format(readmeCN) def lines = readmeCN.readLines("UTF-8") def sb = new StringBuilder() readmeCN.eachLine { line -> if (line.contains("* ###")) { if (line.contains("UtilsTransActivity")) { sb.append(line) } else { String utilsName = line.substring(line.indexOf("[") + 1, line.indexOf("Utils")) sb.append("* ### About ").append(utilsName).append(line.substring(line.indexOf(" -> "))) } } else if (line.contains(": ") && !line.contains("[")) { sb.append(line.substring(0, line.indexOf(':')).trim()) } else if (line.contains("") || line.contains("")) { return } else { sb.append(line) } sb.append(FormatUtils.LINE_SEP) } readmeEng.write(sb.toString(), "UTF-8") } } ```
/content/code_sandbox/buildSrc/src/main/java/com/blankj/plugin/readme/ReadmeCorePlugin.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
348
```groovy class ModuleConfig { boolean isApply // boolean useLocal // String localPath // String remotePath // def dep // String getGroupId() { String[] splits = remotePath.split(":") return splits.length == 3 ? splits[0] : null } String getArtifactId() { String[] splits = remotePath.split(":") return splits.length == 3 ? splits[1] : null } String getVersion() { String[] splits = remotePath.split(":") return splits.length == 3 ? splits[2] : null } @Override String toString() { return "ModuleConfig { isApply = ${getFlag(isApply)}" + ", dep = " + dep + " }" } static String getFlag(boolean b) { return b ? "" : "" } } ```
/content/code_sandbox/buildSrc/src/main/groovy/ModuleConfig.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
196
```groovy package com.blankj.plugin.readme class FormatUtils { static def LINE_SEP = System.getProperty("line.separator") static def LONG_SPACE = " " static def format(File readmeCN) { def sb = new StringBuilder(), lines = readmeCN.readLines("UTF-8"), i = 0, size = lines.size() for (; i < size; ++i) { String line = lines.get(i) if (line.contains("* ###")) { sb.append(line).append(LINE_SEP) .append("```").append(LINE_SEP) def maxLen = 0 line = lines.get(i += 2) // get the max length of space for (def j = i; !line.equals("```"); line = lines.get(++j)) { maxLen = Math.max(maxLen, line.replace(" ", "").replace(",", ", ").indexOf(':')) } line = lines.get(i) for (; !line.equals("```"); line = lines.get(++i)) { def noSpaceLine = line.replace(" ", "") def spaceLen = maxLen - line.replace(" ", "").replace(",", ", ").indexOf(':') sb.append(noSpaceLine.substring(0, noSpaceLine.indexOf(':')).replace(",", ", ")) .append(LONG_SPACE.substring(0, spaceLen))// add the space .append(': ') .append(line.substring(line.indexOf(':') + 1).trim()) .append(LINE_SEP) } sb.append("```") } else { sb.append(line) } sb.append(LINE_SEP) } readmeCN.write(sb.toString(), "UTF-8") } } ```
/content/code_sandbox/buildSrc/src/main/java/com/blankj/plugin/readme/FormatUtils.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
358
```groovy class LibConfig { String path String getGroupId() { String[] splits = path.split(":") return splits.length == 3 ? splits[0] : null } String getArtifactId() { String[] splits = path.split(":") return splits.length == 3 ? splits[1] : null } String getVersion() { String[] splits = path.split(":") return splits.length == 3 ? splits[2] : null } @Override String toString() { return "LibConfig { path = $path }" } static String getFlag(boolean b) { return b ? "" : "" } } ```
/content/code_sandbox/buildSrc/src/main/groovy/LibConfig.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
147
```groovy import org.gradle.BuildListener import org.gradle.BuildResult import org.gradle.api.Task import org.gradle.api.execution.TaskExecutionListener import org.gradle.api.initialization.Settings import org.gradle.api.invocation.Gradle import org.gradle.api.tasks.TaskState import java.text.SimpleDateFormat /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/22 * desc : * </pre> */ class TaskDurationUtils { static List<TaskInfo> taskInfoList = [] static long startMillis static init(Gradle grd) { startMillis = System.currentTimeMillis() grd.addListener(new TaskExecutionListener() { @Override void beforeExecute(Task task) { task.ext.startTime = System.currentTimeMillis() } @Override void afterExecute(Task task, TaskState state) { def exeDuration = System.currentTimeMillis() - task.ext.startTime if (exeDuration >= 500) { taskInfoList.add(new TaskInfo(task: task, exeDuration: exeDuration)) } } }) grd.addBuildListener(new BuildListener() { @Override void beforeSettings(Settings settings) { super.beforeSettings(settings) } @Override void buildStarted(Gradle gradle) {} @Override void settingsEvaluated(Settings settings) {} @Override void projectsLoaded(Gradle gradle) {} @Override void projectsEvaluated(Gradle gradle) {} @Override void buildFinished(BuildResult buildResult) { if (!taskInfoList.isEmpty()) { Collections.sort(taskInfoList, new Comparator<TaskInfo>() { @Override int compare(TaskInfo t, TaskInfo t1) { return t1.exeDuration - t.exeDuration } }) StringBuilder sb = new StringBuilder() int buildSec = (System.currentTimeMillis() - startMillis) / 1000; int m = buildSec / 60; int s = buildSec % 60; def timeInfo = (m == 0 ? "${s}s" : "${m}m ${s}s (${buildSec}s)") sb.append("BUILD FINISHED in $timeInfo\n") taskInfoList.each { sb.append(String.format("%7sms %s\n", it.exeDuration, it.task.path)) } def content = sb.toString() GLog.d(content) File file = new File(grd.rootProject.buildDir.getAbsolutePath(), "build_time_records_" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".txt") file.getParentFile().mkdirs() file.write(content) } } }) } private static class TaskInfo { Task task long exeDuration } } ```
/content/code_sandbox/buildSrc/src/main/groovy/TaskDurationUtils.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
600
```groovy class Config { static applicationId = 'com.blankj.androidutilcode' static appName = 'Util' static compileSdkVersion = 29 static minSdkVersion = 14 static targetSdkVersion = 29 static versionCode = 1_031_001 static versionName = '1.31.1'// E.g. 1.9.72 => 1,009,072 // lib version static gradlePluginVersion = '4.1.0' static kotlinVersion = '1.3.72' static androidxVersion = '1.0.0' static modules = [ /*Don't delete this line*/ /*Generated by "module_config.json"*/ plugin_api_gradle_plugin : new ModuleConfig(isApply: true , useLocal: true , localPath: "./plugin/api-gradle-plugin"), plugin_bus_gradle_plugin : new ModuleConfig(isApply: true , useLocal: true , localPath: "./plugin/bus-gradle-plugin"), plugin_lib_base_transform : new ModuleConfig(isApply: true , useLocal: true , localPath: "./plugin/lib/base-transform", remotePath: "com.blankj:base-transform:1.0"), plugin_buildSrc_plugin : new ModuleConfig(isApply: true , useLocal: true , localPath: "./plugin/buildSrc-plugin"), feature_mock : new ModuleConfig(isApply: false, useLocal: true , localPath: "./feature/mock"), feature_launcher_app : new ModuleConfig(isApply: true , useLocal: true , localPath: "./feature/launcher/app"), feature_main_app : new ModuleConfig(isApply: false, useLocal: true , localPath: "./feature/main/app"), feature_main_pkg : new ModuleConfig(isApply: true , useLocal: true , localPath: "./feature/main/pkg"), feature_subutil_app : new ModuleConfig(isApply: false, useLocal: true , localPath: "./feature/subutil/app"), feature_subutil_pkg : new ModuleConfig(isApply: true , useLocal: true , localPath: "./feature/subutil/pkg"), feature_subutil_export : new ModuleConfig(isApply: true , useLocal: true , localPath: "./feature/subutil/export"), feature_utilcode_app : new ModuleConfig(isApply: false, useLocal: true , localPath: "./feature/utilcode/app"), feature_utilcode_pkg : new ModuleConfig(isApply: true , useLocal: true , localPath: "./feature/utilcode/pkg"), feature_utilcode_export : new ModuleConfig(isApply: true , useLocal: true , localPath: "./feature/utilcode/export", remotePath: "com.blankj:utilcode-export:1.1"), lib_base : new ModuleConfig(isApply: true , useLocal: true , localPath: "./lib/base"), lib_common : new ModuleConfig(isApply: true , useLocal: true , localPath: "./lib/common"), lib_subutil : new ModuleConfig(isApply: true , useLocal: true , localPath: "./lib/subutil"), lib_utilcode : new ModuleConfig(isApply: true , useLocal: true , localPath: "./lib/utilcode", remotePath: "com.blankj:utilcodex:$Config.versionName"), lib_utildebug : new ModuleConfig(isApply: true , useLocal: true , localPath: "./lib/utildebug"), lib_utildebug_no_op : new ModuleConfig(isApply: true , useLocal: true , localPath: "./lib/utildebug-no-op"), /*Don't delete this line*/ ] static plugins = [ plugin_gradle : new PluginConfig(path: "com.android.tools.build:gradle:$gradlePluginVersion"), plugin_kotlin : new PluginConfig(path: "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"), // maven plugin_maven : new PluginConfig(path: "com.github.dcendents:android-maven-gradle-plugin:2.1", id: "com.github.dcendents.android-maven"), // path isApply = false // mavenLocal isApply = true bintrayUpload plugin_api : new PluginConfig(isApply: true, useLocal: false, path: "com.blankj:api-gradle-plugin:1.5", id: "com.blankj.api"), //./gradlew clean :plugin_api-gradle-plugin:mavenLocal // mavenLocal //./gradlew clean :plugin_api-gradle-plugin:bintrayUpload // jcenter plugin_bus : new PluginConfig(isApply: true, useLocal: false, path: "com.blankj:bus-gradle-plugin:2.6", id: "com.blankj.bus"), //./gradlew clean :plugin_bus-gradle-plugin:mavenLocal // mavenLocal //./gradlew clean :plugin_bus-gradle-plugin:bintrayUpload // jcenter plugin_buildSrc: new PluginConfig(isApply: false, useLocal: false, path: "com.blankj:buildSrc-plugin:1.0", id: "com.blankj.buildSrc"), //./gradlew clean :plugin_bus-gradle-plugin:mavenLocal // mavenLocal //./gradlew clean :plugin_bus-gradle-plugin:bintrayUpload // jcenter ] static libs = [ androidx_appcompat : new LibConfig(path: "androidx.appcompat:appcompat:$androidxVersion"), androidx_material : new LibConfig(path: "com.google.android.material:material:$androidxVersion"), androidx_multidex : new LibConfig(path: "androidx.multidex:multidex:2.0.0"), androidx_constraint: new LibConfig(path: "androidx.constraintlayout:constraintlayout:1.1.3"), kotlin : new LibConfig(path: "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"), leakcanary : new LibConfig(path: "com.squareup.leakcanary:leakcanary-android:2.1"), free_proguard : new LibConfig(path: "com.blankj:free-proguard:1.0.2"), swipe_panel : new LibConfig(path: "com.blankj:swipe-panel:1.2"), gson : new LibConfig(path: "com.google.code.gson:gson:2.8.5"), glide : new LibConfig(path: "com.github.bumptech.glide:glide:4.7.1"), retrofit : new LibConfig(path: "com.squareup.retrofit2:retrofit:2.4.0"), commons_io : new LibConfig(path: "commons-io:commons-io:2.6"), eventbus_lib : new LibConfig(path: "org.greenrobot:eventbus:3.1.1"), eventbus_processor : new LibConfig(path: "org.greenrobot:eventbus-annotation-processor:3.0.1"), photo_view : new LibConfig(path: "com.github.chrisbanes:PhotoView:2.0.0"), test_junit : new LibConfig(path: "junit:junit:4.12"), test_robolectric : new LibConfig(path: "org.robolectric:robolectric:4.3.1"), ] } //./gradlew clean :lib_utilcode:bintrayUpload ```
/content/code_sandbox/buildSrc/src/main/groovy/Config.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,627
```groovy import org.gradle.api.Project import org.gradle.api.ProjectEvaluationListener import org.gradle.api.ProjectState import org.gradle.api.invocation.Gradle /** * <pre> * author: blankj * blog : path_to_url * time : 2019/07/13 * desc : * </pre> */ class ConfigUtils { static init(Gradle gradle) { generateDep(gradle) addCommonGradle(gradle) TaskDurationUtils.init(gradle) } /** * depConfig dep */ private static void generateDep(Gradle gradle) { def configs = [:] for (Map.Entry<String, ModuleConfig> entry : Config.modules.entrySet()) { def (name, config) = [entry.key, entry.value] if (config.useLocal) { config.dep = gradle.rootProject.findProject(name) } else { config.dep = config.remotePath } configs.put(name, config) } GLog.l("generateDep = ${GLog.object2String(configs)}") } private static addCommonGradle(Gradle gradle) { gradle.addProjectEvaluationListener(new ProjectEvaluationListener() { @Override void beforeEvaluate(Project project) { // project build.gradle do sth. if (project.name.contains("plugin")) { return } if (project.name.endsWith("_app")) { GLog.l(project.toString() + " applies buildApp.gradle") project.apply { from "${project.rootDir.path}/buildApp.gradle" } } else { GLog.l(project.toString() + " applies buildLib.gradle") project.apply { from "${project.rootDir.path}/buildLib.gradle" } } } @Override void afterEvaluate(Project project, ProjectState state) { // project build.gradle do sth. } }) } static getApplyPlugins() { def plugins = [:] for (Map.Entry<String, PluginConfig> entry : Config.plugins.entrySet()) { if (entry.value.isApply) { plugins.put(entry.key, entry.value) } } GLog.d("getApplyPlugins = ${GLog.object2String(plugins)}") return plugins } static getApplyPkgs() { def pkgs = [:] for (Map.Entry<String, ModuleConfig> entry : Config.modules.entrySet()) { if (entry.value.isApply && entry.key.endsWith("_pkg")) { pkgs.put(entry.key, entry.value) } } GLog.d("getApplyPkgs = ${GLog.object2String(pkgs)}") return pkgs } static getApplyExports() { def exports = [:] for (Map.Entry<String, ModuleConfig> entry : Config.modules.entrySet()) { if (entry.value.isApply && entry.key.endsWith("_export")) { exports.put(entry.key, entry.value) } } GLog.d("getApplyExports = ${GLog.object2String(exports)}") return exports } } ```
/content/code_sandbox/buildSrc/src/main/groovy/ConfigUtils.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
670
```groovy final class PluginConfig { boolean isApply = true // boolean useLocal // String path // String id // ID String getGroupId() { String[] splits = path.split(":") return splits.length == 3 ? splits[0] : null } String getArtifactId() { String[] splits = path.split(":") return splits.length == 3 ? splits[1] : null } String getVersion() { String[] splits = path.split(":") return splits.length == 3 ? splits[2] : null } @Override String toString() { return "PluginConfig { isApply = ${getFlag(isApply)}" + ", useLocal = ${getFlag(useLocal)}" + ", path = " + path + ", id = " + id + " }" } static String getFlag(boolean b) { return b ? "" : "" } } ```
/content/code_sandbox/buildSrc/src/main/groovy/PluginConfig.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
212
```groovy /** * <pre> * author: blankj * blog : path_to_url * time : 2019/07/13 * desc : * </pre> */ class GLog { def static debugSwitch = true static d(Object... contents) { if (!debugSwitch) return contents return l(contents) } static l(Object... contents) { StringBuilder sb = new StringBuilder() sb.append(LogConst.BORDER_TOP) sb.append(borderMsg(processContents(contents))) sb.append(LogConst.BORDER_BTM) print sb.toString() return contents } private static borderMsg(String msg) { StringBuilder sb = new StringBuilder() object2String(msg).split(LogConst.LINE_SEP).each { line -> sb.append(LogConst.BORDER_LFT).append(line).append(LogConst.LINE_SEP) } return sb } private static processContents(final Object... contents) { String body = LogConst.NULL if (contents != null) { if (contents.length == 1) { body = object2String(contents[0]) } else { StringBuilder sb = new StringBuilder() int i = 0 for (int len = contents.length; i < len; ++i) { Object content = contents[i] sb.append("args[$i] = ") .append(object2String(content)) .append(LogConst.LINE_SEP) } body = sb.toString() } } return body.length() == 0 ? LogConst.NOTHING : body } static String object2String(Object object) { if (object == null) return "null"; if (object.getClass().isArray()) return LogFormatter.array2String(object); if (object instanceof List) return LogFormatter.list2String(object); if (object instanceof Map) return LogFormatter.map2String(object); if (object instanceof Throwable) return LogFormatter.throwable2String(object); return object.toString(); } static class LogFormatter { private static array2String(Object object) { if (object instanceof Object[]) { return Arrays.deepToString((Object[]) object); } else if (object instanceof boolean[]) { return Arrays.toString((boolean[]) object); } else if (object instanceof byte[]) { return Arrays.toString((byte[]) object); } else if (object instanceof char[]) { return Arrays.toString((char[]) object); } else if (object instanceof double[]) { return Arrays.toString((double[]) object); } else if (object instanceof float[]) { return Arrays.toString((float[]) object); } else if (object instanceof int[]) { return Arrays.toString((int[]) object); } else if (object instanceof long[]) { return Arrays.toString((long[]) object); } else if (object instanceof short[]) { return Arrays.toString((short[]) object); } throw new IllegalArgumentException("Array has incompatible type: " + object.getClass()); } private static list2String(List list) { StringBuilder sb = new StringBuilder() sb.append("[") list.each { v -> if (v instanceof Map || v instanceof List) { sb.append(String.format("$LogConst.LINE_SEP%${deep++ * 8}s${object2String(v)},", "")) deep-- } else { sb.append(String.format("$LogConst.LINE_SEP%${deep * 8}s$v,", "")) } } sb.deleteCharAt(sb.length() - 1) if (deep - 1 == 0) { sb.append("$LogConst.LINE_SEP]") } else { sb.append(String.format("$LogConst.LINE_SEP%${(deep - 1) * 8}s]", "")) } return sb.toString() } private static deep = 1; private static map2String(Map map) { StringBuilder sb = new StringBuilder() sb.append("[") map.each { k, v -> if (v instanceof Map || v instanceof List) { sb.append(String.format("$LogConst.LINE_SEP%${deep++ * 8}s%-26s: ${object2String(v)},", "", k)) deep-- } else { sb.append(String.format("$LogConst.LINE_SEP%${deep * 8}s%-26s: $v,", "", k)) } } sb.deleteCharAt(sb.length() - 1) if (deep - 1 == 0) { sb.append("$LogConst.LINE_SEP]") } else { sb.append(String.format("$LogConst.LINE_SEP%${(deep - 1) * 8}s]", "")) } return sb.toString() } private static throwable2String(Throwable throwable) { final List<Throwable> throwableList = new ArrayList<>(); while (throwable != null && !throwableList.contains(throwable)) { throwableList.add(throwable); throwable = throwable.getCause(); } final int size = throwableList.size(); final List<String> frames = new ArrayList<>(); List<String> nextTrace = getStackFrameList(throwableList.get(size - 1)); for (int i = size; --i >= 0;) { final List<String> trace = nextTrace; if (i != 0) { nextTrace = getStackFrameList(throwableList.get(i - 1)); removeCommonFrames(trace, nextTrace); } if (i == size - 1) { frames.add(throwableList.get(i).toString()); } else { frames.add(" Caused by: " + throwableList.get(i).toString()); } frames.addAll(trace); } StringBuilder sb = new StringBuilder(); for (final String element : frames) { sb.append(element).append(LogConst.LINE_SEP); } return sb.toString(); } private static List<String> getStackFrameList(final Throwable throwable) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); final String stackTrace = sw.toString(); final StringTokenizer frames = new StringTokenizer(stackTrace, LogConst.LINE_SEP); final List<String> list = new ArrayList<>(); boolean traceStarted = false; while (frames.hasMoreTokens()) { final String token = frames.nextToken(); // Determine if the line starts with <whitespace>at final int at = token.indexOf("at"); if (at != -1 && token.substring(0, at).trim().isEmpty()) { traceStarted = true; list.add(token); } else if (traceStarted) { break; } } return list; } private static void removeCommonFrames(final List<String> causeFrames, final List<String> wrapperFrames) { int causeFrameIndex = causeFrames.size() - 1; int wrapperFrameIndex = wrapperFrames.size() - 1; while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) { // Remove the frame from the cause trace if it is the same // as in the wrapper trace final String causeFrame = causeFrames.get(causeFrameIndex); final String wrapperFrame = wrapperFrames.get(wrapperFrameIndex); if (causeFrame.equals(wrapperFrame)) { causeFrames.remove(causeFrameIndex); } causeFrameIndex--; wrapperFrameIndex--; } } } static class LogConst { static LINE_SEP = System.getProperty("line.separator"); static BORDER_TOP = "" + LINE_SEP static BORDER_LFT = " "; static BORDER_BTM = "" + LINE_SEP static final NOTHING = "log nothing"; static final NULL = "null"; } } ```
/content/code_sandbox/buildSrc/src/main/groovy/GLog.groovy
groovy
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,637
```shell #!/bin/bash if [[ `git status --porcelain` ]]; then # changes >&2 echo "You have unstaged changes. Please commit before you run this." exit 1 fi # REPO=git@github.com:Blizzard/node-rdkafka.git REPO=path_to_url git remote add deploy $REPO # Get the most recent stuff if we don't have it git fetch deploy gh-pages || exit $? make docs || exit $? # Get package version and save to variable PACKAGE=$(node -pe 'require("./package.json").name.split("/")[1]') VERSION=$(node -pe 'require("./package.json").version') # Make a temporary folder TEMPDIR=$(mktemp -d) VERSIONDIR="$TEMPDIR/$VERSION" cp -r docs $VERSIONDIR # Now, checkout the gh-pages, but first get current checked out branch # CURRENT_BRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD) COMMIT_MESSAGE=$(git log --pretty='format:%B' -1) COMMIT_AUTHOR=$(git log --pretty='format:%aN <%aE>' -1) if [[ `git checkout --quiet -b gh-pages deploy/gh-pages` ]]; then >&2 echo "Could not checkout gh-pages" exit 1 fi rm -rf current rm -rf $VERSION cp -r $VERSIONDIR $VERSION cp -r $VERSIONDIR current git add --all git commit --author="$COMMIT_AUTHOR" -m "Updated docs for '$COMMIT_MESSAGE'" rm -rf $TEMPDIR git push $REPO gh-pages || exit $? git checkout $CURRENT_BRANCH ```
/content/code_sandbox/make_docs.sh
shell
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
357
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var kafka = require('bindings')('node-librdkafka'); module.exports = kafka; ```
/content/code_sandbox/librdkafka.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
69
```python { "variables": { # may be redefined in command line on configuration stage # "BUILD_LIBRDKAFKA%": "<!(echo ${BUILD_LIBRDKAFKA:-1})" "BUILD_LIBRDKAFKA%": "<!(node ./util/get-env.js BUILD_LIBRDKAFKA 1)", }, "targets": [ { "target_name": "node-librdkafka", 'sources': [ 'src/binding.cc', 'src/callbacks.cc', 'src/common.cc', 'src/config.cc', 'src/connection.cc', 'src/errors.cc', 'src/kafka-consumer.cc', 'src/producer.cc', 'src/topic.cc', 'src/workers.cc', 'src/admin.cc' ], "include_dirs": [ "<!(node -e \"require('nan')\")", "<(module_root_dir)/" ], 'conditions': [ [ 'OS=="win"', { 'actions': [ { 'action_name': 'nuget_librdkafka_download', 'inputs': [ 'deps/windows-install.py' ], 'outputs': [ 'deps/precompiled/librdkafka.lib', 'deps/precompiled/librdkafkacpp.lib' ], 'message': 'Getting librdkafka from nuget', 'action': ['python', '<@(_inputs)'] } ], 'cflags_cc' : [ '-std=c++17' ], 'msvs_settings': { 'VCLinkerTool': { 'AdditionalDependencies': [ 'librdkafka.lib', 'librdkafkacpp.lib' ], 'AdditionalLibraryDirectories': [ '../deps/precompiled/' ] }, 'VCCLCompilerTool': { 'AdditionalOptions': [ '/GR' ], 'AdditionalUsingDirectories': [ 'deps/precompiled/' ], 'AdditionalIncludeDirectories': [ 'deps/librdkafka/src', 'deps/librdkafka/src-cpp' ] } }, 'include_dirs': [ 'deps/include' ] }, { 'conditions': [ [ "<(BUILD_LIBRDKAFKA)==1", { "dependencies": [ "deps/librdkafka.gyp:librdkafka" ], "include_dirs": [ "deps/librdkafka/src", "deps/librdkafka/src-cpp" ], 'conditions': [ [ 'OS=="linux"', { "libraries": [ "../build/deps/librdkafka.so", "../build/deps/librdkafka++.so", "-Wl,-rpath='$$ORIGIN/../deps'", ], } ], [ 'OS=="mac"', { "libraries": [ "../build/deps/librdkafka.dylib", "../build/deps/librdkafka++.dylib", ], } ] ], }, # Else link against globally installed rdkafka and use # globally installed headers. On Debian, you should # install the librdkafka1, librdkafka++1, and librdkafka-dev # .deb packages. { "libraries": ["-lrdkafka", "-lrdkafka++"], "include_dirs": [ "/usr/include/librdkafka", "/usr/local/include/librdkafka", "/opt/include/librdkafka", ], }, ], [ 'OS=="linux"', { 'cflags_cc' : [ '-std=c++17' ], 'cflags_cc!': [ '-fno-rtti' ] } ], [ 'OS=="mac"', { 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.11', 'GCC_ENABLE_CPP_RTTI': 'YES', 'OTHER_LDFLAGS': [ '-L/usr/local/opt/openssl/lib' ], 'OTHER_CPLUSPLUSFLAGS': [ '-I/usr/local/opt/openssl/include', '-std=c++17' ], }, } ] ] } ] ] } ] } ```
/content/code_sandbox/binding.gyp
python
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
934
```powershell choco install openssl.light choco install make ```
/content/code_sandbox/win_install.ps1
powershell
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
12
```shell #!/bin/bash COMPOSE_VERSION=$(docker-compose --version) DOCKER_VERSION=$(docker --version) # Start the docker compose file echo "Running docker compose up. Docker version $DOCKER_VERSION. Compose version $COMPOSE_VERSION. " docker-compose up -d if [ "$?" == "1" ]; then echo "Failed to start docker images." exit 1 fi # List of topics to create in container topics=( "test" "test2" "test3" "test4" "test5" "test6" ) # Run docker-compose exec to make them for topic in "${topics[@]}" do echo "Making topic $topic" until docker-compose exec kafka \ kafka-topics --create --topic $topic --partitions 1 --replication-factor 1 --if-not-exists --zookeeper zookeeper:2181 do topic_result="$?" if [ "$topic_result" == "1" ]; then echo "Bad status code: $topic_result. Trying again." else # If it is some unknown status code, die. exit 1 fi done done ```
/content/code_sandbox/run_docker.sh
shell
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
256
```yaml --- zookeeper: image: confluentinc/cp-zookeeper ports: - "2181:2181" environment: ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_TICK_TIME: 2000 kafka: image: confluentinc/cp-kafka links: - zookeeper ports: - "9092:9092" environment: KAFKA_BROKER_ID: 1 KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181' KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://localhost:9092' KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 KAFKA_DEFAULT_REPLICATION_FACTOR: 1 KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 ```
/content/code_sandbox/docker-compose.yml
yaml
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
209
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var Kafka = require('../'); var count = 0; var total = 0; var store = []; var host = process.argv[2] || 'localhost:9092'; var topic = process.argv[3] || 'test'; var consumer = new Kafka.KafkaConsumer({ 'metadata.broker.list': host, 'group.id': 'node-rdkafka-bench', 'fetch.wait.max.ms': 100, 'fetch.message.max.bytes': 1024 * 1024, 'enable.auto.commit': false // paused: true, }, { 'auto.offset.reset': 'earliest' }); var interval; consumer.connect() .once('ready', function() { consumer.subscribe([topic]); consumer.consume(); }) .once('data', function() { interval = setInterval(function() { console.log('%d messages per second', count); if (count > 0) { store.push(count); } count = 0; }, 1000); }) .on('data', function(message) { count += 1; total += 1; }); process.once('SIGTERM', shutdown); process.once('SIGINT', shutdown); process.once('SIGHUP', shutdown); function shutdown() { clearInterval(interval); if (store.length > 0) { var calc = 0; for (var x in store) { calc += store[x]; } var mps = parseFloat(calc * 1.0/store.length); console.log('%d messages per second on average', mps); } var killTimer = setTimeout(function() { process.exit(); }, 5000); consumer.disconnect(function() { clearTimeout(killTimer); process.exit(); }); } ```
/content/code_sandbox/bench/consumer-subscribe.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
426
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var Kafka = require('../'); var crypto = require('crypto'); var count = 0; var total = 0; var totalComplete = 0; var verifiedComplete = 0; var errors = 0; var store = []; var started; var done = false; var host = process.argv[2] || '127.0.0.1:9092'; var topicName = process.argv[3] || 'test'; var compression = process.argv[4] || 'gzip'; var MAX = process.argv[5] || 10000000; var producer = new Kafka.Producer({ 'metadata.broker.list': host, 'group.id': 'node-rdkafka-bench', 'compression.codec': compression, 'retry.backoff.ms': 200, 'message.send.max.retries': 10, 'socket.keepalive.enable': true, 'queue.buffering.max.messages': 100000, 'queue.buffering.max.ms': 1000, 'batch.num.messages': 1000 }); // Track how many messages we see per second var interval; var ok = true; function getTimer() { if (!interval) { interval = setTimeout(function() { interval = false; if (!done) { console.log('%d messages per sent second', count); store.push(count); count = 0; getTimer(); } else { console.log('%d messages remaining sent in last batch <1000ms', count); } }, 1000); } return interval; } var t; crypto.randomBytes(4096, function(ex, buffer) { producer.connect() .on('ready', function() { getTimer(); started = new Date().getTime(); var sendMessage = function() { try { var errorCode = producer.produce(topicName, null, buffer, null); verifiedComplete += 1; } catch (e) { console.error(e); errors++; } count += 1; totalComplete += 1; if (totalComplete === MAX) { shutdown(); } if (total < MAX) { total += 1; // This is 100% sync so we need to setImmediate to give it time // to breathe. setImmediate(sendMessage); } }; sendMessage(); }) .on('event.error', function(err) { console.error(err); process.exit(1); }) .on('disconnected', shutdown); }); function shutdown(e) { done = true; clearInterval(interval); var killTimer = setTimeout(function() { process.exit(); }, 5000); producer.disconnect(function() { clearTimeout(killTimer); var ended = new Date().getTime(); var elapsed = ended - started; // console.log('Ended %s', ended); console.log('total: %d messages over %d ms', total, elapsed); console.log('%d messages / second', parseInt(total / (elapsed / 1000))); process.exit(); }); } ```
/content/code_sandbox/bench/producer-raw-rdkafka.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
702
```shell #!/bin/bash kafka_root=${KAFKA_ROOT:-/opt/kafka} # Generate and insert some messages OS=$(uname -s) function initializeTopic { topic=$1 host=$2 msg_size=$3 batch_size=$4 batch_count=$5 if [ $host == "localhost:9092" ]; then ${kafka_root}/bin/kafka-topics.sh --create --zookeeper localhost:2181 \ --replication-factor 1 --partitions 1 --topic ${topic} fi echo "Generating messages (size: ${msg_size})" : > /tmp/msgs # Truncate /tmp/msgs for i in $(seq 1 ${batch_size}); do if [ $OS == 'Darwin' ]; then printf %s\\n "$(head -c${msg_size} /dev/urandom | base64)" >> /tmp/msgs else printf %s\\n "$(head --bytes=${msg_size} /dev/urandom | base64 --wrap=0)" >> /tmp/msgs fi done echo "Done generating messages" for i in $(seq 1 ${batch_count}); do echo "Adding $(wc -l /tmp/msgs) messages to topic ${topic}" "${kafka_root}/bin/kafka-console-producer.sh" \ --broker-list ${host} --topic ${topic} < /tmp/msgs done } initializeTopic "librdtesting-01" "localhost:9092" "4096" "5000" "2000" ```
/content/code_sandbox/bench/seed.sh
shell
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
351
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var Kafka = require('../'); var crypto = require('crypto'); var count = 0; var total = 0; var totalComplete = 0; var store = []; var host = process.argv[2] || '127.0.0.1:9092'; var topicName = process.argv[3] || 'test'; var compression = process.argv[4] || 'gzip'; var MAX = process.argv[5] || 1000000; var stream = Kafka.Producer.createWriteStream({ 'metadata.broker.list': host, 'group.id': 'node-rdkafka-bench', 'compression.codec': compression, 'retry.backoff.ms': 200, 'message.send.max.retries': 10, 'socket.keepalive.enable': true, 'queue.buffering.max.messages': 100000, 'queue.buffering.max.ms': 1000, 'batch.num.messages': 1000, }, {}, { topic: topicName, pollInterval: 20 }); stream.on('error', function(e) { console.log(e); process.exit(1); }); // Track how many messages we see per second var interval; var done = false; function log() { console.log('%d messages per sent second', count); store.push(count); count = 0; } crypto.randomBytes(4096, function(ex, buffer) { var x = function(e) { if (e) { console.error(e); } count += 1; totalComplete += 1; if (totalComplete >= MAX && !done) { done = true; clearInterval(interval); setTimeout(shutdown, 5000); } }; function write() { if (!stream.write(buffer, 'base64', x)) { return stream.once('drain', write); } else { total++; } if (total < MAX) { // we are not done setImmediate(write); } } write(); interval = setInterval(log, 1000); stream.on('error', function(err) { console.log(err); }); // stream.on('end', shutdown); }); process.once('SIGTERM', shutdown); process.once('SIGINT', shutdown); process.once('SIGHUP', shutdown); function shutdown() { if (store.length > 0) { var calc = 0; for (var x in store) { calc += store[x]; } var mps = parseFloat(calc * 1.0/store.length); console.log('%d messages per second on average', mps); console.log('%d messages total', total); } clearInterval(interval); stream.end(); stream.on('close', function() { console.log('total: %d', total); }); } ```
/content/code_sandbox/bench/producer-rdkafka.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
651
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var Kafka = require('../'); var count = 0; var total = 0; var store = []; var host = process.argv[2] || 'localhost:9092'; var topic = process.argv[3] || 'test'; var consumer = new Kafka.KafkaConsumer({ 'metadata.broker.list': host, 'group.id': 'node-rdkafka-bench-s', 'fetch.wait.max.ms': 100, 'fetch.message.max.bytes': 1024 * 1024, 'enable.auto.commit': false // paused: true, }, { 'auto.offset.reset': 'earliest' }); var interval; consumer.connect() .once('ready', function() { consumer.subscribe([topic]); consumer.consume(); }) .on('rebalance', function() { console.log('rebalance'); }) .once('data', function() { interval = setInterval(function() { console.log('%d messages per second', count); if (count > 0) { store.push(count); } count = 0; }, 1000); }) .on('data', function(message) { count += 1; total += 1; }); function shutdown() { clearInterval(interval); if (store.length > 0) { var calc = 0; for (var x in store) { calc += store[x]; } var mps = parseFloat(calc * 1.0/store.length); console.log('%d messages per second on average', mps); } var killTimer = setTimeout(function() { process.exit(); }, 5000); consumer.disconnect(function() { clearTimeout(killTimer); process.exit(); }); } ```
/content/code_sandbox/bench/consumer-raw-rdkafka.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
421
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var Writable = require('stream').Writable; var Kafka = require('../'); var count = 0; var total = 0; var store = []; var host = process.argv[2] || 'localhost:9092'; var topic = process.argv[3] || 'test'; var stream = Kafka.createReadStream({ 'metadata.broker.list': host, 'group.id': 'node-rdkafka-benchs', 'fetch.wait.max.ms': 100, 'fetch.message.max.bytes': 1024 * 1024, 'enable.auto.commit': false // paused: true, }, { 'auto.offset.reset': 'earliest' }, { fetchSize: 16, topics: [topic] }); // Track how many messages we see per second var interval; var isShuttingDown = false; stream .on('error', function(err) { console.log('Shutting down due to error'); console.log(err.stack); shutdown(); }) .once('data', function(d) { interval = setInterval(function() { if (isShuttingDown) { clearInterval(interval); } console.log('%d messages per second', count); if (count > 0) { // Don't store ones when we didn't get data i guess? store.push(count); // setTimeout(shutdown, 500); } count = 0; }, 1000).unref(); }) .on('end', function() { // Can be called more than once without issue because of guard var console.log('Shutting down due to stream end'); shutdown(); }) .pipe(new Writable({ objectMode: true, write: function(message, encoding, cb) { count += 1; total += 1; setImmediate(cb); } })); process.once('SIGTERM', shutdown); process.once('SIGINT', shutdown); process.once('SIGHUP', shutdown); function shutdown() { if (isShuttingDown) { return; } clearInterval(interval); isShuttingDown = true; if (store.length > 0) { var calc = 0; for (var x in store) { calc += store[x]; } var mps = parseFloat(calc * 1.0/store.length); console.log('%d messages per second on average', mps); } // Destroy the stream stream.destroy(); stream.once('end', function() { console.log('total: %d', total); }); } ```
/content/code_sandbox/bench/kafka-consumer-stream.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
600
```javascript require('./checks/librdkafka-exists'); require('./checks/librdkafka-correct-version'); require('./librdkafka-defs-generator.js'); require('./update-version'); ```
/content/code_sandbox/ci/prepublish.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
38
```javascript const fs = require('fs'); const path = require('path'); const LIBRDKAFKA_VERSION = require('../package.json').librdkafka; const LIBRDKAFKA_DIR = path.resolve(__dirname, '../deps/librdkafka/'); function getHeader(file) { return `// ====== Generated from librdkafka ${LIBRDKAFKA_VERSION} file ${file} ======`; } function readLibRDKafkaFile(file) { return fs.readFileSync(path.resolve(LIBRDKAFKA_DIR, file)).toString(); } function extractConfigItems(configStr) { const [_header, config] = configStr.split(/-{5,}\|.*/); const re = /(.*?)\|(.*?)\|(.*?)\|(.*?)\|(.*?)\|(.*)/g; const configItems = []; let m; do { m = re.exec(config); if (m) { const [ _fullString, property, consumerOrProducer, range, defaultValue, importance, descriptionWithType, ] = m.map(el => (typeof el === 'string' ? el.trim() : el)); const splitDescriptionRe = /(.*?)\s*?<br>.*?:\s.*?(.*?)\*/; const [_, description, rawType] = splitDescriptionRe.exec(descriptionWithType); configItems.push({ property, consumerOrProducer, range, defaultValue, importance, description, rawType, }); } } while (m); return configItems.map(processItem); } function processItem(configItem) { // These items are overwritten by node-rdkafka switch (configItem.property) { case 'dr_msg_cb': return { ...configItem, type: 'boolean' }; case 'dr_cb': return { ...configItem, type: 'boolean | Function' }; case 'rebalance_cb': return { ...configItem, type: 'boolean | Function' }; case 'offset_commit_cb': return { ...configItem, type: 'boolean | Function' }; } switch (configItem.rawType) { case 'integer': return { ...configItem, type: 'number' }; case 'boolean': return { ...configItem, type: 'boolean' }; case 'string': case 'CSV flags': return { ...configItem, type: 'string' }; case 'enum value': return { ...configItem, type: configItem.range .split(',') .map(str => `'${str.trim()}'`) .join(' | '), }; default: return { ...configItem, type: 'any' }; } } function generateInterface(interfaceDef, configItems) { const fields = configItems .map(item => [ `/**`, ` * ${item.description}`, ...(item.defaultValue ? [` *`, ` * @default ${item.defaultValue}`] : []), ` */`, `"${item.property}"?: ${item.type};`, ] .map(row => ` ${row}`) .join('\n') ) .join('\n\n'); return `export interface ` + interfaceDef + ' {\n' + fields + '\n}'; } function addSpecialGlobalProps(globalProps) { globalProps.push({ "property": "event_cb", "consumerOrProducer": "*", "range": "", "defaultValue": "true", "importance": "low", "description": "Enables or disables `event.*` emitting.", "rawType": "boolean", "type": "boolean" }); } function generateConfigDTS(file) { const configuration = readLibRDKafkaFile(file); const [globalStr, topicStr] = configuration.split('Topic configuration properties'); const [globalProps, topicProps] = [extractConfigItems(globalStr), extractConfigItems(topicStr)]; addSpecialGlobalProps(globalProps); const [globalSharedProps, producerGlobalProps, consumerGlobalProps] = [ globalProps.filter(i => i.consumerOrProducer === '*'), globalProps.filter(i => i.consumerOrProducer === 'P'), globalProps.filter(i => i.consumerOrProducer === 'C'), ]; const [topicSharedProps, producerTopicProps, consumerTopicProps] = [ topicProps.filter(i => i.consumerOrProducer === '*'), topicProps.filter(i => i.consumerOrProducer === 'P'), topicProps.filter(i => i.consumerOrProducer === 'C'), ]; let output = `${getHeader(file)} // Code that generated this is a derivative work of the code from Nam Nguyen // path_to_url `; output += [ generateInterface('GlobalConfig', globalSharedProps), generateInterface('ProducerGlobalConfig extends GlobalConfig', producerGlobalProps), generateInterface('ConsumerGlobalConfig extends GlobalConfig', consumerGlobalProps), generateInterface('TopicConfig', topicSharedProps), generateInterface('ProducerTopicConfig extends TopicConfig', producerTopicProps), generateInterface('ConsumerTopicConfig extends TopicConfig', consumerTopicProps), ].join('\n\n'); fs.writeFileSync(path.resolve(__dirname, '../config.d.ts'), output); } function updateErrorDefinitions(file) { const rdkafkacpp_h = readLibRDKafkaFile(file); const m = /enum ErrorCode {([^}]+)}/g.exec(rdkafkacpp_h); if (!m) { throw new Error(`Can't read rdkafkacpp.h file`) } const body = m[1] .replace(/(\t)|( +)/g, ' ') .replace(/\n\n/g, '\n') .replace(/\s+=\s+/g, ': ') .replace(/[\t ]*#define +(\w+) +(\w+)/g, (_, define, original) => { const value = new RegExp(`${original}\\s+=\\s+(\\d+)`).exec(m[1])[1]; return ` ${define}: ${value},`; }) // validate body const emptyCheck = body .replace(/((\s+\/\*)|( ?\*)).*/g, '') .replace(/ ERR_\w+: -?\d+,?\r?\n/g, '') .trim() if (emptyCheck !== '') { throw new Error(`Fail to parse ${file}. It contains these extra details:\n${emptyCheck}`); } const error_js_file = path.resolve(__dirname, '../lib/error.js'); const error_js = fs.readFileSync(error_js_file) .toString() .replace(/(\/\/.*\r?\n)?LibrdKafkaError.codes = {[^}]+/g, `${getHeader(file)}\nLibrdKafkaError.codes = {\n${body}`) fs.writeFileSync(error_js_file, error_js); fs.writeFileSync(path.resolve(__dirname, '../errors.d.ts'), `${getHeader(file)}\nexport const CODES: { ERRORS: {${body.replace(/[ \.]*(\*\/\r?\n \w+: )(-?\d+),?/g, ' (**$2**) $1number,')}}}`) } (async function updateTypeDefs() { generateConfigDTS('CONFIGURATION.md'); updateErrorDefinitions('src-cpp/rdkafkacpp.h'); })() ```
/content/code_sandbox/ci/librdkafka-defs-generator.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
1,578
```javascript const path = require('path'); const semver = require('semver'); const { spawn } = require('child_process'); const fs = require('fs'); const root = path.resolve(__dirname, '..'); const pjsPath = path.resolve(root, 'package.json'); const pjs = require(pjsPath); function parseVersion(tag) { const { major, minor, prerelease, patch } = semver.parse(tag); // Describe will give is commits since last tag const [commitsSinceTag, hash] = prerelease[0] ? prerelease[0].split('-') : [ 1, process.env.TRAVIS_COMMIT || '' ]; return { major, minor, prerelease, patch, commit: commitsSinceTag - 1, hash }; } function getCommandOutput(command, args, cb) { let output = ''; const cmd = spawn(command, args); cmd.stdout.on('data', (data) => { output += data; }); cmd.on('close', (code) => { if (code != 0) { cb(new Error(`Command returned unsuccessful code: ${code}`)); return; } cb(null, output.trim()); }); } function getVersion(cb) { // path_to_url if (process.env.TRAVIS_TAG) { setImmediate(() => cb(null, parseVersion(process.env.TRAVIS_TAG.trim()))); return; } getCommandOutput('git', ['describe', '--tags'], (err, result) => { if (err) { cb(err); return; } cb(null, parseVersion(result.trim())); }); } function getBranch(cb) { if (process.env.TRAVIS_TAG) { // TRAVIS_BRANCH matches TRAVIS_TAG when TRAVIS_TAG is set // "git branch --contains tags/TRAVIS_TAG" doesn't work on travis so we have to assume 'master' setImmediate(() => cb(null, 'master')); return; } else if (process.env.TRAVIS_BRANCH) { setImmediate(() => cb(null, process.env.TRAVIS_BRANCH.trim())); return; } getCommandOutput('git', ['rev-parse', '--abbrev-ref', 'HEAD'], (err, result) => { if (err) { cb(err); return; } cb(null, result.trim()); }); } function getPackageVersion(tag, branch) { const baseVersion = `v${tag.major}.${tag.minor}.${tag.patch}`; console.log(`Package version is "${baseVersion}"`); // never publish with an suffix // fixes path_to_url // baseVersion += '-'; // if (tag.commit === 0 && branch === 'master') { // return baseVersion; // } // if (branch !== 'master') { // baseVersion += (tag.commit + 1 + '.' + branch); // } else { // baseVersion += (tag.commit + 1); // } return baseVersion; } getVersion((err, tag) => { if (err) { throw err; } getBranch((err, branch) => { if (err) { throw err; } pjs.version = getPackageVersion(tag, branch); fs.writeFileSync(pjsPath, JSON.stringify(pjs, null, 2)); }) }); ```
/content/code_sandbox/ci/update-version.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
727
```javascript const path = require('path'); const fs = require('fs'); const root = path.resolve(__dirname, '..', '..'); const pjsPath = path.join(root, 'package.json'); const librdkafkaPath = path.resolve(root, 'deps', 'librdkafka'); const pjs = require(pjsPath); const majorMask = 0xff000000; const minorMask = 0x00ff0000; const patchMask = 0x0000ff00; const revMask = 0x000000ff; // Read the header file const headerFileLines = fs.readFileSync(path.resolve(librdkafkaPath, 'src', 'rdkafka.h')).toString().split('\n'); const precompilerDefinitions = headerFileLines.filter((line) => line.startsWith('#def')); const definedLines = precompilerDefinitions.map(definedLine => { const content = definedLine.split(' ').filter(v => v != ''); return { command: content[0], key: content[1], value: content[2] }; }); const defines = {}; for (let item of definedLines) { if (item.command == '#define') { defines[item.key] = item.value; } } function parseLibrdkafkaVersion(version) { const intRepresentation = parseInt(version); const major = (intRepresentation & majorMask) >> (8 * 3); const minor = (intRepresentation & minorMask) >> (8 * 2); const patch = (intRepresentation & patchMask) >> (8 * 1); const rev = (intRepresentation & revMask) >> (8 * 0); return { major, minor, patch, rev }; } function versionAsString(version) { return [ version.major, version.minor, version.patch, version.rev === 255 ? null : version.rev, ].filter(v => v != null).join('.'); } const librdkafkaVersion = parseLibrdkafkaVersion(defines.RD_KAFKA_VERSION); const versionString = versionAsString(librdkafkaVersion); if (pjs.librdkafka !== versionString) { console.error(`Librdkafka version of ${versionString} does not match package json: ${pjs.librdkafka}`); process.exit(1); } ```
/content/code_sandbox/ci/checks/librdkafka-correct-version.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
494
```javascript const path = require('path'); const fs = require('fs'); const root = path.resolve(__dirname, '..', '..'); const librdkafkaPath = path.resolve(root, 'deps', 'librdkafka'); // Ensure librdkafka is in the deps directory - this makes sure we don't accidentally // publish on a non recursive clone :) if (!fs.existsSync(librdkafkaPath)) { console.error(`Could not find librdkafka at path ${librdkafkaPath}`); process.exit(1); } ```
/content/code_sandbox/ci/checks/librdkafka-exists.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
112
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ 'use strict'; module.exports = ProducerStream; var Writable = require('stream').Writable; var util = require('util'); var ErrorCode = require('./error').codes; util.inherits(ProducerStream, Writable); /** * Writable stream integrating with the Kafka Producer. * * This class is used to write data to Kafka in a streaming way. It takes * buffers of data and puts them into the appropriate Kafka topic. If you need * finer control over partitions or keys, this is probably not the class for * you. In that situation just use the Producer itself. * * The stream detects if Kafka is already connected. You can safely begin * writing right away. * * This stream does not operate in Object mode and can only be given buffers. * * @param {Producer} producer - The Kafka Producer object. * @param {array} topics - Array of topics * @param {object} options - Topic configuration. * @constructor * @extends stream.Writable */ function ProducerStream(producer, options) { if (!(this instanceof ProducerStream)) { return new ProducerStream(producer, options); } if (options === undefined) { options = {}; } else if (typeof options === 'string') { options = { encoding: options }; } else if (options === null || typeof options !== 'object') { throw new TypeError('"streamOptions" argument must be a string or an object'); } if (!options.objectMode && !options.topic) { throw new TypeError('ProducerStreams not using objectMode must provide a topic to produce to.'); } if (options.objectMode !== true) { this._write = this._write_buffer; } else { this._write = this._write_message; } Writable.call(this, options); this.producer = producer; this.topicName = options.topic; this.autoClose = options.autoClose === undefined ? true : !!options.autoClose; this.connectOptions = options.connectOptions || {}; this.producer.setPollInterval(options.pollInterval || 1000); if (options.encoding) { this.setDefaultEncoding(options.encoding); } // Connect to the producer. Unless we are already connected if (!this.producer.isConnected()) { this.connect(this.connectOptions); } var self = this; this.once('finish', function() { if (this.autoClose) { this.close(); } }); } ProducerStream.prototype.connect = function(options) { this.producer.connect(options, function(err, data) { if (err) { this.emit('error', err); return; } }.bind(this)); }; /** * Internal stream write method for ProducerStream when writing buffers. * * This method should never be called externally. It has some recursion to * handle cases where the producer is not yet connected. * * @param {buffer} chunk - Chunk to write. * @param {string} encoding - Encoding for the buffer * @param {Function} cb - Callback to call when the stream is done processing * the data. * @private * @see path_to_url#L1901 */ ProducerStream.prototype._write_buffer = function(data, encoding, cb) { if (!(data instanceof Buffer)) { this.emit('error', new Error('Invalid data. Can only produce buffers')); return; } var self = this; if (!this.producer.isConnected()) { this.producer.once('ready', function() { self._write(data, encoding, cb); }); return; } try { this.producer.produce(self.topicName, null, data, null); setImmediate(cb); } catch (e) { if (ErrorCode.ERR__QUEUE_FULL === e.code) { // Poll for good measure self.producer.poll(); // Just delay this thing a bit and pass the params // backpressure will get exerted this way. setTimeout(function() { self._write(data, encoding, cb); }, 500); } else { if (self.autoClose) { self.close(); } setImmediate(function() { cb(e); }); } } }; /** * Internal stream write method for ProducerStream when writing objects. * * This method should never be called externally. It has some recursion to * handle cases where the producer is not yet connected. * * @param {object} message - Message to write. * @param {string} encoding - Encoding for the buffer * @param {Function} cb - Callback to call when the stream is done processing * the data. * @private * @see path_to_url#L1901 */ ProducerStream.prototype._write_message = function(message, encoding, cb) { var self = this; if (!this.producer.isConnected()) { this.producer.once('ready', function() { self._write(message, encoding, cb); }); return; } try { this.producer.produce(message.topic, message.partition, message.value, message.key, message.timestamp, message.opaque, message.headers); setImmediate(cb); } catch (e) { if (ErrorCode.ERR__QUEUE_FULL === e.code) { // Poll for good measure self.producer.poll(); // Just delay this thing a bit and pass the params // backpressure will get exerted this way. setTimeout(function() { self._write(message, encoding, cb); }, 500); } else { if (self.autoClose) { self.close(); } setImmediate(function() { cb(e); }); } } }; function writev(producer, topic, chunks, cb) { // @todo maybe a produce batch method? var doneCount = 0; var err = null; var chunk = null; function maybeDone(e) { if (e) { err = e; } doneCount ++; if (doneCount === chunks.length) { cb(err); } } function retry(restChunks) { // Poll for good measure producer.poll(); // Just delay this thing a bit and pass the params // backpressure will get exerted this way. setTimeout(function() { writev(producer, topic, restChunks, cb); }, 500); } for (var i = 0; i < chunks.length; i++) { chunk = chunks[i]; try { if (Buffer.isBuffer(chunk)) { producer.produce(topic, null, chunk, null); } else { producer.produce(chunk.topic, chunk.partition, chunk.value, chunk.key, chunk.timestamp, chunk.opaque, chunk.headers); } maybeDone(); } catch (e) { if (ErrorCode.ERR__QUEUE_FULL === e.code) { retry(chunks.slice(i)); } else { cb(e); } break; } } } ProducerStream.prototype._writev = function(data, cb) { if (!this.producer.isConnected()) { this.once('ready', function() { this._writev(data, cb); }); return; } var self = this; var len = data.length; var chunks = new Array(len); var size = 0; for (var i = 0; i < len; i++) { var chunk = data[i].chunk; chunks[i] = chunk; size += chunk.length; } writev(this.producer, this.topicName, chunks, function(err) { if (err) { self.close(); cb(err); return; } cb(); }); }; ProducerStream.prototype.close = function(cb) { var self = this; if (cb) { this.once('close', cb); } // Use interval variables in here if (self.producer._isConnected) { self.producer.disconnect(function() { // Previously this set the producer to null. I'm not sure there is any benefit // to that other than I guess helping flag it for GC? // path_to_url close(); }); } else if (self.producer._isConnecting){ self.producer.once('ready', function() { // Don't pass CB this time because it has already been passed self.close(); }); } else { setImmediate(close); } function close() { self.emit('close'); } }; ```
/content/code_sandbox/lib/producer-stream.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
1,867
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var librdkafka = require('../librdkafka'); module.exports = Topic; var topicKey = 'RdKafka::Topic::'; var topicKeyLength = topicKey.length; // Take all of the topic special codes from librdkafka and add them // to the object // You can find this list in the C++ code at // path_to_url#L1250 for (var key in librdkafka.topic) { // Skip it if it doesn't start with ErrorCode if (key.indexOf('RdKafka::Topic::') !== 0) { continue; } // Replace/add it if there are any discrepancies var newKey = key.substring(topicKeyLength); Topic[newKey] = librdkafka.topic[key]; } /** * Create a topic. Just returns the string you gave it right now. * * Looks like a class, but all it does is return the topic name. * This is so that one day if there are interface changes that allow * different use of topic parameters, we can just add to this constructor and * have it return something richer */ function Topic(topicName) { return topicName; } ```
/content/code_sandbox/lib/topic.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
302
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ 'use strict'; module.exports = { create: createAdminClient, }; var Client = require('./client'); var util = require('util'); var Kafka = require('../librdkafka'); var LibrdKafkaError = require('./error'); var shallowCopy = require('./util').shallowCopy; /** * Create a new AdminClient for making topics, partitions, and more. * * This is a factory method because it immediately starts an * active handle with the brokers. * */ function createAdminClient(conf, initOauthBearerToken) { var client = new AdminClient(conf); if (initOauthBearerToken) { client.refreshOauthBearerToken(initOauthBearerToken); } // Wrap the error so we throw if it failed with some context LibrdKafkaError.wrap(client.connect(), true); // Return the client if we succeeded return client; } /** * AdminClient class for administering Kafka * * This client is the way you can interface with the Kafka Admin APIs. * This class should not be made using the constructor, but instead * should be made using the factory method. * * <code> * var client = AdminClient.create({ ... }); * </code> * * Once you instantiate this object, it will have a handle to the kafka broker. * Unlike the other node-rdkafka classes, this class does not ensure that * it is connected to the upstream broker. Instead, making an action will * validate that. * * @param {object} conf - Key value pairs to configure the admin client * topic configuration * @constructor */ function AdminClient(conf) { if (!(this instanceof AdminClient)) { return new AdminClient(conf); } conf = shallowCopy(conf); /** * NewTopic model. * * This is the representation of a new message that is requested to be made * using the Admin client. * * @typedef {object} AdminClient~NewTopic * @property {string} topic - the topic name to create * @property {number} num_partitions - the number of partitions to give the topic * @property {number} replication_factor - the replication factor of the topic * @property {object} config - a list of key values to be passed as configuration * for the topic. */ this._client = new Kafka.AdminClient(conf); this._isConnected = false; this.globalConfig = conf; } /** * Connect using the admin client. * * Should be run using the factory method, so should never * need to be called outside. * * Unlike the other connect methods, this one is synchronous. */ AdminClient.prototype.connect = function() { LibrdKafkaError.wrap(this._client.connect(), true); this._isConnected = true; }; /** * Disconnect the admin client. * * This is a synchronous method, but all it does is clean up * some memory and shut some threads down */ AdminClient.prototype.disconnect = function() { LibrdKafkaError.wrap(this._client.disconnect(), true); this._isConnected = false; }; /** * Refresh OAuthBearer token, initially provided in factory method. * Expiry is always set to maximum value, as the callback of librdkafka * for token refresh is not used. * * @param {string} tokenStr - OAuthBearer token string * @see connection.cc */ AdminClient.prototype.refreshOauthBearerToken = function (tokenStr) { if (!tokenStr || typeof tokenStr !== 'string') { throw new Error("OAuthBearer token is undefined/empty or not a string"); } this._client.setToken(tokenStr); }; /** * Create a topic with a given config. * * @param {NewTopic} topic - Topic to create. * @param {number} timeout - Number of milliseconds to wait while trying to create the topic. * @param {function} cb - The callback to be executed when finished */ AdminClient.prototype.createTopic = function(topic, timeout, cb) { if (!this._isConnected) { throw new Error('Client is disconnected'); } if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } if (!timeout) { timeout = 5000; } this._client.createTopic(topic, timeout, function(err) { if (err) { if (cb) { cb(LibrdKafkaError.create(err)); } return; } if (cb) { cb(); } }); }; /** * Delete a topic. * * @param {string} topic - The topic to delete, by name. * @param {number} timeout - Number of milliseconds to wait while trying to delete the topic. * @param {function} cb - The callback to be executed when finished */ AdminClient.prototype.deleteTopic = function(topic, timeout, cb) { if (!this._isConnected) { throw new Error('Client is disconnected'); } if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } if (!timeout) { timeout = 5000; } this._client.deleteTopic(topic, timeout, function(err) { if (err) { if (cb) { cb(LibrdKafkaError.create(err)); } return; } if (cb) { cb(); } }); }; /** * Create new partitions for a topic. * * @param {string} topic - The topic to add partitions to, by name. * @param {number} totalPartitions - The total number of partitions the topic should have * after the request * @param {number} timeout - Number of milliseconds to wait while trying to create the partitions. * @param {function} cb - The callback to be executed when finished */ AdminClient.prototype.createPartitions = function(topic, totalPartitions, timeout, cb) { if (!this._isConnected) { throw new Error('Client is disconnected'); } if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } if (!timeout) { timeout = 5000; } this._client.createPartitions(topic, totalPartitions, timeout, function(err) { if (err) { if (cb) { cb(LibrdKafkaError.create(err)); } return; } if (cb) { cb(); } }); }; ```
/content/code_sandbox/lib/admin.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
1,446
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var KafkaConsumer = require('./kafka-consumer'); var Producer = require('./producer'); var HighLevelProducer = require('./producer/high-level-producer'); var error = require('./error'); var util = require('util'); var lib = require('../librdkafka'); var Topic = require('./topic'); var Admin = require('./admin'); var features = lib.features().split(','); module.exports = { Consumer: util.deprecate(KafkaConsumer, 'Use KafkaConsumer instead. This may be changed in a later version'), Producer: Producer, HighLevelProducer: HighLevelProducer, AdminClient: Admin, KafkaConsumer: KafkaConsumer, createReadStream: KafkaConsumer.createReadStream, createWriteStream: Producer.createWriteStream, CODES: { ERRORS: error.codes, }, Topic: Topic, features: features, librdkafkaVersion: lib.librdkafkaVersion }; ```
/content/code_sandbox/lib/index.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
243
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ 'use strict'; module.exports = KafkaConsumer; var Client = require('./client'); var util = require('util'); var Kafka = require('../librdkafka'); var KafkaConsumerStream = require('./kafka-consumer-stream'); var LibrdKafkaError = require('./error'); var TopicPartition = require('./topic-partition'); var shallowCopy = require('./util').shallowCopy; var DEFAULT_CONSUME_LOOP_TIMEOUT_DELAY = 500; var DEFAULT_CONSUME_TIME_OUT = 1000; util.inherits(KafkaConsumer, Client); /** * KafkaConsumer class for reading messages from Kafka * * This is the main entry point for reading data from Kafka. You * configure this like you do any other client, with a global * configuration and default topic configuration. * * Once you instantiate this object, connecting will open a socket. * Data will not be read until you tell the consumer what topics * you want to read from. * * @param {object} conf - Key value pairs to configure the consumer * @param {object} topicConf - Key value pairs to create a default * topic configuration * @extends Client * @constructor */ function KafkaConsumer(conf, topicConf) { if (!(this instanceof KafkaConsumer)) { return new KafkaConsumer(conf, topicConf); } conf = shallowCopy(conf); topicConf = shallowCopy(topicConf); var onRebalance = conf.rebalance_cb; var self = this; // If rebalance is undefined we don't want any part of this if (onRebalance && typeof onRebalance === 'boolean') { conf.rebalance_cb = function(err, assignment) { // Create the librdkafka error err = LibrdKafkaError.create(err); // Emit the event self.emit('rebalance', err, assignment); // That's it try { if (err.code === -175 /*ERR__ASSIGN_PARTITIONS*/) { self.assign(assignment); } else if (err.code === -174 /*ERR__REVOKE_PARTITIONS*/) { self.unassign(); } } catch (e) { // Ignore exceptions if we are not connected if (self.isConnected()) { self.emit('rebalance.error', e); } } }; } else if (onRebalance && typeof onRebalance === 'function') { /* * Once this is opted in to, that's it. It's going to manually rebalance * forever. There is no way to unset config values in librdkafka, just * a way to override them. */ conf.rebalance_cb = function(err, assignment) { // Create the librdkafka error err = err ? LibrdKafkaError.create(err) : undefined; self.emit('rebalance', err, assignment); onRebalance.call(self, err, assignment); }; } // Same treatment for offset_commit_cb var onOffsetCommit = conf.offset_commit_cb; if (onOffsetCommit && typeof onOffsetCommit === 'boolean') { conf.offset_commit_cb = function(err, offsets) { if (err) { err = LibrdKafkaError.create(err); } // Emit the event self.emit('offset.commit', err, offsets); }; } else if (onOffsetCommit && typeof onOffsetCommit === 'function') { conf.offset_commit_cb = function(err, offsets) { if (err) { err = LibrdKafkaError.create(err); } // Emit the event self.emit('offset.commit', err, offsets); onOffsetCommit.call(self, err, offsets); }; } /** * KafkaConsumer message. * * This is the representation of a message read from Kafka. * * @typedef {object} KafkaConsumer~Message * @property {buffer} value - the message buffer from Kafka. * @property {string} topic - the topic name * @property {number} partition - the partition on the topic the * message was on * @property {number} offset - the offset of the message * @property {string} key - the message key * @property {number} size - message size, in bytes. * @property {number} timestamp - message timestamp */ Client.call(this, conf, Kafka.KafkaConsumer, topicConf); this.globalConfig = conf; this.topicConfig = topicConf; this._consumeTimeout = DEFAULT_CONSUME_TIME_OUT; this._consumeLoopTimeoutDelay = DEFAULT_CONSUME_LOOP_TIMEOUT_DELAY; } /** * Set the default consume timeout provided to c++land * @param {number} timeoutMs - number of milliseconds to wait for a message to be fetched */ KafkaConsumer.prototype.setDefaultConsumeTimeout = function(timeoutMs) { this._consumeTimeout = timeoutMs; }; /** * Set the default sleep delay for the next consume loop after the previous one has timed out. * @param {number} intervalMs - number of milliseconds to sleep after a message fetch has timed out */ KafkaConsumer.prototype.setDefaultConsumeLoopTimeoutDelay = function(intervalMs) { this._consumeLoopTimeoutDelay = intervalMs; }; /** * Get a stream representation of this KafkaConsumer * * @see TopicReadable * @example * var consumerStream = Kafka.KafkaConsumer.createReadStream({ * 'metadata.broker.list': 'localhost:9092', * 'group.id': 'librd-test', * 'socket.keepalive.enable': true, * 'enable.auto.commit': false * }, {}, { topics: [ 'test' ] }); * * @param {object} conf - Key value pairs to configure the consumer * @param {object} topicConf - Key value pairs to create a default * topic configuration * @param {object} streamOptions - Stream options * @param {array} streamOptions.topics - Array of topics to subscribe to. * @return {KafkaConsumerStream} - Readable stream that receives messages * when new ones become available. */ KafkaConsumer.createReadStream = function(conf, topicConf, streamOptions) { var consumer = new KafkaConsumer(conf, topicConf); return new KafkaConsumerStream(consumer, streamOptions); }; /** * Get a current list of the committed offsets per topic partition * * Returns an array of objects in the form of a topic partition list * * @param {TopicPartition[]} toppars - Topic partition list to query committed * offsets for. Defaults to the current assignment * @param {number} timeout - Number of ms to block before calling back * and erroring * @param {Function} cb - Callback method to execute when finished or timed * out * @return {Client} - Returns itself */ KafkaConsumer.prototype.committed = function(toppars, timeout, cb) { // We want to be backwards compatible here, and the previous version of // this function took two arguments // If CB is not set, shift to backwards compatible version if (!cb) { cb = arguments[1]; timeout = arguments[0]; toppars = this.assignments(); } else { toppars = toppars || this.assignments(); } var self = this; this._client.committed(toppars, timeout, function(err, topicPartitions) { if (err) { cb(LibrdKafkaError.create(err)); return; } cb(null, topicPartitions); }); return this; }; /** * Seek consumer for topic+partition to offset which is either an absolute or * logical offset. * * Does not return anything, as it is asynchronous. There are special cases * with the timeout parameter. The consumer must have previously been assigned * to topics and partitions that seek seeks to seek. * * @example * consumer.seek({ topic: 'topic', partition: 0, offset: 1000 }, 0, function(err) { * if (err) { * * } * }); * * @param {TopicPartition} toppar - Topic partition to seek. * @param {number} timeout - Number of ms to block before calling back * and erroring. If the parameter is null or 0, the call will not wait * for the seek to be performed. Essentially, it will happen in the background * with no notification * @param {Function} cb - Callback method to execute when finished or timed * out. If the seek timed out, the internal state of the consumer is unknown. * @return {Client} - Returns itself */ KafkaConsumer.prototype.seek = function(toppar, timeout, cb) { var self = this; this._client.seek(TopicPartition.create(toppar), timeout, function(err) { if (err) { cb(LibrdKafkaError.create(err)); return; } cb(); }); return this; }; /** * Assign the consumer specific partitions and topics * * @param {array} assignments - Assignments array. Should contain * objects with topic and partition set. * @return {Client} - Returns itself */ KafkaConsumer.prototype.assign = function(assignments) { this._client.assign(TopicPartition.map(assignments)); return this; }; /** * Unassign the consumer from its assigned partitions and topics. * * @return {Client} - Returns itself */ KafkaConsumer.prototype.unassign = function() { this._client.unassign(); return this; }; /** * Get the assignments for the consumer * * @return {array} assignments - Array of topic partitions */ KafkaConsumer.prototype.assignments = function() { return this._errorWrap(this._client.assignments(), true); }; /** * Subscribe to an array of topics (synchronously). * * This operation is pretty fast because it just sets * an assignment in librdkafka. This is the recommended * way to deal with subscriptions in a situation where you * will be reading across multiple files or as part of * your configure-time initialization. * * This is also a good way to do it for streams. * * @param {array} topics - An array of topics to listen to * @throws - Throws when an error code came back from native land * @return {KafkaConsumer} - Returns itself. */ KafkaConsumer.prototype.subscribe = function(topics) { // Will throw if it is a bad error. this._errorWrap(this._client.subscribe(topics)); this.emit('subscribed', topics); return this; }; /** * Get the current subscription of the KafkaConsumer * * Get a list of subscribed topics. Should generally match what you * passed on via subscribe * * @see KafkaConsumer::subscribe * @throws - Throws when an error code came back from native land * @return {array} - Array of strings to show the current assignment */ KafkaConsumer.prototype.subscription = function() { return this._errorWrap(this._client.subscription(), true); }; /** * Get the current offset position of the KafkaConsumer * * Returns a list of RdKafka::TopicPartitions on success, or throws * an error on failure * * @param {TopicPartition[]} toppars - List of topic partitions to query * position for. Defaults to the current assignment * @throws - Throws when an error code came back from native land * @return {array} - TopicPartition array. Each item is an object with * an offset, topic, and partition */ KafkaConsumer.prototype.position = function(toppars) { if (!toppars) { toppars = this.assignments(); } return this._errorWrap(this._client.position(toppars), true); }; /** * Unsubscribe from all currently subscribed topics * * Before you subscribe to new topics you need to unsubscribe * from the old ones, if there is an active subscription. * Otherwise, you will get an error because there is an * existing subscription. * * @throws - Throws when an error code comes back from native land * @return {KafkaConsumer} - Returns itself. */ KafkaConsumer.prototype.unsubscribe = function() { this._errorWrap(this._client.unsubscribe()); this.emit('unsubscribed', []); // Backwards compatible change this.emit('unsubscribe', []); return this; }; /** * Read a number of messages from Kafka. * * This method is similar to the main one, except that it reads a number * of messages before calling back. This may get better performance than * reading a single message each time in stream implementations. * * This will keep going until it gets ERR__PARTITION_EOF or ERR__TIMED_OUT * so the array may not be the same size you ask for. The size is advisory, * but we will not exceed it. * * @param {number} size - Number of messages to read * @param {KafkaConsumer~readCallback} cb - Callback to return when work is done. *//** * Read messages from Kafka as fast as possible * * This method keeps a background thread running to fetch the messages * as quickly as it can, sleeping only in between EOF and broker timeouts. * * Use this to get the maximum read performance if you don't care about the * stream backpressure. * @param {KafkaConsumer~readCallback} cb - Callback to return when a message * is fetched. */ KafkaConsumer.prototype.consume = function(number, cb) { var timeoutMs = this._consumeTimeout !== undefined ? this._consumeTimeout : DEFAULT_CONSUME_TIME_OUT; var self = this; if ((number && typeof number === 'number') || (number && cb)) { if (cb === undefined) { cb = function() {}; } else if (typeof cb !== 'function') { throw new TypeError('Callback must be a function'); } this._consumeNum(timeoutMs, number, cb); } else { // See path_to_url // Docs specify just a callback can be provided but really we needed // a fallback to the number argument // @deprecated if (cb === undefined) { if (typeof number === 'function') { cb = number; } else { cb = function() {}; } } this._consumeLoop(timeoutMs, cb); } }; /** * Open a background thread and keep getting messages as fast * as we can. Should not be called directly, and instead should * be called using consume. * * @private * @see consume */ KafkaConsumer.prototype._consumeLoop = function(timeoutMs, cb) { var self = this; var retryReadInterval = this._consumeLoopTimeoutDelay; self._client.consumeLoop(timeoutMs, retryReadInterval, function readCallback(err, message, eofEvent, warning) { if (err) { // A few different types of errors here // but the two we do NOT care about are // time outs at least now // Broker no more messages will also not come here cb(LibrdKafkaError.create(err)); } else if (eofEvent) { self.emit('partition.eof', eofEvent); } else if (warning) { self.emit('warning', LibrdKafkaError.create(warning)); } else { /** * Data event. called whenever a message is received. * * @event KafkaConsumer#data * @type {KafkaConsumer~Message} */ self.emit('data', message); cb(err, message); } }); }; /** * Consume a number of messages and wrap in a try catch with * proper error reporting. Should not be called directly, * and instead should be called using consume. * * @private * @see consume */ KafkaConsumer.prototype._consumeNum = function(timeoutMs, numMessages, cb) { var self = this; this._client.consume(timeoutMs, numMessages, function(err, messages, eofEvents) { if (err) { err = LibrdKafkaError.create(err); if (cb) { cb(err); } return; } var currentEofEventsIndex = 0; function emitEofEventsFor(messageIndex) { while (currentEofEventsIndex < eofEvents.length && eofEvents[currentEofEventsIndex].messageIndex === messageIndex) { delete eofEvents[currentEofEventsIndex].messageIndex; self.emit('partition.eof', eofEvents[currentEofEventsIndex]) ++currentEofEventsIndex; } } emitEofEventsFor(-1); for (var i = 0; i < messages.length; i++) { self.emit('data', messages[i]); emitEofEventsFor(i); } emitEofEventsFor(messages.length); if (cb) { cb(null, messages); } }); }; /** * This callback returns the message read from Kafka. * * @callback KafkaConsumer~readCallback * @param {LibrdKafkaError} err - An error, if one occurred while reading * the data. * @param {KafkaConsumer~Message} message */ /** * Commit a topic partition or all topic partitions that have been read * * If you provide a topic partition, it will commit that. Otherwise, * it will commit all read offsets for all topic partitions. * * @param {object|array|null} - Topic partition object to commit, list of topic * partitions, or null if you want to commit all read offsets. * @throws When commit returns a non 0 error code * * @return {KafkaConsumer} - returns itself. */ KafkaConsumer.prototype.commit = function(topicPartition) { this._errorWrap(this._client.commit(topicPartition), true); return this; }; /** * Commit a message * * This is basically a convenience method to map commit properly. We need to * add one to the offset in this case * * @param {object} - Message object to commit * @throws When commit returns a non 0 error code * * @return {KafkaConsumer} - returns itself. */ KafkaConsumer.prototype.commitMessage = function(msg) { var topicPartition = { topic: msg.topic, partition: msg.partition, offset: msg.offset + 1 }; this._errorWrap(this._client.commit(topicPartition), true); return this; }; /** * Commit a topic partition (or all topic partitions) synchronously * * @param {object|array|null} - Topic partition object to commit, list of topic * partitions, or null if you want to commit all read offsets. * @throws {LibrdKafkaError} - if the commit fails * * @return {KafkaConsumer} - returns itself. */ KafkaConsumer.prototype.commitSync = function(topicPartition) { this._errorWrap(this._client.commitSync(topicPartition), true); return this; }; /** * Commit a message synchronously * * @see KafkaConsumer#commitMessageSync * @param {object} msg - A message object to commit. * * @throws {LibrdKafkaError} - if the commit fails * * @return {KafkaConsumer} - returns itself. */ KafkaConsumer.prototype.commitMessageSync = function(msg) { var topicPartition = { topic: msg.topic, partition: msg.partition, offset: msg.offset + 1 }; this._errorWrap(this._client.commitSync(topicPartition), true); return this; }; /** * Get last known offsets from the client. * * The low offset is updated periodically (if statistics.interval.ms is set) * while the high offset is updated on each fetched message set from the * broker. * * If there is no cached offset (either low or high, or both), then this will * throw an error. * * @param {string} topic - Topic to recieve offsets from. * @param {number} partition - Partition of the provided topic to recieve offsets from * @return {Client~watermarkOffsets} - Returns an object with a high and low property, specifying * the high and low offsets for the topic partition * @throws {LibrdKafkaError} - Throws when there is no offset stored */ KafkaConsumer.prototype.getWatermarkOffsets = function(topic, partition) { if (!this.isConnected()) { throw new Error('Client is disconnected'); } return this._errorWrap(this._client.getWatermarkOffsets(topic, partition), true); }; /** * Store offset for topic partition. * * The offset will be committed (written) to the offset store according to the auto commit interval, * if auto commit is on, or next manual offset if not. * * enable.auto.offset.store must be set to false to use this API, * * @see path_to_url#L1702 * * @param {Array.<TopicPartition>} topicPartitions - Topic partitions with offsets to store offsets for. * @throws {LibrdKafkaError} - Throws when there is no offset stored */ KafkaConsumer.prototype.offsetsStore = function(topicPartitions) { if (!this.isConnected()) { throw new Error('Client is disconnected'); } return this._errorWrap(this._client.offsetsStore(topicPartitions), true); }; /** * Resume consumption for the provided list of partitions. * * @param {Array.<TopicPartition>} topicPartitions - List of topic partitions to resume consumption on. * @throws {LibrdKafkaError} - Throws when there is no offset stored */ KafkaConsumer.prototype.resume = function(topicPartitions) { if (!this.isConnected()) { throw new Error('Client is disconnected'); } return this._errorWrap(this._client.resume(topicPartitions), true); }; /** * Pause producing or consumption for the provided list of partitions. * * @param {Array.<TopicPartition>} topicPartitions - List of topics to pause consumption on. * @throws {LibrdKafkaError} - Throws when there is no offset stored */ KafkaConsumer.prototype.pause = function(topicPartitions) { if (!this.isConnected()) { throw new Error('Client is disconnected'); } return this._errorWrap(this._client.pause(topicPartitions), true); }; ```
/content/code_sandbox/lib/kafka-consumer.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
4,825
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var util = module.exports = {}; util.shallowCopy = function (obj) { if (!util.isObject(obj)) { return obj; } var copy = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { copy[k] = obj[k]; } } return copy; }; util.isObject = function (obj) { return obj && typeof obj === 'object'; }; ```
/content/code_sandbox/lib/util.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
139
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var Topic = require('./topic'); module.exports = TopicPartition; /** * Map an array of topic partition js objects to real topic partition objects. * * @param array The array of topic partition raw objects to map to topic * partition objects */ TopicPartition.map = function(array) { return array.map(function(element) { return TopicPartition.create(element); }); }; /** * Take a topic partition javascript object and convert it to the class. * The class will automatically convert offset identifiers to special constants * * @param element The topic partition raw javascript object */ TopicPartition.create = function(element) { // Just ensure we take something that can have properties. The topic partition // class will element = element || {}; return new TopicPartition(element.topic, element.partition, element.offset); }; /** * Create a topic partition. Just does some validation and decoration * on topic partitions provided. * * Goal is still to behave like a plain javascript object but with validation * and potentially some extra methods */ function TopicPartition(topic, partition, offset) { if (!(this instanceof TopicPartition)) { return new TopicPartition(topic, partition, offset); } // Validate that the elements we are iterating over are actual topic partition // js objects. They do not need an offset, but they do need partition if (!topic) { throw new TypeError('"topic" must be a string and must be set'); } if (partition === null || partition === undefined) { throw new TypeError('"partition" must be a number and must set'); } // We can just set topic and partition as they stand. this.topic = topic; this.partition = partition; if (offset === undefined || offset === null) { this.offset = Topic.OFFSET_STORED; } else if (typeof offset === 'string') { switch (offset.toLowerCase()) { case 'earliest': case 'beginning': this.offset = Topic.OFFSET_BEGINNING; break; case 'latest': case 'end': this.offset = Topic.OFFSET_END; break; case 'stored': this.offset = Topic.OFFSET_STORED; break; default: throw new TypeError('"offset", if provided as a string, must be beginning, end, or stored.'); } } else if (typeof offset === 'number') { this.offset = offset; } else { throw new TypeError('"offset" must be a special string or number if it is set'); } } ```
/content/code_sandbox/lib/topic-partition.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
586
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ module.exports = Producer; var Client = require('./client'); var util = require('util'); var Kafka = require('../librdkafka.js'); var ProducerStream = require('./producer-stream'); var LibrdKafkaError = require('./error'); var shallowCopy = require('./util').shallowCopy; util.inherits(Producer, Client); /** * Producer class for sending messages to Kafka * * This is the main entry point for writing data to Kafka. You * configure this like you do any other client, with a global * configuration and default topic configuration. * * Once you instantiate this object, you need to connect to it first. * This allows you to get the metadata and make sure the connection * can be made before you depend on it. After that, problems with * the connection will by brought down by using poll, which automatically * runs when a transaction is made on the object. * * @param {object} conf - Key value pairs to configure the producer * @param {object} topicConf - Key value pairs to create a default * topic configuration * @extends Client * @constructor */ function Producer(conf, topicConf) { if (!(this instanceof Producer)) { return new Producer(conf, topicConf); } conf = shallowCopy(conf); topicConf = shallowCopy(topicConf); /** * Producer message. This is sent to the wrapper, not received from it * * @typedef {object} Producer~Message * @property {string|buffer} message - The buffer to send to Kafka. * @property {Topic} topic - The Kafka topic to produce to. * @property {number} partition - The partition to produce to. Defaults to * the partitioner * @property {string} key - The key string to use for the message. * @see Consumer~Message */ var gTopic = conf.topic || false; var gPart = conf.partition || null; var dr_cb = conf.dr_cb || null; var dr_msg_cb = conf.dr_msg_cb || null; // delete keys we don't want to pass on delete conf.topic; delete conf.partition; delete conf.dr_cb; delete conf.dr_msg_cb; // client is an initialized consumer object // @see NodeKafka::Producer::Init Client.call(this, conf, Kafka.Producer, topicConf); // Delete these keys after saving them in vars this.globalConfig = conf; this.topicConfig = topicConf; this.defaultTopic = gTopic || null; this.defaultPartition = gPart == null ? -1 : gPart; this.sentMessages = 0; this.pollInterval = undefined; if (dr_msg_cb || dr_cb) { this._cb_configs.event.delivery_cb = function(err, report) { if (err) { err = LibrdKafkaError.create(err); } this.emit('delivery-report', err, report); }.bind(this); this._cb_configs.event.delivery_cb.dr_msg_cb = !!dr_msg_cb; if (typeof dr_cb === 'function') { this.on('delivery-report', dr_cb); } } } /** * Produce a message to Kafka synchronously. * * This is the method mainly used in this class. Use it to produce * a message to Kafka. * * When this is sent off, there is no guarantee it is delivered. If you need * guaranteed delivery, change your *acks* settings, or use delivery reports. * * @param {string} topic - The topic name to produce to. * @param {number|null} partition - The partition number to produce to. * @param {Buffer|null} message - The message to produce. * @param {string} key - The key associated with the message. * @param {number|null} timestamp - Timestamp to send with the message. * @param {object} opaque - An object you want passed along with this message, if provided. * @param {object} headers - A list of custom key value pairs that provide message metadata. * @throws {LibrdKafkaError} - Throws a librdkafka error if it failed. * @return {boolean} - returns an error if it failed, or true if not * @see Producer#produce */ Producer.prototype.produce = function(topic, partition, message, key, timestamp, opaque, headers) { if (!this._isConnected) { throw new Error('Producer not connected'); } // I have removed support for using a topic object. It is going to be removed // from librdkafka soon, and it causes issues with shutting down if (!topic || typeof topic !== 'string') { throw new TypeError('"topic" must be a string'); } this.sentMessages++; partition = partition == null ? this.defaultPartition : partition; return this._errorWrap( this._client.produce(topic, partition, message, key, timestamp, opaque, headers)); }; /** * Create a write stream interface for a producer. * * This stream does not run in object mode. It only takes buffers of data. * * @param {object} conf - Key value pairs to configure the producer * @param {object} topicConf - Key value pairs to create a default * topic configuration * @param {object} streamOptions - Stream options * @return {ProducerStream} - returns the write stream for writing to Kafka. */ Producer.createWriteStream = function(conf, topicConf, streamOptions) { var producer = new Producer(conf, topicConf); return new ProducerStream(producer, streamOptions); }; /** * Poll for events * * We need to run poll in order to learn about new events that have occurred. * This is no longer done automatically when we produce, so we need to run * it manually, or set the producer to automatically poll. * * @return {Producer} - returns itself. */ Producer.prototype.poll = function() { if (!this._isConnected) { throw new Error('Producer not connected'); } this._client.poll(); return this; }; /** * Set automatic polling for events. * * We need to run poll in order to learn about new events that have occurred. * If you would like this done on an interval with disconnects and reconnections * managed, you can do it here * * @param {number} interval - Interval, in milliseconds, to poll * * @return {Producer} - returns itself. */ Producer.prototype.setPollInterval = function(interval) { // If we already have a poll interval we need to stop it if (this.pollInterval) { clearInterval(this.pollInterval); this.pollInterval = undefined; } if (interval === 0) { // If the interval was set to 0, bail out. We don't want to process this. // If there was an interval previously set, it has been removed. return; } var self = this; // Now we want to make sure we are connected. if (!this._isConnected) { // If we are not, execute this once the connection goes through. this.once('ready', function() { self.setPollInterval(interval); }); return; } // We know we are connected at this point. // Unref this interval this.pollInterval = setInterval(function() { try { self.poll(); } catch (e) { // We can probably ignore errors here as far as broadcasting. // Disconnection issues will get handled below } }, interval).unref(); // Handle disconnections this.once('disconnected', function() { // Just rerun this function with interval 0. If any // poll interval is set, this will remove it self.setPollInterval(0); }); return this; }; /** * Flush the producer * * Flush everything on the internal librdkafka producer buffer. Do this before * disconnects usually * * @param {number} timeout - Number of milliseconds to try to flush before giving up. * @param {function} callback - Callback to fire when the flush is done. * * @return {Producer} - returns itself. */ Producer.prototype.flush = function(timeout, callback) { if (!this._isConnected) { throw new Error('Producer not connected'); } if (timeout === undefined || timeout === null) { timeout = 500; } this._client.flush(timeout, function(err) { if (err) { err = LibrdKafkaError.create(err); } if (callback) { callback(err); } }); return this; }; /** * Save the base disconnect method here so we can overwrite it and add a flush */ Producer.prototype._disconnect = Producer.prototype.disconnect; /** * Disconnect the producer * * Flush everything on the internal librdkafka producer buffer. Then disconnect * * @param {number} timeout - Number of milliseconds to try to flush before giving up, defaults to 5 seconds. * @param {function} cb - The callback to fire when */ Producer.prototype.disconnect = function(timeout, cb) { var self = this; var timeoutInterval = 5000; if (typeof timeout === 'function') { cb = timeout; } else { timeoutInterval = timeout; } this.flush(timeoutInterval, function() { self._disconnect(cb); }); }; /** * Init a transaction. * * Initialize transactions, this is only performed once per transactional producer. * * @param {number} timeout - Number of milliseconds to try to initialize before giving up, defaults to 5 seconds. * @param {function} cb - Callback to return when operation is completed * @return {Producer} - returns itself. */ Producer.prototype.initTransactions = function(timeout, cb) { if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } this._client.initTransactions(timeout, function(err) { cb(err ? LibrdKafkaError.create(err) : err); }); }; /** * Begin a transaction. * * 'initTransaction' must have been called successfully (once) before this function is called. * * @return {Producer} - returns itself. */ Producer.prototype.beginTransaction = function(cb) { this._client.beginTransaction(function(err) { cb(err ? LibrdKafkaError.create(err) : err); }); }; /** * Commit the current transaction (as started with 'beginTransaction'). * * @param {number} timeout - Number of milliseconds to try to commit before giving up, defaults to 5 seconds * @param {function} cb - Callback to return when operation is completed * @return {Producer} - returns itself. */ Producer.prototype.commitTransaction = function(timeout, cb) { if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } this._client.commitTransaction(timeout, function(err) { cb(err ? LibrdKafkaError.create(err) : err); }); }; /** * Aborts the ongoing transaction. * * @param {number} timeout - Number of milliseconds to try to abort, defaults to 5 seconds * @param {function} cb - Callback to return when operation is completed * @return {Producer} - returns itself. */ Producer.prototype.abortTransaction = function(timeout, cb) { if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } this._client.abortTransaction(timeout, function(err) { cb(err ? LibrdKafkaError.create(err) : err); }); }; /** * Send the current offsets of the consumer to the ongoing transaction. * * @param {number} offsets - Offsets to send as part of the next commit * @param {Consumer} consumer - An instance of the consumer * @param {number} timeout - Number of milliseconds to try to send offsets, defaults to 5 seconds * @param {function} cb - Callback to return when operation is completed * @return {Producer} - returns itself. */ Producer.prototype.sendOffsetsToTransaction = function(offsets, consumer, timeout, cb) { if (typeof timeout === 'function') { cb = timeout; timeout = 5000; } this._client.sendOffsetsToTransaction(offsets, consumer.getClient(), timeout, function(err) { cb(err ? LibrdKafkaError.create(err) : err); }); }; ```
/content/code_sandbox/lib/producer.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
2,715
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ module.exports = LibrdKafkaError; var util = require('util'); var librdkafka = require('../librdkafka'); util.inherits(LibrdKafkaError, Error); LibrdKafkaError.create = createLibrdkafkaError; LibrdKafkaError.wrap = errorWrap; /** * Enum for identifying errors reported by the library * * You can find this list in the C++ code at * path_to_url#L148 * * @readonly * @enum {number} * @constant */ // ====== Generated from librdkafka 2.5.0 file src-cpp/rdkafkacpp.h ====== LibrdKafkaError.codes = { /* Internal errors to rdkafka: */ /** Begin internal error codes */ ERR__BEGIN: -200, /** Received message is incorrect */ ERR__BAD_MSG: -199, /** Bad/unknown compression */ ERR__BAD_COMPRESSION: -198, /** Broker is going away */ ERR__DESTROY: -197, /** Generic failure */ ERR__FAIL: -196, /** Broker transport failure */ ERR__TRANSPORT: -195, /** Critical system resource */ ERR__CRIT_SYS_RESOURCE: -194, /** Failed to resolve broker */ ERR__RESOLVE: -193, /** Produced message timed out*/ ERR__MSG_TIMED_OUT: -192, /** Reached the end of the topic+partition queue on * the broker. Not really an error. * This event is disabled by default, * see the `enable.partition.eof` configuration property. */ ERR__PARTITION_EOF: -191, /** Permanent: Partition does not exist in cluster. */ ERR__UNKNOWN_PARTITION: -190, /** File or filesystem error */ ERR__FS: -189, /** Permanent: Topic does not exist in cluster. */ ERR__UNKNOWN_TOPIC: -188, /** All broker connections are down. */ ERR__ALL_BROKERS_DOWN: -187, /** Invalid argument, or invalid configuration */ ERR__INVALID_ARG: -186, /** Operation timed out */ ERR__TIMED_OUT: -185, /** Queue is full */ ERR__QUEUE_FULL: -184, /** ISR count < required.acks */ ERR__ISR_INSUFF: -183, /** Broker node update */ ERR__NODE_UPDATE: -182, /** SSL error */ ERR__SSL: -181, /** Waiting for coordinator to become available. */ ERR__WAIT_COORD: -180, /** Unknown client group */ ERR__UNKNOWN_GROUP: -179, /** Operation in progress */ ERR__IN_PROGRESS: -178, /** Previous operation in progress, wait for it to finish. */ ERR__PREV_IN_PROGRESS: -177, /** This operation would interfere with an existing subscription */ ERR__EXISTING_SUBSCRIPTION: -176, /** Assigned partitions (rebalance_cb) */ ERR__ASSIGN_PARTITIONS: -175, /** Revoked partitions (rebalance_cb) */ ERR__REVOKE_PARTITIONS: -174, /** Conflicting use */ ERR__CONFLICT: -173, /** Wrong state */ ERR__STATE: -172, /** Unknown protocol */ ERR__UNKNOWN_PROTOCOL: -171, /** Not implemented */ ERR__NOT_IMPLEMENTED: -170, /** Authentication failure*/ ERR__AUTHENTICATION: -169, /** No stored offset */ ERR__NO_OFFSET: -168, /** Outdated */ ERR__OUTDATED: -167, /** Timed out in queue */ ERR__TIMED_OUT_QUEUE: -166, /** Feature not supported by broker */ ERR__UNSUPPORTED_FEATURE: -165, /** Awaiting cache update */ ERR__WAIT_CACHE: -164, /** Operation interrupted */ ERR__INTR: -163, /** Key serialization error */ ERR__KEY_SERIALIZATION: -162, /** Value serialization error */ ERR__VALUE_SERIALIZATION: -161, /** Key deserialization error */ ERR__KEY_DESERIALIZATION: -160, /** Value deserialization error */ ERR__VALUE_DESERIALIZATION: -159, /** Partial response */ ERR__PARTIAL: -158, /** Modification attempted on read-only object */ ERR__READ_ONLY: -157, /** No such entry / item not found */ ERR__NOENT: -156, /** Read underflow */ ERR__UNDERFLOW: -155, /** Invalid type */ ERR__INVALID_TYPE: -154, /** Retry operation */ ERR__RETRY: -153, /** Purged in queue */ ERR__PURGE_QUEUE: -152, /** Purged in flight */ ERR__PURGE_INFLIGHT: -151, /** Fatal error: see RdKafka::Handle::fatal_error() */ ERR__FATAL: -150, /** Inconsistent state */ ERR__INCONSISTENT: -149, /** Gap-less ordering would not be guaranteed if proceeding */ ERR__GAPLESS_GUARANTEE: -148, /** Maximum poll interval exceeded */ ERR__MAX_POLL_EXCEEDED: -147, /** Unknown broker */ ERR__UNKNOWN_BROKER: -146, /** Functionality not configured */ ERR__NOT_CONFIGURED: -145, /** Instance has been fenced */ ERR__FENCED: -144, /** Application generated error */ ERR__APPLICATION: -143, /** Assignment lost */ ERR__ASSIGNMENT_LOST: -142, /** No operation performed */ ERR__NOOP: -141, /** No offset to automatically reset to */ ERR__AUTO_OFFSET_RESET: -140, /** Partition log truncation detected */ ERR__LOG_TRUNCATION: -139, /** End internal error codes */ ERR__END: -100, /* Kafka broker errors: */ /** Unknown broker error */ ERR_UNKNOWN: -1, /** Success */ ERR_NO_ERROR: 0, /** Offset out of range */ ERR_OFFSET_OUT_OF_RANGE: 1, /** Invalid message */ ERR_INVALID_MSG: 2, /** Unknown topic or partition */ ERR_UNKNOWN_TOPIC_OR_PART: 3, /** Invalid message size */ ERR_INVALID_MSG_SIZE: 4, /** Leader not available */ ERR_LEADER_NOT_AVAILABLE: 5, /** Not leader for partition */ ERR_NOT_LEADER_FOR_PARTITION: 6, /** Request timed out */ ERR_REQUEST_TIMED_OUT: 7, /** Broker not available */ ERR_BROKER_NOT_AVAILABLE: 8, /** Replica not available */ ERR_REPLICA_NOT_AVAILABLE: 9, /** Message size too large */ ERR_MSG_SIZE_TOO_LARGE: 10, /** StaleControllerEpochCode */ ERR_STALE_CTRL_EPOCH: 11, /** Offset metadata string too large */ ERR_OFFSET_METADATA_TOO_LARGE: 12, /** Broker disconnected before response received */ ERR_NETWORK_EXCEPTION: 13, /** Coordinator load in progress */ ERR_COORDINATOR_LOAD_IN_PROGRESS: 14, /** Group coordinator load in progress */ ERR_GROUP_LOAD_IN_PROGRESS: 14, /** Coordinator not available */ ERR_COORDINATOR_NOT_AVAILABLE: 15, /** Group coordinator not available */ ERR_GROUP_COORDINATOR_NOT_AVAILABLE: 15, /** Not coordinator */ ERR_NOT_COORDINATOR: 16, /** Not coordinator for group */ ERR_NOT_COORDINATOR_FOR_GROUP: 16, /** Invalid topic */ ERR_TOPIC_EXCEPTION: 17, /** Message batch larger than configured server segment size */ ERR_RECORD_LIST_TOO_LARGE: 18, /** Not enough in-sync replicas */ ERR_NOT_ENOUGH_REPLICAS: 19, /** Message(s) written to insufficient number of in-sync replicas */ ERR_NOT_ENOUGH_REPLICAS_AFTER_APPEND: 20, /** Invalid required acks value */ ERR_INVALID_REQUIRED_ACKS: 21, /** Specified group generation id is not valid */ ERR_ILLEGAL_GENERATION: 22, /** Inconsistent group protocol */ ERR_INCONSISTENT_GROUP_PROTOCOL: 23, /** Invalid group.id */ ERR_INVALID_GROUP_ID: 24, /** Unknown member */ ERR_UNKNOWN_MEMBER_ID: 25, /** Invalid session timeout */ ERR_INVALID_SESSION_TIMEOUT: 26, /** Group rebalance in progress */ ERR_REBALANCE_IN_PROGRESS: 27, /** Commit offset data size is not valid */ ERR_INVALID_COMMIT_OFFSET_SIZE: 28, /** Topic authorization failed */ ERR_TOPIC_AUTHORIZATION_FAILED: 29, /** Group authorization failed */ ERR_GROUP_AUTHORIZATION_FAILED: 30, /** Cluster authorization failed */ ERR_CLUSTER_AUTHORIZATION_FAILED: 31, /** Invalid timestamp */ ERR_INVALID_TIMESTAMP: 32, /** Unsupported SASL mechanism */ ERR_UNSUPPORTED_SASL_MECHANISM: 33, /** Illegal SASL state */ ERR_ILLEGAL_SASL_STATE: 34, /** Unuspported version */ ERR_UNSUPPORTED_VERSION: 35, /** Topic already exists */ ERR_TOPIC_ALREADY_EXISTS: 36, /** Invalid number of partitions */ ERR_INVALID_PARTITIONS: 37, /** Invalid replication factor */ ERR_INVALID_REPLICATION_FACTOR: 38, /** Invalid replica assignment */ ERR_INVALID_REPLICA_ASSIGNMENT: 39, /** Invalid config */ ERR_INVALID_CONFIG: 40, /** Not controller for cluster */ ERR_NOT_CONTROLLER: 41, /** Invalid request */ ERR_INVALID_REQUEST: 42, /** Message format on broker does not support request */ ERR_UNSUPPORTED_FOR_MESSAGE_FORMAT: 43, /** Policy violation */ ERR_POLICY_VIOLATION: 44, /** Broker received an out of order sequence number */ ERR_OUT_OF_ORDER_SEQUENCE_NUMBER: 45, /** Broker received a duplicate sequence number */ ERR_DUPLICATE_SEQUENCE_NUMBER: 46, /** Producer attempted an operation with an old epoch */ ERR_INVALID_PRODUCER_EPOCH: 47, /** Producer attempted a transactional operation in an invalid state */ ERR_INVALID_TXN_STATE: 48, /** Producer attempted to use a producer id which is not * currently assigned to its transactional id */ ERR_INVALID_PRODUCER_ID_MAPPING: 49, /** Transaction timeout is larger than the maximum * value allowed by the broker's max.transaction.timeout.ms */ ERR_INVALID_TRANSACTION_TIMEOUT: 50, /** Producer attempted to update a transaction while another * concurrent operation on the same transaction was ongoing */ ERR_CONCURRENT_TRANSACTIONS: 51, /** Indicates that the transaction coordinator sending a * WriteTxnMarker is no longer the current coordinator for a * given producer */ ERR_TRANSACTION_COORDINATOR_FENCED: 52, /** Transactional Id authorization failed */ ERR_TRANSACTIONAL_ID_AUTHORIZATION_FAILED: 53, /** Security features are disabled */ ERR_SECURITY_DISABLED: 54, /** Operation not attempted */ ERR_OPERATION_NOT_ATTEMPTED: 55, /** Disk error when trying to access log file on the disk */ ERR_KAFKA_STORAGE_ERROR: 56, /** The user-specified log directory is not found in the broker config */ ERR_LOG_DIR_NOT_FOUND: 57, /** SASL Authentication failed */ ERR_SASL_AUTHENTICATION_FAILED: 58, /** Unknown Producer Id */ ERR_UNKNOWN_PRODUCER_ID: 59, /** Partition reassignment is in progress */ ERR_REASSIGNMENT_IN_PROGRESS: 60, /** Delegation Token feature is not enabled */ ERR_DELEGATION_TOKEN_AUTH_DISABLED: 61, /** Delegation Token is not found on server */ ERR_DELEGATION_TOKEN_NOT_FOUND: 62, /** Specified Principal is not valid Owner/Renewer */ ERR_DELEGATION_TOKEN_OWNER_MISMATCH: 63, /** Delegation Token requests are not allowed on this connection */ ERR_DELEGATION_TOKEN_REQUEST_NOT_ALLOWED: 64, /** Delegation Token authorization failed */ ERR_DELEGATION_TOKEN_AUTHORIZATION_FAILED: 65, /** Delegation Token is expired */ ERR_DELEGATION_TOKEN_EXPIRED: 66, /** Supplied principalType is not supported */ ERR_INVALID_PRINCIPAL_TYPE: 67, /** The group is not empty */ ERR_NON_EMPTY_GROUP: 68, /** The group id does not exist */ ERR_GROUP_ID_NOT_FOUND: 69, /** The fetch session ID was not found */ ERR_FETCH_SESSION_ID_NOT_FOUND: 70, /** The fetch session epoch is invalid */ ERR_INVALID_FETCH_SESSION_EPOCH: 71, /** No matching listener */ ERR_LISTENER_NOT_FOUND: 72, /** Topic deletion is disabled */ ERR_TOPIC_DELETION_DISABLED: 73, /** Leader epoch is older than broker epoch */ ERR_FENCED_LEADER_EPOCH: 74, /** Leader epoch is newer than broker epoch */ ERR_UNKNOWN_LEADER_EPOCH: 75, /** Unsupported compression type */ ERR_UNSUPPORTED_COMPRESSION_TYPE: 76, /** Broker epoch has changed */ ERR_STALE_BROKER_EPOCH: 77, /** Leader high watermark is not caught up */ ERR_OFFSET_NOT_AVAILABLE: 78, /** Group member needs a valid member ID */ ERR_MEMBER_ID_REQUIRED: 79, /** Preferred leader was not available */ ERR_PREFERRED_LEADER_NOT_AVAILABLE: 80, /** Consumer group has reached maximum size */ ERR_GROUP_MAX_SIZE_REACHED: 81, /** Static consumer fenced by other consumer with same * group.instance.id. */ ERR_FENCED_INSTANCE_ID: 82, /** Eligible partition leaders are not available */ ERR_ELIGIBLE_LEADERS_NOT_AVAILABLE: 83, /** Leader election not needed for topic partition */ ERR_ELECTION_NOT_NEEDED: 84, /** No partition reassignment is in progress */ ERR_NO_REASSIGNMENT_IN_PROGRESS: 85, /** Deleting offsets of a topic while the consumer group is * subscribed to it */ ERR_GROUP_SUBSCRIBED_TO_TOPIC: 86, /** Broker failed to validate record */ ERR_INVALID_RECORD: 87, /** There are unstable offsets that need to be cleared */ ERR_UNSTABLE_OFFSET_COMMIT: 88, /** Throttling quota has been exceeded */ ERR_THROTTLING_QUOTA_EXCEEDED: 89, /** There is a newer producer with the same transactionalId * which fences the current one */ ERR_PRODUCER_FENCED: 90, /** Request illegally referred to resource that does not exist */ ERR_RESOURCE_NOT_FOUND: 91, /** Request illegally referred to the same resource twice */ ERR_DUPLICATE_RESOURCE: 92, /** Requested credential would not meet criteria for acceptability */ ERR_UNACCEPTABLE_CREDENTIAL: 93, /** Indicates that the either the sender or recipient of a * voter-only request is not one of the expected voters */ ERR_INCONSISTENT_VOTER_SET: 94, /** Invalid update version */ ERR_INVALID_UPDATE_VERSION: 95, /** Unable to update finalized features due to server error */ ERR_FEATURE_UPDATE_FAILED: 96, /** Request principal deserialization failed during forwarding */ ERR_PRINCIPAL_DESERIALIZATION_FAILURE: 97 }; /** * Representation of a librdkafka error * * This can be created by giving either another error * to piggy-back on. In this situation it tries to parse * the error string to figure out the intent. However, more usually, * it is constructed by an error object created by a C++ Baton. * * @param {object|error} e - An object or error to wrap * @property {string} message - The error message * @property {number} code - The error code. * @property {string} origin - The origin, whether it is local or remote * @constructor */ function LibrdKafkaError(e) { if (!(this instanceof LibrdKafkaError)) { return new LibrdKafkaError(e); } if (typeof e === 'number') { this.message = librdkafka.err2str(e); this.code = e; this.errno = e; if (e >= LibrdKafkaError.codes.ERR__END) { this.origin = 'local'; } else { this.origin = 'kafka'; } Error.captureStackTrace(this, this.constructor); } else if (!util.isError(e)) { // This is the better way this.message = e.message; this.code = e.code; this.errno = e.code; if (e.code >= LibrdKafkaError.codes.ERR__END) { this.origin = 'local'; } else { this.origin = 'kafka'; } Error.captureStackTrace(this, this.constructor); } else { var message = e.message; var parsedMessage = message.split(': '); var origin, msg; if (parsedMessage.length > 1) { origin = parsedMessage[0].toLowerCase(); msg = parsedMessage[1].toLowerCase(); } else { origin = 'unknown'; msg = message.toLowerCase(); } // special cases if (msg === 'consumer is disconnected' || msg === 'producer is disconnected') { this.origin = 'local'; this.code = LibrdKafkaError.codes.ERR__STATE; this.errno = this.code; this.message = msg; } else { this.origin = origin; this.message = msg; this.code = typeof e.code === 'number' ? e.code : -1; this.errno = this.code; this.stack = e.stack; } } if (e.hasOwnProperty('isFatal')) this.isFatal = e.isFatal; if (e.hasOwnProperty('isRetriable')) this.isRetriable = e.isRetriable; if (e.hasOwnProperty('isTxnRequiresAbort')) this.isTxnRequiresAbort = e.isTxnRequiresAbort; } function createLibrdkafkaError(e) { return new LibrdKafkaError(e); } function errorWrap(errorCode, intIsError) { var returnValue = true; if (intIsError) { returnValue = errorCode; errorCode = typeof errorCode === 'number' ? errorCode : 0; } if (errorCode !== LibrdKafkaError.codes.ERR_NO_ERROR) { var e = LibrdKafkaError.create(errorCode); throw e; } return returnValue; } ```
/content/code_sandbox/lib/error.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
4,076
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ module.exports = Client; var Emitter = require('events').EventEmitter; var util = require('util'); var Kafka = require('../librdkafka.js'); var assert = require('assert'); var LibrdKafkaError = require('./error'); util.inherits(Client, Emitter); /** * Base class for Consumer and Producer * * This should not be created independently, but rather is * the base class on which both producer and consumer * get their common functionality. * * @param {object} globalConf - Global configuration in key value pairs. * @param {function} SubClientType - The function representing the subclient * type. In C++ land this needs to be a class that inherits from Connection. * @param {object} topicConf - Topic configuration in key value pairs * @constructor * @extends Emitter */ function Client(globalConf, SubClientType, topicConf) { if (!(this instanceof Client)) { return new Client(globalConf, SubClientType, topicConf); } Emitter.call(this); // This superclass must be initialized with the Kafka.{Producer,Consumer} // @example var client = new Client({}, Kafka.Producer); // remember this is a superclass so this will get taken care of in // the producer and consumer main wrappers var no_event_cb = globalConf.event_cb === false; topicConf = topicConf || {}; // delete this because librdkafka will complain since this particular // key is a real conf value delete globalConf.event_cb; this._client = new SubClientType(globalConf, topicConf); var extractFunctions = function(obj) { obj = obj || {}; var obj2 = {}; for (var p in obj) { if (typeof obj[p] === "function") { obj2[p] = obj[p]; } } return obj2; } this._cb_configs = { global: extractFunctions(globalConf), topic: extractFunctions(topicConf), event: {}, } if (!no_event_cb) { this._cb_configs.event.event_cb = function(eventType, eventData) { switch (eventType) { case 'error': this.emit('event.error', LibrdKafkaError.create(eventData)); break; case 'stats': this.emit('event.stats', eventData); break; case 'log': this.emit('event.log', eventData); break; default: this.emit('event.event', eventData); this.emit('event.' + eventType, eventData); } }.bind(this); } this.metrics = {}; this._isConnected = false; this.errorCounter = 0; /** * Metadata object. Starts out empty but will be filled with information after * the initial connect. * * @type {Client~Metadata} */ this._metadata = {}; var self = this; this.on('ready', function(info) { self.metrics.connectionOpened = Date.now(); self.name = info.name; }) .on('disconnected', function() { // reset metrics self.metrics = {}; self._isConnected = false; // keep the metadata. it still may be useful }) .on('event.error', function(err) { self.lastError = err; ++self.errorCounter; }); } /** * Connect to the broker and receive its metadata. * * Connects to a broker by establishing the client and fetches its metadata. * * @param {object} metadataOptions - Options to be sent to the metadata. * @param {string} metadataOptions.topic - Topic to fetch metadata for. Empty string is treated as empty. * @param {boolean} metadataOptions.allTopics - Fetch metadata for all topics, not just the ones we know about. * @param {int} metadataOptions.timeout - The timeout, in ms, to allow for fetching metadata. Defaults to 30000ms * @param {Client~connectionCallback} cb - Callback that indicates we are * done connecting. * @return {Client} - Returns itself. */ Client.prototype.connect = function(metadataOptions, cb) { var self = this; var next = function(err, data) { self._isConnecting = false; if (cb) { cb(err, data); } }; if (this._isConnected) { setImmediate(next); return self; } if (this._isConnecting) { this.once('ready', function() { next(null, this._metadata); }); return self; } this._isConnecting = true; var fail = function(err) { var callbackCalled = false; var t; if (self._isConnected) { self._isConnected = false; self._client.disconnect(function() { if (callbackCalled) { return; } clearTimeout(t); callbackCalled = true; next(err); return; }); // don't take too long. this is a failure, after all t = setTimeout(function() { if (callbackCalled) { return; } callbackCalled = true; next(err); return; }, 10000).unref(); self.emit('connection.failure', err, self.metrics); } else { next(err); } }; this._client.configureCallbacks(true, this._cb_configs); this._client.connect(function(err, info) { if (err) { fail(LibrdKafkaError.create(err)); return; } self._isConnected = true; // Otherwise we are successful self.getMetadata(metadataOptions || {}, function(err, metadata) { if (err) { // We are connected so we need to disconnect fail(LibrdKafkaError.create(err)); return; } self._isConnecting = false; // We got the metadata otherwise. It is set according to above param // Set it here as well so subsequent ready callbacks // can check it self._isConnected = true; /** * Ready event. Called when the Client connects successfully * * @event Client#ready * @type {object} * @property {string} name - the name of the broker. */ self.emit('ready', info, metadata); next(null, metadata); return; }); }); return self; }; /** * Set initial token before any connection is established for oauthbearer authentication flow. * Expiry is always set to maximum value, as the callback of librdkafka * for token refresh is not used. * Call this method again to refresh the token. * * @param {string} tokenStr - OAuthBearer token string * @see connection.cc * @return {Client} - Returns itself. */ Client.prototype.setOauthBearerToken = function (tokenStr) { if (!tokenStr || typeof tokenStr !== 'string') { throw new Error("OAuthBearer token is undefined/empty or not a string"); } this._client.setToken(tokenStr); return this; }; /** * Get the native Kafka client. * * You probably shouldn't use this, but if you want to execute methods directly * on the c++ wrapper you can do it here. * * @see connection.cc * @return {Connection} - The native Kafka client. */ Client.prototype.getClient = function() { return this._client; }; /** * Find out how long we have been connected to Kafka. * * @return {number} - Milliseconds since the connection has been established. */ Client.prototype.connectedTime = function() { if (!this.isConnected()) { return 0; } return Date.now() - this.metrics.connectionOpened; }; /** * Whether or not we are connected to Kafka. * * @return {boolean} - Whether we are connected. */ Client.prototype.isConnected = function() { return !!(this._isConnected && this._client); }; /** * Get the last error emitted if it exists. * * @return {LibrdKafkaError} - Returns the LibrdKafkaError or null if * one hasn't been thrown. */ Client.prototype.getLastError = function() { return this.lastError || null; }; /** * Disconnect from the Kafka client. * * This method will disconnect us from Kafka unless we are already in a * disconnecting state. Use this when you're done reading or producing messages * on a given client. * * It will also emit the disconnected event. * * @fires Client#disconnected * @return {function} - Callback to call when disconnection is complete. */ Client.prototype.disconnect = function(cb) { var self = this; if (!this._isDisconnecting && this._client) { this._isDisconnecting = true; this._client.disconnect(function() { // this take 5000 milliseconds. Librdkafka needs to make sure the memory // has been cleaned up before we delete things. @see RdKafka::wait_destroyed self._client.configureCallbacks(false, self._cb_configs); // Broadcast metrics. Gives people one last chance to do something with them self._isDisconnecting = false; /** * Disconnect event. Called after disconnection is finished. * * @event Client#disconnected * @type {object} * @property {date} connectionOpened - when the connection was opened. */ var metricsCopy = Object.assign({}, self.metrics); self.emit('disconnected', metricsCopy); if (cb) { cb(null, metricsCopy); } }); } return self; }; /** * Get client metadata. * * Note: using a <code>metadataOptions.topic</code> parameter has a potential side-effect. * A Topic object will be created, if it did not exist yet, with default options * and it will be cached by librdkafka. * * A subsequent call to create the topic object with specific options (e.g. <code>acks</code>) will return * the previous instance and the specific options will be silently ignored. * * To avoid this side effect, the topic object can be created with the expected options before requesting metadata, * or the metadata request can be performed for all topics (by omitting <code>metadataOptions.topic</code>). * * @param {object} metadataOptions - Metadata options to pass to the client. * @param {string} metadataOptions.topic - Topic string for which to fetch * metadata * @param {number} metadataOptions.timeout - Max time, in ms, to try to fetch * metadata before timing out. Defaults to 3000. * @param {Client~metadataCallback} cb - Callback to fire with the metadata. */ Client.prototype.getMetadata = function(metadataOptions, cb) { if (!this.isConnected()) { return cb(new Error('Client is disconnected')); } var self = this; this._client.getMetadata(metadataOptions || {}, function(err, metadata) { if (err) { if (cb) { cb(LibrdKafkaError.create(err)); } return; } // No error otherwise self._metadata = metadata; if (cb) { cb(null, metadata); } }); }; /** * Query offsets from the broker. * * This function makes a call to the broker to get the current low (oldest/beginning) * and high (newest/end) offsets for a topic partition. * * @param {string} topic - Topic to recieve offsets from. * @param {number} partition - Partition of the provided topic to recieve offsets from * @param {number} timeout - Number of ms to wait to recieve a response. * @param {Client~watermarkOffsetsCallback} cb - Callback to fire with the offsets. */ Client.prototype.queryWatermarkOffsets = function(topic, partition, timeout, cb) { if (!this.isConnected()) { if (cb) { return cb(new Error('Client is disconnected')); } else { return; } } var self = this; if (typeof timeout === 'function') { cb = timeout; timeout = 1000; } if (!timeout) { timeout = 1000; } this._client.queryWatermarkOffsets(topic, partition, timeout, function(err, offsets) { if (err) { if (cb) { cb(LibrdKafkaError.create(err)); } return; } if (cb) { cb(null, offsets); } }); }; /** * Query offsets for times from the broker. * * This function makes a call to the broker to get the offsets for times specified. * * @param {TopicPartition[]} toppars - Array of topic partitions. The offset in these * should instead refer to a timestamp you want * offsets for * @param {number} timeout - Number of ms to wait to recieve a response. * @param {Client~offsetsForTimesCallback} cb - Callback to fire with the filled in offsets. */ Client.prototype.offsetsForTimes = function(toppars, timeout, cb) { if (!this.isConnected()) { if (cb) { return cb(new Error('Client is disconnected')); } else { return; } } var self = this; if (typeof timeout === 'function') { cb = timeout; timeout = 1000; } if (!timeout) { timeout = 1000; } this._client.offsetsForTimes(toppars, timeout, function(err, toppars) { if (err) { if (cb) { cb(LibrdKafkaError.create(err)); } return; } if (cb) { cb(null, toppars); } }); }; /** * Wrap a potential RdKafka error. * * This internal method is meant to take a return value * from a function that returns an RdKafka error code, throw if it * is an error (Making it a proper librdkafka error object), or * return the appropriate value otherwise. * * It is intended to be used in a return statement, * * @private * @param {number} errorCode - Error code returned from a native method * @param {bool} intIsError - If specified true, any non-number return type will be classified as a success * @return {boolean} - Returns true or the method return value unless it throws. */ Client.prototype._errorWrap = function(errorCode, intIsError) { var returnValue = true; if (intIsError) { returnValue = errorCode; errorCode = typeof errorCode === 'number' ? errorCode : 0; } if (errorCode !== LibrdKafkaError.codes.ERR_NO_ERROR) { var e = LibrdKafkaError.create(errorCode); throw e; } return returnValue; }; /** * This callback is used to pass metadata or an error after a successful * connection * * @callback Client~connectionCallback * @param {Error} err - An error, if one occurred while connecting. * @param {Client~Metadata} metadata - Metadata object. */ /** * This callback is used to pass offsets or an error after a successful * query * * @callback Client~watermarkOffsetsCallback * @param {Error} err - An error, if one occurred while connecting. * @param {Client~watermarkOffsets} offsets - Watermark offsets */ /** * This callback is used to pass toppars or an error after a successful * times query * * @callback Client~offsetsForTimesCallback * @param {Error} err - An error, if one occurred while connecting. * @param {TopicPartition[]} toppars - Topic partitions with offsets filled in */ /** * @typedef {object} Client~watermarkOffsets * @property {number} high - High (newest/end) offset * @property {number} low - Low (oldest/beginning) offset */ /** * @typedef {object} Client~MetadataBroker * @property {number} id - Broker ID * @property {string} host - Broker host * @property {number} port - Broker port. */ /** * @typedef {object} Client~MetadataTopic * @property {string} name - Topic name * @property {Client~MetadataPartition[]} partitions - Array of partitions */ /** * @typedef {object} Client~MetadataPartition * @property {number} id - Partition id * @property {number} leader - Broker ID for the partition leader * @property {number[]} replicas - Array of replica IDs * @property {number[]} isrs - Arrqay of ISRS ids */ /** * Metadata object. * * This is the representation of Kafka metadata in JavaScript. * * @typedef {object} Client~Metadata * @property {number} orig_broker_id - The broker ID of the original bootstrap * broker. * @property {string} orig_broker_name - The name of the original bootstrap * broker. * @property {Client~MetadataBroker[]} brokers - An array of broker objects * @property {Client~MetadataTopic[]} topics - An array of topics. */ ```
/content/code_sandbox/lib/client.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
3,765
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ 'use strict'; module.exports = KafkaConsumerStream; var Readable = require('stream').Readable; var util = require('util'); util.inherits(KafkaConsumerStream, Readable); /** * ReadableStream integrating with the Kafka Consumer. * * This class is used to read data off of Kafka in a streaming way. It is * useful if you'd like to have a way to pipe Kafka into other systems. You * should generally not make this class yourself, as it is not even exposed * as part of module.exports. Instead, you should KafkaConsumer.createReadStream. * * The stream implementation is slower than the continuous subscribe callback. * If you don't care so much about backpressure and would rather squeeze * out performance, use that method. Using the stream will ensure you read only * as fast as you write. * * The stream detects if Kafka is already connected. If it is, it will begin * reading. If it is not, it will connect and read when it is ready. * * This stream operates in objectMode. It streams {Consumer~Message} * * @param {Consumer} consumer - The Kafka Consumer object. * @param {object} options - Options to configure the stream. * @param {number} options.waitInterval - Number of ms to wait if Kafka reports * that it has timed out or that we are out of messages (right now). * @param {array} options.topics - Array of topics, or a function that parses * metadata into an array of topics * @constructor * @extends stream.Readable * @see Consumer~Message */ function KafkaConsumerStream(consumer, options) { if (!(this instanceof KafkaConsumerStream)) { return new KafkaConsumerStream(consumer, options); } if (options === undefined) { options = { waitInterval: 1000 }; } else if (typeof options === 'number') { options = { waitInterval: options }; } else if (options === null || typeof options !== 'object') { throw new TypeError('"options" argument must be a number or an object'); } var topics = options.topics; if (typeof topics === 'function') { // Just ignore the rest of the checks here } else if (!Array.isArray(topics)) { if (typeof topics !== 'string' && !(topics instanceof RegExp)) { throw new TypeError('"topics" argument must be a string, regex, or an array'); } else { topics = [topics]; } } options = Object.create(options); var fetchSize = options.fetchSize || 1; // Run in object mode by default. if (options.objectMode === null || options.objectMode === undefined) { options.objectMode = true; // If they did not explicitly set high water mark, and we are running // in object mode, set it to the fetch size + 2 to ensure there is room // for a standard fetch if (!options.highWaterMark) { options.highWaterMark = fetchSize + 2; } } if (options.objectMode !== true) { this._read = this._read_buffer; } else { this._read = this._read_message; } Readable.call(this, options); this.consumer = consumer; this.topics = topics; this.autoClose = options.autoClose === undefined ? true : !!options.autoClose; this.waitInterval = options.waitInterval === undefined ? 1000 : options.waitInterval; this.fetchSize = fetchSize; this.connectOptions = options.connectOptions || {}; this.streamAsBatch = options.streamAsBatch || false; // Hold the messages in here this.messages = []; var self = this; this.consumer .on('unsubscribed', function() { // Invalidate the stream when we unsubscribe self.push(null); }); if (options.initOauthBearerToken) { this.consumer.setOauthBearerToken(options.initOauthBearerToken); } // Call connect. Handles potentially being connected already this.connect(this.connectOptions); this.once('end', function() { if (this.autoClose) { this.destroy(); } }); } /** * Refresh OAuthBearer token, initially provided in factory method. * Expiry is always set to maximum value, as the callback of librdkafka * for token refresh is not used. * * @param {string} tokenStr - OAuthBearer token string * @see connection.cc */ KafkaConsumerStream.prototype.refreshOauthBearerToken = function (tokenStr) { this.consumer.setOauthBearerToken(tokenStr); }; /** * Internal stream read method. This method reads message objects. * @param {number} size - This parameter is ignored for our cases. * @private */ KafkaConsumerStream.prototype._read_message = function(size) { if (this.messages.length > 0) { return this.push(this.messages.shift()); } if (!this.consumer) { // This consumer is set to `null` in the close function return; } if (!this.consumer.isConnected()) { this.consumer.once('ready', function() { // This is the way Node.js does it // path_to_url#L1733 this._read(size); }.bind(this)); return; } if (this.destroyed) { return; } var self = this; // If the size (number of messages) we are being advised to fetch is // greater than or equal to the fetch size, use the fetch size. // Only opt to use the size in case it is LESS than the fetch size. // Essentially, we want to use the smaller value here var fetchSize = size >= this.fetchSize ? this.fetchSize : size; this.consumer.consume(fetchSize, onread); // Retry function. Will wait up to the wait interval, with some // random noise if one is provided. Otherwise, will go immediately. function retry() { if (!self.waitInterval) { setImmediate(function() { self._read(size); }); } else { setTimeout(function() { self._read(size); }, self.waitInterval * Math.random()).unref(); } } function onread(err, messages) { // If there was an error we still want to emit it. // Essentially, if the user does not register an error // handler, it will still cause the stream to blow up. // // But... if one is provided, consumption will move on // as normal if (err) { self.emit('error', err); } // If there are no messages it means we reached EOF or a timeout. // Do what we used to do if (err || messages.length < 1) { // If we got an error or if there were no messages, initiate a retry retry(); return; } else { if (self.streamAsBatch) { self.push(messages); } else { for (var i = 0; i < messages.length; i++) { self.messages.push(messages[i]); } // Now that we have added them all the inner messages buffer, // we can just push the most recent one self.push(self.messages.shift()); } } } }; /** * Internal stream read method. This method reads message buffers. * @param {number} size - This parameter is ignored for our cases. * @private */ KafkaConsumerStream.prototype._read_buffer = function(size) { if (this.messages.length > 0) { return this.push(this.messages.shift()); } if (!this.consumer) { // This consumer is set to `null` in the close function return; } if (!this.consumer.isConnected()) { this.consumer.once('ready', function() { // This is the way Node.js does it // path_to_url#L1733 this._read(size); }.bind(this)); return; } if (this.destroyed) { return; } var self = this; // If the size (number of messages) we are being advised to fetch is // greater than or equal to the fetch size, use the fetch size. // Only opt to use the size in case it is LESS than the fetch size. // Essentially, we want to use the smaller value here var fetchSize = size >= this.fetchSize ? this.fetchSize : size; this.consumer.consume(fetchSize, onread); // Retry function. Will wait up to the wait interval, with some // random noise if one is provided. Otherwise, will go immediately. function retry() { if (!self.waitInterval) { setImmediate(function() { self._read(size); }); } else { setTimeout(function() { self._read(size); }, self.waitInterval * Math.random()).unref(); } } function onread(err, messages) { // If there was an error we still want to emit it. // Essentially, if the user does not register an error // handler, it will still cause the stream to blow up. // // But... if one is provided, consumption will move on // as normal if (err) { self.emit('error', err); } // If there are no messages it means we reached EOF or a timeout. // Do what we used to do if (err || messages.length < 1) { // If we got an error or if there were no messages, initiate a retry retry(); return; } else { if (self.streamAsBatch) { self.push(messages); } else { for (var i = 0; i < messages.length; i++) { self.messages.push(messages[i].value); } // Now that we have added them all the inner messages buffer, // we can just push the most recent one self.push(self.messages.shift()); } } } }; KafkaConsumerStream.prototype.connect = function(options) { var self = this; function connectCallback(err, metadata) { if (err) { self.emit('error', err); self.destroy(); return; } try { // Subscribe to the topics as well so we will be ready // If this throws the stream is invalid // This is the magic part. If topics is a function, before we subscribe, // pass the metadata in if (typeof self.topics === 'function') { var topics = self.topics(metadata); self.consumer.subscribe(topics); } else { self.consumer.subscribe(self.topics); } } catch (e) { self.emit('error', e); self.destroy(); return; } // start the flow of data self.read(); } if (!this.consumer.isConnected()) { self.consumer.connect(options, connectCallback); } else { // Immediately call the connect callback setImmediate(function() { connectCallback(null, self.consumer._metadata); }); } }; KafkaConsumerStream.prototype.destroy = function() { if (this.destroyed) { return; } this.destroyed = true; this.close(); }; KafkaConsumerStream.prototype.close = function(cb) { var self = this; if (cb) { this.once('close', cb); } if (!self.consumer._isConnecting && !self.consumer._isConnected) { // If we aren't even connected just exit. We are done. close(); return; } if (self.consumer._isConnecting) { self.consumer.once('ready', function() { // Don't pass the CB because it has already been passed. self.close(); }); return; } if (self.consumer._isConnected) { self.consumer.unsubscribe(); self.consumer.disconnect(function() { close(); }); } function close() { self.emit('close'); } }; ```
/content/code_sandbox/lib/kafka-consumer-stream.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
2,641
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ module.exports = HighLevelProducer; var util = require('util'); var Producer = require('../producer'); var LibrdKafkaError = require('../error'); var EventEmitter = require('events').EventEmitter; var RefCounter = require('../tools/ref-counter'); var shallowCopy = require('../util').shallowCopy; var isObject = require('../util').isObject; util.inherits(HighLevelProducer, Producer); var noopSerializer = createSerializer(function (v) { return v; }); /** * Create a serializer * * Method simply wraps a serializer provided by a user * so it adds context to the error * * @returns {function} Serialization function */ function createSerializer(serializer) { var applyFn = function serializationWrapper(v, cb) { try { return cb ? serializer(v, cb) : serializer(v); } catch (e) { var modifiedError = new Error('Could not serialize value: ' + e.message); modifiedError.value = v; modifiedError.serializer = serializer; throw modifiedError; } }; // We can check how many parameters the function has and activate the asynchronous // operation if the number of parameters the function accepts is > 1 return { apply: applyFn, async: serializer.length > 1 }; } /** * Producer class for sending messages to Kafka in a higher level fashion * * This is the main entry point for writing data to Kafka if you want more * functionality than librdkafka supports out of the box. You * configure this like you do any other client, with a global * configuration and default topic configuration. * * Once you instantiate this object, you need to connect to it first. * This allows you to get the metadata and make sure the connection * can be made before you depend on it. After that, problems with * the connection will by brought down by using poll, which automatically * runs when a transaction is made on the object. * * This has a few restrictions, so it is not for free! * * 1. You may not define opaque tokens * The higher level producer is powered by opaque tokens. * 2. Every message ack will dispatch an event on the node thread. * 3. Will use a ref counter to determine if there are outgoing produces. * * This will return the new object you should use instead when doing your * produce calls * * @param {object} conf - Key value pairs to configure the producer * @param {object} topicConf - Key value pairs to create a default * topic configuration * @extends Producer * @constructor */ function HighLevelProducer(conf, topicConf) { if (!(this instanceof HighLevelProducer)) { return new HighLevelProducer(conf, topicConf); } // Force this to be true for the high level producer conf = shallowCopy(conf); conf.dr_cb = true; // producer is an initialized consumer object // @see NodeKafka::Producer::Init Producer.call(this, conf, topicConf); var self = this; // Add a delivery emitter to the producer this._hl = { deliveryEmitter: new EventEmitter(), messageId: 0, // Special logic for polling. We use a reference counter to know when we need // to be doing it and when we can stop. This means when we go into fast polling // mode we don't need to do multiple calls to poll since they all will yield // the same result pollingRefTimeout: null, }; // Add the polling ref counter to the class which ensures we poll when we go active this._hl.pollingRef = new RefCounter(function() { self._hl.pollingRefTimeout = setInterval(function() { try { self.poll(); } catch (e) { if (!self._isConnected) { // If we got disconnected for some reason there is no point // in polling anymore clearInterval(self._hl.pollingRefTimeout); } } }, 1); }, function() { clearInterval(self._hl.pollingRefTimeout); }); // Default poll interval. More sophisticated polling is also done in create rule method this.setPollInterval(1000); // Listen to all delivery reports to propagate elements with a _message_id to the emitter this.on('delivery-report', function(err, report) { if (report.opaque && report.opaque.__message_id !== undefined) { self._hl.deliveryEmitter.emit(report.opaque.__message_id, err, report.offset); } }); // Save old produce here since we are making some modifications for it this._oldProduce = this.produce; this.produce = this._modifiedProduce; // Serializer information this.keySerializer = noopSerializer; this.valueSerializer = noopSerializer; } /** * Produce a message to Kafka asynchronously. * * This is the method mainly used in this class. Use it to produce * a message to Kafka. * * When this is sent off, and you recieve your callback, the assurances afforded * to you will be equal to those provided by your ack level. * * @param {string} topic - The topic name to produce to. * @param {number|null} partition - The partition number to produce to. * @param {Buffer|null} message - The message to produce. * @param {string} key - The key associated with the message. * @param {number|null} timestamp - Timestamp to send with the message. * @param {object} headers - A list of custom key value pairs that provide message metadata. * @param {function} callback - Callback to call when the delivery report is recieved. * @throws {LibrdKafkaError} - Throws a librdkafka error if it failed. * @return {boolean} - returns an error if it failed, or true if not * @see Producer#produce */ HighLevelProducer.prototype._modifiedProduce = function(topic, partition, message, key, timestamp, headers, callback) { // headers are optional if (arguments.length === 6) { callback = headers; headers = undefined; } // Add the message id var opaque = { __message_id: this._hl.messageId++, }; this._hl.pollingRef.increment(); var self = this; var resolvedSerializedValue; var resolvedSerializedKey; var calledBack = false; // Actually do the produce with new key and value based on deserialized // results function doProduce(v, k) { try { var r = self._oldProduce(topic, partition, v, k, timestamp, opaque, headers); self._hl.deliveryEmitter.once(opaque.__message_id, function(err, offset) { self._hl.pollingRef.decrement(); setImmediate(function() { // Offset must be greater than or equal to 0 otherwise it is a null offset // Possibly because we have acks off callback(err, offset >= 0 ? offset : null); }); }); return r; } catch (e) { callback(e); } } function produceIfComplete() { if (resolvedSerializedKey !== undefined && resolvedSerializedValue !== undefined) { doProduce(resolvedSerializedValue, resolvedSerializedKey); } } // To run on a promise if returned by the serializer function finishSerializedValue(v) { if (!calledBack) { resolvedSerializedValue = v; produceIfComplete(); } } // To run on a promise of returned by the serializer function finishSerializedKey(k) { resolvedSerializedKey = k; if (!calledBack) { produceIfComplete(); } } function failSerializedValue(err) { if (!calledBack) { calledBack = true; callback(err); } } function failSerializedKey(err) { if (!calledBack) { calledBack = true; callback(err); } } function valueSerializerCallback(err, v) { if (err) { failSerializedValue(err); } else { finishSerializedValue(v); } } function keySerializerCallback(err, v) { if (err) { failSerializedKey(err); } else { finishSerializedKey(v); } } try { if (this.valueSerializer.async) { // If this is async we need to give it a callback this.valueSerializer.apply(message, valueSerializerCallback); } else { var serializedValue = this.valueSerializer.apply(message); // Check if we were returned a promise in order to support promise behavior if (serializedValue && typeof serializedValue.then === 'function' && typeof serializedValue.catch === 'function') { // This is a promise. We need to hook into its then and catch serializedValue.then(finishSerializedValue).catch(failSerializedValue); } else { resolvedSerializedValue = serializedValue; } } if (this.keySerializer.async) { // If this is async we need to give it a callback this.keySerializer.apply(key, keySerializerCallback); } else { var serializedKey = this.keySerializer.apply(key); // Check if we were returned a promise in order to support promise behavior if (serializedKey && typeof serializedKey.then === 'function' && typeof serializedKey.catch === 'function') { // This is a promise. We need to hook into its then and catch serializedKey.then(finishSerializedKey).catch(failSerializedKey); } else { resolvedSerializedKey = serializedKey; } } // Only do the produce here if we are complete. That is, if the key // and value have been serialized. produceIfComplete(); } catch (e) { setImmediate(function() { calledBack = true; callback(e); }); } }; /** * Set the key serializer * * This allows the value inside the produce call to differ from the value of the * value actually produced to kafka. Good if, for example, you want to serialize * it to a particular format. */ HighLevelProducer.prototype.setKeySerializer = function(serializer) { this.keySerializer = createSerializer(serializer); }; /** * Set the value serializer * * This allows the value inside the produce call to differ from the value of the * value actually produced to kafka. Good if, for example, you want to serialize * it to a particular format. */ HighLevelProducer.prototype.setValueSerializer = function(serializer) { this.valueSerializer = createSerializer(serializer); }; ```
/content/code_sandbox/lib/producer/high-level-producer.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
2,328
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ module.exports = RefCounter; /** * Ref counter class. * * Is used to basically determine active/inactive and allow callbacks that * hook into each. * * For the producer, it is used to begin rapid polling after a produce until * the delivery report is dispatched. */ function RefCounter(onActive, onPassive) { this.context = {}; this.onActive = onActive; this.onPassive = onPassive; this.currentValue = 0; this.isRunning = false; } /** * Increment the ref counter */ RefCounter.prototype.increment = function() { this.currentValue += 1; // If current value exceeds 0, activate the start if (this.currentValue > 0 && !this.isRunning) { this.isRunning = true; this.onActive(this.context); } }; /** * Decrement the ref counter */ RefCounter.prototype.decrement = function() { this.currentValue -= 1; if (this.currentValue <= 0 && this.isRunning) { this.isRunning = false; this.onPassive(this.context); } }; ```
/content/code_sandbox/lib/tools/ref-counter.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
287
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ ```
/content/code_sandbox/test/error.spec.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
50
```javascript /* * node-rdkafka - Node.js wrapper for RdKafka C/C++ library * * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ var KafkaConsumer = require('../lib/kafka-consumer'); var t = require('assert'); var client; var defaultConfig = { 'client.id': 'kafka-mocha', 'group.id': 'kafka-mocha-grp', 'metadata.broker.list': 'localhost:9092' }; var topicConfig = {}; module.exports = { 'KafkaConsumer client': { 'beforeEach': function() { client = new KafkaConsumer(defaultConfig, topicConfig); }, 'afterEach': function() { client = null; }, 'does not modify config and clones it': function () { t.deepStrictEqual(defaultConfig, { 'client.id': 'kafka-mocha', 'group.id': 'kafka-mocha-grp', 'metadata.broker.list': 'localhost:9092' }); t.deepStrictEqual(client.globalConfig, { 'client.id': 'kafka-mocha', 'group.id': 'kafka-mocha-grp', 'metadata.broker.list': 'localhost:9092' }); t.notEqual(defaultConfig, client.globalConfig); }, 'does not modify topic config and clones it': function () { t.deepStrictEqual(topicConfig, {}); t.deepStrictEqual(client.topicConfig, {}); t.notEqual(topicConfig, client.topicConfig); }, }, }; ```
/content/code_sandbox/test/kafka-consumer.spec.js
javascript
2016-08-11T17:44:28
2024-08-15T04:21:29
node-rdkafka
Blizzard/node-rdkafka
2,087
337