Alert dialog before a new thread - multithreading

I have the code.
After clicking on the button, an alertdialog of the download warning should appear. And request a json file from the server.
btnEnter = findViewById(R.id.btn_enter)
btnEnter.setOnClickListener {
val gson = Gson().toJson(authorization)
val message = gson.toByteArray(StandardCharsets.UTF_8)
val url = URL("my URL")
val responseServer: String?
val progressBar = AlertDialog.Builder(this)
progressBar.setCancelable(false)
progressBar.setView(R.layout.progress_bar)
dialog = progressBar.create()
dialog.show()
if (isOnline(this)) {
responseServer = sendJson(url, message)
if (responseServer != null){
responseAuthorization = Gson().fromJson(responseServer, ResponseAuthorization::class.java)
}else{
Toast.makeText(applicationContext, "Error", Toast.LENGTH_SHORT).show()
val vibration = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibration.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
}
} else {
AlertDialog.Builder(this)
.setTitle("No connection")
.setMessage("No connection")
.setPositiveButton("OK"){ _, _ -> finish() }.show()
}
}
and
private fun sendJson(url: URL, message: ByteArray): String?{
var str: String? = null
val t1 = Thread(Runnable {
try {
with(url.openConnection() as HttpURLConnection) {
doInput = true
doOutput = true
requestMethod = "POST"
setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded"
)
setRequestProperty("Accept", "application/json")
DataOutputStream(outputStream).write(message)
if (inputStream != null) {
str = BufferedReader(InputStreamReader(inputStream)).use {
it.readText()
}
}
}
} catch (ex: Exception) {
str = null
println(ex)
}
})
t1.start()
t1.join()
return str
}
Alert dialog appears after the thread is executed. How to make it appear before the thread

Related

How to wait result from OKHTTP response without freezing app Kotlin?

I am writing a small application in Kotlin with JetpackCompose and my application freezes (CountDownLatch) when a request is called, is there any way to avoid this?
Without CountDownLatch, okhttp does not have time to return the result before the method completes.
MainActivity.kt
fun infoServer() {
val viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
var txt = remember {
mutableStateOf(0)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.padding(10.dp)
) {
Text(
text = "Player Count ",
style = MaterialTheme.typography.body1
)
Text(
text = txt.value.toString(),
style = MaterialTheme.typography.body1,
fontWeight = FontWeight.Bold
)
}
Row(horizontalArrangement = Arrangement.Center) {
eveButton(
text = "Update",
onClick = ({
viewModel.updatePlayerCount()
txt.value = viewModel.res
}),
modifier = Modifier
.padding(10.dp)
)
eveButton(
text = "Clear",
onClick = ({
txt.value = 0
}),
modifier = Modifier
.padding(10.dp)
)
}
}
}
MainActivityViewModel.kt
class MainActivityViewModel : ViewModel() {
var res = 0
fun updatePlayerCount() {
res = MainActivityModel().updateServerPlayers()
}
}
MainACtivityModel.kt
class MainActivityModel {
var result = 0
fun updateServerPlayers(): Int {
val client = OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.callTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
val request = Request.Builder()
.url("https://esi.evetech.net/latest/status/?datasource=tranquility")
.method("GET", null)
.build()
var countDownLatch = CountDownLatch(1)
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.d("Error Connection", e.toString())
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Error $response")
try {
var json =JSONObject(response.body!!.string())
countDownLatch.countDown()
result = json.getInt("players")
}
catch (e: Exception) {
Log.d("OKHTTP", e.toString())
}
}
}
})
countDownLatch.await()
Log.d("OKHTTP2", result.toString())
return result
}
}

when battery is low connect device when i connect device automatically dismiss alert dialog box from activities

This is my broadcast reciver fun in mainactivity.kt file
private val mPlugInReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val bm = context.getSystemService(Application.BATTERY_SERVICE) as BatteryManager
val batLevel:Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
System.out.println("integerBatteryLevel ===="+batLevel)
if(batLevel < 20){
System.out.println("this is low battaroy below 20 % ===="+batLevel)
}else
{
System.out.println("this is nice battaroy more than 20 % ===="+batLevel)
}
when (intent.action) {
Intent.ACTION_POWER_CONNECTED -> {
Toast.makeText(context, "Power connected", Toast.LENGTH_SHORT).show()
openDialogForBatteryStatus(false)
}
Intent.ACTION_POWER_DISCONNECTED -> {
if(batLevel > 20){
openDialogForBatteryStatus(false)
}else
{
Toast.makeText(context, "Power disconnected", Toast.LENGTH_SHORT).show()
openDialogForBatteryStatus(true)
}
}
}
}
}
This is My BaseActivity Calling Alert Dialog box
open class BaseActivity : AppCompatActivity() {
fun openDialogForBatteryLevel(show: Boolean){
val dialogView = layoutInflater.inflate(R.layout.dialog_battery_low, null)
val dialog = AlertDialog.Builder(this#BaseActivity)
dialog.setView(dialogView).setCancelable(false)
val d= dialog.create()
if(show){
if(d.isShowing)
d.show()
}else{
d.dismiss()
}
dialogView.txtViewDescription.text = "Your Phone Battery is low"
dialogView.txtViewOk.setOnClickListener{
this.finishAffinity()
}
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
fun openDialogForBatteryStatus(show: Boolean) {
val dialogView = layoutInflater.inflate(R.layout.dialog_battery_low, null)
val dialog = AlertDialog.Builder(this#BaseActivity)
dialog.setView(dialogView).setCancelable(false)
val d= dialog.create()
if(show){
if(d.isShowing)
d.show()
}else{
d.dismiss()
}
dialogView.txtViewDescription.text = "Please Remove charger"
dialogView.txtViewOk.setOnClickListener{
this.finishAffinity()
}
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
}
What you are doing is creating the new dialog everytime u call the method openDialogForBatteryLevel() and every time you try to dismiss you are dismissing the new object of dialog and not the one attached to the window . You should globally hold the object (preferably weak reference of the object) and initialize it only if it is not initialized and do the operation on it.
Again i change my BaseActivity than too Some red line it show in code
fun openDialogForBatteryLevel(show: Boolean, message : String): AlertDialog{
val dialog
val dialogView
var d
if(alertD == null){
dialog = AlertDialog.Builder(this#BaseActivity)
dialogView = layoutInflater.inflate(R.layout.dialog_battery_low, null)
dialog.setView(dialogView).setCancelable(false)
d = dialog.create()
}else{
d = alertD
}
if(show){
if(d.isShowing)
d.show()
}else{
d.dismiss()
}
dialogView.txtViewDescription.text = message
dialogView.txtViewOk.setOnClickListener{
this.finishAffinity()
}
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return d
}
open class BaseActivity : AppCompatActivity() {
fun openDialogForBatteryLevel(){
val dialogView = layoutInflater.inflate(R.layout.dialog_battery_low, null)
val dialog = AlertDialog.Builder(this#BaseActivity)
.setView(dialogView).setCancelable(false)
.show()
dialogView.txtViewDescription.text = "Your Phone Battery is low"
dialogView.txtViewOk.setOnClickListener{
this.finishAffinity()
}
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialogView.txtViewOk.setOnClickListener {
dialog.dismiss()
}
}
fun openDialogForBatteryStatus(){
val dialogView = layoutInflater.inflate(R.layout.dialog_battery_low, null)
val dialog = AlertDialog.Builder(this#BaseActivity)
.setView(dialogView).setCancelable(false)
.show()
dialogView.txtViewDescription.text = "Please Remove charger"
dialogView.txtViewOk.setOnClickListener{
this.finishAffinity()
}
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialogView.txtViewOk.setOnClickListener {
dialog.dismiss()
}
}
}

How can an App write and read file in Documents folder?

I wrote an App, in Kotlin with Android Studio that write some strings to a file.
All work, I can write and read inside the App, but I can't see the file looking in Documents folder.
How can I use the folder Documents as a storage space?
Thank you
These are the function I use:
fun saveTextFile(view: View, nomeFile: String, testo: String, contesto: Context){
var fileStream: FileOutputStream
try {
fileStream = contesto.openFileOutput(nomeFile, MODE_APPEND) // OK esegue append
fileStream.write(testo.toByteArray())
fileStream.close()
}catch (e: Exception){
e.printStackTrace()
}
}
fun readTextFile(view: View, nomeFile: String, contesto: Context): String{
var fileInputStream: FileInputStream? = null
fileInputStream = contesto.openFileInput(nomeFile)
var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)
val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)
val stringBuilder: StringBuilder = StringBuilder()
var text: String? = null
while ({ text = bufferedReader.readLine(); text }() != null) {
stringBuilder.append(text)
}
inputStreamReader.close();
return(stringBuilder.toString())
}
Thank you, Livio
For writing in Documents folder of your device , you just need to make use of MediaStore for the same. You can take input for this function anything that you want like String , bitmap , PdfDocument and other's too .
For Your UseCase you can do the following ,
Global Variable :
private var imageUri: Uri? = null
override suspend fun saveDocument(context : Context, text : String) {
withContext(Dispatchers.IO) {
try {
val collection =
MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val dirDest = File(
Environment.DIRECTORY_DOCUMENTS,
context.getString(R.string.app_name)
)
val date = System.currentTimeMillis()
val fileName = "$date.txt"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.RELATIVE_PATH,
"$dirDest${File.separator}")
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
}
}
val imageUri = context.contentResolver.insert(collection, contentValues)
withContext(Dispatchers.IO) {
imageUri?.let { uri ->
context.contentResolver.openOutputStream(uri, "w").use { out -> out?.write(text.toByteArray())
}
contentValues.clear()
contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
context.contentResolver.update(uri, contentValues, null, null)
}
}
} catch (e: FileNotFoundException) {
null
}
}
}
For Updating the already existing file , do the following . After creating file for the first time I have saved the imageUri in a global variable (If you want to store it permanently / or for a while you can use Jetpack Datastore / Shared Preference to save the same ):
suspend fun updateData(context: Context,text : String){
withContext(Dispatchers.IO) {
try {
val collection =
MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val dirDest = File(
Environment.DIRECTORY_DOCUMENTS,
context.getString(R.string.app_name)
)
val fileName = "test.txt"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(
MediaStore.MediaColumns.RELATIVE_PATH,
"$dirDest${File.separator}"
)
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
}
withContext(Dispatchers.IO) {
imageUri?.let { uri ->
context.contentResolver.openOutputStream(uri, "wa").use { out ->
out?.write(text.toByteArray())
}
contentValues.clear()
contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
context.contentResolver.update(uri, contentValues, null, null)
}
}
} catch (e: FileNotFoundException) {
null
}
}
}
For Reading the File , Do the following :
suspend fun read(context: Context, source: Uri): String = withContext(Dispatchers.IO) {
val resolver: ContentResolver = context.contentResolver
resolver.openInputStream(source)?.use { stream -> stream.readText() }
?: throw IllegalStateException("could not open $source")
}
private fun InputStream.readText(charset: Charset = Charsets.UTF_8): String =
readBytes().toString(charset)
This is how the final code looks like :
class MainActivity : AppCompatActivity() {
private lateinit var btn: Button
private var imageUri: Uri? = null
private lateinit var btn2: Button
private lateinit var btn3 : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn = findViewById(R.id.btnAdd)
btn2 = findViewById(R.id.getText)
btn3 = findViewById(R.id.updateText)
btn.setOnClickListener {
lifecycleScope.launch {
saveDocument(applicationContext, "Original ")
}
}
btn3.setOnClickListener {
lifecycleScope.launch {
updateData(applicationContext,"Appended")
}
}
btn2.setOnClickListener {
lifecycleScope.launch {
imageUri?.let { it1 ->
val data = read(applicationContext, it1)
Toast.makeText(applicationContext, "The data is $data ", Toast.LENGTH_LONG)
.show()
}
}
}
}
suspend fun saveDocument(context: Context, text: String) {
withContext(Dispatchers.IO) {
try {
val collection =
MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val dirDest = File(
Environment.DIRECTORY_DOCUMENTS,
context.getString(R.string.app_name)
)
val date = System.currentTimeMillis()
val fileName = "test.txt"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(
MediaStore.MediaColumns.RELATIVE_PATH,
"$dirDest${File.separator}"
)
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
}
imageUri = context.contentResolver.insert(collection, contentValues)
withContext(Dispatchers.IO) {
imageUri?.let { uri ->
context.contentResolver.openOutputStream(uri, "w").use { out ->
out?.write(text.toByteArray())
}
contentValues.clear()
contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
context.contentResolver.update(uri, contentValues, null, null)
}
}
} catch (e: FileNotFoundException) {
null
}
}
}
suspend fun updateData(context: Context, text: String) {
withContext(Dispatchers.IO) {
try {
val collection =
MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val dirDest = File(
Environment.DIRECTORY_DOCUMENTS,
context.getString(R.string.app_name)
)
val fileName = "test.txt"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(
MediaStore.MediaColumns.RELATIVE_PATH,
"$dirDest${File.separator}"
)
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
}
withContext(Dispatchers.IO) {
imageUri?.let { uri ->
context.contentResolver.openOutputStream(uri, "wa").use { out ->
out?.write(text.toByteArray())
}
contentValues.clear()
contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
context.contentResolver.update(uri, contentValues, null, null)
}
}
} catch (e: FileNotFoundException) {
null
}
}
}
suspend fun read(context: Context, source: Uri): String = withContext(Dispatchers.IO) {
val resolver: ContentResolver = context.contentResolver
resolver.openInputStream(source)?.use { stream -> stream.readText() }
?: throw IllegalStateException("could not open $source")
}
private fun InputStream.readText(charset: Charset = Charsets.UTF_8): String =
readBytes().toString(charset)
I have three buttons . With the first I create a file , then the uri gets stored in the global variable . Then onClick of second button I add to the already existing file and then read the file using the third button using the same imageUri stored in the global variable
This is the demo for the same . Check when the buttons are being pressed and the output in the form of Toast at the bottom .

how to fix conversion error when converting from java to kotlin

I am a student, new to kotlin, so I am converting java codes to kotlin to learn and see how it works, but I didnt understand what the error says.
private val _songs = ArrayList<SongInfo>()
internal lateinit var recyclerView: RecyclerView
internal lateinit var seekBar: SeekBar
internal lateinit var songAdapter: SongAdapter
internal var mediaPlayer: MediaPlayer? = null
private val myHandler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
seekBar = findViewById(R.id.seekBar) as SeekBar
songAdapter = SongAdapter(this, _songs)
recyclerView.adapter = songAdapter
val linearLayoutManager = LinearLayoutManager(this)
val dividerItemDecoration = DividerItemDecoration(recyclerView.context,
linearLayoutManager.orientation)
recyclerView.layoutManager = linearLayoutManager
recyclerView.addItemDecoration(dividerItemDecoration)
songAdapter.setOnItemClickListener { b, view, obj, position ->
if (b.text == "Stop") {
mediaPlayer!!.stop()
mediaPlayer!!.reset()
mediaPlayer!!.release()
mediaPlayer = null
b.text = "Play"
} else {
val runnable = Runnable {
try {
mediaPlayer = MediaPlayer()
mediaPlayer!!.setDataSource(obj.songUrl)
mediaPlayer!!.prepareAsync()
mediaPlayer!!.setOnPreparedListener { mp ->
mp.start()
seekBar.progress = 0
seekBar.max = mediaPlayer!!.duration
Log.d("Prog", "run: " + mediaPlayer!!.duration)
}
b.text = "Stop"
} catch (e: Exception) {
}
}
myHandler.postDelayed(runnable, 100)
}
}
checkUserPermission()
val t = runThread()
t.start()
}
inner class runThread : Thread() {
override fun run() {
while (true) {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
Log.d("Runwa", "run: " + 1)
if (mediaPlayer != null) {
seekBar.post { seekBar.progress = mediaPlayer!!.currentPosition }
Log.d("Runwa", "run: " + mediaPlayer!!.currentPosition)
}
}
}
}
private fun checkUserPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 123)
return
}
}
loadSongs()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
123 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadSongs()
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
checkUserPermission()
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun loadSongs() {
val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"
val cursor = contentResolver.query(uri, null, selection, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
val name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
val artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
val url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
val s = SongInfo(name, artist, url)
_songs.add(s)
} while (cursor.moveToNext())
}
cursor.close()
songAdapter = SongAdapter(this#MainActivity, _songs)
}
}
}
This is the error:
"Error:(46, 44) Type mismatch: inferred type is (???, ???, ???, ???)
-> Any but SongAdapter.OnItemClickListener was expected Error:(46, 46) Cannot infer a type for this parameter. Please specify it explicitly."
Batch conversion to Kotlin is not the best way to learn the language. I suggest you to re-implement your Android component in Kotlin manually, to get the feeling of language.
The error you see says: "I can not understand how this lambda with 4 parameters can be an instance of SongAdapter.OnItemClickListener, please help". You can try anonymous class in this place.

Unable to create or search index using groovy

I'm using below method to check and create elasticsearch index. This script works perfectly for Elasticsearch 2.3 and 2.4 versions. I'm trying things with Elasticsearch version 5.0 but it isn't working. All i'm trying is to create an index and search index dynamically using groovy script.
static def checkOrCreateESIndex(String baseUrl, String path)
{
try
{
def res_GET = null
def res_PUT = null
def status_message = null
def http = new HTTPBuilder(baseUrl)
println "New ES Check Index : "+baseUrl+path
http.request(Method.GET, ContentType.JSON)
{
uri.path = path
requestContentType = ContentType.XML
headers.'Accept-Encoding' = 'gzip,deflate'
headers.Accept = 'application/json';
response.success = { resp ->
res_GET = 200
println "SUCCESS! ${resp.status}"
}
response.failure = { resp ->
res_GET = 400
println "Failure! ${resp.status}"
}
}
if (res_GET != 200)
{
String params = "{\"settings\":{\"number_of_shards\":2,\"number_of_replicas\":0},\"mappings\":{\"run\":{\"_timestamp\":{\"enabled\":true},\"properties\":{\"70 Percentile\":{\"type\":\"float\"},\"80 Percentile\":{\"type\":\"float\"},\"85 Percentile\":{\"type\":\"float\"},\"95 Percentile\":{\"type\":\"float\"},\"90 Percentile\":{\"type\":\"float\"},\"Average\":{\"type\":\"float\"},\"Fail\":{\"type\":\"string\"},\"Maximum\":{\"type\":\"float\"},\"Minimum\":{\"type\":\"float\"},\"Pass\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"ProjectName\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"RunID\":{\"type\":\"string\"},\"VirtualUsers\":{\"type\":\"string\"},\"Release\":{\"type\":\"string\"},\"BuildNumber\":{\"type\":\"string\"},\"StartTime\":{\"type\":\"string\"},\"EndTime\":{\"type\":\"string\"},\"StdDeviation\":{\"type\":\"string\"},\"TestName\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"TransactionName\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"Baseline\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"SLAviolationcount\":{\"type\":\"float\"}}}}}"
def bodyMap2 = new JsonSlurper().parseText(params)
def response_body = null
def response_header = null
def http2 = new HTTPBuilder(baseUrl)
println "New ES Create Index : "+baseUrl+path
println "New ES Mapping : "+params
http2.request(Method.PUT)
{
uri.path = path
requestContentType = ContentType.JSON
headers.'Accept' = 'application/json';
body = bodyMap2
headers.'Accept-Encoding' = 'gzip,deflate'
headers.'Cookie' = 'JSESSIONID=934ED773C47D81C74C63BEAFE1D6CA1B'
response.success = { resp ->
res_PUT = 200
println "SUCCESS! ${resp.status}"
}
response.failure = { resp ->
res_PUT = 400
println "Failure! ${resp.status}"
}
}
}
if (res_GET == 200)
{
status_message = "IDX_EXISTS"
}
else if (res_GET != 200 && res_PUT == 200)
{
status_message = "IDX_CREATED"
}
else
{
status_message = "IDX_FAIL"
}
return status_message
}
catch (groovyx.net.http.HttpResponseException ex)
{
ex.printStackTrace()
return null
}
catch (java.net.ConnectException ex)
{
ex.printStackTrace()
return null
}
}
static def postElasticSearchMessage(String baseUrl, String path,String params)
{
try
{
def res_ES = null
def bodyMap = new JsonSlurper().parseText(params)
def response_body = null
def response_header = null
def http = new HTTPBuilder(baseUrl)
http.request(Method.POST)
{
uri.path = path
requestContentType = ContentType.JSON
body = bodyMap
headers.'Accept-Encoding' = 'gzip,deflate'
headers.'Cookie' = 'JSESSIONID=934ED773C47D81C74C63BEAFE1D6CA1B'
response.success = { resp ->
res_ES = 'Y'
println "SUCCESS! ${resp.status}"
}
response.failure = { resp ->
res_ES = 'N'
println "FAILURE! ${resp.status}"
}
}
return res_ES
}
catch (groovyx.net.http.HttpResponseException ex)
{
ex.printStackTrace()
return 'N'
}
catch (java.net.ConnectException ex)
{
ex.printStackTrace()
return 'N'
}
}
Below is my index structure:
{\"settings\":{\"number_of_shards\":2,\"number_of_replicas\":0},\"mappings\":{\"run\":{\"_timestamp\":{\"enabled\":true},\"properties\":{\"70 Percentile\":{\"type\":\"float\"},\"80 Percentile\":{\"type\":\"float\"},\"85 Percentile\":{\"type\":\"float\"},\"95 Percentile\":{\"type\":\"float\"},\"90 Percentile\":{\"type\":\"float\"},\"Average\":{\"type\":\"float\"},\"Fail\":{\"type\":\"string\"},\"Maximum\":{\"type\":\"float\"},\"Minimum\":{\"type\":\"float\"},\"Pass\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"ProjectName\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"RunID\":{\"type\":\"string\"},\"VirtualUsers\":{\"type\":\"string\"},\"Release\":{\"type\":\"string\"},\"BuildNumber\":{\"type\":\"string\"},\"StartTime\":{\"type\":\"string\"},\"EndTime\":{\"type\":\"string\"},\"StdDeviation\":{\"type\":\"string\"},\"TestName\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"TransactionName\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"Baseline\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"SLAviolationcount\":{\"type\":\"float\"}}}}}
how would i make this work for elasticsearch version 5.0. Kindly help me with the index structure and search query for 5.0. That would be really helpful.Thanks in advance.

Resources