Xml is working fine but json is not in jax rs - api

I am learning restful api with jax rs(jersey) and I making a messageResource class in which I am getting messages .everything works fine with xml but get function is not working with json .I have tried content type and accept headers too but its not working and returning 500 error and content type text/html.
Even the maven dependency moxy is also set in pom.xml
Can anybody help me finding the error.
package org.restfulapi.messenger.resources;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.restfulapi.messenger.services.DataNotFoundException;
import org.restfulapi.messenger.services.Link;
import org.restfulapi.messenger.services.Message;
import org.restfulapi.messenger.services.MessageService;
#Path("messages")
#Produces(value= {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
#Consumes(value= {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public class MessageResource
{
MessageService service=new MessageService();
#GET
#Path("/{messageID}")
public Message getMessage(#PathParam("messageID")int id,#Context UriInfo uriinfo )
{
Message msg=service.getMessage(id);
if(service.getMessage(id)==null)
{
throw new DataNotFoundException("message with id "+id+"not found");
}
return msg;
}
#GET
public List<Message> getMessages(#QueryParam("year")int year,
#QueryParam("start") int start,
#QueryParam("size") int size)
{
if(year>0)
{
return service.getbyyear(year);
}
if(start>0 & size>0)
{
return service.get(start, size);
}
return service.getMessages();
}
#POST
public Response addMessage(Message msg) throws URISyntaxException
{
return Response.created(new URI("/messenger/webapi/messages"+msg.getId())).entity(service.addMessage(msg)).build();
}
package org.restfulapi.messenger.services;
import java.util.List;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class MessageService {
private HashMap<Integer, Message> messages = Database.getMessages();
public MessageService()
{
}
public ArrayList<Message> getMessages() {
return new ArrayList<Message>(messages.values());
}
;
public Message getMessage(int id) {
return messages.get(id);
}
public ArrayList<Message> getbyyear(int year)
{
ArrayList<Message> result =new ArrayList();
Calendar cal=Calendar.getInstance();
for(Message msg:messages.values())
{
cal.setTime(msg.getCreated());
if(cal.get(Calendar.YEAR)==year)
result.add(msg);
}
return result;
}
public List<Message> get(int start,int size)
{
ArrayList<Message> result =new ArrayList<Message>(messages.values());
return result.subList(start, start+size);
}
public Message addMessage(Message message) {
message.setId(messages.size() + 1);
messages.put(message.getId(), message);
return message;
}
}
package org.restfulapi.messenger.services;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Message {
private int id;
private String msg;
private Date created;
private String author;
private ArrayList<Link> links=new ArrayList();
public ArrayList<Link> getLinks() {
return links;
}
public void setLinks(ArrayList<Link> links) {
this.links = links;
}
public Message()
{
}
public Message(int id, String msg, String author) {
this.id = id;
this.msg = msg;
this.author = author;
this.created = new Date();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void addLink(String uri, String rel) {
Link l=new Link(uri,rel);
links.add(l);
}
}
public class Database
{
private static HashMap<Integer,Message> messages=new HashMap();
public static HashMap<Integer,Message> getMessages()
{
return messages;
}
}

Related

Rest api development: getting error: MessageBodyWriter not found for media type=application/xml

I am new to developing REST api, and trying to create a small dummy REST API.
I am using tomcat version 8.5.X. Eclipse Version: 2019-12 (4.14.0).
Below is my code.
MessageResuroce.java:
package org.vaibhavc.practice.microservice.messanger.resources;
import java.util.List;
import org.vaibhavc.practice.microservice.messanger.model.Message;
import org.vaibhavc.practice.microservice.messanger.service.MessageService;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.GenericEntity;
#Path("/messages")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_XML)
public Response getMessage() {
List<Message> newMessage = messageService.getAllMessages();
GenericEntity<List<Message>> list = new GenericEntity<List<Message>>(newMessage) {};
return Response.ok(list).build();
}
}
Message.java
package org.vaibhavc.practice.microservice.messanger.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Message {
private long id;
private String message;
private Date created;
private String author;
public Message(){
}
public Message(long id, String message, String author) {
this.id = id;
this.message = message;
this.created = new Date();
this.author = author;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
MessageService.java
package org.vaibhavc.practice.microservice.messanger.service;
import java.util.ArrayList;
import java.util.List;
import org.vaibhavc.practice.microservice.messanger.model.Message;
public class MessageService {
public List<Message> getAllMessages(){
Message m1 = new Message(1L,"Hello world!","Vaibhav");
Message m2 = new Message(2L,"Hello jersery!","Vaibhav");
List<Message> list = new ArrayList<>();
list.add(m1);
list.add(m2);
return list;
}
}
code built and compiled successfully.
When I trying to access url "http://localhost:8080/messanger/webapi/messages" I am getting error as follow:
SEVERE: MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList, genericType=java.util.List.
Any idea what I am missing here?
Please add jersey-media-moxy library in your class path and check
Maven Code Snippet
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.31</version>

How can i display the message from receiver in an chat application in android studio?

We have programmed a chat application with Firebase in which the sender's messages are to be displayed on the right and those of the recipient on the left side.
The sender's messages are correctly displayed on the right side if you send the message with the Send button.
Unfortunately, the messages to the receiver are not shown on the left side.
Our Recyclerview java Code is this one:
package com.example.myapplicationsonet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Message_recyclerview extends AppCompatActivity {
TextView tvUsername;
ImageButton ibtnSend;
EditText etMessage;
FirebaseUser fuser;
DatabaseReference databaseReference;
MessageAdapter messageAdapter;
List<message_helperclass> mChat;
RecyclerView recyclerView;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_message_recyclerview );
recyclerView = (RecyclerView) findViewById(R.id.rvmessage);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
tvUsername = (TextView) findViewById(R.id.textView_message_username);
etMessage = (EditText) findViewById(R.id.messagebox);
ibtnSend = (ImageButton) findViewById(R.id.button_send);
intent = getIntent();
final String username = intent.getStringExtra("username");
fuser = FirebaseAuth.getInstance().getCurrentUser();
fuser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(username);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
tvUsername.setText(username);
readMessages(fuser.getUid(), username);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ibtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMessage.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(), username, msg);
}else {
Toast.makeText(Message_recyclerview.this, "Du kannst keine leeren Nachrichten versenden", Toast.LENGTH_LONG).show();
}
etMessage.setText("");
}
});
}
private void sendMessage(String sender, String receiver, String message ){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
databaseReference.child("Chats").push().setValue(hashMap);
}
private void readMessages(final String myid, final String username){
mChat = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
message_helperclass chat = snapshot.getValue(message_helperclass.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(username) ||
chat.getReceiver().equals(username) && chat.getSender().equals(myid)){
mChat.add(chat);
}
messageAdapter = new MessageAdapter(Message_recyclerview.this, mChat);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
And this is our Adapter Class:
package com.example.myapplicationsonet;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<message_helperclass> mChat;
FirebaseUser fUser;
public MessageAdapter(Context mContext, List<message_helperclass> mChat){
this.mChat = mChat;
this.mContext = mContext;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT){
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
message_helperclass chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
}
}
#Override
public int getItemViewType(int position) {
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fUser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
Unfortunately, we cannot find the error why the recipient messages are not displayed on the left.
I hope you can help us. It would be important.
Thanks!
Can't Comment, but have you checked your chat_item_right and chat_item_left XML file? Your code appears right so the error might be there.

How to create MAD army base droid?

DBHELPER..........}}}}}}}}}
package com.example.userlap.model2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String Database="Model.db";
public DBHelper(Context context) {
super(context, Database, null, 1);
//SQLiteDatabase db=this.getWritableDatabase() ;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ UserProfile.Users.TableName+" ("+ UserProfile.Users.Col_1+" Integer primary key AUTOINCREMENT,"+ UserProfile.Users.Col_2 +" TEXT,"+ UserProfile.Users.Col_3 +" TEXT,"+ UserProfile.Users.Col_4 +" TEXT,"+ UserProfile.Users.Col_5 +" TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+ UserProfile.Users.TableName);
onCreate(db);
}
public boolean addInfo(String uname,String DOb,String password,String Gender){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(UserProfile.Users.Col_2,uname);
cv.put(UserProfile.Users.Col_3,DOb);
cv.put(UserProfile.Users.Col_4,password);
cv.put(UserProfile.Users.Col_5,Gender);
long ans=db.insert(UserProfile.Users.TableName,null,cv);
if(ans==-1){
return false;
}
else
return true;
}
public boolean updateInfor(int id,String uname,String DOb,String password,String Gender){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(UserProfile.Users.Col_2,uname);
cv.put(UserProfile.Users.Col_3,DOb);
cv.put(UserProfile.Users.Col_4,password);
cv.put(UserProfile.Users.Col_5,Gender);
long ans=db.update(UserProfile.Users.TableName,cv,"UserInfo="+id,null);
if(ans==-1){
return false;
}
else
return true;
}
public List readAllInfor(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
public List readAllInfor(int id){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName+" where _ID="+id,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
public Integer deleteInfo(int id){
SQLiteDatabase db=this.getWritableDatabase();
return db.delete(UserProfile.Users.TableName,"_ID=?"+id,null);
}
}
USERPROFILE-----------------------------------------------------
package com.example.userlap.model2;
import android.provider.BaseColumns;
public class UserProfile {
private UserProfile() {
}
public final static class Users implements BaseColumns{
public static final String Col_1="_ID";
public static final String Col_2="userName";
public static final String Col_3="dateOfBirth";
public static final String Col_4="Password";
public static final String Col_5="Gender";
public static final String TableName="UserInfo";
}
}
HOME---------------------------------------------------
package com.example.userlap.model2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
DBHelper mydb;
Button register,login;
EditText id,pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mydb=new DBHelper(this);
register=(Button)findViewById(R.id.button2);
login=(Button)findViewById(R.id.button) ;
id=(EditText)findViewById(R.id.editText);
pw=(EditText)findViewById(R.id.editText2);
login();
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i1=new Intent(Home.this,ProfileManagement.class);
startActivity(i1);
}
});
}
public void login(){
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<ui> list=(ArrayList<ui>)mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list.isEmpty()){
for(ui u:list){
if(u.getID()==Integer.parseInt(id.getText().toString()) && u.getPasssword().equals(pw.getText().toString())){
Intent i1=new Intent(Home.this,EditProfile.class);
startActivity(i1);
}
}
}
}
});
}
}
ProfileManagement----------------------------
package com.example.userlap.model2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class ProfileManagement extends AppCompatActivity {
Button edit,register;
EditText uname,pass,dob;
DBHelper mydb;
RadioButton type;
RadioGroup gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
mydb=new DBHelper(this);
edit=(Button)findViewById(R.id.button6);
register=(Button)findViewById(R.id.button7);
uname=(EditText)findViewById(R.id.editText6);
pass=(EditText)findViewById(R.id.editText7);
dob=(EditText)findViewById(R.id.editText8);
gender=(RadioGroup)findViewById(R.id.radioGroup2);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2=new Intent(ProfileManagement.this,EditProfile.class);
startActivity(i2);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean res= mydb.addInfo(uname.getText().toString(),dob.getText().toString(),pass.getText().toString(),gtype(gender));
if(res=true){
Toast.makeText(ProfileManagement.this,"Successful",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(ProfileManagement.this,"NOT ",Toast.LENGTH_LONG).show();
}
});
}
public String gtype(View v){
int res=gender.getCheckedRadioButtonId();
type=(RadioButton)findViewById(res);
return type.getText().toString();
}
}
EditProfile-----------------------------------------------------------
package com.example.userlap.model2;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
public class EditProfile extends AppCompatActivity {
Button search,edit,delete;
DBHelper mydb;
RadioButton type,male,female;
RadioGroup gender;
EditText uname,pass,dob,id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mydb=new DBHelper(this);
//ArrayList<ui> list11=new ArrayList<>();
setContentView(R.layout.activity_edit_profile);
search=(Button)findViewById(R.id.button3);
edit=(Button)findViewById(R.id.button4);
delete=(Button)findViewById(R.id.button5);
uname=(EditText)findViewById(R.id.editText3);
pass=(EditText)findViewById(R.id.editText5);
dob=(EditText)findViewById(R.id.editText4);
gender=(RadioGroup)findViewById(R.id.radioGroup);
id=(EditText)findViewById(R.id.editText9);
male=(RadioButton)findViewById(R.id.radioButton);
female=(RadioButton)findViewById(R.id.radioButton2);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
}
}
}
});
}
public String gtype(View v){
int res=gender.getCheckedRadioButtonId();
type=(RadioButton)findViewById(res);
return type.getText().toString();
}
}
ui-----------------------------------------------------------------------------------
package com.example.userlap.model2;
public class ui {
private String usename;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
private int ID;
private String Passsword;
private String DOB;
private String Gender;
public String getUsename() {
return usename;
}
public void setUsename(String usename) {
this.usename = usename;
}
public String getPasssword() {
return Passsword;
}
public void setPasssword(String passsword) {
Passsword = passsword;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
}
selecting a single record
public List readAllInfor(int id){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName+" where _ID="+id,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
-- Calling it
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
Selecting all records
public List readAllInfor(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
--calling it
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor();
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
-- USING CURSORS --
Selecting a single Record
public MovieDetailsVO getMovie(int movie_id) {
MovieDetailsVO movieDetails = new MovieDetailsVO();
SQLiteDatabase db = this.getReadableDatabase();
//specify the columns to be fetched
String[] columns = {KEY_MOVIE_ID, KEY_MOVIE_NAME, KEY_GENRE, KEY_YEAR, KEY_RATING};
//Select condition
String selection = KEY_MOVIE_ID + " = ?";
//Arguments for selection
String[] selectionArgs = {String.valueOf(movie_id)};
Cursor cursor = db.query(TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
movieDetails.setMovieId(cursor.getInt(0));
movieDetails.setMovieName(cursor.getString(1));
movieDetails.setGenre(cursor.getString(2));
movieDetails.setYear(cursor.getInt(3));
movieDetails.setRating(cursor.getDouble(4));
}
db.close();
return movieDetails;
}
Retrieving all Records
public List getAllMovies() {
List movieDetailsList = new ArrayList();
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " ORDER BY " + KEY_MOVIE_ID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//if TABLE has rows
if (cursor.moveToFirst()) {
//Loop through the table rows
do {
MovieDetailsVO movieDetails = new MovieDetailsVO();
movieDetails.setMovieId(cursor.getInt(0));
movieDetails.setMovieName(cursor.getString(1));
movieDetails.setGenre(cursor.getString(2));
movieDetails.setYear(cursor.getInt(3));
movieDetails.setRating(cursor.getDouble(4));
//Add movie details to list
movieDetailsList.add(movieDetails);
} while (cursor.moveToNext());
}
db.close();
return movieDetailsList;
}

How to format SimpleIntegerProperty output

I do have a SimpleIntegerProperty which contains a number which is the time in 100ms steps like 40 is 4,0 seconds
I do want to display this value to the user with a Label which should display "4,0 s"
I would like to bind the value with the bindings api like
label.textProperty().bind(myobject.secondsProperty().asString());
but how do i create a simple and reusable Converter, i do need only the unidirectional binding.
There is an overloaded form of the asString(...) method that takes a format string as an argument:
String secondsFormat = "%.1f s" ;
label.textProperty().bind(myobject.secondsProperty().asString(secondsFormat));
If you really need a StringConverter, you can do
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
#Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
#Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
and then
label.textProperty().bind(Bindings.createStringBinding(
() -> deciSecondsConverter.toString(myobject.getSeconds()),
myobject.secondsProperty()
));
SSCCE:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class StopwatchTest extends Application {
#Override
public void start(Stage primaryStage) {
IntegerProperty tenthsOfSeconds = new SimpleIntegerProperty();
Label label = new Label();
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
#Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
#Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
label.textProperty().bind(Bindings.createStringBinding(() ->
deciSecondsConverter.toString(tenthsOfSeconds.get()),
tenthsOfSeconds));
new AnimationTimer() {
#Override
public void handle(long now) {
tenthsOfSeconds.set((int)System.currentTimeMillis() % 60000 / 100);
}
}.start();
label.setPadding(new Insets(5, 20, 5, 20));
primaryStage.setScene(new Scene(label, 80, 30));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Hadoop Record Reader only reads first line then input stream seems to be closed

I'm trying to implement a hadoop job, that counts how often a object (Click) appears in a dataset.
Therefore i wrote a custom file input format. The record reader seems to read only the first line of the given file and the close the input stream.
Here is the code:
The Pojo class:
package model;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.WritableComparable;
public class Click implements WritableComparable<Click> {
private String user;
private String clickStart;
private String date;
private String clickTarget;
#Override
public void write(DataOutput out) throws IOException {
out.writeUTF(user);
out.writeUTF(clickStart);
out.writeUTF(date);
out.writeUTF(clickTarget);
}
#Override
public void readFields(DataInput in) throws IOException {
user = in.readUTF();
clickStart = in.readUTF();
date = in.readUTF();
clickTarget = in.readUTF();
}
public int compareTo(Click arg0) {
int response = clickTarget.compareTo(arg0.clickTarget);
if (response == 0) {
response = date.compareTo(arg0.date);
}
return response;
}
public String getUser(String user) {
return this.user;
}
public void setUser(String user) {
this.user = user;
}
public String getClickStart() {
return clickStart;
}
public void setClickStart(String clickStart) {
this.clickStart = clickStart;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getClickTarget() {
return clickTarget;
}
public void setClickTarget(String clickTarget) {
this.clickTarget = clickTarget;
}
public String toString() {
return clickStart + "\t" + date;
}
}
Here is the FileInputFormat class:
package ClickAnalysis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import model.Click;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.tools.ant.types.CommandlineJava.SysProperties;
public class ClickAnalysisInputFormat extends FileInputFormat<Click, IntWritable>{
#Override
public RecordReader<Click, IntWritable> createRecordReader(
InputSplit split, TaskAttemptContext context) throws IOException,
InterruptedException {
System.out.println("Creating Record Reader");
return new ClickReader();
}
public static class ClickReader extends RecordReader<Click, IntWritable> {
private BufferedReader in;
private Click key;
private IntWritable value;
#Override
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException {
key = new Click();
value = new IntWritable(1);
System.out.println("Starting to read ...");
FileSplit split = (FileSplit) inputSplit;
Configuration conf = context.getConfiguration();
Path path = split.getPath();
InputStream is = path.getFileSystem(conf).open(path);
in = new BufferedReader(new InputStreamReader(is));
}
#Override
public boolean nextKeyValue() throws IOException, InterruptedException {
String line = in.readLine();
System.out.println("line: " + line);
boolean hasNextKeyValue;
if (line == null) {
System.out.println("line is null");
hasNextKeyValue = false;
} else {
String[] click = StringUtils.split(line, '\\', ';');
System.out.println(click[0].toString());
System.out.println(click[1].toString());
System.out.println(click[2].toString());
key.setClickStart(click[0].toString());
key.setDate(click[1].toString());
key.setClickTarget(click[2].toString());
value.set(1);
System.out.println("done with first line");
hasNextKeyValue = true;
}
System.out.println(hasNextKeyValue);
return hasNextKeyValue;
}
#Override
public Click getCurrentKey() throws IOException, InterruptedException {
return this.key;
}
#Override
public IntWritable getCurrentValue() throws IOException, InterruptedException {
return this.value;
}
#Override
public float getProgress() throws IOException, InterruptedException {
return 0;
}
public void close() throws IOException {
in.close();
System.out.println("in closed");
}
}
}
The Mapper class:
package ClickAnalysis;
import java.io.IOException;
import model.Click;
import model.ClickStartTarget;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Mapper;
import org.jruby.RubyProcess.Sys;
public class ClickAnalysisMapper extends Mapper<Click, IntWritable, Click, IntWritable> {
private static final IntWritable outputValue = new IntWritable();
#Override
protected void map(Click key, IntWritable value, Context context) throws IOException, InterruptedException {
System.out.println("Key: " + key.getClickStart() + " " + key.getDate() + " " + key.getClickTarget() + " Value: " + value);
outputValue.set(value.get());
System.out.println(outputValue.get());
context.write(key, outputValue);
System.out.println("nach context");
}
}
Partitioner class:
package ClickAnalysis;
import model.Click;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Partitioner;
public class ClickAnalysisPartitioner extends Partitioner<Click, IntWritable> {
#Override
public int getPartition(Click key, IntWritable value, int numPartitions) {
System.out.println("in Partitioner drinnen");
int partition = numPartitions;
return partition;
}
}
Hadoop Job, which is triggered via an Restful web service call in a servlet container, but this shouldn't be the problem:
package ClickAnalysis;
import model.Click;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
public class ClickAnalysisJob {
public int run() throws Exception {
// TODO Auto-generated method stub
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "ClickAnalysisJob");
job.setJarByClass(ClickAnalysisJob.class);
// Job Input path
FileInputFormat.setInputPaths(job, "hdfs://localhost:9000/user/hadoop/testdata1.csv");
// Job Output path
Path out = new Path("hdfs://localhost:9000/user/hadoop/clickdataAnalysis_out");
FileOutputFormat.setOutputPath(job, out);
out.getFileSystem(conf).delete(out,true);
job.setMapperClass(ClickAnalysisMapper.class);
job.setReducerClass(Reducer.class);
job.setPartitionerClass(ClickAnalysisPartitioner.class);
//job.setReducerClass(ClickAnalysisReducer.class);
job.setInputFormatClass(ClickAnalysisInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setOutputKeyClass(Click.class);
job.setOutputValueClass(IntWritable.class);
job.setMapOutputKeyClass(Click.class);
job.setMapOutputValueClass(IntWritable.class);
System.out.println("in run drinnen");
//job.setGroupingComparatorClass(ClickTargetAnalysisComparator.class);
job.setNumReduceTasks(1);
int result = job.waitForCompletion(true)? 0:1;
return result;
}
}
Next the dataset (example):
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein anderes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein anderes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein drittes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein viertes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
When I run the program the syso's are showing following:
in run drinnen
Creating Record Reader
Starting to read ...
line: /web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1
2014-07-08
ein ziel
done with first line
true
Key: /web/big-data-test-site/test-seite-1 2014-07-08 ein ziel Value: 1
1
in closed
analyze Method: 1
From that i conclude that the record reader only reads the first line.
Why is this happening and how is it fixed?