post to wcf using volley (android) - android-volley

i am trying to solve this error from a week but any of my workaround is not working unfortunately
i am trying to send json String like this String={"name":"ABC"} to WCF(ASP.NET) using volley library post method but its not working anyhow gives this error
BasicNetwork.performRequest: Unexpected response code 400 for http://192.168.1.11/MyDemoService/Service1.svc/insert
i am not sure what is wrong and where is the mistake is being made
Here is the WCF Code:
[WebInvoke(Method = "POST", UriTemplate = "insert", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string insert(string name);
insert Function :
public string insert(string name)
{
//write database related insert logic here.
//string response2="{\"name\":\"mohib\"}";
//info m = JsonConvert.DeserializeObject<info>(name);
//string n = m.name;
// string ds = name;
string conStr = #"Data Source=CRESIDIAN-DELL;Initial Catalog=WCFTest;User Id=sa;Password=1234";
// string msg = "true";
try
{
SqlConnection con = new SqlConnection(conStr);
con.Open();
string query = "insert into DemoTable (name) values ('" + name + "')";
SqlCommand com = new SqlCommand(query, con);
com.ExecuteNonQuery();
msg = "Inserted";
con.Close();
}
catch (Exception e)
{
e.ToString();
}
return msg;
}
WCF Web Config :
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services >
<service name="WCFDemo.Service1">
<endpoint address="" binding="webHttpBinding" contract="WCFDemo.IService1" behaviorConfiguration="MyConfig">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors >
<behavior name="MyConfig">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Volley Code in Android (Client):
String url="http://192.168.1.11/MyDemoService/Service1.svc/insert";
JSONObject params = new JSONObject();
try {
params.put("name", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
Log.d("Tag",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
BaseApplication.getInstance().addToRequestQueue(jsonObjReq,"Post Request");

Related

Can't find user tables MVC Web API

After successful registration, can't find aspnet user tables and also when I tried to login, it returns invalid grant type
public IdentityResult Register(string username, string password)
{
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = username, Email = username };
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 3
};
IdentityResult result = manager.Create(user, password);
return result;
}
when I tried to login, it returns invalid grant type
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userStore = new UserStore<IdentityUser>(new ApplicationDbContext());
var manager = new UserManager<IdentityUser>(userStore);
var user = await manager.FindAsync(context.UserName, context.Password);
if(user !=null)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("Username", user.UserName));
identity.AddClaim(new Claim("Email", user.Email));
identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
context.Validated();
}
else
{
return;
}
}
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("MyEntities")
{
}
public DbSet<userlogindetails> userlogindetails{ get; set; }
}
webconfig
<add name="MyEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC\SQLEXPRESS;initial catalog=MyDB;user id=user;password=pass;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
It turns out that i need to add Default ConnectionString
<add name="DefaultConnection" connectionString="Data Source=My-PC\SQLEXPRESS;Initial Catalog=MyDB;User ID=username;Password=pass" providerName="System.Data.SqlClient" />

WCF slow first call

I create one WCF service from scratch with the Visual Studio project creation wizard.
Here is the interface of the service:
namespace ServiceTest {
[ServiceContract]
public interface IService1 {
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType {
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue {
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue {
get { return stringValue; }
set { stringValue = value; }
}
}
And the implementation:
namespace ServiceTest {
public class Service1 : IService1 {
public string GetData(int value) {
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite) {
if (composite == null) {
throw new ArgumentNullException("composite");
}
if (composite.BoolValue) {
composite.StringValue += "Suffix";
}
return composite;
}
}
And Web.config:
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
<directoryBrowse enabled="true"/>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
And in the other side, the client (a simple console application) with the code:
namespace ClientServiceTest {
class Program {
static void Main(string[] args) {
Service1Client client = new Service1Client();
DateTime begin = DateTime.Now;
string res = client.GetData(0);
TimeSpan interval = DateTime.Now - begin;
;
}
}
My question is:
On the first call, the interval.TotalMilliseconds is around 250.
If I play again the call with the same client, I get around 10 ms.
How can I reduce this initial cost?
I'm assuming the first call causes the Application Pool to load and then load the service and everything is already loaded for the second call.
In IIS Manager, try setting the Start Mode for the Application Pool that your WCF service is running in to AlwaysRunning and the Idle Time-out Action to Suspend. You might also want to increase the Idle Time-out(minutes).

Wearable.MessageApi.sendMessage returning Success but onMessageReceived is not calling

Working on Wear application, I have created Wear application with Mobile and wear applications. Sending data from mobile application, through "MessageApi.SendMessageResult" and returning status is SUCCESS but message is not received in wear application. Please find the code in below and let me know i am missing any thing.
Mobile App Code:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {
private static final String START_ACTIVITY = "/start_activity";
private static final String WEAR_MESSAGE_PATH = "/message";
private GoogleApiClient mApiClient;
private ArrayAdapter<String> mAdapter;
private ListView mListView;
private EditText mEditText;
private Button mSendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initGoogleApiClient();
}
private void initGoogleApiClient() {
mApiClient = new GoogleApiClient.Builder( this )
.addApi( Wearable.API )
.build();
mApiClient.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mApiClient.disconnect();
}
private void init() {
mListView = (ListView) findViewById( R.id.list_view );
mEditText = (EditText) findViewById( R.id.input );
mSendButton = (Button) findViewById( R.id.btn_send );
mAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1 );
mListView.setAdapter( mAdapter );
mSendButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = mEditText.getText().toString();
if (!TextUtils.isEmpty(text)) {
mAdapter.add(text);
mAdapter.notifyDataSetChanged();
sendMessage(WEAR_MESSAGE_PATH, text);
}
}
});
}
private void sendMessage( final String path, final String text ) {
new Thread( new Runnable() {
#Override
public void run() {
//Previous code
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mApiClient ).await();
Log.d("MessageAPI","nodes :: "+nodes);
for(com.google.android.gms.wearable.Node node : nodes.getNodes()) {
Log.d("MessageAPI","nodes for :: "+node);
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
mApiClient, node.getId(), path, text.getBytes() ).await();
Log.d("MessageAPI","node.getId() : "+node.getId());
Log.d("MessageAPI","text.getBytes() : "+text.getBytes());
Log.d("MessageAPI","path : "+path);
Log.d("MessageAPI","nodes result Status:: "+result.getStatus().isSuccess());
}
/*PutDataMapRequest putDMR = PutDataMapRequest.create(path);
putDMR.getDataMap().putAll(getDatMap());
PutDataRequest request = putDMR.asPutDataRequest();
DataApi.DataItemResult result = Wearable.DataApi.putDataItem(mApiClient, request).await();
if (result.getStatus().isSuccess()) {
Log.v("MessageAPI", "nodes DataMap: " + getDatMap() + " sent successfully to data layer ");
} else {
// Log an error
Log.v("MessageAPI", "nodes ERROR: failed to send DataMap to data layer");
}*/
runOnUiThread( new Runnable() {
#Override
public void run() {
mEditText.setText( "" );
}
});
}
}).start();
}
#Override
public void onConnected(Bundle bundle) {
sendMessage(START_ACTIVITY, "Wear my TEST MESSAGE");
}
#Override
public void onConnectionSuspended(int i) {
}
private DataMap getDatMap(){
DataMap dataMap = new DataMap();
dataMap.putLong("time", new Date().getTime());
dataMap.putString("hole", "1");
dataMap.putString("front", "250");
dataMap.putString("middle", "260");
dataMap.putString("back", "270");
return dataMap;
}
}
Mobile App manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ptrprograms.wearmessageapi" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
wearApp Code
public class WearMessageListenerService extends WearableListenerService {
private static final String START_ACTIVITY = "/start_activity";
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d("MessageAPI","onMessageReceived :: "+ messageEvent.getPath());
/* if( messageEvent.getPath().equalsIgnoreCase( START_ACTIVITY ) ) {
Intent intent = new Intent( this, MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
} else {
super.onMessageReceived(messageEvent);
}*/
showToast("onMessageReceived:: "+messageEvent.getPath());
Intent intent = new Intent( this, MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
super.onDataChanged(dataEventBuffer);
Log.d("MessageAPI","onMessageReceived : onDataChanged: ");
}
}
wearApp manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- <service android:name=".WearMessageListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>-->
<service android:name=".WearMessageListenerService">
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/prefix" />
<!--<data android:scheme="wear" android:host="*"
android:path="/start_activity" />-->
<!--<action android:name="com.google.android.gms.wearable.CAPABILITY_CHANGED" />
<action android:name="com.google.android.gms.wearable.CHANNEL_EVENT" />-->
<!-- <data android:scheme="wear" android:host="*" android:path="/start_activity" />-->
</service>
</application>
1) Problem is in wearApp in WearMessageListenerService. You don't call
super.onMessageReceived(messageEvent);
i.e you consume all messages. When you call super method you pass message to Wearable.MessageApi.addListener(...
2) I don't see in your wear app that you register MessageApi listener.
3) You mix MessageApi with Data Layer api.
4) In wear app in Main activity you need connect with google play services too. To register MessageApi listener in onConnected method.
5) Please check https://github.com/mariopce/android-wear-bilateral-communication.
This is example of using MessageApi for 2-way communication (mobile-wear-mobile)

How to get Android Application to push notifications after ui thread is closed

How to get push notification working after manually closing UI on Android?
Hi, I need some help, Couldn't find any solutions by searching.
Application basically is like any other messaging applications, ex. Whatsapp.
I have MessageService running as own process, even UI closed, it stays alive.
This is how my application basically works:
MainActivity start service
MessageService send broadCast to
messageReceiver gets broadCast and run messageLoader
MessagesLoader extends AsyncTask gets changes from database
MessagesLoader push notification.
Every these parts working correctly when UI running
When I close UI, messageService restarts again, but no push notifications after UI closed.
Any help to get this work would be appreciated.
Thanks
Here is some code snippet to understand how my thing works..
MainActivity.java
...........................
#Override
protected void onResume() {
super.onResume();
serviceIntent = new Intent(getApplicationContext(), MessageService.class);
startService(serviceIntent);
registerReceiver(messageReceiver, new IntentFilter(MessageService.MESSAGES_BROADCAST_ACTION));
}
...........................
MessageService.java
public class MessageService extends Service {
Updater updater;
BroadcastReceiver messageBroadcaster;
Intent intent;
Context context;
static final public String MESSAGES_BROADCAST_ACTION = "com.<Your Package>";
public MessageService() {
}
#Override
public IBinder onBind(Intent intent) {
this.intent = intent;
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
this.updater = new Updater();
this.context = getApplicationContext();
this.intent = new Intent(this, NotificationActivity.class);
Toast.makeText(this, "Message Service Created", Toast.LENGTH_LONG).show();
}
#Override
public synchronized int onStartCommand(Intent intent, int flags, int startId) {
if (!updater.isRunning()) {
updater.start();
updater.isRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public synchronized void onDestroy() {
super.onDestroy();
if (updater.isRunning) {
updater.interrupt();
updater.isRunning = false;
updater = null;
}
Toast.makeText(this, "Message Service Destroyed", Toast.LENGTH_LONG).show();
}
class Updater extends Thread {
public boolean isRunning = false;
public long DELAY = 2500;
#Override
public void run() {
super.run();
isRunning = true;
while (isRunning) {
sendResult();
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
isRunning = false;
}
}
}
public boolean isRunning() {
return this.isRunning;
}
}
public void sendResult() {
sendBroadcast(intent);
}
}
MessageReceiver.java
public class MessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MessageService.class);
context.startService(serviceIntent);
new MessagesLoader(context).execute();
}
}
MessageLoader.java
public class MessagesLoader extends AsyncTask<String,Void,String> {
public MessagesLoader(Context context) {
this.context = context;
this.intent = new Intent(this.context, ChatsActivity.class);
this.prev_count = prev_count;
Intent intent = new Intent(context, ChatsActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
this.mBuilder = new android.support.v4.app.NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("YOUR APP");
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
StringBuffer result = new StringBuffer("");
try {
URL url = new URL("http://yourURL.com/get_data.php");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
String urlParameters = "<OWN PARAMETERS>";
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
con.connect();
InputStream inputStream = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return new String(result);
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
initData(result);
}
public void initData(String result) {
// Actually Store Data to sharedPreferences
String error = "";
JSONObject obj = new JSONObject();
// ...ETC
int count = 5;
showNotification(5);
}
public void showNotification(int count) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this.context, ChatsActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this.context, 0, mIntent, 0);
Intent cIntent = new Intent(this.context, NotificationActionService.class);
PendingIntent cPIntent = PendingIntent.getService(this.context, 0, cIntent, 0);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText("YOUR BIG TEXT");
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder
.setContentIntent(pIntent)
.setContentText("YOUR CONTENT TEXT")
.setAutoCancel(true)
.setLights(R.color.white, 1000, 500)
.setSound(soundUri)
.setGroup("YOUR GROUP")
.setTicker("YOUR TICKER TEXT")
.setWhen(System.currentTimeMillis())
.setCategory("YOUR CATEGORY")
.setStyle(bigTextStyle)
.addAction(0, "Show Messages", pIntent);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(mIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackage" >
android:versionCode="1"
android:versionName="1.0"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:configChanges="orientation"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourpackage.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<service android:name="com.yourpackage.MessageService"
android:process=":messageService"
android:enabled="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/messageService">
<intent-filter>
<action android:name="com.yourpackage.MessageService" />
</intent-filter>
</service>
<receiver android:name="com.yourpackage.MessageReceiver">
<intent-filter>
<action android:name="com.yourpackage.MessageReceiver" />
</intent-filter>
</receiver>
</application>
</manifest>
I've found the solution. Now my application is always showing me new messages info even without UI running.
Here is solution to fix this problem.
MainActivity.java
#Override
protected void onResume() {
super.onresume();
serviceIntent = new Intent(getApplicationContext(), MessageService.class);
startService(serviceIntent);
/* COMMENTED OUT LINE BELOW */
//registerReceiver(messageReceiver, new IntentFilter(MessageService.MESSAGES_BROADCAST_ACTION));
}
MessageService.java
#Override
public void onCreate() {
super.onCreate();
updater = new Updater();
context = getApplicationContext();
/* AND ADDED THAT LINE HERE AND */
registerReceiver(messageReceiver, new IntentFilter(MESSAGES_BROADCAST_ACTION));
intent = new Intent(MESSAGES_BROADCAST_ACTION);
Toast.makeText(this, "Message Service Created", Toast.LENGTH_LONG).show();
}

Spring Batch - Copying file from remote location

I am new to Spring batch. I need to achieve the following:
Step 1: Copy a file from remote location to local directory.
Step 2: Process each line of the file.
Step 3: Store the processed line into a database.
I am sure about the last two steps, but how can I achieve the first step?
Thanks for your help.
you can write a tasklet to achieve this this tasklet would be in separate step
<step id="movingFile" next="step2">
<tasklet ref="voterImportFileMovingTasklet" />
<listeners>
<listener ref="stepLevelListener" />
</listeners>
</step>
<step id="step2" >
<chunk reader="FileReader" processor="ItemProcessor" writer="ItemWriter" commit-interval="300"
skip-limit="1000">
<skippable-exception-classes>
<include class="java.lang.Exception" />
</skippable-exception-classes>
<listeners>
<listener ref="voterImportListener" />
</listeners>
</chunk>
</step>
Tasklet will be
public class FileMovingTasklet implements Tasklet, InitializingBean {
private Resource sourceDirectory;
private Resource targetDirectory;
private static final Log LOG = LogFactory.getLog(FileMovingTasklet.class);
public Resource getSourceDirectory() {
return sourceDirectory;
}
public void setSourceDirectory(Resource sourceDirectory) {
this.sourceDirectory = sourceDirectory;
}
public Resource getTargetDirectory() {
return targetDirectory;
}
public void setTargetDirectory(Resource targetDirectory) {
this.targetDirectory = targetDirectory;
}
#Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(sourceDirectory, "Source directory must be set");
Assert.notNull(targetDirectory, "Target directory must be set");
}
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
InputStream inStream = null;
OutputStream outStream = null;
File[] files;
File dir = sourceDirectory.getFile();
Assert.state(dir.isDirectory());
files = dir.listFiles();
File bfile = null;
for (int i = 0; i < files.length; i++) {
bfile = new File(targetDirectory.getURL().getPath() + File.separator + files[i].getName());
inStream = new FileInputStream(files[i]);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
return RepeatStatus.FINISHED;
}

Resources