MediaRecorder: java.lang.IllegalStateException at - android-mediarecorder

When I start the device and open my app everything works fine, but after use of another app on the device my app gave this error.
public void startRecorder(){
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setOutputFile("/dev/null");
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
mRecorder.start();
} catch (java.io.IOException ioe) {
mRecorder = null;
android.util.Log.e("[Monkey]", "IOException: " + android.util.Log.getStackTraceString(ioe));
} catch (java.lang.SecurityException e) {
mRecorder = null;
android.util.Log.e("[Monkey]", "SecurityException: " + android.util.Log.getStackTraceString(e));
}
}
}
10-08 10:32:42.260 18121-18121/com.avatarmind.ipaldecibel E/###: JNI_MOTIONSERVICE LOAD
10-08 10:32:42.260 18121-18121/com.avatarmind.ipaldecibel E/###: MotionService Setup
10-08 10:32:42.526 18121-18121/com.avatarmind.ipaldecibel E/MediaRecorder: start failed: -38
10-08 10:32:42.529 18121-18121/com.avatarmind.ipaldecibel E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.avatarmind.ipaldecibel, PID: 18121
java.lang.RuntimeException: Unable to resume activity {com.avatarmind.ipaldecibel/com.avatarmind.ipaldecibel.MainActivity}: java.lang.IllegalStateException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3173)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3204)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1406)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:772)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:662)
Caused by: java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.avatarmind.ipaldecibel.MainActivity.startRecorder(MainActivity.java:300)
at com.avatarmind.ipaldecibel.MainActivity.onResume(MainActivity.java:262)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1258)
at android.app.Activity.performResume(Activity.java:6342)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3162)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3204) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2548) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1406) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5509) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:772) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:662) 

It seems that when resume application and try to call mRecorder.start() u have an illegal state. Possibly u don't release the MediaRecorder when your Activity pause.
Try with the next code:
#Override
protected void onPause() {
super.onPause();
// if we are using MediaRecorder, release it first
releaseMediaRecorder();
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
// clear recorder configuration
mMediaRecorder.reset();
// release the recorder object
mMediaRecorder.release();
mMediaRecorder = null;
}
}

try use, for 21-30 api it work
setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)

Related

Getting 400 from samltest.id when attempting SP-initiated worflow

I have used itfoxtec's SAML2 library to implement an SP in my ASP.NET MVC app. I am testing using samltest.id as the IdP. The IdP-initiated workflow works perfectly, but the SP-initiated workflow always gets a 400 error back from samltest.id. I have attempted to look through samltest.id's log to see if an error is being recorded there for my request, but I cannot seem to find anything there.
This is the Action that handles the URL that he user would go to when initiating SSO:
public ActionResult SSOLogin() {
LogManager logger = new LogManager("SSOLogin");
string hostname = this.GetHostname();
SchoolSettings settings = this.GetClientSettings();
if (settings.UseSAMLSSO) {
Saml2Configuration samlConfig = null;
try {
samlConfig = SamlConfigLoader.GetSaml2Config(HttpContext, settings, this.IsSandbox());
} catch (Exception e) {
logger.exception($"loading Saml2Configuration for {hostname}", e);
}
if (samlConfig != null) {
try {
var binding = new Saml2RedirectBinding();
binding.SetRelayStateQuery(new Dictionary<string, string> { { "Home/Index", Url.Content("~/") } });
return binding.Bind(new Saml2AuthnRequest(samlConfig) {
}).ToActionResult();
} catch (Exception e) {
logger.error($"Exception redirecting to IdP. {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
ViewBag.ssoerror = $"Error redirecting to IdP for {hostname}";
}
} else {
logger.critical($"Could not load SAML2 configuration for {hostname}");
ViewBag.ssoerror = $"Could not load SAML2 configuration for {hostname}";
}
} else {
ViewBag.ssoerror = "SSO is not configured for this client. Please contact Support";
}
return Redirect("/Home/SSOError");
}
The method that loads a client-specific metadata looks like this:
public static Saml2Configuration GetSaml2Config(HttpContextBase context, SchoolSettings forSchool, bool forSandbox) {
LogManager log = new LogManager("getSaml2Config");
Saml2Configuration config = new Saml2Configuration();
if (!forSandbox) {
config.Issuer = _saml2Issuer;
} else {
config.Issuer = _saml2IssuerSandbox;
}
config.SignatureAlgorithm = _saml2SignatureAlgo;
config.CertificateValidationMode = X509CertificateValidationMode.None;
config.RevocationMode = (X509RevocationMode)Enum.Parse(typeof(X509RevocationMode), ConfigurationManager.AppSettings["Saml2:RevocationMode"]);
config.AllowedAudienceUris.Add(config.Issuer);
var entityDescriptor = new EntityDescriptor();
if (forSchool.SAMLMetadataLocationIsUrl) {
try {
entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(forSchool.SAMLMetadataLocation));
} catch (Exception e) {
log.error($"Exception caught loading metadata from school {forSchool.Hostname} at URL {forSchool.SAMLMetadataLocation}\n Exception {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
entityDescriptor.IdPSsoDescriptor = null;
}
} else {
var schoolMetadataPath = context.Server.MapPath("~/App_Data/SAMLMetadata/" + forSchool.SAMLMetadataLocation);
log.info($"Loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}");
try {
entityDescriptor.ReadIdPSsoDescriptorFromFile(schoolMetadataPath);
} catch (IOException ioe) {
log.error($"IOException caught loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}: {ioe.Message}\n{ioe.StackTrace}");
entityDescriptor.IdPSsoDescriptor = null;
} catch (Exception e) {
log.error($"Exception caught loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}\n Exception {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
entityDescriptor.IdPSsoDescriptor = null;
}
}
if (entityDescriptor.IdPSsoDescriptor != null) {
if (entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.Count() > 0) {
config.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
} else {
log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SingleSignOnServices that could be parsed.");
}
if (entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.Count() > 0) {
config.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
} else {
log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SingleLogoutServices that could be parsed.");
}
if (entityDescriptor.IdPSsoDescriptor.SigningCertificates.Count() > 0) {
config.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
} else {
log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SigningCertificates that could be parsed.");
}
} else {
throw new Exception("IdPSsoDescriptor not loaded from metadata.");
}
return config;
}
If it would help to clarify the situation, I can add the code for the AssertionConsumerService Action which works perfectly in an IdP-initiated scenario.
I discovered the problem. It comes down to this line of code in the GetSaml2Config method:
config.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
This naively takes the first SingleSignOnService element in the metadata and decides that it is the correct one to use, but that was not always the case that this assumption was true. What I really wanted was to get a SingleSignOnService element for and HTTP-POST binding:
config.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.Where(s => s.Binding.ToString().IndexOf("HTTP-POST") > 0).FirstOrDefault()?.Location;
This works well for all of the cases that I have found since.
Your code looks correct.
It is probably an integration issue but very hard to find if the IdP do not log an error message.
What error status message do you get back instead of success, maybe that tells you something.
Maybe the IdP do not accept the SAML 2.0 Authn Response, here is something to look for:
The config.SingleSignOnDestination probably is required
Meybe the IdP requere the request to be signed
It is also possible to add other attributes in the request, do the IdP documentation describe any requirements?

Network errors recent build about 75% of time

I get network errors running on android. These do not appear in simulator or ios builds. The errors appears about 75% of the time and then will work correctly for one time. I did some debugging and the network call returns a 0 for response code and null for response content.
I've attached the call below for my get command. This code has not changed in many years (3?). I tried 2 different applications now and both exhibit the same behavior.
I've tried going back to older builds but my 'pro' license only allows me to go back to 1 latest???
I know its not the server as it works for iOS and simulator and 2 different application. I have been unable to figure this out.
An suggestions? I tried to use the new Rest, but it doesn't find the class (i went to latest).
public int doGet(final String url) {
if ( Display.getInstance().isEdt() ){
Log.e("*** Performing a GET network call on the EDT");
}
final ConnectionRequest request = new ConnectionRequest() {
#Override
protected void handleException(Exception err) {
if (Dialog.show("Connection error",
"Check your internet connection", "Retry", "Exit")) {
Display.getInstance().exitApplication();
} else {
retry();
}
}
};
request.setUrl(url);
request.setPost(false);
request.setFollowRedirects(false);
request.setReadResponseForErrors(true);
request.setSilentRetryCount(1);
request.addResponseCodeListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.d("Response code ResponseCodeListener, setting to -1");
responseCode = -1;
}
});
request.addResponseListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Log.e("Response listener action for GET performed " );
ConnectionRequest cr = (ConnectionRequest) evt.getSource();
responseCode = cr.getResponseCode();
Log.e("Response listener action for GET performed: " + cr.getResponseCode() );
if (cr.getResponseCode() == 200) {
responseData = new String(cr.getResponseData());
} else {
Log.e("Response code: " + cr.getResponseCode() + " of " + cr.getUrl() );
}
}
});
// request will be handled asynchronously
NetworkManager.getInstance().setTimeout(15000);
synchronized (lock) {
depth++;
}
try {
request.setDuplicateSupported(true);
NetworkManager.getInstance().addToQueueAndWait(request);
} finally {
synchronized (lock) {
depth--;
}
}
Log.d("Response: {0} {1}", responseCode, responseData);
return responseCode;
}
Log entries:
02-11 10:08:26.932 20250-20326/? D/Word Time: [Thread-18] 0:0:2,486 - Get: /jgame/game/6647?tkn=08F0D0B4E7EE80370B982DBEA261500ADB53266C1847175152-1461100
02-11 10:08:26.933 20250-20326/? D/Word Time: [Thread-18] 0:0:2,488 - Calling: GET http://server.wordtimelive.xyz/jgame/game/6647?tkn=08F0D0B4E7EE80370B982DBEA261500ADB53266C1847175152-1461100
02-11 10:08:26.934 20250-20326/? D/Word Time: [Thread-18] 0:0:2,489 - Get: http://server.wordtimelive.xyz/jgame/game/6647?tkn=08F0D0B4E7EE80370B982DBEA261500ADB53266C1847175152-1461100
02-11 10:08:27.207 20250-20326/? D/Word Time: [Thread-18] 0:0:2,762 - Response: 0 null
02-11 10:08:27.209 20250-20326/? D/Word Time: [Thread-18] 0:0:2,763 - content null of GET: http://server.wordtimelive.xyz/jgame/game/6647?tkn=08F0D0B4E7EE80370B982DBEA261500ADB53266C1847175152-1461100
Thanks for the help in tracking this. Steve fixed the concurrent modification exception in this commit https://github.com/codenameone/CodenameOne/commit/685172518e00a7b846993bbc35967cf49a0bc611
Based on the description it sounds like this is indeed the problem you were experiencing. It will be in the servers tomorrow (Friday February 16th 2018) and you can verify it.

showForm - java.lang.reflect.InvocationTargetException

I have an application on which I was working couple days ago - app was working.
when I try work on it yesterday one of initial screen give me an error
java.lang.reflect.InvocationTargetException
when I call s.showForm("Main",null)
I am using win10, and netbeans 8, latest Codenameone plugin - just reinstall just in case.
I am not sure what could cased this problem.
Thank you for sugestions
Function code:
public void autologin(final StateMachine s,Form f)
{
common.log("Login Auto Login");
autologin=true;
Hashtable hUserDetails = new Hashtable();
Hashtable hLoginDetails = new Hashtable();
hUserDetails = common.readHashtable(constant.getStoreUserDetails());
hLoginDetails = common.readHashtable(constant.getStoreLoginDetails());
if ( hUserDetails!= null && hLoginDetails != null )
{
common.log("Login Check for sessionToken : " + hLoginDetails.get("sessionToken".toString()) );
String SavedSessionToken = hLoginDetails.get("sessionToken".toString()).toString();
common.log("SavedSessionToken : " + SavedSessionToken );
if ( SavedSessionToken.length() > 1 )
{
common.log("Login execute userLogin");
common.log("Call UserLogin user : "+hUserDetails.get("username").toString());
common.log("Call UserLogin pass: "+ hUserDetails.get("password").toString());
UserLogin( s, hUserDetails.get("username").toString(), hUserDetails.get("password").toString(),1);
}else{
common.log("Login sessionToken not found - show Main");
s.showForm("Main",null);
}
}else{
common.log("Login hUserDetails - null; redirect to Main");
try{
s.showForm("Main",null);
}catch (Exception e ){
common.log("autologin showForm Exception "+e );
}
}
}
error message
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.codename1.impl.javase.Executor$1$1.run(Executor.java:100)
at com.codename1.ui.Display.processSerialCalls(Display.java:1148)
at com.codename1.ui.Display.mainEDTLoop(Display.java:965)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Caused by: java.lang.NullPointerException
at userclasses.StateMachine.postMain(StateMachine.java:221)
at generated.StateMachineBase.postShow(StateMachineBase.java:1844)
at com.codename1.ui.util.UIBuilder.postShowImpl(UIBuilder.java:2598)
at com.codename1.ui.util.UIBuilder.showForm(UIBuilder.java:2516)
at com.codename1.ui.util.UIBuilder.showForm(UIBuilder.java:2561)
at userclasses.Login.autologin(Login.java:249)
at userclasses.StateMachine.postSplash(StateMachine.java:539)
at generated.StateMachineBase.postShow(StateMachineBase.java:1820)
at com.codename1.ui.util.UIBuilder.postShowImpl(UIBuilder.java:2598)
at com.codename1.ui.util.UIBuilder.showForm(UIBuilder.java:2516)
at com.codename1.ui.util.UIBuilder.showForm(UIBuilder.java:2561)
at generated.StateMachineBase.startApp(StateMachineBase.java:66)
at generated.StateMachineBase.<init>(StateMachineBase.java:31)
at generated.StateMachineBase.<init>(StateMachineBase.java:118)
at userclasses.StateMachine.<init>(StateMachine.java:53)
at com.degmorinc.app.Degmor.DegmorIncSupport.start(DegmorIncSupport.java:20)
... 9 more
Java Result: 1

error handling in Akka Kafka Producer

I am using reactive-kafka-core 0.10.1 (targeting Kafka 0.9.x). It looks like Kafka producer actor is stopped whenever an error is encountered from the callback function. Is there any way to customize this behavior? Our use case is to try to recover and resend the messages.
private def processElement(element: ProducerMessage[K, V]) = {
val record = richProducer.props.partitionizer(element.value) match {
case Some(partitionId) => new ProducerRecord(richProducer.props.topic, partitionId, element.key, element.value)
case None => new ProducerRecord(richProducer.props.topic, element.key, element.value)
}
richProducer.producer.send(record, new Callback {
override def onCompletion(metadata: RecordMetadata, exception: Exception) = {
if (exception != null) {
handleError(exception)
}
}
})
()} private def handleError(ex: Throwable) = {
log.error(ex, "Stopping Kafka subscriber due to fatal error.")
stop()
}

What should we use for ClientResponse and GenericType in latest version (3.0.x) Resteasy?

I am developing Resteasy. I migrated my application's maven dependencies from 2.2.x to 3.0.x and suddenly I saw most of the API's are deprecated. So this migration has affect to my code and test cases as its simply saying deprecated in my whole code.
I am taking example of my test cases:
Test case with earlier version(in latest version it deprectaed as mentioned in link: ClientRequestFactory RestEasy Deprecated... Any other RestEasy alternative ?):
import org.jboss.resteasy.util.GenericType;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
#Test
public void testGetStudent() throws Exception{
String str = "http://localhost:8080/RESTfulExample/rest/restwebservice/list";
ClientRequest request = new ClientRequest(str);
ClientResponse<List<Student>> response = request.get(new GenericType<List<Student>>(){});
List<Student> students = response.getEntity();
System.out.println("Size : "+students.size());
}
So I refactore my test case to use
#Test
public void testGetStudents(){
final String str = "http://localhost:8080/RESTfulExample/rest/restwebservice/list";
Client client = ClientBuilder.newClient();
// Client client = ClientBuilder.newBuilder().build(); // This also works, OR
Response response = client.target(str).request().get();
// This will gives us whole XML output
String s = response.readEntity(String.class);
System.out.println(s);
**What is the replacement of below two lines in latest version? How I can get List of Student Object ?**
// ClientResponse<List<Student>> response = request.get(new GenericType<List<Student>>(){});
// List<Student> students = response.getEntity();
}
Please guide. What is the replacement of below two lines in latest version? How I can get List of Student Object ?
Edit-1: I tried below, but giving following error:
Students.java
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "students")
public class Students {
#XmlElement(name="student")
private ArrayList<Student> users;
public ArrayList<Student> getUsers() {
return users;
}
public void setUsers(ArrayList<Student> users) {
this.users = users;
}
}
But its giving me errors:
#Test
public void testGetStudents(){
final String str = "http://localhost:8080/RESTfulExample/rest/restwebservice/list";
Client client = ClientBuilder.newClient();
// Client client = ClientBuilder.newBuilder().build(); // This also works, OR
Response response = client.target(str).request().get();
// This will gives us whole XML output
String stringOutput = response.readEntity(String.class);
System.out.println("STATUS : "+response.getStatus());
System.out.println(stringOutput);
Students students = response.readEntity(Students.class);
System.out.println("Size : "+students.getUsers().size());
}
java.lang.IllegalStateException: RESTEASY003765: Response is closed.
at org.jboss.resteasy.specimpl.BuiltResponse.abortIfClosed(BuiltResponse.java:256)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.abortIfClosed(ClientResponse.java:328)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:152)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:219)
at com.mkyong.rest.test.RestEasySampleTest.testGetStudents(RestEasySampleTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The Resteasy Client-API has been marked deprecated as JAX-RS standardized a Client-API. You can now use the equivalent javax.ws.rs classes:
javax.ws.rs.client.Client client = javax.ws.rs.client.ClientBuilder.newClient();
javax.ws.rs.client.WebTarget target = client.target("someUrl");
List<Student> students =
target.request().get(new javax.ws.rs.core.GenericType<List<Student>>() {});
Here's an example with query parameters and a check for the HTTP response code, which is handy for failing fast and avoiding stack traces from the JSON mapper, often hiding the real cause:
Response response = null;
try {
response = target.path("apiMethod")
.queryParam("stringParam", "test")
.queryParam("booleanParam", Boolean.FALSE)
.request().accept(MediaType.APPLICATION_JSON).get();
if (response.getStatus() == Response.Status.BAD_REQUEST.getStatusCode()) { // HTTP 400
throw new BadRequestException("invalid parameters!");
} else if (response.getStatus() ==
Response.Status.NOT_FOUND.getStatusCode()) { // HTTP 404
throw new NotFoundException("resource was not found on server!");
}
List<MyPojo> result = response.readEntity(new GenericType<List<MyPojo>>(){});
return result;
} finally {
if (response != null) {
response.close();
}
}

Resources