StackOverFlow - Exception? I can't found the reason :-( - object

I'm going to write a programm that can save a name and a birthday-date. After closing the programm the data shouldn't be lost. If you open the programm, you are able to add an additional user to the according users. Unfortunately I'm always get a stackoverflow - exception and i didn't found the mistake.
<pre> package geburtstagstool;
import java.io.*;
public class GeburtstagsTool
{
public static void main (String[]args) throws Exception
{
Eintrag eintrag = new Eintrag ("Miller","000000");
}
}
class Eintrag implements Serializable
{
Eintrag [] eintrag = new Eintrag [50];
public String name;
public String gebDatum;
int i=0;
public Eintrag (String name, String gebDatum)
{
eintrag[i] = new Eintrag (name,gebDatum);
++i;
}
public void testSchreiben () throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("eintrag.dat"));
oos.writeObject(eintrag);
oos.close();
}
public static Eintrag testLesen() throws IOException, ClassNotFoundException
{
ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("eintrag.dat"));
Eintrag eint = (Eintrag) ois.readObject();
ois.close();
return eint;
}
}
<code>
Thanks for your help.

Here is a fully working solution. This should get you started. Good luck.
GeburtstagsTool class:
public class GeburtstagsTool {
List<Eintrag> eintragList;
public static void main (String[] args) throws IOException, ClassNotFoundException
{
GeburtstagsTool geburtstagsTool = new GeburtstagsTool();
geburtstagsTool.loadEintrag();
System.out.println("What's already in the list: \n" + geburtstagsTool.eintragList);
Eintrag eintrag = new Eintrag("Peyton Manning", "03/24/1976");
geburtstagsTool.eintragList.add(eintrag);
geburtstagsTool.writeEintrag();
}
public void loadEintrag() {}
{
ObjectInputStream ois = null;
try
{
ois = new ObjectInputStream(new FileInputStream("eintrag.dat"));
eintragList = (List<Eintrag>) ois.readObject();
}
catch (IOException e)
{
System.out.println("File doesn't exist");
eintragList = new ArrayList<>();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public void writeEintrag() throws IOException
{
ObjectOutputStream oos = null;
try
{
oos = new ObjectOutputStream(new FileOutputStream("eintrag.dat"));
}
catch (IOException e)
{
e.printStackTrace();
}
oos.writeObject(eintragList);
oos.close();
}
Eintrag class:
public class Eintrag implements Serializable{
String name;
String gebDatum;
public Eintrag(String name, String gebDatum) {
this.name = name;
this.gebDatum = gebDatum;
}
#Override
public String toString()
{
return "Eintrag{" +
"name='" + name + '\'' +
", gebDatum='" + gebDatum + '\'' +
'}';
}

Your problem is here
public Eintrag (String name, String gebDatum)
{
eintrag[i] = new Eintrag (name,gebDatum);
++i;
}
It's an endless loop. It's a recursive call without ending.
You call the constructor that call's it self.. so it does that until the whole stack is full.. and then You get the SF exception :)

Related

How add Multi-Thread to BufferedReader from text file?

I want to add multi-thread BufferedReader from text file
So it will be 2 Threads from 1 text file
==================
output:
Hello. I'm Khalid.
(Hello = Thread1)
(I'm Khalid = Thread2)
This is my code without threads :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class KhalidThread {
public static void main(String[] args) throws IOException {
BufferedReader bread = null;
try{
bread = new BufferedReader(new FileReader("C:\\k.txt"));
String line, content="";
while((line = bread.readLine()) !=null){
content += line + "\r\n";
}
System.out.print(content);
}
finally{
if(bread!=null){
bread.close();
}
}
}
}
You may try doing this:
public static void main(String[] args) throws IOException {
BufferedReader bread = new BufferedReader(new FileReader("D:\\k.txt"));
RunnableClass rc = new RunnableClass(bread);
Thread t1 = new Thread(rc, "Thread1");
Thread t2 = new Thread(rc, "Thread2");
t1.start();
t2.start();
}
static class RunnableClass implements Runnable {
private BufferedReader bread = null;
RunnableClass(BufferedReader bread) {
this.bread = bread;
}
#Override
public void run() {
try {
synchronized (bread) {
String content = bread.readLine();
System.out.println(content + " = " + Thread.currentThread().getName() );
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

spring batch job stuck in loop even when ItemReader returns null

I am converting xml to csv using spring batch and integration. I have a approach that job will start by reading files in from landing dir. while processing it will move files in inprocess dir. on error file will be moved to error dir. on successfully processing/writing file will be moved to output/completed.
After searching a while i got to know that there must be problem with itemreader but it is also returning null. I am not getting where is the problem.
Below is my batch configuration
#Bean
public Job commExportJob(Step parseStep) throws IOException {
return jobs.get("commExportJob")
.incrementer(new RunIdIncrementer())
.flow(parseStep)
.end()
.listener(listener())
.build();
}
#Bean
public Step streamStep() throws IOException {
CommReader itemReader = itemReader(null);
if (itemReader != null) {
return
steps.get("streamStep")
.<Object, Object>chunk(env.getProperty(Const.INPUT_READ_CHUNK_SIZE, Integer.class))
.reader(itemReader)
.processor(itemProcessor())
.writer(itemWriter(null))
.listener(getChunkListener())
.build();
}
return null;
}
#Bean
#StepScope
public ItemWriter<Object> itemWriter(#Value("#{jobParameters['outputFilePath']}") String outputFilePath) {
log.info("CommBatchConfiguration.itemWriter() : " + outputFilePath);
CommItemWriter writer = new CommItemWriter();
return writer;
}
#Bean
#StepScope
public CommReader itemReader(#Value("#{jobParameters['inputFilePath']}") String inputFilePath) {
log.info("CommBatchConfiguration.itemReader() : " + inputFilePath);
CommReader reader = new CommReader(inputFilePath);
// reader.setEncoding(env.getProperty("char.encoding","UTF-8"));
return reader;
}
#Bean
#StepScope
public CommItemProcessor itemProcessor() {
log.info("CommBatchConfiguration.itemProcessor() : Entry");
return new CommItemProcessor(ruleService);
}
CommReader.java
File inputFile = null;
private String jobName;
public CommReader(String inputFilePath) {
inputFile = new File(inputFilePath);
}
#Value("#{stepExecution}")
private StepExecution stepExecution;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
#Override
public Object read() throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
if (inputFile.exists()) {
try {
builder = factory.newDocumentBuilder();
log.info("CommReader.read() :" + inputFile.getAbsolutePath());
Document document = builder.parse(inputFile);
return document;
} catch (ParserConfigurationException | SAXException | TransformerFactoryConfigurationError e) {
log.error("Exception while reading ", e);
}
}
return null;
}
#Override
public void close() throws ItemStreamException {
}
#Override
public void open(ExecutionContext arg0) throws ItemStreamException {
}
#Override
public void update(ExecutionContext arg0) throws ItemStreamException {
}
#Override
public void setResource(Resource arg0) {
}
CommItemProcessor.java
#Autowired
CommExportService ruleService;
public CommItemProcessor(CommExportService ruleService) {
this.ruleService = ruleService;
}
#Override
public Object process(Object bean) throws Exception {
log.info("CommItemProcessor.process() : Item Processor : " + bean);
return bean;
}
CommItemWriter.java
FlatFileItemWriter<byte[]> delegate;
ExecutionContext execContext;
FileOutputStream fileWrite;
File stylesheet;
StreamSource stylesource;
Transformer transformer;
List<List<?>> itemsTotal = null;
int recordCount = 0;
#Autowired
FileUtil fileUtil;
#Value("${input.completed.dir}")
String completedDir;
#Value("${input.inprocess.dir}")
String inprocessDir;
public void update(ExecutionContext arg0) throws ItemStreamException {
this.delegate.update(arg0);
}
public void open(ExecutionContext arg0) throws ItemStreamException {
this.execContext = arg0;
this.delegate.open(arg0);
}
public void close() throws ItemStreamException {
this.delegate.close();
}
#Override
public void write(List<? extends Object> items) throws Exception {
log.info("CommItemWriter.write() : items.size() : " + items.size());
stylesheet = new File("./config/style.xsl");
stylesource = new StreamSource(stylesheet);
String fileName = fileUtil.getFileName();
try {
transformer = TransformerFactory.newInstance().newTransformer(stylesource);
} catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
log.error("Exception while writing",e);
}
for (Object object : items) {
log.info("CommItemWriter.write() : Object : " + object.getClass().getName());
log.info("CommItemWriter.write() : FileName : " + fileName);
Source source = new DOMSource((Document) object);
Result outputTarget = new StreamResult(
new File(fileName));
transformer.transform(source, outputTarget);
}
}
In chunkListener there is nothing much i am doing.
Below is the job listener.
#Override
public void beforeJob(JobExecution jobExecution) {
log.info("JK: CommJobListener.beforeJob()");
}
#Override
public void afterJob(JobExecution jobExecution) {
log.info("JK: CommJobListener.afterJob()");
JobParameters jobParams = jobExecution.getJobParameters();
File inputFile = new File(jobParams.getString("inputFilePath"));
File outputFile = new File(jobParams.getString("outputFilePath"));
try {
if (jobExecution.getStatus().isUnsuccessful()) {
Files.move(inputFile.toPath(), Paths.get(inputErrorDir, inputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
Files.move(outputFile.toPath(), Paths.get(outputErrorDir, outputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
} else {
String inputFileName = inputFile.getName();
Files.move(inputFile.toPath(), Paths.get(inputCompletedDir, inputFileName),
StandardCopyOption.REPLACE_EXISTING);
Files.move(outputFile.toPath(), Paths.get(outputCompletedDir, outputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ioe) {
log.error("IOException occured ",ioe);
}
}
I am also using integration flow.
#Bean
public IntegrationFlow messagesFlow(JobLauncher jobLauncher) {
try {
Map<String, Object> headers = new HashMap<>();
headers.put("jobName", "commExportJob");
return IntegrationFlows
.from(Files.inboundAdapter(new File(env.getProperty(Const.INPUT_LANDING_DIR)))
,
e -> e.poller(Pollers
.fixedDelay(env.getProperty(Const.INPUT_POLLER_DELAY, Integer.class).intValue())
.maxMessagesPerPoll(
env.getProperty(Const.INPUT_MAX_MESSAGES_PER_POLL, Integer.class).intValue())
.taskExecutor(getFileProcessExecutor())))
.handle("moveFile","moveFile")
.enrichHeaders(headers)
.transform(jobTransformer)
.handle(jobLaunchingGw(jobLauncher))
.channel("nullChannel").get();
} catch (Exception e) {
log.error("Exception in Integration flow",e);
}
return null;
}
#Autowired
private Environment env;
#Bean
public MessageHandler jobLaunchingGw(JobLauncher jobLauncher) {
return new JobLaunchingGateway(jobLauncher);
}
#MessagingGateway
public interface IMoveFile {
#Gateway(requestChannel = "moveFileChannel")
Message<File> moveFile(Message<File> inputFileMessage);
}
#Bean(name = "fileProcessExecutor")
public Executor getFileProcessExecutor() {
ThreadPoolTaskExecutor fileProcessExecutor = new ThreadPoolTaskExecutor();
fileProcessExecutor.setCorePoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_POOLSIZE, Integer.class));
fileProcessExecutor.setMaxPoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_MAXPOOLSIZE, Integer.class));
fileProcessExecutor.setQueueCapacity(env.getRequiredProperty(Const.INPUT_EXECUTOR_QUEUECAPACITY, Integer.class));
fileProcessExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
fileProcessExecutor.initialize();
return fileProcessExecutor;
}
Try to return document itself instead of Object in read method of CommReader.java and then check whether its coming null or not in the writer to stop it.

How to get JSONArray which has no JSONArray keyword in Android Studio

I am new to this JSON, I am trying to get the JSON values, it is actually as JSONArray with No name. I have gone through some tutorials where they accessed through JSONArray Keyword. But in my JSON File there is no such ArrayName. Kindly help me to solve this. This is my JSON Value:
[
{"id":"4","name":"Trichy"},
{"id":"5","name":"Pondy"},
{"id":"6","name":"Kovai"},
{"id":"7","name":"Madurai"},
{"id":"8","name":"Chennai"},
{"id":"9","name":"Hyderabad"}
]
I need to get "name" from this. Here comes my MainActivity file.
try {
// Locate the NodeList name
JSONArray json=new JSONArray(???); //I dont know what to give here
for (int i = 0; i < json.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
This is my City.java file.
package com.example.user.spinnercontrol;
public class Cites {
private String city;
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city=city;
}
}
This is my JSON.java file (for reference)
package com.example.user.spinnercontrol;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONCity {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
MainActivity class should be like this ::
public class MainActivity extends Activity {
JSONObject jsonobject;
ArrayList<String> worldlist = new ArrayList<>();
ArrayList<Cites> cit = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONArray arr = JSONCity.getJSONfromURL("http://www.prateektechnosoft.com/justcall/cities/getall");
for (int i = 0; i < arr.length(); i++) {
try {
jsonobject = arr.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

spinner setOnItemSelectedListener doesn't work

I have a spinner that I put its items dynamically from my database but the problem is I can't know which item is selected by the method setOnItemSelectedListener
Here is my java code :
public class Choix extends Activity {
JSONArray ja1 = null;
List<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
Spinner spinner;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choix_espace);
spinner = (Spinner) findViewById(R.id.spinner);
liste_ecoles k = new liste_ecoles();
k.execute();
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private class liste_ecoles extends AsyncTask<String, Integer, Object> {
String ch1="";
#Override
protected Object doInBackground(String... params) {
JSONArray ja = null;
try {
URL twitter = new URL("...");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
}
} catch (Exception e) {
}
return ja;
}
#Override
protected void onPostExecute(Object resultat) {
JSONArray ja = (JSONArray) resultat;
if (resultat != null) {
try {
for (int i = 0; i < ja.length(); i++) {
JSONObject jo1 = null;
jo1 = ja.getJSONObject(i);
ch1 = jo1.getString("nom_ecole");
list.add(ch1);
}
}
catch (Exception e) {
}
}
}
}
}
so can someone helps me please ?
I solved my problem ; I've just added " dataAdapter.notifyDataSetChanged(); " after adding items on my spinner

RecordControl with platformRequest could they work?

My goal is to produce an application that dial a phone number then record the conservation.
I have tested this code which record voice and then play it on my 5310 correctly.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VoiceRecordMidlet extends MIDlet {
private Display display;
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(new VoiceRecordForm());
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
}
class VoiceRecordForm extends Form implements CommandListener {
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.OK, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
System.getProperty("audio.encodings");
System.getProperty("supports.audio.capture");
System.getProperty("supports.recording");
t.start();
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/amr");
p2.prefetch();
p2.start();
}
catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
Thread t = new Thread() {
public void run() {
try {
System.getProperty("audio.encodings");
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
};
};
}
Then I made some changes in my code to record conservations
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VoiceRecordMidlet extends MIDlet {
private Display display;
Form f = new VoiceRecordForm();
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
class VoiceRecordForm extends Form implements CommandListener {
private MIDlet m;
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
private TextField phoneField;
private String n;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.SCREEN, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.phoneField =new TextField("number","",20,phoneField.PHONENUMBER);
append(phoneField);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
System.getProperty("audio.encodings");
System.getProperty("supports.audio.capture");
System.getProperty("supports.recording");
t.start();
try
{
n=phoneField.getString().trim();
platformRequest("tel:"+n);
}
catch(javax.microedition.io.ConnectionNotFoundException e)
{
e.printStackTrace();
}
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/amr");
p2.prefetch();
p2.start();
}
catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
Thread t = new Thread() {
public void run() {
try {
System.getProperty("audio.encodings");
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
};
};
}}
But when pressing record command following error getted
**Error: javax.microedition.media.MediaException: RecordControl**
Any help please?

Resources