I am very new to Android Kotlin programming. I am making an app to create, read and delete file using Storage Access Framework. I did it by implementing deprecated startActivityForResult intent to perform file read, create, delete tasks. I tried to implement it using Activity Result API but I got stuck in request code which I could not find it.
In new implementation, there is resultCode but no requestCode.
My implemetation is below. How I can I implement the following using Activity Result API ?
How can I get request code from Activity Result API ?
fun createFile()
{
val filename: String = etFileName.text.toString()
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/*"
addCategory(Intent.CATEGORY_OPENABLE)
putExtra(Intent.EXTRA_TITLE, filename)
}
startActivityForResult(intent, WRITE_REQUEST_CODE)
}
fun readFile(){
etFileName.setText("")
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "text/*"
}
startActivityForResult(intent, READ_REQUEST_CODE)
}
fun deleteFile(uri: Uri){
val filename = queryName(contentResolver, uri)
DocumentsContract.deleteDocument(contentResolver, uri)
Toast.makeText(applicationContext, "Done deleting $filename", Toast.LENGTH_SHORT).show()
}
fun writeText(uri: Uri) : String{
//var writetext: String = "typing high speed"
var writeStream = contentResolver.openFileDescriptor(uri, "w")
val filename: String = queryName(contentResolver, uri)
etFileName.setText(filename)
var fileOutputStream = FileOutputStream(writeStream?.fileDescriptor)
fileOutputStream.write(filename.toByteArray())
fileOutputStream.close()
return filename.toString()
}
fun openFileContent(uri: Uri): String{
val inputStream = contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
val filename = queryName(contentResolver, uri)
etFileName.setText(filename)
var currentline = reader.readLine()
while (currentline != null) {
stringBuilder.append(currentline + "\n")
currentline = reader.readLine()
}
inputStream?.close()
val str = stringBuilder.toString()
Log.d("Uri Read", ": $str")
return str
}
private fun queryName(resolver: ContentResolver, uri: Uri): String {
val returnCursor: Cursor = resolver.query(uri, null, null, null, null)!!
val nameIndex: Int = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
returnCursor.moveToFirst()
val name: String = returnCursor.getString(nameIndex)
returnCursor.close()
return name
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val uri =resultData?.data
Log.d("Uri Read", "$uri")
if (uri != null) {
val readfile: String = openFileContent(uri)
etContent.setText(readfile)
}
} else if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
resultData?.data?.also { uri ->
Log.i("Uri Write", "Uri: $uri") // 1
val write = writeText(uri) // 2
etContent.setText(write)
}
} else if (requestCode == DELETE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val uri =resultData?.data
Log.d("Uri Delete", "$uri")
if (uri != null) {
deleteFile(uri)
}
}
}
Since the above method is deprecated, I tried to implement it using Intent launcher, but there is no reference to requestCode anywhere so I am stuck here. It is as shown below :
val startforFile: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
result: ActivityResult ->
// could not find reference to requestCode here
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val uri =resultData?.data
Log.d("Uri Read", "$uri")
if (uri != null) {
val readfile: String = openFileContent(uri)
etContent.setText(readfile)
}
} else if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
resultData?.data?.also { uri ->
Log.i("Uri Write", "Uri: $uri") // 1
val write = writeText(uri) // 2
etContent.setText(write)
}
} else if (requestCode == DELETE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val uri =resultData?.data
Log.d("Uri Delete", "$uri")
if (uri != null) {
deleteFile(uri)
}
}
}
Can anyone show me how it is done correctly ?
There are two ways with ActivityResultContracts.StartActivityForResult.
Make multiple requests by registering multiple listeners:
val startForFileRead: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
result: ActivityResult ->
if (resultCode == Activity.RESULT_OK) {
val uri =resultData?.data
Log.d("Uri Read", "$uri")
if (uri != null) {
val readfile: String = openFileContent(uri)
etContent.setText(readfile)
}
}
}
val startForFileWrite: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
result: ActivityResult ->
if (resultCode == Activity.RESULT_OK) {
resultData?.data?.also { uri ->
Log.i("Uri Write", "Uri: $uri") // 1
val write = writeText(uri) // 2
etContent.setText(write)
}
}
}
val startForFileDelete: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
result: ActivityResult ->
if (resultCode == Activity.RESULT_OK) {
val uri =resultData?.data
Log.d("Uri Delete", "$uri")
if (uri != null) {
deleteFile(uri)
}
}
}
Put an extra in your Intent returned from the other activity. Unpack it as your request code.
const val REQUEST_CODE = "REQUEST_CODE"
//...
val startForFile: ActivityResultLauncher<Intent> =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val requestCode = result.data?.extras?.getInt(REQUEST_CODE)
if (requestCode == null) {
Log.e("FileResultLauncher", "No REQUEST_CODE was returned in data intent.")
return#registerForActivityResult
}
val uri = result.data?.data
if (uri == null || result.resultCode != RESULT_OK) {
Log.i("FileResultLauncher", "No Uri returned or result wasn't OK.")
return#registerForActivityResult
}
when (requestCode) {
READ_REQUEST_CODE -> {
Log.d("Uri Read", "$uri")
val readfile: String = openFileContent(uri)
etContent.setText(readfile)
}
WRITE_REQUEST_CODE -> {
Log.i("Uri Write", "Uri: $uri") // 1
val write = writeText(uri) // 2
etContent.setText(write)
}
DELETE_REQUEST_CODE -> {
Log.d("Uri Delete", "$uri")
deleteFile(uri)
}
}
}
Related
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
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 .
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.
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.
This code works fine on SonyEricsson and Motorola cellphones, but on Nokia it either fails at the beginnig not making any request at all or returns empty response, depending on model.
HttpConnection hc = null;
InputStream is = null;
InputStreamReader isr = null;
String result = "";
try
{
hc = (HttpConnection) Connector.open(url);
int rc = hc.getResponseCode();
if (rc != HttpConnection.HTTP_OK)
{
throw new IOException(hc.getResponseMessage());
}
is = hc.openInputStream();
isr = new InputStreamReader(is, "utf-8");
int ch;
while ((ch = is.read()) != -1)
{
result += (char) ch;
}
}
finally
{
if (is != null)
{
is.close();
}
if (hc != null)
{
hc.close();
}
}
return result;
Tried different codes with byte buffers, streams, etc, result is always the same. What's the problem?
try it
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class Transport {
public static int BUFFER_LENGTH = 100;//1024;
public static boolean USE_FLUSH = false;
static {
if (DeviceDetect.getDeivice() == DeviceDetect.SAMSUNG) {
BUFFER_LENGTH = 1024;
USE_FLUSH = true;
}
}
public static String SESSION_COOKIE = null;
private static int rnd = 1;
private static final String request(String url, String method, Hashtable params) throws IOException {
HttpConnection conn = null;
DataOutputStream dos = null;
InputStream in = null;
try {
String encodedParams = null;
if (params != null && params.size() > 0) {
encodedParams = getEncodedParams(params);
}
if (method == null) {
if (encodedParams.length() < 2000) {
method = "GET";
} else {
method = "POST";
}
}
method = method != null && method.equalsIgnoreCase("POST") ? HttpConnection.POST : HttpConnection.GET;
if (method.equalsIgnoreCase(HttpConnection.GET)) {
if (encodedParams != null) {
url += (url.indexOf("?") == -1 ? "?" : "&") + encodedParams;
encodedParams = null;
}
url += (url.indexOf("?") == -1 ? "?" : "&") + "_rnd=" + rnd++;
}
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
if (conn == null) {
throw new IOException("HttpConnection is null, please check Access Point configuration");
}
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (SESSION_COOKIE != null) {
conn.setRequestProperty("Cookie", SESSION_COOKIE);
}
byte[] buff = new byte[BUFFER_LENGTH];
if (encodedParams != null) {
byte[] bytes = encodedParams.getBytes("UTF-8");
String lengthStr = bytes.length + "";
conn.setRequestProperty("Content-Length", lengthStr);
dos = conn.openDataOutputStream();
if (dos == null) {
throw new IOException("OutputStream is null, please check Access Point configuration");
}
for (int i = 0, l = bytes.length; i < l; i += Transport.BUFFER_LENGTH) {
if (Transport.BUFFER_LENGTH == 1) {
dos.writeByte(bytes[i]);
} else {
int count = Math.min(Transport.BUFFER_LENGTH, l - i);
System.arraycopy(bytes, i, buff, 0, count);
dos.write(buff, 0, count);
}
if (Transport.USE_FLUSH) {
dos.flush();
}
}
dos.flush();
try {
dos.close();
} catch (IOException ex) {
}
}
String setCookie = conn.getHeaderField("Set-Cookie");
if (setCookie != null) {
int ind1 = setCookie.indexOf("JSESSIONID=");
if (ind1 > -1) {
int ind2 = setCookie.indexOf(";", ind1);
SESSION_COOKIE = ind2 == -1 ? setCookie.substring(ind1) : setCookie.substring(ind1, ind2 + 1);
}
}
in = conn.openInputStream();
if (in == null) {
throw new IOException("InputStream is null, please check Access Point configuration");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = in.read(buff);
while (n > -1) {
baos.write(buff, 0, n);
n = in.read(buff);
}
baos.flush();
baos.close();
String response = new String(baos.toByteArray(), "UTF-8");
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
return response;
} finally {
try {
dos.close();
} catch (Exception ex) {
}
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
}
}
public static String getEncodedParams(Hashtable params) throws IOException {
String str = "";
Enumeration keys = params.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
Object value = params.get(name);
if (value == null || name == null) {
continue;
}
str += "&" + URLEncoder.encode(name.toString(), "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8");
}
if (str.length() > 1) {
str = str.substring(1);
}
return str;
}
}
I am not sure if this will work for you but I had a similar problem and found that specifying a port number made it work (on some older Nokia models). i.e convert:
http://www.mysite.com/my_page.html
to:
http://mysite.com:80/my_page.html