This week's book giveaway is in the Cloud forum.We're giving away four copies of Terraform in Action and have Scott Winkler on-line!See this thread for details.
Win a copy of Terraform in Action this week in the Cloud forum!

# Beth Candida

Greenhorn
since Apr 26, 2012
Cows and Likes
Cows
0
In last 30 days
0
Total given
0
Likes
0
0
Total given
0
Given in last 30 days
0
Scavenger Hunt
Ranch Hand Scavenger Hunt
Greenhorn Scavenger Hunt

## Recent posts by Beth Candida

True. Hence, I hav written teh following logic in my code:

//descending order
if(bankName1== null || bankName2==null)
{
firstCmp = 0;
}
else{
firstCmp = bankName2.compareTo(bankName1);
}

I am not sure if it right or not.cause it sorts right in some cases..
7 years ago
Thanks! I have mdofied the main function to call my custom sort method. Please find below the updated main class. However, it would be great if someone could help me with the sorting logic:

*********************
Main function class.
***********
import java.util.Arrays;

public class SortPersonObject{

public static void main(String args[]){

PersonInfo[] persn = new PersonInfo[10];

PersonInfo person1 = new PersonInfo("ABC", "123","Honda Accord",null);
PersonInfo person2 = new PersonInfo("ABC", "999","Honda","CarLoan");
PersonInfo person3 = new PersonInfo("XYZ", "234","Altima","CarLoan");
PersonInfo person6 = new PersonInfo(null, "345",null,null);
PersonInfo person8 = new PersonInfo("ABC", "6345",null,"CarLoan");
PersonInfo person9 = new PersonInfo(null, "16345","Altima",null);
PersonInfo person10 = new PersonInfo("XYZ", "3495",null,"CarLoan");
PersonInfo person7 = new PersonInfo("XYZ", "342","Honda Accord",null);
PersonInfo person4 = new PersonInfo("ABC", "567","Altima","CarLoan");
PersonInfo person5 = new PersonInfo("XYZ", "321","Honda",null);

persn[0]=person1;
persn[1]=person2;
persn[2]=person3;
persn[3]=person4;
persn[4]=person5;
persn[5]=person6;
persn[6]=person7;
persn[7]=person8;
persn[8]=person9;
persn[9]=person10;

Arrays.sort(persn, PersonInfo.PersonComparator);

int i=0;
for(PersonInfo temp: persn){
System.out.println("persns " + ++i + " : number --> " + temp.getIdNumber() +
", Bank Name --> " + temp.getBankName() + ", Car Name --> " +temp.getCarName() + ", Loan --> " +temp.getLoan() );
}

}
}
7 years ago
hi All,

I have a following problemStatment with reagrds to sorting of arrayList. request you to provide me help in solving teh same.

Statement:
I have an ArrayList holding a Person objects. The Person object contains the following 3 String parameters: bankName, idNumber, carName.

The list will be an unsorted arraylist. I need a function which would take the unsortedList and return me the sorted list.

Order of priority for Sorting Rules:
1. Person associated to a XYZ bank.
2. Person associated to a ABC bank.
If the bankName associated to the perosn is null OR if 2 people have the same bankName, then switch to the next below category for sorting.
3. Person Having a car Honda Accord
4. Person Having a car Honda
5. Person Having a car Altima
If the carName associated to the person is null, OR if 2 people have the same bankName and same CarName then switch to the next category for sorting i.e dispaly the person who has taken the CarLoan first.
6. Person having car Loan
7. Person having the biggest idNumber
8. All other persons not falling in the above categories.

***************************
MainFunction Class:
***************************

*********************************
Sort Function Class
*********************************
7 years ago
hi,

I deploy my war file (created in target folder at the time maven install) of the application on the weblogic console.
8 years ago
I am still getting the same error even after making the bean ID chnange. I even did a maven clean install + update maven project.
I am not sure why my code is braeking on server restart.
8 years ago
hi All,

I am getting the following error while starting my weblogic server:
2013-09-13 17:36:15 INFO SimpleStepHandler:133 - Executing step: [step1]
2013-09-13 17:36:15 ERROR AbstractStep:212 - Encountered an error executing the step
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory\$2.getObject(AbstractBeanFactory.java:332)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:328)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at org.springframework.batch.core.step.item.SimpleChunkProvider\$1.doInIteration(SimpleChunkProvider.java:108)

My classes and xml files are as follows:

*******************************************************
*********************

private static final Logger LOGGER = LoggerFactory.getLogger(SampleReader.class);

// @Autowired
//private PhoneOptDAO phoneDAO;

@Autowired

public String read() throws Exception, UnexpectedInputException,
ParseException, NonTransientResourceException {

try {

// Directory path here

LOGGER.debug("some message to log");

LOGGER.info("**********************some message to log : : : "+path);

String files = null;
List<String> dataList = new ArrayList<String>();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();

if(listOfFiles!=null){
if(listOfFiles.length>0){

for (int i = 0; i < listOfFiles.length; i++)
{

if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);

int status = updateMetaData(files, "N", "I");

} catch (SQLException e) {

System.out.println(e.getMessage());

}

return null;
}

private int updateMetaData(String fileName, String pStat, String newStat){
int updstatus =0;

//ApplicationContext context =
//new ClassPathXmlApplicationContext("Spring-Module.xml");

System.out.println("file name: "+fileName +" updated in Metadata table!" +updstatus);

return updstatus;

}
}

*******************************************************************************
launch-context.xml
*******************************

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:component-scan base-package="com.abc.batch" />

<import resource="../../../../Spring-Module.xml"/>

<context:property-placeholder location="classpath:batch-default.properties"/>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>

<bean id="jobRegistry"
class="org.springframework.batch.core.configuration.support.MapJobRegistry" />

<bean class="org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor">
<property name="jobRegistry" ref="jobRegistry" />
</bean>

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>

<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>

<batch:job-repository id="jobRepository" />

<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="\${batch.jdbc.driver}" />
<property name="url" value="\${batch.jdbc.url}" />
<property name="maxActive" value="\${batch.jdbc.max.active}" />
</bean>

<jdbc:initialize-database data-source="dataSource" enabled="\${batch.data.source.init}">
<jdbc:script location="\${batch.schema.script}" />
</jdbc:initialize-database>

</beans>

*****************************************************************************

Spring-Module.xml
****************************
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<import resource="database/Spring-Datasource.xml"/>

</beans>

*******************************************************************************
**********************
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<constructor-arg index="0" ref="dataSource"/>
</bean>

</beans>

****************************************************************

*********************************

package com.abc.batch.dao.impl;

@Service

{
@Autowired
setDataSource(dataSource);
}

public int findTotalCustomer(){

String sql = "SELECT COUNT(*) FROM FILE_METADATA";

int total = getJdbcTemplate().queryForInt(sql);

}

@Override

String sql = "update FILE_METADATA set status=?, bby_aud_ts= sysdate where file_name=? and status = ?";

int rows= getJdbcTemplate().update(sql, new Object[] {m1.getNewStatus(),m1.getFile(),m1.getPrevStatus()});

return rows;
}

@Override

String sql = "Insert into file_metadata (FILE_ID,FILE_NAME,BBY_CR_TS,BBY_AUD_TS,STATUS) values "
+ "(999,?,to_date('14-AUG-13','DD-MON-RR'),null,?)";

getJdbcTemplate().update(sql, new Object[] {file.getFile(),file.getNewStatus()});

}

@Override
// TODO Auto-generated method stub
return null;
}

}

********************************************
batch-feed-context.xml
*****************
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:util="http://www.springframework.org/schema/util" xmlns:int-file="http://www.springframework.org/schema/integration/file"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.0.xsd
http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file-2.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd

<import resource="launch-context.xml" />

<!-- Jobs -->
<bean id="scheduledLauncher" class="com.abc.batch.scheduler.ScheduledLauncher">
<property name="jobLauncher" ref="jobLauncher" />
</bean>
cron="0/15 * * * * ?" />

<!-- cron="0 0 3,15 * * ?" />-->
<!-- cron="0/15 * * * * ?" />-->
<!-- cron="0 35 16 ? * MON-FRI" /> -->
<!-- cron="0 0 3,15 * * ?" /> -->

<job id="sampleBatchJob" xmlns="http://www.springframework.org/schema/batch"
job-repository="jobRepository">
<step id="step1">
writer="batchWriter" commit-interval="10">
</chunk>
</step>
</job>

scope="step">
</bean>

<!-- Item Processors -->

<bean id="batchProcessor"
class="com.abc.batch.processor.SampleProcessor"/>

<!-- Item Writers -->
<bean id="batchWriter"
class="com.abc.batch.writer.SampleWriter"
scope="step"/>

******************************************************

ANy help is highly appreciated

</beans>

8 years ago
Thanks buddy!
But there has now been a tweak in my requirement, there will be 1002 strings in my main list and i need to make chunks of 100.. How should i go about this using sublist? cause it gives me index out of bound excepotion...

Do you have a sample main program using which i can replicate my scenario?
8 years ago
I have a list holding 1000 Strings/records.

I need to do processing in chunks i.e. select first 100 (configurable property) records in my list, perform some validation and update data base activities.
Once these 100 records are done..I want to select the next 100 records in the main list..and carry the same procedure.

This Process should continue until all the records in my main list are processed.

Any help will be highly appreciated.

Cheers!
8 years ago
I have written a spring batch code,

Following is the properties file:

batch.jdbc.testWhileIdle=false
batch.schema=
batch.data.source.init=false

batch.jdbc.max.active=100

batch.jdbc.driver=oracle.jdbc.OracleDriver
batch.jdbc.url=jdbc:oracle:thin:@********
batch.jdbc.user=***
batch.schema.script=*************
batch.drop.script=*****************************

batch.jdbc.max.active=100

Connection is also succesfully established.

But my area of worry is how should i use this connection in my implementation of ItemReader class. I want to connect to the oracle database in my implementation of ItemReader class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public String read() throws Exception, UnexpectedInputException,
ParseException, NonTransientResourceException {

try{
String name = null;

Connection conn = null;
PreparedStatement ps = null;

//Connection code needed here

String sqlQuery = "select * from temp_table where id=?";

ResultSet rs=null;

int ID =190;
for(int i=0;i<50;i++){

ps = conn.prepareStatement(sqlQuery);
ps.setInt(1,ID);
rs= ps.executeQuery();

while (rs.next()){

String firstName = rs.getString("Name");

return firstName;
}
ID++;

}
}

catch(Exception e){

}

return null;
}

}

8 years ago
8 years ago
this my goal: I first need to connect to the UNIX box and then read a flat file kept on the server.

Any help is appreciated cause I am running out of days..
8 years ago
The following is my code:

It fails while establishing the connection:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)

code:

import java.io.*;
import java.text.*;
import java.util.*;

import org.apache.commons.net.ftp.*;

/**
*
* @author shussain
* @version 0.1
*/
public class FtpTestClient {

public final static int DEFAULT_FTP_PORT = 21;

private FTPClient ftpc;

public static void main(String[] args) {

String[] host_names = {"Hostname", "***.**.**.***", ""};
String[] user_names = {"user", "superuser", "hostuser"};
String[] passwords = {"*****", "superpass", "hostpass"};
String ftp_src_folder = "/tmp/r";
String ftp_src_file = "Query.txt";

for (int i = 0; i < host_names.length; i++) {
FtpTestClient.getFile(host_names[i], user_names[i],
}
}

public FtpTestClient(String host, String login, String passwd)
throws Exception
{
}
/**
* Creates a new instance of FtpTestClient
*
*
* @param host Server host name
* @param port Server port number
* @throws Exception if client create fails
*/
public FtpTestClient(String host, String port, String login, String passwd)
throws Exception
{
try {
ftpc = new FTPClient();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}

/**
* get a single file from the server. Destination filename is same as that
* on server.
*
* @param server ftp server name
* @param folder source folder on the ftp server
* @param fname file to be transferred
* @return true if successful
*/
public static boolean getFile(String server, String username,
String password, String folder, String fname)
{
boolean status = false;

FTPClient ftp = null;
try {
ftp = new FTPClient();

ftp.connect( server );

ftp.changeWorkingDirectory( folder );

File file = new File(fname);
FileOutputStream fos = new FileOutputStream( file );

ftp.retrieveFile(fname, fos);
fos.close();

status = true;

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ftp.logout();
ftp.disconnect();
} catch (Exception e) {}
}

return status;
}

public static void getAllFiles( String server,
String folder,
String destinationFolder,
Calendar start,
Calendar end ) {
try {
// Connect and logon to FTP Server
FTPClient ftp = new FTPClient();
ftp.connect( server );
System.out.println("Connected to " +
server + ".");

// List the files in the directory
ftp.changeWorkingDirectory( folder );
FTPFile[] files = ftp.listFiles();
System.out.println( "Number of files in dir: " + files.length );
DateFormat df = DateFormat.getDateInstance( DateFormat.SHORT );
for( int i=0; i<files.length; i++ ) {
Date fileDate = files[ i ].getTimestamp().getTime();
if( fileDate.compareTo( start.getTime() ) >= 0 &&
fileDate.compareTo( end.getTime() ) <= 0 ) {
System.out.print( df.format( files[ i ].getTimestamp().getTime() ) );
System.out.println( "\t" + files[ i ].getName() );
File file = new File( destinationFolder +
File.separator + files[ i ].getName() );
FileOutputStream fos = new FileOutputStream( file );
ftp.retrieveFile( files[ i ].getName(), fos );
fos.close();
file.setLastModified( fileDate.getTime() );
}
}

// Logout from the FTP Server and disconnect
ftp.logout();
ftp.disconnect();

} catch( Exception e ) {
e.printStackTrace();
}
}

/**
* Gets all files which matches a specified file name template. The template
* is a regular expression.
*
* @param server ftp server name
* @param folder source folder on the ftp server
* @param ftempl regular expression for file name
* @return true if successful
* @throws Exception if unable to connect and other problems.
*/
public static boolean getFilesOfType(String server, String username,
String password, String folder, String ftempl)
throws Exception
{
FTPClient ftp = null;
boolean status = false;

try {
// Connect and logon to FTP Server
ftp = new FTPClient();
ftp.connect( server );

// List the files in the directory

ftp.changeWorkingDirectory( folder );
FTPFile[] files = ftp.listFiles();

// get files which match name template
// at present just check for prefix
for (int i = 0; i < files.length; i++) {
/*
if (files[i].matches(ftempl)) {

}*/
}
} catch (Exception e) {
throw e;
}

finally {
// close connection
if (ftp != null && ftp.isConnected()) {
ftp.disconnect();
}
}

return status;
}

/**
* Upload a single file to the server. Destination filename is same as that
* on server.
*
* @param server ftp server name
* @param folder source folder on the ftp server
* @param fname file to be transferred
* @return true if successful
*/
public boolean putFile(String server, String username,
String password, String folder, String fname)
throws Exception {
return false;
}

public void setMode(int type) {

}

public int getMode() {
return -1;
}

}
8 years ago
hi All,

I have no hands on working experience with Spring Batch framework which is why i am damn nervous.
I need a simple spring batch framework code and example that will print "Hello World" I searched over the web, but could nt find anything really worthy. Hence, i thought of asking the ranchers who have always helped me in my time of need.

I need this program/code, so that I can debug and understand the flow.

My ultimate goal is to create a batch Job using spring framework within 5 days... ..that will read file from the SSH unix Terminal and insert values in database.
If anyone, can help me achieve my ultimate goal..i will be more than obliged to that person...