What should we use for ClientResponse and GenericType in latest version (3.0.x) Resteasy? - 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();
}
}

Related

MediaRecorder: java.lang.IllegalStateException at

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)

Solr NonRepeatableRequestException in save action

I have configured Spring data solr 1.5.4 to use Apache Solr 5.2.1 and this is my configuration:
#Bean
public SolrTemplate solrTemplate() {
return new SolrTemplate(solrServerFactory());
}
#Bean
public SolrServerFactory solrServerFactory() {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
return new HttpSolrServerFactory(solrServer(), "", credentials, "BASIC");
}
#Bean
public SolrServer solrServer() {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);
params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, username);
params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, password);
params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345);
params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true);
params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345);
params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345);
params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345);
params.set(HttpClientUtil.PROP_USE_RETRY, false);
HttpClient httpClient = HttpClientUtil.createClient(params);
HttpSolrServer httpSolrServer = new HttpSolrServer("http://" + host + ":" + port + "/solr/", httpClient);
return httpSolrServer;
}
but when I want to save the document, this exception occurs:
14:28:45,863 Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
14:28:45,863 at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:660)
14:28:45,863 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
14:28:45,863 at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
Please help me.
Until this is fixed, implement PreemptiveAuthInterceptor and addRequestInterceptor before createClient
Sample is available at PreemptiveAuthInterceptor.java
e.g.
ModifiableSolrParams params = new ModifiableSolrParams();
params.add(HttpClientUtil.PROP_BASIC_AUTH_USER, uname);
params.add(HttpClientUtil.PROP_BASIC_AUTH_PASS, pwd);
params.add(HttpClientUtil.PROP_BASIC_AUTH_PASS, pwd);
HttpClientUtil.addRequestInterceptor(new PreemptiveAuthInterceptor());
CloseableHttpClient httpclient = HttpClientUtil.createClient(params);

500 Error - Unable to select and perform a post action

I am not good with Web API. Here is my problem. I send an Json serialized object from my Windows Form Application. The object is an Entity table. When I do a get response it returns a 500 server error. Basically I plan to have multiple post methods in one controller which I may not be doing right. So I need you guys to guide me on what I have been doing wrong.
Here is my Controller:
[ResponseType(typeof(HttpWebResponse)), HttpPost, ActionName("MerchandiseApi")]
public HttpResponseMessage PostMain(IList<IMF_Main> mainFromConsolidator)
{
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest, 2);
using (var anthill = new AnthillConsolidatorEntities())
{
var main = new IMF_Main();
foreach (var item in mainFromConsolidator)
{
main.BrandID = item.BrandID;
main.ItemID = item.ItemID;
main.CategoryID = item.CategoryID;
main.SubCategoryID = item.SubCategoryID;
main.ClassID = item.ClassID;
main.GenderID = item.GenderID;
main.CoaID = item.CoaID;
main.SubCoaID = item.SubCoaID;
main.First_SRP = item.First_SRP;
main.Current_SRP = item.Current_SRP;
main.Previous_SRP = item.Previous_SRP;
main.isSenior = item.isSenior;
main.isActive = item.isActive;
main.DateCreated = item.DateCreated;
anthill.IMF_Main.Add(main);
anthill.SaveChanges();
}
}
return Request.CreateResponse(HttpStatusCode.OK, 1);
}
Here's my WebApiConfig:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "MerchandiseApi",
routeTemplate: "api/{controller}/{action}"
);
}
Here is where the Uri gets built: I have 2 more tables to send but I will start with this. This goes to my first Post method to the server
var jsonMain = JsonConvert.SerializeObject(consolidatorEntities.IMF_Main, Formatting.None);
HttpPost("http://localhost:50826/api/Merchandise/PostMain", jsonMain) == 1.ToString()
public string HttpPost(string uri, string json)
{
string content = "";
try
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
byte[] bodyBytes = Encoding.UTF8.GetBytes(json);
request.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
request.GetRequestStream().Close();
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncod
ing("UTF-8"));
content = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error sending data to Anthill \nException: " + ex, "Monytron - Consolidator", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return content;
}
Problem
The main problem is with your routing. Routes will check in order so when you post a request to http://localhost:50826/api/Merchandise/PostMain and you have these routes in order:
"api/{controller}/{id}"
"api/{controller}/{action}"
So the first route will match:
If your PostMain method is the only action with [HttpPost], then mainFromConsolidator will be null in your foreach loop you will receive a NullReferenceException that result in a 500 error.
If you have multiple method decorated with [HttpPost], then the call is ambiguous between those actions and you will receive an InvalidOperationExpception with "Multiple actions were found that match the request" message that result in a 500 error.
The other problem is you are using an ActionName("MerchandiseApi") but didn't post to that action.
Solution
You can use multiple solutions. As an option you can define only one route:
"api/{controller}/{action}/{id}"
This way you can create a controller that contains actions like these:
public class SomeController
{
// matches GET /api/some/action1
[HttpGet]
public HttpResponseMessage Action1()
// matches GET /api/some/action2/5
[HttpGet]
public HttpResponseMessage Action2(int id)
// matches POST /api/some/action3
[HttpPost]
public HttpResponseMessage Action3(SomeType someParameter)
// matches POST /api/some/action4
[HttpPost]
public HttpResponseMessage Action4(SomeType someParameter)
}
Anyway if you decide to define multiple routes, pay attention that routes will match in order and also if you used ActionName attribute, then use that name in url to call that action.

Unsupported Media Type Spring ReST resource

I have a simple method defined in my Rest Resource as below:
#RequestMapping(value = "/{studyId}/cases/{caseId}/exportlocation/{exportLocation}", method = RequestMethod.PUT)
#Timed
public void exportCase(#PathVariable Long studyId, #PathVariable Long caseId, #PathVariable String exportLocation,
#RequestBody Case acase) throws Exception {
log.debug("REST request to export Case {} for Study : {}", acase, studyId);
String exportFileName = exportService.exportCase(acase, "test");
// if (exportFileName == null) {
// response.sendError(HttpServletResponse.SC_NOT_FOUND, "Can't Export");
// }
// return exportFileName;
}
When I make a call on the page, I can see the URL as being /app/rest/studies/1/cases/1/exportlocation/test
I have the Request Mapping defined as
#RequestMapping(value = StudyResource.REQUEST_MAPPING, produces = MediaType.APPLICATION_JSON_VALUE)
#Secured(AuthoritiesConstants.USER)
public class StudyResource {
private final Logger log = LoggerFactory.getLogger(StudyResource.class);
public static final String REQUEST_MAPPING = "/app/rest/studies";
But keep getting a 415 Unsupported Media type. Can someone please look at the lines of code and tell me what is wrong. I highly appreciate your time and help.
My JS layer from where the calls are made on the page are as shown"
$scope.exportCase = function(studyId, caseId, exportLocation){
StudyService.updatecase.get({studyId:studyId,caseId:caseId}).$promise.then(function(acase){
$scope.acase = acase;
console.log(acase);
});
StudyService.exportcase.exportc({studyId: studyId,caseId:caseId,exportLocation:exportLocation},$scope.acase,
function () {
AND JS Service part below
exportcase : $resource('app/rest/studies/:studyId/cases/:caseId/exportlocation/:exportLocation', {}, {
'exportc' : {
method : 'PUT',
params : {
studyId : '#studyId',
caseId : '#caseId',
exportLocation : '#exportLocation'
}
},
})

How to make a correct select query on google endpoint?

I created an Android project using Google Cloud Endpoints, I created a model class Poll.java and now I want to make a query in the PollEndpoint.java class, to retrieve a poll with a specific author.
This is the query code in PollEndpoint.java
#ApiMethod(name = "getSpecificPoll", path="lastpoll")
public Poll getSpecificPoll(#Named("creator") String creator) {
EntityManager mgr = getEntityManager();
Poll specificPoll = null;
try {
Query query = mgr.createQuery("select from Poll where creator
='"+creator+"'");
specificPoll = (Poll) query.getSingleResult();
} finally {
mgr.close();
}
return specificPoll;
}
The code in the client part is:
private class PollQuery extends AsyncTask<Void, Void, Poll> {
#Override
protected Poll doInBackground(Void... params) {
Poll pollQuery = new Poll();
Pollendpoint.Builder builderQuery = new Pollendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new
JacksonFactory(),null);
builderQuery = CloudEndpointUtils.updateBuilder(builderQuery);
Pollendpoint endpointQuery = builderQuery.build();
try {
pollQuery =
endpointQuery.getSpecificPoll("Bill").execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (pollQuery != null){
System.out.println(pollQuery.getKeyPoll().getId());
} else System.out.println("Null query");
return null;
}
The problem is that the server throw an exception:
javax.persistence.PersistenceException: FROM clause of query has class com.development.pollmeproject.Poll but no alias
at org.datanucleus.api.jpa.NucleusJPAHelper.getJPAExceptionForNucleusException(NucleusJPAHelper.java:302)
I think that the query statement is not correct, how can I write a correct one?
The query you provided is NOT valid JPQL. JPQL is more of the form
SELECT p FROM Poll p WHERE p.creator = :creatorParam
The error message does tell you that though, so I'm not sure why you're not sure of it

Resources