spring batch job stuck in loop even when ItemReader returns null - spring-integration

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.

Related

Problem with integrate Strip in Android Studio

java.lang.NullPointerException: Parameter specified as non-null is
null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter,
parameter id
at com.stripe.android.paymentsheet.PaymentSheet$CustomerConfiguration.(PaymentSheet.kt)
at com.abdullahalzazai.welcome2.MainActivity2.paymentFlow(MainActivity2.java:102)
at com.abdullahalzazai.welcome2.MainActivity2.access$000(MainActivity2.java:29)
at com.abdullahalzazai.welcome2.MainActivity2$1.onClick(MainActivity2.java:57)
at android.view.View.performClick(View.java:5637)
public class MainActivity2 extends AppCompatActivity {
Button payment;
String PublishableKey ="pk_test_51MWOxeHw41kgZTMnEfStv1DZsXRvXAQk3RrZrv7tH3U8KHzGhvpNJsyrri7SQpY9nOvyeLIbTfTVa1tK7nh5egfu00A0dBYpw9";
String SecretKey="sk_test_51MWOxeHw41kgZTMnhE1cH6j3eo9SaiSCz1bO2JdI5A0T3392jHFHMhexotB8MslRlHwOGoEDqtsKnY5opU3kLTxB00XBmE2Dox";
String CustomerId;
String EphericalKey;
String ClientSecret;
PaymentSheet paymentSheet;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
payment= findViewById(R.id.payment);
PaymentConfiguration.init(this,PublishableKey);
paymentSheet = new PaymentSheet(this,paymentSheetResult -> {
onPaymentresult(paymentSheetResult);
});
payment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paymentFlow();
}
});
StringRequest request = new StringRequest(Request.Method.POST, "https://api.stripe.com/v1/customers ",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
CustomerId = object.getString("id");
Toast.makeText(MainActivity2.this,CustomerId,Toast.LENGTH_SHORT).show();
getEmphericalKey();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization","Bearer"+SecretKey);
return header;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void paymentFlow() {
paymentSheet.presentWithPaymentIntent(ClientSecret,new PaymentSheet.Configuration("Learn with Arvind",new PaymentSheet.CustomerConfiguration(
CustomerId,
EphericalKey
)));
}
private void onPaymentresult(PaymentSheetResult paymentSheetResult) {
if (paymentSheetResult instanceof PaymentSheetResult.Completed){
Toast.makeText(this,"payment success",Toast.LENGTH_SHORT).show();
}
}
private void getEmphericalKey() {
StringRequest request = new StringRequest(Request.Method.POST, "https://api.stripe.com/v1/ephemeral_keys",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
EphericalKey = object.getString("id");
Toast.makeText(MainActivity2.this,CustomerId,Toast.LENGTH_SHORT).show();
getClintSecret(CustomerId,EphericalKey);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization","Bearer"+SecretKey);
header.put("Stripe-Version","2022-08-01");
return header;
}
#Nullable
#Override
protected Map<String, String> getPostParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("customer",CustomerId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void getClintSecret(String customerId, String ephericalKey) {
StringRequest request = new StringRequest(Request.Method.POST, " https://api.stripe.com/v1/payment_intents",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
ClientSecret=object.getString("client_secret");
Toast.makeText(MainActivity2.this,ClientSecret,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization","Bearer"+SecretKey);
return header;
}
#Nullable
#Override
protected Map<String, String> getPostParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("customer",CustomerId);
params.put("amount","100"+"00");
params.put("currency_payment_methods[enabled]","true");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}`

SFTP #Poller not triggering polling nothing happens

I am trying to set the spring boot application which will pool the csv . i do not see any activity happning in the spring boot application nor on filezilla SFTP server but if I change the same code to FTP then it works
#Component
#EnableIntegration
public class IntegrationConfiguration {
#Autowired
FTPConfigProperties ftpConfigProperties;
#Autowired
private BeanFactory beanFactory;
#Value("classpath:certificate.crt")
Resource certficateFile;
#Bean
public SessionFactory<ChannelSftp.LsEntry> ftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost("127.0.0.1");
factory.setPort(990);
factory.setUser("abhinav");
factory.setPassword("nssdw");
factory.setPrivateKey(certficateFile);
factory.setAllowUnknownKeys(true);
return new CachingSessionFactory<ChannelSftp.LsEntry>(factory, 100000);
}
#Bean
public SftpInboundFileSynchronizer ftpInboundFileSynchronizer() {
SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(ftpSessionFactory());
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setRemoteDirectory("/");
fileSynchronizer.setFilter(filter());
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setPreserveTimestamp(true);
fileSynchronizer.setBeanFactory(beanFactory);
return fileSynchronizer;
}
//here the poller is configured
#Bean
#InboundChannelAdapter(channel = "fromSftpChannel", poller = #Poller(fixedDelay = "10000"))
public MessageSource<File> ftpMessageSource() throws Exception {
SftpInboundFileSynchronizingMessageSource source = new SftpInboundFileSynchronizingMessageSource(
ftpInboundFileSynchronizer());
source.setLocalDirectory(new File("ftp-inbound"));
source.setAutoCreateLocalDirectory(true);
source.setMaxFetchSize(1);
source.setBeanFactory(beanFactory);
source.setUseWatchService(true);
return source;
}
public CompositeFileListFilter<ChannelSftp.LsEntry> filter() {
CompositeFileListFilter<ChannelSftp.LsEntry> filter = new CompositeFileListFilter<ChannelSftp.LsEntry>();
filter.addFilter(new SftpSimplePatternFileListFilter("*.csv"));
filter.addFilter(acceptOnceFilter());
filter.addFilter(new LastModifiedLsEntryFileListFilter());
return filter;
}
#Bean
public SftpPersistentAcceptOnceFileListFilter acceptOnceFilter() {
SftpPersistentAcceptOnceFileListFilter filter = new SftpPersistentAcceptOnceFileListFilter(metadataStore(),"ftpPersistentAcceptOnce");
filter.setFlushOnUpdate(true);
return filter;
}
#Bean
public ConcurrentMetadataStore metadataStore() {
PropertiesPersistingMetadataStore propertiesPersistingMetadataStore = new PropertiesPersistingMetadataStore();
propertiesPersistingMetadataStore.setBaseDirectory("./metastore");
propertiesPersistingMetadataStore.setFileName("ftpStream.properties");
return propertiesPersistingMetadataStore;
}
#Bean
#ServiceActivator(inputChannel = "jobChannel", outputChannel = "nullChannel")
protected JobLaunchingMessageHandler launcher(JobLauncher jobLauncher) {
return new JobLaunchingMessageHandler(jobLauncher);
}
}
here the next call where I trigger the spring batch then it goes to service actuator
#Component
public class FileToJobTransformer implements ApplicationContextAware {
private ApplicationContext context;
#Autowired
private Job job;
#Transformer(inputChannel = "fromSftpChannel", outputChannel = "jobChannel")
public JobLaunchRequest transform(File aFile) throws Exception {
String fileName = aFile.getName();
JobParameters jobParameters = new JobParametersBuilder().addString(
"input.file", aFile.getAbsolutePath()).toJobParameters();
JobLaunchRequest request = new JobLaunchRequest(job, jobParameters);
return request;
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}
the custome code is as follow
public class LastModifiedLsEntryFileListFilter implements FileListFilter<ChannelSftp.LsEntry> {
private static final long DEFAULT_AGE = 60;
private volatile long age = DEFAULT_AGE;
public long getAge() {
return this.age;
}
public void setAge(long age) {
setAge(age, TimeUnit.SECONDS);
}
public void setAge(long age, TimeUnit unit) {
this.age = unit.toSeconds(age);
}
#Override
public List<ChannelSftp.LsEntry> filterFiles(ChannelSftp.LsEntry[] files) {
System.out.println("files = [" + files.length + "]");
List<ChannelSftp.LsEntry> list = new ArrayList<ChannelSftp.LsEntry>();
long now = System.currentTimeMillis() / 1000;
for (ChannelSftp.LsEntry file : files) {
if (file.getAttrs()
.isDir()) {
continue;
}
int lastModifiedTime = file.getAttrs()
.getMTime();
if (lastModifiedTime + this.age <= now) {
list.add(file);
}
}
Collections.reverse(list);
ArrayList<ChannelSftp.LsEntry> oneElementList = new ArrayList<ChannelSftp.LsEntry>(1) ;
oneElementList.add(list.get(0));
return oneElementList;
}
}

Spring FTP Integration should look for modified file with same name

I am using FileSystemPersistentAcceptOnceFileListFilter and PropertiesPersistingMetadataStore to check if there is any new file (or) any file with same name (or) same file got modified then the payload should invoke the file. But it is not listening for the existing file got modified/modified with time.
Please suggest any good solution for resolving this issue
#Bean
#InboundChannelAdapter(value = "inputChannel", poller = #Poller(fixedDelay = "1000", maxMessagesPerPoll = "1"))
public MessageSource<File> receive() throws Exception {
FtpInboundFileSynchronizingMessageSource messageSource = new FtpInboundFileSynchronizingMessageSource(
synchronizer());
Logger.info(messageSource, "receive ");
messageSource.setLocalDirectory(Temp);
messageSource.setAutoCreateLocalDirectory(true);
messageSource
.setLocalFilter(fileSystemPersistentAcceptOnceFileListFilter());
return messageSource;
}
#Bean
public FileListFilter<FTPFile> compositeFilter() throws Exception {
Pattern pattern = Pattern.compile(".*\\.xml$");
CompositeFileListFilter<FTPFile> compositeFileListFilter = new CompositeFileListFilter<FTPFile>();
FileListFilter<FTPFile> fileListFilter = new FtpRegexPatternFileListFilter(
pattern);
compositeFileListFilter.addFilter(fileListFilter);
compositeFileListFilter.addFilter(getAcceptOnceFileFilter());
Logger.info(compositeFileListFilter.getClass().getName(), " compositeFilter ");
return compositeFileListFilter;
}
#Bean
public FileListFilter<FTPFile> getAcceptOnceFileFilter() {
FileListFilter<FTPFile> ftpPersistentAcceptOnceFileListFilter = null;
try {
ftpPersistentAcceptOnceFileListFilter = new FtpPersistentAcceptOnceFileListFilter(
getMetadataStore(), "######");
} catch (Exception e) {
e.printStackTrace();
}
Logger.info(ftpPersistentAcceptOnceFileListFilter.getClass().getName(), " getAcceptOnceFileFilter ");
return ftpPersistentAcceptOnceFileListFilter;
}
#Bean
public PropertiesPersistingMetadataStore getMetadataStore()
throws Exception {
PropertiesPersistingMetadataStore metadataStore = new PropertiesPersistingMetadataStore();
metadataStore.setBaseDirectory("temp");
metadataStore.afterPropertiesSet();
Logger.info(metadataStore.getClass().getName(), " metadataStore ");
return metadataStore;
}
#Bean
public AbstractInboundFileSynchronizer<FTPFile> synchronizer()
throws Exception {
AbstractInboundFileSynchronizer<FTPFile> fileSynchronizer = new FtpInboundFileSynchronizer(
sessionFactory());
fileSynchronizer.setRemoteDirectory("/RemoteFile/");
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setFilter(compositeFilter());
Logger.info(fileSynchronizer.getClass().getName(), " fileSynchronizer ");
return fileSynchronizer;
}
#Bean
public FileSystemPersistentAcceptOnceFileListFilter fileSystemPersistentAcceptOnceFileListFilter() {
ConcurrentMetadataStore metaDataStore;
FileSystemPersistentAcceptOnceFileListFilter fileSystemPersistentFilter = null;
try {
metaDataStore = getMetadataStore();
fileSystemPersistentFilter = new FileSystemPersistentAcceptOnceFileListFilter(
metaDataStore, "######");
fileSystemPersistentFilter.setFlushOnUpdate(true);
return fileSystemPersistentFilter;
} catch (Exception e) {
e.printStackTrace();
}
Logger.info(fileSystemPersistentFilter.getClass().getName(), " fileSystemPersistentFilter ");
return fileSystemPersistentFilter;
}
#Bean(name = "sessionFactory")
public SessionFactory<FTPFile> sessionFactory() throws SocketException, IOException {
DefaultFtpSessionFactory ftp = new DefaultFtpSessionFactory();
ftp.setHost(hostName);
ftp.setUsername(username);
ftp.setPassword(passWord);
ftp.setBufferSize(1000);
return ftp;
}
#Bean(name = "inputChannel")
public PollableChannel inputChannel() {
QueueChannel channel = new QueueChannel();
return channel;
}
#Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata defaultPoller() {
PollerMetadata pollerMetadata = new PollerMetadata();
pollerMetadata.setTrigger(new PeriodicTrigger(10));
return pollerMetadata;
}
#ServiceActivator(inputChannel = "inputChannel")
public void foo(String payload) {
System.out.println("payload: " + payload);
}
}
The FileSystemPersistentAcceptOnceFileListFilter is for local files, after the transfer already. To meet your requirements there is similar FtpPersistentAcceptOnceFileListFilter for remote entries.

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

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 :)

Android app - using AsyncTask - stops opening a URL in WebView, it is opened by the default browser if I call another URL

I'm beginning to develop in android using the material from http://developer.android.com.
I took one of their examples and modified it, so that my application can connect to a webpage. It works well when it is opened but if I click on an actionBar item which should open another page the new page isn't opened in the WebView, but it's launched the default browser.
I tried in many way to understand how to avoid that, but my little experience didn't allow me to fixe the problem.
Can you help me?
Many thanks.
Nino
public class MainActivity extends Activity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
public static String PAGINA ="http://www.kibao.org/simu/wap.php?lng=";
public static String BASE ="http://www.kibao.org";
public static String ATTUALE ="";
public static String lng = "";
final Context context = this;
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
public static boolean refreshDisplay = true;
public static String sPref = null;
public static String pagina = "";
private NetworkReceiver receiver = new NetworkReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
lng = getResources().getString(R.string.lng);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
if (refreshDisplay) {
ATTUALE=PAGINA.concat(lng);
loadPage(ATTUALE);
}
}
#Override
public void onDestroy() {
super.onStop();
String ciao = getResources().getString(R.string.ciao);
show_toast(ciao);
if (receiver != null) {
this.unregisterReceiver(receiver);
}
}
private void updateConnectedFlags() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
wifiConnected = false;
mobileConnected = false;
}
}
private void loadPage(String pgUrl) {
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected))) {
new DownloadWebpageTask().execute(pgUrl);
} else {
showErrorPage();
}
}
// Displays an error if the app is unable to load content.
private void showErrorPage() {
....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu1:
if (refreshDisplay) {
ATTUALE=BASE.concat("/partite.php?lng=");
ATTUALE=ATTUALE.concat(lng);
loadPage(ATTUALE);
}
return true;
....
default:
return super.onOptionsItemSelected(item);
}
}
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadWebpageFromNetwork(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
#Override
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(ATTUALE);
}
}
private String loadWebpageFromNetwork(String urlString) throws IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
pagina = getStringFromInputStream(stream);
} finally {
if (stream != null) {
stream.close();
}
}
return pagina;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
........
}
This DownloadWebpageTask tries to "download" a webpage into a string, using a webview. This is not the correct way to do it. You are using the wrong tutorial. Don't use AsyncTasks for this. Start all over, using this:
http://developer.android.com/reference/android/webkit/WebView.html
or
http://www.mkyong.com/android/android-webview-example/
Simply call webview.loadUrl(url) again with a different url if you want to load a different page. It's as simple as that.
I've found another solution that works. I added the line
myWebView.setWebViewClient(new WebViewClient());
in the onPostExecute:
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(ATTUALE);
}
Thanks, Frank.
PS I've tried to add a comment to the last Frank's post, but I didn't succeed!

Resources