value Engine is not a member of object android.speech.tts.TextToSpeech - java

In java, using android-19, this works fine:
import android.speech.tts.TextToSpeech.Engine;
But in scala:
import android.speech.tts.TextToSpeech.Engine
^
error: value Engine is not a member of object android.speech.tts.TextToSpeech
This is weird because I can import EngineInfo without problems, but it does not recognize the class Engine, although it is clearly in the android.jar
Any fix or workaround? Is this a scala issue? I'm developping on Eclipse 3.7 using AndroidProguardScala v51 and Scala IDE version 3.0.1
EDIT
The context in which I am using this is for example the following:
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(this, mTtsListener)
}

Unfortunately, TextToSpeech.Engine is declared non-static which means something like this:
public class TextToSpeech {
public class Engine {
// ...
}
// ...
}
So according to this, you can't access it. Here's my workaround using a wrapper:
object ConstantsWrapper {
private val cls = classOf[TextToSpeech#Engine]
def apply(fieldName: String) = cls.getDeclaredField(fieldName).get(null)
.toString
val CHECK_VOICE_DATA_PASS = apply("CHECK_VOICE_DATA_PASS")
// Insert more here
}
if (resultCode == ConstantsWrapper.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(this, mTtsListener)
}

Related

Error invoking bsh method: eval Sourced file: inline evaluation of: `import org.skyscreamer.jsonassert.Customization; Constructor error: Can't find

I use jmeter to comapre json data.use org.skyscreamer.jsonassert.
suceess in idea with jdk8, but failed in jmeter
this is error info.
i have imported jsonassert-1.5.1.jar and android-json-0.0.20131108.vaadin1.jar into %Jmeter%lib,jackson use 2.13.3 version.jmeter version is 5.5 .
Response code:500
Response message:org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.skyscreamer.jsonassert.Customization; import org.skyscreamer.jsonasse . . . '' : Constructor error: Can't find constructor: org.skyscreamer.jsonassert.comparator.CustomComparator( org.skyscreamer.jsonassert.JSONCompareMode, org.skyscreamer.jsonassert.Customization ) in class: org.skyscreamer.jsonassert.comparator.CustomComparator
this is beanshell sampler ,the code i write in the jmeter
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONCompare;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.ValueMatcher;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.json.JSONException;
String newResponseMessage = vars.get("new_S{custNo}");
String oldResponseMessage = vars.get("old_S{custNo}");
log.info("oldRes"+oldResponseMessage);
log.info("newRes"+newResponseMessage);
ValueMatcher matcher = new ValueMatcher() {
public boolean equal(Object o1, Object o2) {
return true;
}
};
Customization customization = new Customization("orgSeqNo", matcher);
JSONCompareResult result;
try {
result = JSONCompare.compareJSON(newResponseMessage, oldResponseMessage, new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,customization));
if (result.passed()) {
System.out.println("no different");
} else {
System.out.println(result.getMessage());
log.error(result.getMessage());
// ctx.getEngine().stopTest();
}
}catch (JSONException e){
log.error("Beanshell failure: ", e);
throw ex;
}
code in jmeter beanshell sampler
error info picture
i have imported jsonassert-1.5.1.jar and android-json-0.0.20131108.vaadin1.jar into %Jmeter%lib and %Jmeter%/lib/ext both,jackson use 2.13.3 version.jmeter version is 5.5 .
enter image description here
I use jmeter to comapre json data.use org.skyscreamer.jsonassert.
suceess in idea with jdk8, but failed in jmeter
these are codes i write with jdk8,success run,but failed in jmeter
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.1</version>
</dependency>
public class Main {
static String jsonStr1 = "{\"orgSeqNo\":\"123123\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":103,\"phone\":\"13213137625\"},{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
static String jsonStr2 = "{\"orgSeqNo\":\"12e9fc45c09b4a69b7aa2bbcb1313cba\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"103\",\"phone\":\"13213137625\"},{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
static String jsonStr3 = "{\"orgSeqNo\":\"12e9fc45c09b4a69b7aa2bbcb1313cba\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"103\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
static String jsonStr4 = "{\"orgSeqNo\":\"12e9fc45c09b4a69b7aa2bbcb1313cba\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":103,\"phone\":\"13213137625\"},{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
public static void main(String[] args) {
// Customization customization = new Customization("orgSeqNo", (o1, o2) -> true);
ValueMatcher matcher = new ValueMatcher() {
#Override
public boolean equal(Object o1, Object o2) {
return true;
}
};
Customization customization = new Customization("orgSeqNo", matcher);
JSONCompareResult result = null;
try {
result = JSONCompare.compareJSON(jsonStr1, jsonStr3, new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,customization));
if (result1.passed()) {
System.out.println("no different");
} else {
System.out.println(result.getMessage());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
next is result,i want jmeter also like this result
person.addresses[addrId=1].addrType
Expected: 103
got: 103
Program execution result picture
i have imported jsonassert-1.5.1.jar and android-json-0.0.20131108.vaadin1.jar into %Jmeter%lib,jackson use 2.13.3 version.jmeter version is 5.5 .
run success in jvm , but error info in jmeter...
Beanshell != Java so even given your code "suceess in idea with jdk8" it doesn't necessarily mean that it will "suceess" in JMeter's Beanshell components.
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so my expectation is that if you switch to the JSR223 Sampler and use groovy your code will "suceess" as well.
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

React Native - unit test fails because of Native Module

I am getting a weird anomaly when I declare a Native Java Module the new code doesn't pass unit test. Basically whatever I import from NativeModules in React Native lacks a definition: So the Unit test fails because TypeError: Cannot read property 'HelloWorld' of undefined
Steps to reproduce:
import { NativeModules } from 'react-native';
const Thing = NativeModules.SomeModule;
export const helloWorld = (addedText: string) => {
return Thing.HelloWorld(addedText);
};
export default Thing;
but the error is
TypeError: Cannot read property 'HelloWorld' of undefined
4 |
5 | export const helloWorld = (addedText: string) => {
> 6 | return Thing.HelloWorld(addedText);
| ^
7 | };
8 |
9 | export default Thing;
the actual Java is
public class SomeModule extends ReactContextBaseJavaModule {
SomeModule(ReactApplicationContext context) {
super(context);
}
#Override
public String getName() {
return "SomeModule";
}
void HelloWorld(String addedText){
try {
Log.w("HELLO_WORLD", addedText);
}
catch (Exception e) {
Log.e("DEVICE_MODULE_HELLO_WORLD_FAILED", "HelloWorld() Failed");
}
}
}
and this runs fine (when you run it) but the unit tests hate it. The issue seems to be that the React Native test lacks an awareness of the structure of const helloWorld = (addedText: string) => { return Thing.HelloWorld(addedText); }; so I dutifully made this d.ts to help
declare namespace Thing {
function helloWorld(addedText: string): void;
}
but it still fails when at unit test, it feels wrong for me to simply assume this has been overlooked, so I am assuming I must have implemented something incorrectly. Can anyone shed light on the correct way of doing this?
the answer is to mock out the function
in the test file, (the test to whatever part of your code in react-native calls helloWorld("bob chips")) (i.e not where it exports) you have to mock out the Java module as follows. Note this is global (once) at the top of the file that launched the failed test - perhaps you put helloWorld("bob chips") in Place.tsx if so perhaps the Place.test.tsx fails - because it references helloWorld("bob chips"), if so in the one that has tests that fail - inside Place.test.tsx - do this once at the top of the file:
jest.mock('react-native', () => {
const RN = jest.requireActual('react-native');
RN.NativeModules.SomeModule = {
HelloWorld: jest.fn(),
};
// mock modules created through UIManager
RN.UIManager.getViewManagerConfig = (name) => {
if (name === 'SomeModule') {
return { HelloWorld: jest.fn() };
}
return {};
};
return RN;
});
this then suppresses jest trying to test it, and allows you to write tests in java to compensate

Scala URLClassLoader is not reloading class file

I am running a scala project where I need to execute some rules. The rules will be dynamically added or removed from scala class file at runtime.
So, I want whenever the rules class modify, it should reload to get the changes without stopping the execution process.
I used runtime.getruntime.exec() to compile it
and am URL Class loader to get the modified code from classes
The exec() run fines. and in target folder classes gets modifies also, even when I am using URL Class Loader, not getting any error.
But it is giving me same result which i have on starting of the project. It's not giving me modification code.
Below is the code which I am using.
package RuleEngine
import akka.actor._
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import scala.io.StdIn
import Executor.Compute
import scala.concurrent.{Await, ExecutionContextExecutor}
import scala.concurrent.duration._
object StatsEngine {
def main(args: Array[String]) {
implicit val system: ActorSystem = ActorSystem("StatsEngine")
implicit val materializer: ActorMaterializer = ActorMaterializer()
implicit val executionContext: ExecutionContextExecutor = system.dispatcher
implicit val timeout = Timeout(10 seconds)
val computeDataActor = system.actorOf(Props[Compute],"ComputeData")
val route = {
post {
path("computedata"/) {
computeDataActor ! "Execute"
complete("done")
}
}
}
val bindingFuture = Http().bindAndHandle(route , "localhost", 9000)
println(s"Server online at http://localhost:9000/\nPress RETURN to stop...")
}
}
This is the main object file where I have created Akka HTTP to make API's
It will call computeDataActor whose code is below.
package Executor
import java.io.File
import java.net.URLClassLoader
import CompiledRules.RulesList
import akka.actor.Actor
class Compute extends Actor{
def exceuteRule(): Unit ={
val rlObj = new RulesList
rlObj.getClass.getDeclaredMethods.map(name=>name).foreach(println)
val prcs = Runtime.getRuntime().exec("scalac /home/hduser/MStatsEngine/Test/RuleListCollection/src/main/scala/CompiledRules/RuleList.scala -d /home/hduser/MStatsEngine/Test/RuleListCollection/target/scala-2.11/classes/")
prcs.waitFor()
val fk = new File("/home/hduser/MStatsEngine/Test/RuleListCollection/target/scala-2.11/classes/").toURI.toURL
val classLoaderUrls = Array(fk)
val urlClassLoader = new URLClassLoader(classLoaderUrls)
val beanClass = urlClassLoader.loadClass("CompiledRules.RulesList")
val constructor = beanClass.getConstructor()
val beanObj = constructor.newInstance()
beanClass.getDeclaredMethods.map(x=>x.getName).foreach(println)
}
override def receive: Receive ={
case key:String => {
exceuteRule()
}
}
}
Rules are imported which is mentioned below.
package CompiledRules
class RulesList{
def R1 : Any = {
return "executing R1"
}
def R2 : Any = {return "executing R2"}
// def R3 : Any = {return "executing R3"}
//def R4 : Any = {return "executing R4"}
def R5 : Any = {return "executing R5"}
}//Replace
So, whene i execute code, and on calling API, I will get ouput as
R1
R2
R5
Now, without stopping the project, I will uncomment R3 and R4. And I will call API again,
As I am executing code again, using
runtime.getruntime.exec()
it will compile the file and update classes in target
So, i used URLClassLoader to get new object of modification code.
But Unfortunately I am getting same result always which i have on starting of the project
R1
R2
R5
Below is link for complete project
Source Code
val beanClass = urlClassLoader.loadClass("CompiledRules.RulesList")
val constructor = beanClass.getConstructor()
val beanObj = constructor.newInstance()
Is just creating the newInstance of Already loaded class.
Java's builtin Class loaders always checks if a class is already loaded before loading it.
loadClass
protected Class<?> loadClass(String name,
boolean resolve)
throws ClassNotFoundException
Loads the class with the specified binary name. The default implementation of this method searches for classes in the following order:
Invoke findLoadedClass(String) to check if the class has already been loaded.
Invoke the loadClass method on the parent class loader. If the parent is null the class loader built-in to the virtual machine is used, instead.
Invoke the findClass(String) method to find the class.
To reload a class you will have to implement your own ClassLoader subclass as in this link

how to use try-resources in kotlin?

I am trying to use kotlin instead of Java, I cannot find a good way to do with try resource:
Java Code like this:
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
public class HelloTensorFlow {
public static void main(String[] args) throws Exception {
try (Graph g = new Graph()) {
final String value = "Hello from " + TensorFlow.version();
// Construct the computation graph with a single operation, a constant
// named "MyConst" with a value "value".
try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
// The Java API doesn't yet include convenience functions for adding operations.
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
}
// Execute the "MyConst" operation in a Session.
try (Session s = new Session(g);
// Generally, there may be multiple output tensors,
// all of them must be closed to prevent resource leaks.
Tensor output = s.runner().fetch("MyConst").run().get(0)) {
System.out.println(new String(output.bytesValue(), "UTF-8"));
}
}
}
}
I do it in kotlin, I have to do this:
fun main(args: Array<String>) {
val g = Graph();
try {
val value = "Hello from ${TensorFlow.version()}"
val t = Tensor.create(value.toByteArray(Charsets.UTF_8))
try {
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build()
} finally {
t.close()
}
var sess = Session(g)
try {
val output = sess.runner().fetch("MyConst").run().get(0)
println(String(output.bytesValue(), Charsets.UTF_8))
} finally {
sess?.close()
}
} finally {
g.close()
}
}
I have try to use use like this:
Graph().use {
it -> ....
}
I got error like this:
Error:(16, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
#InlineOnly public inline fun ???.use(block: (???) -> ???): ??? defined in kotlin.io
I just use wrong dependency:
compile "org.jetbrains.kotlin:kotlin-stdlib"
replace it with:
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

Aspect-Oriented programming issue in grails . Point-cut methods are not executing

I am using Grails 2.4.3 . In resource.groovy I have added component-scan
xmlns aop:"http://www.springframework.org/schema/aop"
context.'component-scan'('base-package': 'com')
Then in src/groovy I have created groovy class
package com.demo.aspects.mongo.history;
import grails.transaction.Transactional
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.aspectj.lang.annotation.After
import org.springframework.stereotype.Component
#Aspect
#Component
#Transactional
public class MongoAspectAdvice {
#After("execution(* com.demo.global.BaseOptionService.save(..))")
def afterMethod(){
println "after method execution"
}
#Before("execution(* com.demo.global.BaseOptionService.save(..))")
def beforeMethod(){
println "before method execution"
}
}
And save funtion in com.demo.global.BaseOptionService is defined as
def save(def entity){
if(entity.id == null){
entity.createdDate = new Date()
}
entity.lastUpdatedDate = new Date()
log.debug(entity)
neo4jTemplate.save(entity)
}
And BaseOptionService is extended by UserService in which BaseOptionService method is called.
UserService.groovy
class UserService extends BaseOptionService{
def addUser(username,email,role,phonenumber){
log.debug "user ===== "+username
UserCommand userCommand = new UserCommand()
userCommand.username = username
userCommand.email = email
userCommand.phonenumber = phonenumber
userCommand.role = role
if(userCommand.labels?.empty == true || userCommand.labels == null){
if(role == null){
userCommand.addLabel(null)
}else{
userCommand.addLabel("_USER")
userCommand.addLabel(role)
}
}
userCommand.isActive = true
userCommand.token = null
UserDomain user = userCommand.getUser()
log.debug "user == "+user
save(user)
return user
}
def removeLabels(id,label){
UserDomain user = findOne(id,UserDomain)
if(user.labels?.contains(label)){
user.labels.remove(label)
}
save(user)
return user
}
def serviceMethod() {
}
}
When save function is executing , I haven't seen println statement of afterMethod and beforeMethod in console and there is no error . I am not sure what wrong I am doing. Please help.
when your application start, the component scan will scan all packages for check what beans are present.
This process anyway don't instantiate the bean if it's not referenced by any other class. In other way you are telling that yes i have a MongoAspectAdvice class that is annotated with #Component so it's also a singleton but where you use it?
Try to import it in UserService.
Then if stil not working ( for check that you can put a breakpoint in that class ) add the following code to you resources.groovy:
// Place your Spring DSL code here
beans = {
mongoAspectAdvice(MongoAspectAdvice) { bean ->
bean.autowire = "byName"
}
And then import in your service:
def mongoAspectAdvice
However you can replicate this behaviour by using some grails ad-hc closures:
def beforeInterceptor = {
println "Tracing action ${actionUri}"
}
And
def afterInterceptor = {
println "Tracing action ${actionUri}"
}
Put them in BaseOptionService

Categories

Resources