How do I write a ExtensionFunctionDefinition in saxon 9.5? - xslt

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);
}
};
}
}

Related

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

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()));
}
}
}

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);
}
}

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;
}

I'm getting NoSuchMethodException map<init>method required while compling my mapreduce code

I tried to find out Top N words from my input text file I tried but unable to compile the code I'm getting a run-time exception () not found in mapper. Please help me on this and I am very new to hadoop trying to expertise in this field. Any advice and suggestions from the experts really helps me to be successful.
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class topn {
/* Mapper Class */
public class topnmap extends Mapper<LongWritable,Text,Text,IntWritable>
{
public void init()
{
}
String token=",";
Text word =new Text();
public void map(LongWritable key,Text value,Context context)
{
String wrd;
String line=value.toString().replaceAll(token, " ").trim();
StringTokenizer str=new StringTokenizer(line);
while(str.hasMoreTokens())
{
wrd=str.nextToken();
word.set(wrd);
try {
context.write(word,new IntWritable(1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/*combiner Class */
public class topncombiner extends Reducer<Text,IntWritable,Text,IntWritable>
{
public void reduce(Text key,Iterable<IntWritable> value,Context context)
{
int sum=0;
for(IntWritable val:value)
{
sum +=val.get();
}
try {
context.write(key,new IntWritable(sum));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/* Reducer */
public class topnreduce extends Reducer<Text,IntWritable,Text,IntWritable>
{
public void init()
{
}
private Map<Text,IntWritable> m1=new HashMap();
public void reduce(Text key,Iterable<IntWritable> value,Context context)
{
int sum=0;
for(IntWritable val:value)
{
sum +=val.get();
}
m1.put(key,new IntWritable(sum));
}
/*Clean up */
protected void cleanup(Context context) throws IOException,InterruptedException
{
Map<Text,IntWritable> sortedmap= sortbyvalues(m1);
for(Text key:sortedmap.keySet())
{
context.write(new Text(key.toString()), sortedmap.get(key));
}
}
}
/* comparable method */
private static <K extends Comparable,V extends Comparable> Map<K,V> sortbyvalues(Map<K,V> map) {
List<Map.Entry<K,V>> entry=new LinkedList<Map.Entry<K,V>>(map.entrySet());
Collections.sort(entry,new Comparator<Map.Entry<K,V>>() {
#Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
// TODO Auto-generated method stub
return o2.getValue().compareTo(o1.getValue());
}
});
Map<K,V> sortedmap=new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entr:entry)
{
sortedmap.put(entr.getKey(), entr.getValue());
}
return sortedmap;
}
public static void main(String args[]) throws IOException,
ClassNotFoundException, InterruptedException
{
Configuration conf=new Configuration();
Job job=new Job(conf);
job.setJarByClass(topn.class);
job.setCombinerClass(topncombiner.class);
job.setMapperClass(topnmap.class);
job.setReducerClass(topnreduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.setInputPaths(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
Your Mapper, Reducer, and Combiner classes need to be static. Otherwise Hadoop can't access them without an instance of the outer class, which it won't have.