I´m using JDO + DataNucleus and implement a AttributeConverter with Jackson Json.
Already have a generic method for AttributeConverter:
#Override
public String convertToDatastore(ArrayList<Object> alist) {
String jsonString = null;
try {
jsonString = mapper.writeValueAsString(alist);
} catch (IOException e) {
e.printStackTrace();
}
return jsonString;
}
But, in Deserialize JSON to Object i read that i need to specify the class
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> obj = null;
try
{
obj = mapper.readValue(s, mapper.getTypeFactory().constructCollectionType(
List.class, TelephoneNumber.class));
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return obj;
}
but jsonString is a arrayList object
how can I do this?
thanks
Related
I am using Swagger with a .Net Core API.
When there is a bug in the API I want to receive an InternalServerError
However there is no NotOK method to do this.
Currently I have the following in my base controller
using System;
using Microsoft.AspNetCore.Mvc;
namespace MyApi.Controllers
{
public class BaseController : Controller
{
public IActionResult RouteInterfaceMethod<TResponse>(Func<TResponse> function)
{
// try
// {
IActionResult res = null;
TResponse ret = function();
res = Ok(ret);
return res;
// }
// catch (Exception e)
// {
// var msg = MakeErrorMessage(e);
// return base.NotFound( msg);
// }
}
}
}
And am about to un-comment the code ,is there an alternative to using NotFound()
You can return InternalServerError in this way
catch (Exception e)
{
var msg = MakeErrorMessage(e);
return StatusCode(HttpStatusCode.InternalServerError, msg);
}
or just re-throw an exception
catch (Exception e)
{
var msg = MakeErrorMessage(e);
throw;
}
public class PlayVideoActivity extends Activity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video);
Intent intent=getIntent();
int no=intent.getIntExtra("index",0);
Toast.makeText(getBaseContext(),"Hello",Toast.LENGTH_SHORT).show();
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(MainActivity.musicPath[no]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
I'm trying to play video using mediaplayer and surface view, but it is not playing,i writing my code here .please tell me the what is the problem in my code? thanks in advance
.......................................................................................................................................................................................
i have been facing some problem with displaying the record from RMS. Im doing some e-wallet application for the j2me and here is my source code. it tell me that the recordwith#id has been added but I failed to retrieve and display the income amount from the users.
this the code for my RMS
//variable for record store
RecordStore ew_rs;
public static int addCount = 0;
public static int editCount = 0;
public static int deleteCount = 0;
public addIncome(){
this("tmpfile");
}
public addIncome(String filename) {
super();
try{
ew_rs = RecordStore.openRecordStore(filename, true);
ew_rs.addRecordListener(this);
} catch (RecordStoreException e){
e.printStackTrace();
}
}
public void closeRMS(){
try {
if (ew_rs.getNumRecords() > 0) {
ew_rs.closeRecordStore();
} else {
ew_rs.closeRecordStore();
RecordStore.deleteRecordStore(ew_rs.getName());
}
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RecordStoreException e) {
e.printStackTrace();
}
}
//variable declaration for income adding
int ew_incomeID;
float ew_incomeAmount=0;
public addIncome(int incomeID, float incomeAmount){
this.ew_incomeID = incomeID;
this.ew_incomeAmount = incomeAmount;
}
public int getIncID(){
return ew_incomeID;
}
public void setIncID(int incomeID){
this.ew_incomeID = incomeID;
}
public float getIncAmt(){
return ew_incomeAmount;
}
public void setIncAmt(float incomeAmt){
this.ew_incomeAmount = incomeAmt;
}
public void recordAdded(RecordStore recordStore, int recordId) {
addCount++;
try {
System.out.println("Record with ID# " + recordId +
" added in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void recordChanged(RecordStore recordStore, int recordId) {
editCount++;
try {
System.out.println("Record with ID# " + recordId +
" changed in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void recordDeleted(RecordStore recordStore, int recordId) {
deleteCount++;
try {
System.out.println("Record with ID# " + recordId +
" deleted in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//add income
public void addIncomeFunction(int id , float IncAmt){
id = getIncID();
IncAmt = getIncAmt();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
int convertAmt = Float.floatToIntBits(IncAmt);
try {
out.writeUTF(String.valueOf(id));
out.writeInt(convertAmt);
}catch (IOException e) {
e.printStackTrace();
}
byte[] b = baos.toByteArray();
try {
ew_rs.addRecord(b, 0, b.length);
} catch (RecordStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
baos.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//retrieve income
public byte[] getIncome(){
byte[] read = null;
try{
read = new byte[ew_rs.getSize()];
RecordEnumeration re = ew_rs.enumerateRecords(null, null, false);
ByteArrayInputStream bais = new ByteArrayInputStream(re.nextRecord());
DataInputStream in = new DataInputStream(bais);
for (int i = 0; i < re.numRecords() && re.hasNextElement(); i++) {
try {
in.readInt();
Float.intBitsToFloat(in.readInt());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (RecordStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return read;
}
public RecordEnumeration enumerate(){
try {
return ew_rs.enumerateRecords(null, null, false);
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
and the code for my display
MainMenu m;
addIncome income;
public Display d;
private static final Command cmdOk = new Command("Ok", Command.OK, 1);
private static final Command cmdBack = new Command("Back", Command.OK, 1);
public BalanceForm(MainMenu m){
this("Balance", m);
this.addCommand(cmdOk);
this.addCommand(cmdBack);
this.setCommandListener(this);
}
public BalanceForm(String arg0, MainMenu m){
super(arg0);
this.m = m;
}
public void prepareView(Display display){
this.setCommandListener(this);
this.d = display;
}
public void showView(){
d.setCurrent(this);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdBack)
{
m.showMenu();
}
else{
byte[] b = income.getIncome();
ByteArrayInputStream bais = new ByteArrayInputStream(b);
DataInputStream in = new DataInputStream(bais);
try {
System.out.println(in.readInt());
System.out.println(in.readUTF());
//this.append(in.readUTF());
//this.append(String.valueOf(in.readInt()));
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I use lucene for N-Gram matching. I set a field to be analyzed using an N-Gram analyzer. I want to see how the tokens resulting from the analysis look like to make sure the n-grams are being correctly computed.
If I call the method Fieldable.tokenStreamValue() on the analyzed field of a document, I get null, while calling Fieldable.isTokenized() returns true.
I must add that the results of querying are consistent with n-grams being correctly generated.
Any explanations for this? I am essentially trying to do what is mentioned here:
How can I read a Lucene document field tokens after they are analyzed?
Here is the full code:
public class TestLuceneNgram {
public static class NGramQuery extends BooleanQuery {
public NGramQuery(final String queryTerm) throws IOException {
StringReader strReader = new StringReader(queryTerm);
TokenStream tokens = new NGramTokenizer(strReader);
CharTermAttribute termAtt = (CharTermAttribute) tokens
.addAttribute(CharTermAttribute.class);
while (tokens.incrementToken()) {
System.out.println(termAtt);
Term t = new Term("NGRAM_FIELD", termAtt.toString());
add(new TermQuery(t), BooleanClause.Occur.SHOULD);
}
}
}
public static class NGramSearcher extends IndexSearcher {
public NGramSearcher(final Directory directory)
throws CorruptIndexException, IOException {
super(IndexReader.open(directory));
}
public TopDocs search(final String term) {
try {
return search(new NGramQuery(term), 10);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public static class SubWordAnalyzer extends Analyzer {
#Override
public TokenStream tokenStream(final String fieldName,
final Reader reader) {
return new NGramTokenizer(reader);
}
}
public static Directory index(final String[] terms) {
Directory indexDirectory = new RAMDirectory();
IndexWriter indexWriter = null;
try {
indexWriter = new IndexWriter(indexDirectory,
new IndexWriterConfig(Version.LUCENE_32,
new SubWordAnalyzer()));
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < terms.length; ++i) {
Document doc = new Document();
doc.add(new Field("NGRAM_FIELD", terms[i], Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.add(new Field("ORIGINAL_FIELD", terms[i], Field.Store.YES,
Field.Index.NOT_ANALYZED));
try {
indexWriter.addDocument(doc);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
indexWriter.optimize();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
indexWriter.close();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return indexDirectory;
}
/**
* #param args
*/
public static void main(final String[] args) {
String[] terms = new String[] { "the first string", "the second one" };
Directory dir = index(terms);
NGramSearcher ngs = null;
try {
ngs = new NGramSearcher(dir);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TopDocs td = ngs.search("second");
System.out.println(td.totalHits);
for (ScoreDoc sd : td.scoreDocs) {
System.out.println(sd.doc + "---" + sd.score);
try {
System.out.println(ngs.doc(sd.doc).getFieldable("NGRAM_FIELD").
tokenStreamValue());
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The first thing to check is whether you are actually storing this field at index time. If you're just indexing it, this is the expected result.
I am using NHibernate and Repository patterns in my application. But not want to use UnitofWork pattern.
There are two types of forms in my app. Collection/Picker forms and Entity forms.
But the problem occurs when a form is ShowDialog()ged from within another form.
Whwn I am doing any database related operation, NHibernate is giving me "a different object with the same identifier value was already associated with the session: XYZ" error. This is caused due to the delayed call of Dispose method by CLR and another part of my problem is in the Session management as far as I guess.
How can I change my repository codes to solve my problem?
Remember, I don't want to expose separate BeginTransaction(), CommitTransaction() like functions in my Repository. These things should be embedded within every Method {SaveOrUpdate(), Save(), Delete, Load(), etc.} as I have already done.
Please tell me how can I get things going with minor changes?
I am doing my things like this:
A picker form works like this,
private void btnPick_Click(object sender, EventArgs e)
{
CourseCollectionForm f = new CourseCollectionForm();
f.FormViewMode = FormViewMode.MultiplePicker;
f.ShowDialog();
int totalCredits = 0;
int totalHours = 0;
FillDataGridViewWithCourses(f.PickedCourseCollection, ref totalCredits, ref totalHours);
FillTotal(totalCredits, totalHours);
}
A Save works like this,
public partial class DepartmentEntityForm : Form
{
private DepartmentRepository _deptRepository = null;
private Department _currentDepartment = null;
private FormViewMode _currentMode = FormViewMode.None;
public DepartmentEntityForm(Department dept, FormViewMode mode)
{
InitializeComponent();
_deptRepository = new DepartmentRepository();
_currentDepartment = dept;
_currentMode = mode;
if(mode == FormViewMode.Edit)
{
MapObjectToControls();
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
Department newDept;
if (mode == FormViewMode.AddNew)
{
newDept = new Department();
}
else if(mode == FormViewMode.Edit)
{
newDept = _currentDepartment;
}
//.............
//.............
_deptRepository.SaveOrUpdate(newDept);
}
}
I declare my individual repositories like this:
FacultyRepository.cs
public class FacultyRepository : Repository<Faculty>
{
}
DepartmentRepository.cs
public class DepartmentRepository : Repository<Department>
{
}
Repository.cs
public class Repository<T> : IRepository<T>
{
ISession _session;
public Repository()
{
_session = SessionFactory.GetOpenSession();
}
public T Get(object id)
{
T obj = default(T);
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
obj = (T)_session.Get<T>(id);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
return obj;
}
public IEnumerable<T> Get(string fieldName, object fieldValue)
{
IEnumerable<T> list = null;
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
list = (IEnumerable<T>)_session.CreateCriteria(typeof(T))
.Add(new NHibernate.Expression.EqExpression(fieldName, fieldValue))
.List<T>();
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
return list;
}
public IEnumerable<T> Get()
{
IEnumerable<T> list = null;
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
list = (IEnumerable<T>)_session.CreateCriteria(typeof(T)).List<T>();
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
return list;
}
public void SaveOrUpdate(T obj)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
_session.SaveOrUpdateCopy(obj);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void SaveOrUpdate(IEnumerable<T> objs)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
foreach (T obj in objs)
{
_session.SaveOrUpdate(obj);
}
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void Delete(T obj)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
_session.Delete(obj);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void Delete(IEnumerable<T> objs)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
foreach (T obj in objs)
{
_session.Delete(obj);
}
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void DeleteAll()
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
DetachedCriteria criterion = DetachedCriteria.For<T>();
IList<T> list = criterion.GetExecutableCriteria(_session).List<T>();
foreach (T item in list)
{
_session.Delete(item);
}
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
throw ex;
}
}
public void Dispose()
{
if (_session != null)
{
_session.Clear();
_session.Close();
_session = null;
}
}
}
SessionFactory.cs
public class SessionFactory
{
private static ISessionFactory _sessionFactory = null;
private SessionFactory(){}
static SessionFactory()
{
if (_sessionFactory == null)
{
Configuration configuration = new Configuration();
configuration.Configure();
_sessionFactory = configuration.BuildSessionFactory();
}
}
public static ISession GetOpenSession()
{
return _sessionFactory.OpenSession();
}
}
OK guys! It has been long since I posted my question and nobody tends to answer it.
I solved it by making ISession static in the SessionFactory and instead of returning a Open ISession for each Repository, I am returning only one static ISession.