Ive had a deeper look at the storage system now, but I just can't get it to work properly. The data seems to be saved, the saved data is definitely not empty and I am still getting a java.lang.NullPointerException.
So here is my Class i want to saved and later read to the Storage.
Band is a trivial Class with name and genre String.
public class Band implements Externalizable{
String name;
String genre;
public Band(String bnd, String gen){
this.name = bnd;
this.genre = gen;
}
public Band() {
}
public String getName(){
return this.name;
}
public String getGenre() { return this.genre; }
public void setName(String name) {
this.name = name;
}
public void setGenre(String genre) {
this.genre = genre;
}
#Override
public String toString(){
String s;
s = this.name;
return s;
}
public int getVersion(){
return 1;
}
#Override
public void externalize(DataOutputStream out) throws IOException {
Util.writeUTF(name, out);
Util.writeUTF(genre, out);
}
#Override
public void internalize(int version, DataInputStream in) throws IOException {
name = Util.readUTF(in);
genre = Util.readUTF(in);
}
public String getObjectId(){
return "Band";
}
}
BandList is just a Class with an ArrayList the Bands are added to.
public class BandList implements Externalizable{
List <Band> bandList;
public List getBandList(){
return this.bandList;
}
public BandList(){
bandList = new ArrayList<Band>();
}
public void setBandList(List<Band> bandList) {
this.bandList = bandList;
}
public int getVersion(){
return 1;
}
#Override
public void externalize(DataOutputStream out) throws IOException {
Util.writeObject(bandList, out);
}
#Override
public void internalize(int version, DataInputStream in) throws IOException {
bandList = (ArrayList<Band>) Util.readObject(in);
}
public String getObjectId(){
return "BandList";
}
}
So, in some other class where the user filled in some TextFields, the band gets added to the BandList and therefore I call saveListsToStorage();
public void saveListsToStorage(){
Storage.getInstance().clearStorage();
Storage.getInstance().writeObject("Bands", bandList);
}
So now, when starting the App, the App is looking for Data in the Storage, if found, it will return the BandList Object stored, otherwise it will return a new BandList Object.
Before that, I regist the Classes with
Util.register("Band", Band.class);
Util.register("BandList", BandList.class);
and finally call this method in the main at the beginning:
public BandList loadSavedBandList() {
String[] temp = Storage.getInstance().listEntries();
for (String s : temp) {
if (s.equals("Bands") == true) {
BandList tempBand = (BandList) Storage.getInstance().readObject("Bands");
return tempBand;
}
}
return new BandList();
}
After saving and then loading it throws the NullPointer exception and I have no clue why. I now used ArrayList instead of LinkedList as Shai told me and I implemented the Externalizable Interface as told in the guide.
Maybe some of you can tell me whats wrong here.
Edit:
Here is the Exception:
java.lang.NullPointerException
at com.rosscode.gehma.Menu_Form.updateBandContainer(Menu_Form.java:95)
at com.rosscode.gehma.Menu_Form.<init>(Menu_Form.java:73)
at com.rosscode.gehma.main.start(main.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.codename1.impl.javase.Executor$1$1.run(Executor.java:106)
at com.codename1.ui.Display.processSerialCalls(Display.java:1152)
at com.codename1.ui.Display.mainEDTLoop(Display.java:969)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Edit 2, Line 95:
if(bandList.getBandList().isEmpty() == false) {
for (int i = 0; i < bandList.getBandList().size(); i++) {
Button temp = new Button(bandList.getBandList().get(i).toString());
temp.addActionListener((e) ->
nextStep()
);
listCont.add(temp);
}
menuForm.revalidate();
}
NullPointerExceptions are pretty amazing things, because not only are they easy to figure out, they even show you the exact line where they happen. All you have to do is look at anything left of a . and check if it's null. As soon as you find it, you find the problem.
So let's look at your code. Sadly I don't know which of those lines is line 95 but I'm guessing it's the one starting with if.
That means either bandList is null or bandList.getBandList() returns null. A quick look into getBandList() shows that it won't be null, as you initialize the list in the constructor of your BandList class. Which only leaves bandList.
Sadly you didn't post where you got that from, but I'm gonna assume you just did something like:
BandList bandList = loadSavedBandList();
So let's look into that method. (btw: I say a bit more about where you have to look if you didn't do this at the end of this answer).
If you couldn't find your key, it would return a new BandList, which couldn't be null. So it has to find something, meaning the key exist but the value is null.
So let's take another step and look at how you save things in the first place.
public void saveListsToStorage(){
Storage.getInstance().clearStorage();
Storage.getInstance().writeObject("Bands", bandList);
}
Now "in some other class" doesn't really explain much. But since you read a null, it means you are writing a null here. Which would mean in this "other class", at least in this method, bandList = null.
With the code you gave, it's impossible for me to look deeper into this issue, but it seems like in "that other class", you got a class attribute named bandList but fail to put anything inside it.
Or maybe you saved everything right, but didn't call
BandList bandList = loadSavedBandList();
in some form or another before your if, which would also pretty much explain the problem. I mean... if you never load the bandList, it will obviously be null...
Related
I wrote this code.
#GetMapping("/test")
public Response search(#RequestParam String value) {
System.out.println(value);
return new Response(value)
}
Some body request like
/test?value=a&value=b&value=c
value binded a,b,c
I want always bind first parmeter. Take a, ignore b, c.
Is there way using #RequestParam?
Or have to use HttpServletRequest and parsing parameter?
In this case you can use #RequestParam List<String> value instead of #RequestParam String value, and get the first value value.get(0) ignore the rest of them
For Example
http://rentacar.com/api/v1/search?make=audi&model=A8&type=6&type=11&type=12&color=RED&color=GREY
Method
public List<Vehicle> search(
#RequestParam(value="make", required=false) String make,
#RequestParam(value="model", required=false) String model,
#RequestParam(value="type", required=false) List<String> types,
#RequestParam(value="color", required=false) List<String> colors)
{
....
}
Great question!
I wrote this code to find out how this works. I included it in the test packages.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles("test")
public class ControllerTest {
#LocalServerPort
private int port;
private URL url;
#Autowired
private TestRestTemplate template;
#Before
public void setUp() throws Exception {
this.url = new URL("http://localhost:" + port + "/test?value=a&value=b&value=c");
}
#Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity(url.toString(),
String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Assert.assertEquals(response.getBody(), "a");
System.out.println("response = " + response);
}
}
I then modified your code to accept an array of strings, and only pass the first element to your Response Constructor.
Notice the changes in your code in the signature and return statement.
#GetMapping("/test")
public String search(#RequestParam String[] value) {
System.out.println(value);
return new Response(value[0]);
}
With your test, you can now explore using a List type for your request param and quickly see how the behaviour has changed.
Having a test similar to this:
public class myClass
{
public int speed100index = 0;
private List<int> values = new List<int> { 200 };
public int Speed100
{
get
{
return values[speed100index];
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var fixture = new Fixture();
var sut = fixture.Create<myClass>();
Assert.AreEqual(sut.Speed100, 200);
}
}
Would have expected this to work, but I can see why it's not. But how do I argue, that this is not a problem with AutoFixture, but a problem with the code?
AutoFixture is giving you feedback about the design of your class. The feedback is, you should follow a more object-oriented design for this class.
Protect your private state, to prevent your class from entering an inconsistent state.
You need to make the speed100index field, private, to ensure it remains consistent with the values List.
Here is what I see if I run debugger on your test:
Autofixture assigns a random number to speed100index field because it is public, and in your array there is nothing at point 53 (from my screenshot)
If you set speed100index to be private, Autofixture will not re-assign the number and your test will pass.
I have a util function as below:
public static boolean isWebElementEnabled(WebElement element) {
try {
return element.isEnabled();
} catch (Exception exx) {
return false;
}
}
public static boolean chkForThisElement(WebElement myElement) {
try {
return myElement.isDisplayed();
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
I call it like this in the base class:
public static boolean isusernameBoxEnabled = isWebElementEnabled(unameBox);
public static boolean ispWordBoxEnabled = isWebElementEnabled(pwordBox);
public static boolean issubmitBtnEnabled = isWebElementEnabled(submitBtn);
public static boolean isctrsDrpdwnEnabled = isWebElementEnabled(multyCts);
When I test it in the Test class, it always returns false. I tried diff ways of testing for existence, but it only returns false.
#Test(priority=1)
public void verifyLoginpagecontrols() {
Assert.assertTrue(isusernameBoxEnabled);
Assert.assertTrue(ispWordBoxEnabled);
Assert.assertTrue(issubmitBtnEnabled);
Assert.assertTrue(isctrsDrpdwnEnabled);
}
i found a solution that works cool with Ff and Chromre driver nevertheless fails in Htmlunit driver.
Solution for the above problem -
// Initialize the home page elements and then check for assertions;
homePagePO searchPage = PageFactory.initElements(driver,
homePagePO.class);
Assert.assertTrue(chkForThisElement(searchPage.AccManagerHref));
Assert.assertTrue(chkForThisElement(searchPage.disHref));
Sorry to say but I find several things wrong with your code :-
You have not initialized the page factory. That is the reason why you are getting the null error.
In your comment, you have said that you are finding elements by using #findBy. But why have you decalared the WebElement as static?.
Why have you declared isusernameBoxEnabled and related boolean variables as global variables. You could use the isWebElementEnabled() function in your assert directly.
Basically your isWebElementEnabled() is not useful at all if you are using page factory.
Because the moment you use unameBox, selenium looks for the element in the webpage and if not found returns a noSuchElement Exception. So unameBox wont reach isWebElementEnabled() if it is not found in the webpage.
You said there is a base class and Test class. But I don't understand how your code works if there are different classes because you have not made a reference to static variable as Assert.assertTrue(baseClass.isusernameBoxEnabled). So I am assuming that you have only one class and different methods.
Try the following code :-
public class Base {
#FindBy()
WebElement unameBox;
#FindBy()
WebElement pwordBox;
#FindBy()
WebElement submitBtn;
#FindBy()
WebElement multyCts;
}
public class Test {
#Test(priority=1)
public void verifyLoginpagecontrols() {
//initialize page factory
Base base = PageFactory.initElements(driver, Base.class);
Assert.assertTrue(base.unameBox.isEnabled());
Assert.assertTrue(base.pwordBox.isEnabled());
Assert.assertTrue(base.submitBtn.isEnabled());
Assert.assertTrue(base.multyCts.isEnabled());
}
}
Hope this helps you.
I am attempting to check for an existing string using a JDO query, in my attempt to prevent the insertion of a duplicate string.
My query to check for an existing string works fine, unless the two strings I am comparing have a comma in the value. If the commas exists, the comparison bombs using "==".
For example, if I query to see if "Architecture" exists, I get the right result (Horrray!).
If I attempt to see if "Architecture, Engineering, and Drafting" exists, and it does, the query comes back and says an identical value does not exist (Boo!).
The code I'm using is as follows:
Called from the RPC
public void addCommas()
{
final Industry e = new Industry();
e.setIndustryName("Architecture, Engineering, and Drafting");
persist(e);
}
public void addNoCommas()
{
final Industry e = new Industry();
e.setIndustryName("Architecture");
persist(e);
}
Persist Operation
private void persist(Industry industry)
{
if (industryNameExists(industry.getIndustryName()))
{
return;
}
final PersistenceManager pm = PMF.get().getPersistenceManager();
pm.currentTransaction().begin();
try
{
pm.makePersistent(industry);
pm.flush();
pm.currentTransaction().commit();
} catch (final Exception ex)
{
throw new RuntimeException(ex);
} finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
}
Query
public static boolean industryNameExists(final String industryName)
{
final PersistenceManager pm = PMF.get().getPersistenceManager();
Query q = null;
q = pm.newQuery(Industry.class);
q.setFilter("industryName == industryNameParam");
q.declareParameters(String.class.getName() + " industryNameParam");
final List<Industry> industry = (List<Industry>) q.execute(industryName.getBytes());
boolean exists = !industry.isEmpty();
if (q != null)
{
q.closeAll();
}
pm.close();
return exists;
}
JDO Entity
#PersistenceCapable(detachable = "true")
public class Industry implements StoreCallback
{
#NotNull(message = "Industry Name is required.")
private String industryName;
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
#PrimaryKey
private Key key;
public Industry()
{
super();
}
public Key getIndustryKey()
{
return key;
}
public String getIndustryName()
{
return industryName;
}
#Override
public void jdoPreStore()
{
if (industryName != null)
{
industryName = industryName.trim();
}
}
public void setIndustryName(final String industryName)
{
this.industryName = industryName;
}
}
Any thoughts on a resolution or pinpointing an oversight would be very much appreciated.
Cheerio.
So you're calling industryNameExists("Architecture, Engineering, and Drafting") and trying to match a JDO with industryName exactly equal "Architecture, Engineering, and Drafting"?
Assuming you don't have any typo or space difference the only thing suspect is the getBytes(). Try the following:
Query q = pm.newQuery(Industry.class, "this.industryName == :industryNameParam");
List<Industry> industry = (List<Industry>) q.execute(industryName);
You can also try variation filters like "this.industryName.equalsIgnoreCase(:industryNameParam)" and "this.industryName.startWith(:industryNameParam)" to troubleshoot.
If it still does not work, try logging the SQL generated for review and compare with a hand-written query that works.
I get the above error sometimes during the read. The exception originates from ASP.NET SqlDataReader whenever you try to read data before calling the Read() method. Since EF does all these internally, I am wondering what else can cause this error. could it be network (or) db connectivity?
thanks
Additional Bounty Info (GenericTypeTea):
I've got the same error after upgrading to EF Code First RC (4.1):
"Invalid attempt to read when no data
is present"
This is the code in question:
using (var context = GetContext())
{
var query = from item in context.Preferences
where item.UserName == userName
where item.PrefName == "TreeState"
select item;
// Error on this line
Preference entity = query.FirstOrDefault();
return entity == null ? null : entity.Value;
}
The table structure is as follows:
Preference
{
Username [varchar(50)]
PrefName [varchar(50)]
Value [varchar(max)] Nullable
}
The table is standalone and has no relationships. This is the DbModelBuilder code:
private void ConfigurePreference(DbModelBuilder builder)
{
builder.Entity<Preference>().HasKey(x => new { x.UserName, x.PrefName });
builder.Entity<Preference>().ToTable("RP_Preference");
}
Exactly the same code works perfectly in CTP5. I'm guessing this is an RC bug, but any ideas of how to fix it would be appreciated.
This error occurs when there is a large amount of data in the RC release. The difference between the RC and CTP5 is that you need to specify the [MaxLength] property that contains a large amount of data.
Are you re-using contexts? I would guess this is happening as a result of something you are doing within GetContext
If GetContext() provides a stale context, in which the DataReader is closed/corrupted, I could see the above happening.
I cannot reproduce your problem on EF4.1 RC1.
POCO:
public class Preference
{
public string UserName { get; set; }
public string PrefName { get; set; }
public string Value { get; set; }
}
Context:
public class PreferenceContext : DbContext
{
public DbSet<Preference> Preferences {get;set;}
public PreferenceContext()
: base("Data Source=localhost;Initial Catalog=_so_question_ef41_rc;Integrated Security=SSPI;") {
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
ConfigurePreference(modelBuilder);
base.OnModelCreating(modelBuilder);
}
private void ConfigurePreference(DbModelBuilder builder)
{
builder.Entity<Preference>().HasKey(x => new { x.UserName, x.PrefName });
builder.Entity<Preference>().ToTable("RP_Preference");
}
}
My little Console App:
class Program
{
static void Main(string[] args)
{
string userName = "Anon";
for (int i = 0; i < 10000; i++)
{
var p = GetPreference(userName);
}
}
private static string GetPreference(string userName)
{
using (var context = new PreferenceContext())
{
var query = from item in context.Preferences
where item.UserName == userName
where item.PrefName == "TreeState"
select item;
// Error on this line
Preference entity = query.FirstOrDefault();
return entity == null ? null : entity.Value;
}
}
}
I do 10,000 reads, and no error. You will need to post more complete code to continue.
Increase the CommandTimeout on the context.
I had the same issue with EF4 - In my case I was (trying to) return the list of entities within the using{} section. This is the same as you are doing in your question:
return entity == null ? null : entity.Value;
} // end using
I moved the return to after the } and it worked.
I think I had the problem because the code was in a function which had already queried the database in another using block, I suspect the table was locking but not reporting the error, ending the using block before the return released the database lock.
Steve