Reading information from CIFS / SMB with an Android application - android

I've been attempting to develop an android application that can pull information from a CIFS / SMB protocol. I've tried JCIFS and keep getting errors with my eclipse application not being able to read the package (even after I've Javadoc'd it), and my last resort was to get help. Therefore, can anyone offer incite / information on how to do this?
I've tried this : Copy all files from server to Android Device
I've tried this : http://jcifs.samba.org/
I've tried this: http://learn-it-stuff.blogspot.com/2012/01/adding-jcifs-api-to-our-android-java.html
Maybe there is a couple things I'm not understanding at the moment that could be fleshed out.
My snippet of the code I'm using (copy and pasted directly from the third link for the most part) :
public void login(String address2, String username2, String password2)
throws Exception {
setDomain(UniAddress.getByName(address2));
setAuthentication(new NtlmPasswordAuthentication(address2, username2,
password2));
SmbSession.logon(getDomain(), authentication);
}
public UniAddress getDomain() {
return domain;
}
/**
* #param domain
* the domain to set
*/
public void setDomain(UniAddress domain) {
this.domain = domain;
}
/**
* #return the authentication
*/
public NtlmPasswordAuthentication getAuthentication() {
return authentication;
}
/**
* #param authentication
* the authentication to set
*/
public void setAuthentication(NtlmPasswordAuthentication authentication) {
this.authentication = authentication;
}
and then from here I'm calling the login(); with a address, username, and password. When I do this the application crashes and gives me an error of "NoClassDefFoundError" at the line: setDomain(UniAddress....), specifically from the UniAddress class.
Could anyone help me with this?

Noticing that you have followed the procedure from:
http://learn-it-stuff.blogspot.com/2012/01/adding-jcifs-api-to-our-android-java.html
in importing jcifs.jar for UniAddress and other jcifs apis,
but for it to work :
jcifs.jar must be present in <Project Name>/libs folder

Related

I want to store the screenshots in android testing and I'm using expresso

Below is the code
#RunWith(AndroidJUnit4.class)
public class ScreenshotJavaTest {
// a handy JUnit rule that stores the method name
#Rule
public TestName nameRule = new TestName();
#Rule
public ActivityScenarioRule<MainActivity> activityScenarioRule =
new ActivityScenarioRule<>(MainActivity.class);
/**
* Captures and saves an image of the entire {#link MainActivity} contents.
*/
#Test
public void saveActivityBitmap() throws IOException {
writeToTestStorage(captureToBitmap(onView(isRoot())), getClass().getSimpleName() + "_" + nameRule.getMethodName());
}
/**
* Captures and saves an image of the 'Hello world' view.
*/
#Test
public void saveViewBitmap() throws IOException {
writeToTestStorage(captureToBitmap(onView(withText("Hello World!"))), getClass().getSimpleName() + "_" + nameRule.getMethodName());
}
/**
* Captures and saves an image of the entire device screen to storage.
*/
#Test
public void saveDeviceScreenBitmap() throws IOException {
writeToTestStorage(takeScreenshot(), getClass().getSimpleName() + "_" + nameRule.getMethodName());
}
}
All test cases are running but I am not able to find any screenshots anywhere in the device file manager. So How I will find those screenshots or there are some other ways we can achieve to get
these screenshots in automation testing
Cannot speak for real devices, but when using the Android Studio Simulator you can find the screenshots using the Device File Explorer at the following path:
/storage/emulated/0/googletest/test_outputfiles
Make sure to add the following line to your gradle file:
testInstrumentationRunnerArguments useTestStorageService: 'true'
I've been searching for hours and this doesn't seem to be documented anywhere.

Limit access to my endpoints to my Android app only

I'm new to the Google App Engine, and I'm trying to make my first engine and connect it to my Android app. I have walked through this tutorial in order to learn about it:
https://cloud.google.com/endpoints/docs/frameworks/legacy/v1/java/helloendpoints-android-studio
I got it to work fine. I can access my app engine from my android app, and get the wanted response. The problem is, I want to restrict the endpoints of my API to my app's users only.
This is my API method (from the tutorial), and as for now, everyone can access my api's explorer and execute methods in it, as long as they are logged in to any Google account.
I want the users to be able to execute this method from my app only.
This is my app engine java file:
package com.example.Barda.myapplication.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.response.UnauthorizedException;
import com.google.appengine.api.users.User;
import javax.inject.Named;
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
clientIds = {Constants.ANDROID_CLIENT_ID},
audiences="firebase-wiki-race.appspot.com",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.Barda.example.com",
ownerName = "backend.myapplication.Barda.example.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) throws UnauthorizedException {
// if (user == null) throw new UnauthorizedException("User is Not Valid");
MyBean response = new MyBean();
response.setData("Hi, " + name);
return response;
}
}
This is constants class:
package com.example.Barda.myapplication.backend;
/**
* Contains the client IDs and scopes for allowed clients consuming your API.
*/
public class Constants {
public static final String ANDROID_CLIENT_ID = "*********************.apps.googleusercontent.com";
}
I have generated using my app's SH-1 and package name the ANDROID_CLIENT_ID.
I have searched online a lot, and read blogs and threads, but I couldn't make it work. Is this a possible thing to do? What am I doing wrong?
You'll want to follow the documentation's guide on adding authorization to the API backend. In this process you define a list of clients that are authorized to use your Endpoint.
Once that's done you can follow the guide on making authenticated calls from Android.

What does Device Id mean Azure Push Notifications in Xamarin Android? How to get it?

We are using Azure Mobile Services to Push notifications to a Xamarin Android and a Xamarin iOS and a Windows Universal App. The Windows Universal App has plenty of documentation around what we need, although we haven’t had a chance to implement it yet. However, both Xamarin Android and iOS are missing all documentation around Push Notifications. If you go to http://azure.microsoft.com/en-us/documentation/services/mobile-services/ and select Xamarin Android or Xamarin iOS and .NET Backend there are zero links for documentation around these APIs. After digging around a ton yesterday I found this: http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-xamarin-android-get-started-push/ and http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-xamarin-ios-get-started-push/ both which were last updated in September of last year. The documentation was promised to be updated over 5 months ago.
When I use the Xamarin Component from Microsoft for Azure Mobile Services: http://components.xamarin.com/view/azure-mobile-services/ I am able to get the MobileServiceClient up and running, but not the Push notifications.
The API:
Push pushManager = MobileService.GetPush();
string deviceId = "what is this???";
//Option 1:
pushManager.RegisterNativeAsync(deviceId);
//Option 2:
GcmRegistration googleNotificationRegistration = new GcmRegistration(deviceId);
pushManager.RegisterAsync(googleNotificationRegistration);
Documentation I’m using:
Push.RegisterAsync:
https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.mobileservices.push.registerasync.aspx
GcmRegistration: I can’t find any documentation for this class
Registration (Base class for GcmRegistration):
https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.mobileservices.registration.aspx
Note: the parameter for Registration is not named deviceId it is named channelUri
Push.RegisterNativeAsync:
https://msdn.microsoft.com/en-us/library/dn643553.aspx
Note: the parameter of RegisterNativeAsync is not named deviceId it is named channelUri
My question is simple:
What is deviceId supposed to be? And how do I get it?
All the documentation above is for Winodws Universal Apps not for Xamarin Apps on Mono.
In the writing up of this question I have found articles about "Get Started with Notification Hubs":
Xamarin iOS - http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-notification-hubs-ios-get-started/
Xamarin Android - http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-notification-hubs-android-get-started/
Are these the example I should be using? They look old and the Android one mentions nothing about Azure Mobile Services. Should I not even be using the Azure Mobile Services Xamarin Component for Android?
tl;dr
deviceId should be just the GCMRegistrationId.
I looked into the source code of the implementations of the component DLLs and also Android SDKs.
Firstly, let's take a look to your option 1 and option 2 behind the scene. Basically both eventually do the same job of creating a GcmRegistration and passing it the internal RegistrationManager.
public Task RegisterAsync (Registration registration)
{
if (registration == null) {
throw new ArgumentNullException ("registration");
}
if (string.IsNullOrWhiteSpace (registration.PushHandle)) {
throw new ArgumentNullException ("registration.deviceId");
}
return this.RegistrationManager.RegisterAsync (registration);
}
public Task RegisterNativeAsync (string deviceId, IEnumerable<string> tags)
{
if (string.IsNullOrWhiteSpace (deviceId)) {
throw new ArgumentNullException ("deviceId");
}
GcmRegistration registration = new GcmRegistration (deviceId, tags);
return this.RegistrationManager.RegisterAsync (registration);
}
Then, one of the API calls that I can find involving the Registration.PushHandle (which is the deviceId you passed) is as below
public async Task<IEnumerable<Registration>> ListRegistrationsAsync (string deviceId)
{
MobileServiceHttpResponse mobileServiceHttpResponse = await this.client.HttpClient.RequestAsync (HttpMethod.Get, string.Format ("/push/registrations?deviceId={0}&platform={1}", new object[] {
Uri.EscapeUriString (deviceId),
Uri.EscapeUriString (Platform.Instance.PushUtility.GetPlatform ())
}), this.client.CurrentUser, null, true, null, MobileServiceFeatures.None);
return JsonConvert.DeserializeObject<IEnumerable<Registration>> (mobileServiceHttpResponse.Content, new JsonConverter[] {
new RegistrationConverter ()
});
}
I have then switched to Android Mobile Services SDK to look for similar code to find some hints. Sadly, it is found called pnsHandle in android but still no hints what it is.
/**
* Registers the client for native notifications with the specified tags
* #param pnsHandle PNS specific identifier
* #param tags Tags to use in the registration
* #return The created registration
* #throws Exception
*/
public Registration register(String pnsHandle, String... tags) throws Exception {
if (isNullOrWhiteSpace(pnsHandle)) {
throw new IllegalArgumentException("pnsHandle");
}
Registration registration = PnsSpecificRegistrationFactory.getInstance().createNativeRegistration(mNotificationHubPath);
registration.setPNSHandle(pnsHandle);
registration.setName(Registration.DEFAULT_REGISTRATION_NAME);
registration.addTags(tags);
return registerInternal(registration);
}
Finally, I guess the below example code from http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-push/#update-app should be calling the same API which now explain everything, i.e. deviceId is just the GCMRegistrationId.
#Override
public void onRegistered(Context context, final String gcmRegistrationId) {
super.onRegistered(context, gcmRegistrationId);
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
ToDoActivity.mClient.getPush().register(gcmRegistrationId, null);
return null;
}
catch(Exception e) {
// handle error
}
return null;
}
}.execute();
}

Robolectric, Dagger and compile time $ModuleAdapter creation

Following on from the other questions in my Android TDD series, I have managed to get as far as using Robolectric, Mockito, Maven and ABS to unit test my Android developments. Evidently, I am seemingly pushing my own knowledge boundaries but the Android CI dream is just too alluring. If you can assist with my next problem I would be very grateful, here it is;
I am wanting to write an integration test case which takes my application's database from v1 to head. I am using Dagger for DI and to facilitate this non-standard JUnit test I am injecting the class required to perform the upgrade into my test, as so;
#RunWith(RobolectricTestRunner.class)
public class TestDatabaseHelper {
private static final String V1_DATABASE_SQL = "res/test-support/v1-database/v1-database.sql";
#Inject private UpgradeAuditService upgradeAuditService;
#Rule public StoutLoggingRule loggingRule = new StoutLoggingRule();
#Rule public DaggerInjector injector = new DaggerInjector();
/**
* Tests upgrading the database from version 1 to HEAD.
*
* #throws NameNotFoundException When there is no app but it's running the app. A WTF moment.
* #throws IOException when something goes wrong.
*/
#Test
#Config(manifest="../OceanLife/AndroidManifest.xml")
public void testUpgradingToHead() throws NameNotFoundException, IOException {
// Given.
final Context testApplicationContext = Robolectric.getShadowApplication().getApplicationContext();
final SQLiteDatabase database = SQLiteDatabase.openDatabase("/data/data/com.oceanlife/databases/oceanlife.db", null, SQLiteDatabase.OPEN_READWRITE);
final int versionCode = testApplicationContext.getPackageManager().getPackageInfo("com.oceanlife", 0).versionCode;
// When.
replaceDatabase(database);
new DatabaseHelper(testApplicationContext, upgradeAuditService).onUpgrade(database, 1, versionCode);
// Then.
final int databaseVersion = SQLiteDatabase.openDatabase("/data/data/com.oceanlife/databases/oceanlife.db", null, SQLiteDatabase.OPEN_READWRITE).getVersion();
assertEquals("Database was not upgraded.", versionCode, databaseVersion);
}
Important points to note;
The test lives under it's own test project, separate to the project under test (see my linked questions for structure)
The failure (stack trace below) comes about when creating the real application's module graph.
The injector rule (described below) links to the test project Module which includes the module used when running my application for real.
What's happening under the DaggerInjector rule?
I attempt to inject any dependencies required by my test.
public class DaggerInjector implements MethodRule {
/**
* #see org.junit.rules.MethodRule#apply(org.junit.runners.model.Statement, org.junit.runners.model.FrameworkMethod, java.lang.Object)
*/
#Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
final ObjectGraph graph = ObjectGraph.create(new OceanLifeTestingModule());
graph.inject(target);
base.evaluate();
}
};
}
}
What does your testing module look like?
Adds entry points (this is dagger-0.9.1, not the latest where inject replaces entryPoints) for the tests and (to-be) test mocks replacements.
/**
* The injection container providing information on
* how to construct test support components.
*
* #author David C Branton
*/
#Module(includes = OceanLifeModule.class,
entryPoints = {FixtureBuilder.class,
TestSpotService.class,
TestDatabaseHelper.class},
complete = true,
overrides = true)
public class OceanLifeTestingModule {
/**
* Constructs this module.
*/
public OceanLifeTestingModule() { }
/**
* Provide the database.
*
* #return the application database.
*/
#Provides SQLiteDatabase provideDatabase() {
return SQLiteDatabase.openDatabase("/data/data/com.oceanlife/databases/oceanlife.db", null, SQLiteDatabase.OPEN_READWRITE);
}
}
My tests run green if I comment out the line of code responsible for creating my real application's object graph. Here is the stack trace;
Error 1: Caught and swallowed from my test perspective
dagger.internal.RuntimeAggregatingPlugin#getModuleAdapter
java.lang.RuntimeException: Unexpected failure loading com.oceanlife.OceanLifeModule$ModuleAdapter
Error 2: Dumped out into the console by Robolectric
java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:653)
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:460)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:222)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:69)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:52)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3079)
at java.lang.Class.getAnnotation(Class.java:3038)
at dagger.internal.plugins.reflect.ReflectivePlugin.getModuleAdapter(ReflectivePlugin.java:51)
at dagger.internal.RuntimeAggregatingPlugin.getModuleAdapter(RuntimeAggregatingPlugin.java:98)
at dagger.internal.RuntimeAggregatingPlugin.getAllModuleAdapters(RuntimeAggregatingPlugin.java:55)
at dagger.ObjectGraph.makeGraph(ObjectGraph.java:115)
at dagger.ObjectGraph.create(ObjectGraph.java:103)
at com.oceanlife.MainApplication.onCreate(MainApplication.java:36)
at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:146)
at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:387)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:227)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Investigation to-date
I've been focusing my efforts on why "Error 1" occurred. From reading the "Compile Time Code Generation" aspect to the user guide I can see that the adapter the RuntimeAggregatingPlugin is looking for (OceanLifeModule$ModuleAdapter) is generated at compile time. From that I've been inspecting my maven configuration and will be happy to provide that should the community feel it is necessary to figuring this out. The low level nature of "Error 2" makes me think it is more derivative than the root cause.
Ok. So this answer pointed me down the right track.
Essentially, this was owing to the fact that my test project didn't understand what the old v1 maps component com.google.android.maps.MapActivity etc. were. The way I resolved my problem was to import the maps.jar into my test project, i.e.;
<dependency>
<groupId>com.google.android.maps</groupId>
<artifactId>maps</artifactId>
<version>17_r3</version>
</dependency>
You can get hold of this via the Android SDK Deployer.

Using Amazon Webservices in android application

I have read on net tutorials that cloud can be used for storing data.So i wanted to ask that whether sql server 2005 table data be stored in amazon cloud.Can anyone give me the sample code to store data from sql server in amazon and retrieve it in android application?
Amazon gives you a server instance with the operating system specified by you. you can technically, install anything on it and host that.
What you should technically do is to take an instance of your desired specification from Amazon.
Write a simple web application (I would do a java webapp. For sure you can go for the same as you already are doing Android programming.) with connectivity to your DB and that has controllers to run your SQL queries and returns the values.
Here is some example code. This uses Spring just so you know. You can use plain MVC as well if you want do it simple to start with.
#RequestMapping ( value = "runquery" , method = RequestMethod.GET )
#ResponseBody
public void runQuery()
{
Statement lStatement = null;
Connection lConnection = null;
ResultSet lResultSet = null;
try
{
lConnection = DBAccess.getConnection();
lStatement = lConnection.createStatement();
lResultSet = lStatement.executeQuery( "select * from table" );
while ( lResultSet.next() )
{
mLogger.info("The result set is : "+lResultSet.toString());
}
}
catch( Exception e )
{
e.printStackTrace();
mLogger.error("Exception occurred while trying to runQuery : "+e.getMessage());
}
finally
{
DBAccess.closeResultSet( lResultSet );
DBAccess.closeStatement( lStatement );
DBAccess.closeDBConnection( lConnection );
}
}

Categories

Resources