not able to add a imageview to custom adapter to be shown into a gridview , it is giving classcast exception on setimageresource - casting

package com.ettv.tv.forealz;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import com.ettv.tv.R;
`import com.ettv.tv.forealz.model.ModelStore;
`import com.ettv.tv.forealz.model.Topic;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
`import static com.ettv.tv.MovieList.list;
// it is the custom adapter
`public class CustomAdapter2 extends BaseAdapter {
`
#Override
public int getCount() {
return topics3.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
` return position;
}
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
convertView = thisInflater.inflate( R.layout.row_item, parent,
false );
//TextView textHeading = (TextView)
convertView.findViewById(R.id.petnames);
ImageView thumbnailImage = (ImageView)
convertView.findViewById(R.id.image);
final List list = new ArrayList<Integer>();
for (Topic topic : topics3) {
thumbnailImage.setImageResource(topics3.get(position).getmDrawable());
}
}
}
return convertView;
}
private List topics3;
private LayoutInflater thisInflater;
public CustomAdapter2(Context con, List<Topic> topics2) {
` this.thisInflater = LayoutInflater.from(con);
this.topics3=topics2;
Log.d("check7",this.topics3.toString());
Log.d("check8", String.valueOf(topics2.size()));
}
}
}

Related

How to apply Interceptor(Schema validation) to a specific endpoint among multiple services deployed on server

I have two soap end points(soap services) deployed in one server. When i override the following interceptor, it is applying to both services. How to enable/disable the interceptor specific to one service. Kindly help
The interceptor code as follows.
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
validatingInterceptor.setValidateRequest(true);
validatingInterceptor.setValidateResponse(true);
validatingInterceptor.setXsdSchemaCollection(LogAnalyzerFile());
interceptors.add(validatingInterceptor);
}
Note: Its an spring boot project, using annotations.
I
package com.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurationSupport;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.SmartEndpointInterceptor;
import org.springframework.ws.server.endpoint.MethodEndpoint;
import org.springframework.ws.soap.SoapBody;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition;
import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
#EnableWs
#Configuration
public class TestConfig extends WsConfigurationSupport implements SmartEndpointInterceptor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#Bean(name="testlog")
public ServletRegistrationBean testlog(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "/File/*");
servletRegistrationBean.setName("Log");
return servletRegistrationBean;
}
#Bean(name = "testFile")
public Wsdl11Definition testFile()
{
SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
wsdl11Definition.setWsdl(new ClassPathResource("test.wsdl"));
logger.info("test.wsdl:");
return wsdl11Definition;
}
#Bean(name = "UploadLogFile")
public XsdSchema UploadLogFile() {
return new SimpleXsdSchema(new ClassPathResource("1.xsd"));
}
#Bean(name = "ErrorInfo")
public XsdSchema ErrorInfo() {
return new SimpleXsdSchema(new ClassPathResource("2.xsd"));
}
public Resource[] getSchemas() {
List<Resource> schemaResources = new ArrayList<>();
schemaResources.add(new ClassPathResource("1.xsd"));
schemaResources.add(new ClassPathResource("2.xsd"));
return schemaResources.toArray(new Resource[schemaResources.size()]);
}
#Override
public boolean shouldIntercept(MessageContext messageContext, Object endpoint) {
if (endpoint instanceof MethodEndpoint) {
MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
return methodEndpoint.getMethod().getDeclaringClass() == YourEndpoint.class;
}
return false;
}
private Boolean validateSchema(Source source_, MessageContext messageContext) throws Exception {
boolean errorFlag = true;
SchemaFactory _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema _schema = _schemaFactory.newSchema(getSchemas()[0].getFile());
Validator _validator = _schema.newValidator();
DOMResult _result = new DOMResult();
try {
_validator.validate(source_, _result);
} catch (SAXException _exception) {
errorFlag = false;
SoapMessage response = (SoapMessage) messageContext.getResponse();
String faultString = StringUtils.hasLength(_exception.getMessage()) ? _exception.getMessage() : _exception.toString();
SoapBody body = response.getSoapBody();
body.addServerOrReceiverFault(faultString, Locale.US);
_exception.printStackTrace();
}
return errorFlag;
}
#Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
WebServiceMessage webServiceMessageRequest = messageContext.getRequest();
SoapMessage soapMessage = (SoapMessage) webServiceMessageRequest;
SoapHeader soapHeader = soapMessage.getSoapHeader();
Source bodySource = soapMessage.getSoapBody().getPayloadSource();
return validateSchema(bodySource,messageContext);
}
#Override
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
#Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return false;
}
#Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
}
}

seek bar not working when playing mp3 song from server

In my app I am trying to play a media player from server along with a seek bar. When I tried to play the song from server, my app was working fine but the seek bar was not getting moved ! Also, The seekbar is not working....
It's not displaying MediaPlayer progress
also, It is playing multiple songs at the same time
solution needed for 2 bugs
Here is a screenshot of that app
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
private ArrayList<SongInfo> _songs = new ArrayList<SongInfo>();
RecyclerView recyclerView;
SeekBar seekBar;
SongAdapter songAdapter;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
SongInfo s = new SongInfo("Cheap Thrills", "sia", "http://176.126.236.250/33Mmt/music/hindi/movies/new/oh_my_god/Go-Go-Govinda_(webmusic.in).mp3");
_songs.add(s);
s = new SongInfo("Cheap Thrills", "sia", "http://176.126.236.250/33Mmt/music/hindi/movies/new/oh_my_god/Go-Go-Govinda_(webmusic.in).mp3");
_songs.add(s);
songAdapter = new SongAdapter(this, _songs);
recyclerView.setAdapter(songAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(songAdapter);
songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
#Override
public void onItemClick(final Button b, View view, SongInfo obj, int position) {
try {
if (b.getText().toString().equals("stop")) {
b.setText("Play");
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}else {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongUrl());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
b.setText("stop");
}
});
}
} catch (IOException e) {
}
}
});
}
}
this is my song adapter code -:
package com.a03.dip.kaliprasadbengalisongs;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongHolder> {
ArrayList<SongInfo> _songs;
Context context;
OnItemClickListener mOnItemClickListener;
SongAdapter(Context context, ArrayList<SongInfo> songs) {
this.context = context;
this._songs = songs;
}
public interface OnItemClickListener {
void onItemClick(Button b ,View view, SongInfo obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
#Override
public SongHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View myView = LayoutInflater.from(context).inflate(R.layout.row_song,viewGroup,false);
return new SongHolder(myView);
}
#Override
public void onBindViewHolder(final SongHolder songHolder, final int i) {
final SongInfo c = _songs.get(i);
songHolder.songName.setText(_songs.get(i).songName());
songHolder.artistName.setText(_songs.get(i).artistName());
songHolder.btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(songHolder.btnAction,v, c, i);
}
}
});
}
#Override
public int getItemCount() {
return _songs.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView songName,artistName;
Button btnAction;
public SongHolder(View itemView) {
super(itemView);
songName = (TextView) itemView.findViewById(R.id.tvSongName);
artistName = (TextView) itemView.findViewById(R.id.tvArtistName);
btnAction = (Button) itemView.findViewById(R.id.btnPlay);
}
}
}
and here is songInfo class -----
package com.a03.dip.kaliprasadbengalisongs;
import android.media.MediaPlayer;
public class SongInfo {
public String songName ,artistName,songUrl;
public SongInfo() {
}
public SongInfo(String songName, String artistName, String songUrl) {
this.songName = songName;
this.artistName = artistName;
this.songUrl = songUrl;
}
public String songName() {
return songName;
}
public String artistName() {
return artistName;
}
public String getSongUrl() {
return songUrl;
}
}
you have to use seekbar listener on ur activity.
seekBar.setOnSeekBarChangeListener(new >SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int >progress,
boolean fromUser) {
if (fromUser) {
mPlayer.seekTo(progress);
}
}

java.lang.ClassCastException: android.app.ReceiverRestrictedContext cannot be cast to android.app.Activity

This is my manifest
<receiver android:name="com.devfret.mobile.Fretlink.receivers.GpsLocationReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.LOCALE_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
At the time I close the gps, I get crash . with this line=>
status.startResolutionForResult( (Activity)ctx , 1000);
my classes which I call this method (CheckAndOpenGps)extends AppCompatActivity .
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.devfret.mobile.Fretlink.R;
public class GpsLocationReceiver extends BroadcastReceiver {
public GpsLocationReceiver() {
}
private GoogleApiClient googleApiClient;
public Context contex;
ContentResolver contentResolver;
// int mode = Settings.Secure.getInt(
// contentResolver, Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
//String locationMode="Gps is not activated";
LocationManager locationManager;
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
this.contex = context;
contentResolver = context.getContentResolver();
locationManager = (LocationManager) contex.
getSystemService(Context.LOCATION_SERVICE);
if (!IsGpsStatusActive(locationManager)) {
Toast.makeText(context, "GPS is not working. Please Activate the GPS", Toast.LENGTH_SHORT).show();//emre changed
CheckAndOpenGps(context, googleApiClient);
}
}
public static Boolean IsGpsStatusActive(LocationManager locationManager)//e
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return false;
} else
return true;
}
public static void buildAlertMessageNoGps(final Context ctx, final GoogleApiClient googleApiClient) // emre yazdi
{
final LayoutInflater mInflater = LayoutInflater.from(ctx);
final AlertDialog.Builder builder = new AlertDialog.Builder(mInflater.getContext());
final AlertDialog.Builder builderexit = new AlertDialog.Builder(mInflater.getContext());
builder.setMessage(R.string.gps_off_turn_on).setCancelable(false).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused")
final int id) {
CheckAndOpenGps(ctx, googleApiClient);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
builderexit.setMessage(R.string.canoot_work_without_gps).setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused")
final int id) {
System.exit(0);
}
});
final AlertDialog alertexit = builderexit.create();
alertexit.show();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
public static void CheckAndOpenGps(final Context ctx, GoogleApiClient googleApiClient) {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(ctx).addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//locationRequest.setInterval(30 * 1000);//emre 30
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
com.google.android.gms.common.api.PendingResult result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
//final GoogleApiClient finalGoogleApiClient = googleApiClient;
result.setResultCallback(new ResultCallback() {
#Override
public void onResult(#NonNull Result result) {
final Status status = result.getStatus();
Log.d("statusCode", String.valueOf(status.getStatusCode()) + " message " + status.getStatusMessage());
//
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult( (Activity)ctx , 1000);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
}
}
The problem: long story short you are trying to cast BroadcastReceiver's context to Activity here:
status.startResolutionForResult( (Activity)ctx , 1000);
Which is wrong, since those are two unrelated objects.
A solution: since the method does require Activity as a parameter, why not pass the activity there.
I suppose your app does have at least one Activity (if not, you can create one), so just pass the status to it in extras:
ctx.startActivity(new Intent(ctx, YourActivityName.class).putExtra("status-to-resolve", status));
And then in its onCreate() method you can unparcel your status and do the resolution:
Status status = (Status) getIntent().getParcelableExtra("status-to-resolve");
status.startResolutionForResult(this, 1000);

A message body writer for Java type was not found

I am receiving following exception:
ClientHandlerException: A message body writer for Java type,
class com.company.testing.repo.model.Privilege,
and MIME media type,
application/octet-stream, was not found
Privilege is an ENUM class:
public enum Privilege {
READ,
WRITE;
}
Resource entry is this:
#Path("repoPrivs")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
Response getGroups(Privilege privilege);
my client code is this:
#Override
public List<MyGroup> getGroups(Privilege privilege) {
IWebParamaterProvider provider = WebParamaterFactory.create("repo-mapping/repoPrivs", //$NON-NLS-1$
SecureAction.READ, webProxy);
provider = provider.setType(MediaType.APPLICATION_JSON);
provider = provider.setAccept(MediaType.APPLICATION_JSON);
List<MyGroup> groups = null;
groups = webProxy.post(provider, new GenericTypeFactory<MyGroup>(), MyGroup.class, privilege);
return groups;
}
Override
public final <T> List<T> post(IWebParamaterProvider provider, GenericTypeFactory<T> genericsFactory,
Class<T> clazz, Object requestEntity){
WebResource resource = ((IWebResourceProvider) provider).getWebResource();
TRACER.trace("POST: " + resource.getURI().toString()); //$NON-NLS-1$
return resource.post(genericsFactory.create(clazz), requestEntity);
}
public GenericType<List<T>> create(final Class<T> clazz) {
ParameterizedType genericType = new ParameterizedType() {
#Override
public Type[] getActualTypeArguments() {
return new Type[] { clazz };
}
#Override
public Type getOwnerType() {
return List.class;
}
#Override
public Type getRawType() {
return List.class;
}
};
return new GenericType<List<T>>(genericType) {
};
}
What is that I am missing
It is very important to provide complete minimal example so other people can help you.
Below you have Jersey 2 and Jersey 1 example and both of them uses in memory test container. Make sure to get the all the required dependencies based on the version.
Jersey 2
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.junit.Assert.*;
public class JerseyVersion2Test extends JerseyTest {
#Path("hello")
public static class HelloResource {
#POST
#Produces(APPLICATION_JSON)
#Consumes(APPLICATION_JSON)
public List<MyGroup> doPost(Privilege privilege) {
List<MyGroup> myGroups = new ArrayList<>();
MyGroup myGroup = new MyGroup();
myGroup.name = "jersey";
myGroup.version = 2;
myGroups.add(myGroup);
return myGroups;
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Override
protected TestContainerFactory getTestContainerFactory() {
return new InMemoryTestContainerFactory();
}
#Test
public void testPost() {
List<MyGroup> myGroups = getGroups();
assertEquals(1, myGroups.size());
}
public enum Privilege {
READ,
WRITE;
}
public List<MyGroup> getGroups() {
List<MyGroup> groups = target("hello").request().
accept(MediaType.APPLICATION_JSON).
post(Entity.json(Privilege.READ)).
readEntity(new GenericTypeFactory<MyGroup>().create(MyGroup.class));
return groups;
}
#JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public static class MyGroup {
private String name;
private double version;
}
public class GenericTypeFactory<T> {
public GenericType<List<T>> create(final Class<T> clazz) {
ParameterizedType genericType = new ParameterizedType() {
#Override
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
#Override
public Type getOwnerType() {
return List.class;
}
#Override
public Type getRawType() {
return List.class;
}
};
return new GenericType<List<T>>(genericType) {
};
}
}
}
Jersey 1
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
import com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory;
import org.junit.Test;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.junit.Assert.assertEquals;
public class JerseyVersion1Test extends JerseyTest {
#Path("hello")
public static class HelloResource {
#POST
#Produces(APPLICATION_JSON)
#Consumes(APPLICATION_JSON)
public List<MyGroup> doPost(Privilege privilege) {
List<MyGroup> myGroups = new ArrayList<>();
MyGroup myGroup = new MyGroup();
myGroup.name = "jersey";
myGroup.version = 1.12;
myGroups.add(myGroup);
return myGroups;
}
}
#Override
protected AppDescriptor configure() {
return new LowLevelAppDescriptor.Builder(HelloResource.class).build();
}
#Override
protected TestContainerFactory getTestContainerFactory() {
return new InMemoryTestContainerFactory();
}
#Test
public void testPost() {
List<MyGroup> myGroups = getGroups();
assertEquals(1, myGroups.size());
}
public enum Privilege {
READ,
WRITE;
}
public List<MyGroup> getGroups() {
WebResource webResource = resource();
List<MyGroup> groups = webResource.path("hello").
accept(MediaType.APPLICATION_JSON).
type(MediaType.APPLICATION_JSON).
post(new GenericTypeFactory<MyGroup>().create(MyGroup.class), Privilege.READ);
return groups;
}
#JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public static class MyGroup {
private String name;
private double version;
}
public class GenericTypeFactory<T> {
public GenericType<List<T>> create(final Class<T> clazz) {
ParameterizedType genericType = new ParameterizedType() {
#Override
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
#Override
public Type getOwnerType() {
return List.class;
}
#Override
public Type getRawType() {
return List.class;
}
};
return new GenericType<List<T>>(genericType) {
};
}
}
}
javax.xml.bind.annotation.XmlRootElement
Java doc:
The #XmlRootElement annotation can be used with the following program
elements:
a top level class
an enum type
[...]
When a top level class or an enum type is annotated with the #XmlRootElement annotation, then its value is represented as XML element in an XML document.
in your case it is clear that Jersey unable to unmarshall the incoming JSON payload to your object, thus the exception
A message body writer for Java type, class com.company.testing.repo.model.Privilege
annotating your Enum (Privilege) with #XmlRootElement should solve the issue.
#XmlRootElement
public enum Privilege {
READ,
WRITE;
}

How do I write a ExtensionFunctionDefinition in saxon 9.5?

The example usage of ExtensionFunctionDefinition from the saxon documentation does not compile with Saxon version 9.5.1-6
The error I get is:
java: <anonymous ShiftLeft$1> is not abstract and does not override abstract method call(net.sf.saxon.expr.XPathContext,net.sf.saxon.om.Sequence[]) in net.sf.saxon.lib.ExtensionFunctionCall
How do I make this code compile in Saxon 9.5?
private static class ShiftLeft extends ExtensionFunctionDefinition {
#Override
public StructuredQName getFunctionQName() {
return new StructuredQName("eg", "http://example.com/saxon-extension", "shift-left");
}
#Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[] {SequenceType.SINGLE_INTEGER, SequenceType.SINGLE_INTEGER};
}
#Override
public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
return SequenceType.SINGLE_INTEGER;
}
#Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException {
long v0 = ((IntegerValue)arguments[0].next()).longValue();
long v1 = ((IntegerValue)arguments[1].next()).longValue();
long result = v0<<v1;
return Value.asIterator(Int64Value.makeIntegerValue(result));
}
};
}
}
import com.saxonica.config.EnterpriseTransformerFactory;
import com.saxonica.config.ProfessionalConfiguration;
import com.saxonica.objectweb.asm.tree.analysis.Value;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.Int64Value;
import net.sf.saxon.value.IntegerValue;
import net.sf.saxon.value.SequenceType;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringWriter;
class ShiftLeft extends ExtensionFunctionDefinition {
#Override
public StructuredQName getFunctionQName() {
return new StructuredQName("eg", "http://example.com/saxon-extension", "shift-left");
}
#Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[]{SequenceType.SINGLE_INTEGER, SequenceType.SINGLE_INTEGER};
}
#Override
public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
return SequenceType.SINGLE_INTEGER;
}
#Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
#Override
public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
long v0 = ((IntegerValue)arguments[0]).longValue();
long v1 = ((IntegerValue)arguments[1]).longValue();
long result = v0<<v1;
return Int64Value.makeIntegerValue(result);
}
};
}
}