signUpUrl returning nullpointerexception - authentication

SignupUrl signupUrl = androidManagementClient
.signupUrls()
.create()
.setProjectId(CLOUD_PROJECT_ID)
.setCallbackUrl(CALLBACKURL).execute();
causes the app to crash due to NPE
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.api.services.androidmanagement.v1.AndroidManagement$SignupUrls com.google.api.services.androidmanagement.v1.AndroidManagement.signupUrls()' on a null object reference
Has anyone seen this before? I've followed all the prerequisites to developing and am currently going of off the sample app, and this is the piece of code that crashes. What could be the reason?
https://developers.google.com/android/management/sample-app
Update as per request:
Code
EnterpriseHelperClass - I'd like to do this programmatically even though I know this can easily be executed via the quickstart guide.
public class EnterpriseCreationHelper {
private static final String CALLBACKURL =
"https://play.google.com/work/adminsignup?enterpriseToken";
private static final String TAG = "MainActivity";
private static String CLOUD_PROJECT_ID = "******-";
private static String SERVICE_ACCOUNT = "****#****-.iam.gserviceaccount.com";
private static String CREDENTIALS_FILE =
"/Users/****/appname/src/******.json";
private static String POLICY_ID = "samplePolicy";
private static AndroidManagement androidManagementClient;
public EnterpriseCreationHelper(AndroidManagement androidManagementClient){
EnterpriseCreationHelper.androidManagementClient = androidManagementClient;
}
public void run() throws IOException {

Your androidManagementClient value is null.
Kindly share the initialisation method of androidManagementClient it will be helpful for us to answer
Thanks

Looks like getAndroidManagementClient is returning a null object, which results in setting androidManagementClient to null. Make sure your credentials are correct, and that this method returns successfully.

Related

javaparser Symbol solver: I can resolve inherited classes of a class but cannot resolve anything else

I have setup the JavaSymbolSolver like below:
Instance Variables:
private CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
private JavaSymbolSolver symbolSolver;
private ParserConfiguration parserConfiguration = new
ParserConfiguration();
private JavaParser parser;
private CompilationUnit compilationUnit = null;
private ParseResult<CompilationUnit> parseResultcompilationUnit = null;
from constructor:
this.combinedTypeSolver.add(new ReflectionTypeSolver());
this.combinedTypeSolver.add((new JavaParserTypeSolver("C:\\Users\\nfountou\\git\\TestingJavaParser\\rsc")));
this.combinedTypeSolver.add((new JavaParserTypeSolver("C:\\Users\\nfountou\\git\\TestingJavaParser")));
this.symbolSolver = new JavaSymbolSolver(this.combinedTypeSolver);
this.parserConfiguration.setSymbolResolver(this.symbolSolver);
this.parser = new JavaParser(parserConfiguration);
FileInputStream in = new FileInputStream(filepath);
this.parseResultcompilationUnit = this.parser.parse(in);
this.compilationUnit = parseResultcompilationUnit.getResult().get();
The test code seems to work fine and I am being able to resolve e.g. class B
of class A as can be seen below:
public class A extends B{
}
the problem is that it seems that I cannot resolve anything else and whatever I tried I receive the message below:
Exception in thread "main" java.lang.IllegalStateException: No data of this type found. Use containsData to check for this first.
For example the source code that I am running for resolving e.g an AssignExpr:
ResolvedType declaringType = ((AssignExpr) value).calculateResolvedType();
(where value is an object that holds an AssignExpr node)
Resolving a superclass works fine and returns the right values:
ResolvedClassDeclaration declaringType = ((ClassOrInterfaceType) value).resolve().getTypeDeclaration().asClass();
Any ideas what am I doing wrong?
I found what was the issue... Source code is fine and it passes the configuration to the parser in the right way. The problem was that as I was refactoring code, I created a class and named it "SymbolSolver" which was causing the problem as javaparser uses a class with that specific name...
Also another problem was that I was using wrapppedNode Nodes which do not hold the configuration from symbolsolver.

Saving JWT token in static filed is best practice?

Saving KeyForHmacSha256, TokenIssuer, TokenAudience and TokenLifetimeMinutes in static filed is best practice or read these value from config file.
public class SecurityConstants
{
public static readonly byte[] KeyForHmacSha256 = new byte[64];
public static readonly string TokenIssuer = string.Empty;
public static readonly string TokenAudience = string.Empty;
public static readonly double TokenLifetimeMinutes = 1;
static SecurityConstants()
{
RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider();
cryptoProvider.GetNonZeroBytes(KeyForHmacSha256);
TokenIssuer = "issuer";
TokenAudience = "http://localhost:90";
}
}
As with about anything, the answer is "it depends."
I would certainly make the argument that the KeyForHmacSha256 variable is pulled from a config file or environment variable, just to keep it out of source control.
Personally, I usually pull in issuer and audience dynamically. The issuer is pulled from the environment so that I don't have to manually set it in each deploy and the audience is determined by who is requesting the token.
The token lifetime has the best case for just being a static definition. If you have a need to make it dynamic, you will need to handle that, but setting it explicitly isn't a security issue.

Returning the class which is a foreign key in the database

I want to ask this question and I tried to search for a while without concrete answers.
I have made a database and used LINQ2SQL to auto-generate the classes needed.
I have set the serialization mode to unidirectional to make sure the classes are being serialized and making the datamembers.
Now, what I want to know is, how I can send the references to the other classes (which has been made through LINQ2SQL).
F.x. I have a Class called Scheduler which is referencing Reservation, and Seat, because Reservation and Seat have foreign keys.
You can see the dbml here:
http://imgur.com/rR6OxDi
The dbml file. This is the model of our database
Also you can see that when I run the WCF test client it does not return the objects of Seats and Reservation.
http://imgur.com/brxNBz7
Hopefully you can all help.
UPDATE
Here is the snippet of the code provided by LINQ2SQL.
This is the fields for the scheduler
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Scheduler")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class Scheduler : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _SchID;
private System.Nullable<System.DateTime> _Date;
private System.Nullable<System.TimeSpan> _Starttime;
private System.Nullable<int> _MovieID;
private System.Nullable<int> _HallID;
private EntitySet<Seat> _Seats;
private EntitySet<Reservation> _Reservations;
private EntityRef<Hall> _Hall;
private EntityRef<Movie> _Movie;
private bool serializing;
And here is the snippet part of the code where it references to Reservation and Seat:
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Scheduler_Seat", Storage="_Seats", ThisKey="SchID", OtherKey="SchedulerID")]
[global::System.Runtime.Serialization.DataMemberAttribute(Order=6, EmitDefaultValue=false)]
public EntitySet<Seat> Seats
{
get
{
if ((this.serializing
&& (this._Seats.HasLoadedOrAssignedValues == false)))
{
return null;
}
return this._Seats;
}
set
{
this._Seats.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Scheduler_Reservation", Storage="_Reservations", ThisKey="SchID", OtherKey="SchedulerID")]
[global::System.Runtime.Serialization.DataMemberAttribute(Order=7, EmitDefaultValue=false)]
public EntitySet<Reservation> Reservations
{
get
{
if ((this.serializing
&& (this._Reservations.HasLoadedOrAssignedValues == false)))
{
return null;
}
return this._Reservations;
}
set
{
this._Reservations.Assign(value);
}
}
Update 2
Here is the Reservation class which LINQ2SQL made:
Here is the fields:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Reservation")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class Reservation : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ResID;
private System.Nullable<int> _CustomerID;
private System.Nullable<int> _SchedulerID;
private string _Row;
private string _Seat;
private EntityRef<Customer> _Customer;
private EntityRef<Scheduler> _Scheduler;
And here is the Scheduler reference part of the class
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Scheduler_Reservation", Storage="_Scheduler", ThisKey="SchedulerID", OtherKey="SchID", IsForeignKey=true, DeleteRule="SET DEFAULT")]
public Scheduler Scheduler
{
get
{
return this._Scheduler.Entity;
}
set
{
Scheduler previousValue = this._Scheduler.Entity;
if (((previousValue != value)
|| (this._Scheduler.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Scheduler.Entity = null;
previousValue.Reservations.Remove(this);
}
this._Scheduler.Entity = value;
if ((value != null))
{
value.Reservations.Add(this);
this._SchedulerID = value.SchID;
}
else
{
this._SchedulerID = default(Nullable<int>);
}
this.SendPropertyChanged("Scheduler");
}
}
}
All of these things should lead to where I could get the object like this:
Scheduler[] schedulers = client.GetAllSchedulers();
Reservation reservation = schedulers[0].Reservations.First();
But get this error due to WCF not sending the object, (which you could see in picture one).
Which is this error:
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Sequence contains
no elements
UPDATE 3:
Ok so it appears that it works somehow.
I just had to make a join between the Scheduler and Reservation.
Also whenever I debug the code I can see the variables are there. (Due to my reputation I can not post links).
But some of you might recognize the following whenever you try to view a result in debug mode:
"expanding the results view will enumerate the ienumerable c#"
Whenever I do this, it works, but not if I run it in release mode.
Looks like only object types (Reservation,Seat) have null values.
I'm guessing either you are missing DataContract/DataMember attributes in your complex types or you might need to include KnownTypeAttribute
It'd be easier to tell if you could provide some code.
EDIT
What your are talking about later is deferred loading. See this blog for more information on deferred vs immediate loading.
When you expand the IEnumerable in debug mode, that makes the request to retrieve/load the objects.
What your probably want is to load your Reservation,Seat objects along with your Scheduler object. Something like the following:
YourDatabaseContext database = new YourDatabaseContext ())
{
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Scheduler>(sch=> sch.Reservation);
options.LoadWith<Scheduler>(sch=> sch.Seat);
database.LoadOptions = options;
}
See DataLoadOptions for more details.
If you want to understand deferred execution. See this article for more details.
Quote from the article:
By default LINQ uses deferred query execution. This means when you write a LINQ query it doesn't execute. LINQ queries execute when you 'touch' the query results. This means you can change the underlying collection and run the same query subsequent times in the same scope. Touching the data means accessing the results, for instance in a for loop or by using an aggregate operator like Average or AsParallel on the results.

Authenticating with ClientLogin and using the Google Reader API in Android

I have to post a message from my android application to Google Reader. I'm Authenticating with ClientLogin and using the Google Reader API.When I'm trying to send the authentication request it's giving an error.
HTTP/1.1 404 Not Found
I think the client was able to communicate with the server but the server could not find what was requested.I'm giving the following url
postURL = "http://www.google.com/reader/api/0/edit" as
HttpPost post = new HttpPost(postURL);.
Please tell me the solution to resolve this issue.
If you're using ClientLogin you will probably need only 2 kinds of tokens to do what you need with the unnoficial Google Reader API:
Authentication Token - This is the main authentication token, and you'll need to send this in the header of every GET/POST request to the API, otherwise you'll get an error (not the one you're having, though). You can do a POST to this url for this (I have a full code example ahead): https://www.google.com/accounts/ClientLogin
Edit Token - This is the edit token, and you'll need to send this as a form parameter of POST request to any edit APIs (like the http://www.google.com/reader/api/0/edit you've mentioned). You can do a GET to this url for this (I have a code example ahead): http://www.google.com/reader/api/0/token
Getting to the 404 error you're reporting, it must be that you have a typo in your url. Copy my url and try it out. Double check it, side by side. Here is the Java code I've used for this - you can try it out also:
private static final String _AUTHPARAMS = "GoogleLogin auth=";
private static final String _GOOGLE_LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
private static final String _READER_BASE_URL = "http://www.google.com/reader/";
private static final String _API_URL = _READER_BASE_URL + "api/0/";
private static final String _TOKEN_URL = _API_URL + "token";
private static final String _USER_INFO_URL = _API_URL + "user-info";
private static final String _USER_LABEL = "user/-/label/";
private static final String _TAG_LIST_URL = _API_URL + "tag/list";
private static final String _EDIT_TAG_URL = _API_URL + "tag/edit";
private static final String _RENAME_TAG_URL = _API_URL + "rename-tag";
private static final String _DISABLE_TAG_URL = _API_URL + "disable-tag";
private static final String _SUBSCRIPTION_URL = _API_URL
+ "subscription/edit";
private static final String _SUBSCRIPTION_LIST_URL = _API_URL
+ "subscription/list";
public static String getGoogleAuthKey() throws IOException {
String _USERNAME = "USER_EMAIL#gmail.com";
String _PASSWORD = "USER_PASSWORD";
Document doc = Jsoup
.connect(_GOOGLE_LOGIN_URL)
.data("accountType", "GOOGLE", "Email", _USERNAME, "Passwd",
_PASSWORD, "service", "reader", "source",
"[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.userAgent("[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.timeout(4000).post();
// RETRIEVES THE RESPONSE TEXT inc SID and AUTH. We only want the AUTH
// key.
String _AUTHKEY = doc
.body()
.text()
.substring(doc.body().text().indexOf("Auth="),
doc.body().text().length());
_AUTHKEY = _AUTHKEY.replace("Auth=", "");
return _AUTHKEY;
}
You can see a code example for getting the edit token and doing an edit in my answer to this other question.
See my answer to this one if you want documentation (unofficial but well structured) - there is no official doc...
The code is based on http://www.chrisdadswell.co.uk/android-coding-example-authenticating-clientlogin-google-reader-api/

Stub not returning correct value with Rhino Mocks 3.6

I'm trying to write a test using Rhino Mocks 3.6 with AAA. The problem I'm running into is that the Stub i've set up doesn't seem to be returning the correct object.
The following test fails:
[SetUp]
public void SetUp()
{
repository = new MockRepository();
webUserDal = repository.Stub<IWebUserDal>();
}
[Test]
public void Test()
{
var user1 = new WebUser{Status = Status.Active, Email = "harry#test.com"};
webUserDal.Stub(x => x.Load(Arg<string>.Is.Anything)).Return(user1);
var user2 = webUserDal.Load("harry#test.com");
Assert.AreEqual(user1.Email, user2.Email);
}
User1's email property is harry#test.com while user2's email property is null
Could anyone shed some light on what I'm doing wrong?
You mixed up the old and new syntax, and it doesn't seem to work nicely together. If you want to use the new syntax (preferred), you have to change your set up method to:
[SetUp]
public void SetUp()
{
webUserDal = MockRepository.GenerateStub<IWebUserDal>();
}
If you create the MockRepository object then you need to run repository.ReplayAll() before you use the mocks, but this is the old syntax. So its better to just use static methods.