Wednesday, November 19, 2014

ByteArrayOutputStream Checked Exceptions

Just realised...

ByteArrayOutputStream actually doesn't declare 'throws IOException' on the methods it does override. I thought it did, because the method I use all the time, write(byte[]), does declare throws IOException, just to annoy us.

What it could do, but doesn't do, is that it could override the other methods so that you don't have to be annoyed by their declaring throws IOException, even though it will, of course,  never throw them.

Checked exceptions...yeah, that experiment turned out great.


----

Update: Here's a variant of FileInputStream which avoids checked exception in try-with-resources; which you could instantiate inside of a utility method, say 'public static FileInputStreamNoce istreamForFile(File srcFile)' wherein you catch FileNotFoundException.

 public static class FileInputStreamNoce extends FileInputStream {
  
  public FileInputStreamNoce(File file) throws FileNotFoundException {
   super(file);
  }
  
  /**
   * This avoids having to catch checked exception in try-with-resources.
   */
  @Override
  public void close() {
   try {
    super.close();
   } catch (IOException e) {
    // well, I don't know what to do here. Log? Re-throw wrapped inside RTE?
   }
  }
 }
 

Wednesday, September 24, 2014

In-App Web Browser Security

Don't give 'foreign' credentials to applications/apps. They might steal them. For example, if an app wants you to connect to your Facebook identity in an in-app browser. The information fed to an in-app browser can be read by the application.

http://furbo.org/2014/09/24/in-app-browsers-considered-harmful/
http://inessential.com/2014/09/24/craig_on_in-app_browsers [via]

Monday, September 15, 2014

Trying IntelliJ

One or two months ago, I tried the NetBeans IDE. Editing was painfully slow. With reservations for the unlikely possibility that it has something to do with my local environment, I can't understand how you can release something like that.

Now, I'm trying IntelliJ. It has pretty solid key bindings emulating the Eclipse bindings, which is great for trying out your normal activities. It also comes with Subversion built in, which is lucky for me because that is what I use when programming on my own.

With only a subset of my needs tried out, it's looking good. I miss two things so far: the linking of current open file to the file hierarchy, so that it (almost) always shows in the file tree; and, I haven't managed to see output from debugging/running. I fear this might be that IntelliJ won't run code until there are no errors, even in unrelated code, and I couldn't find a setting to allow it. (Or maybe it did start my main(), but I didn't see it?)

Other promising areas, both from seeing it first-hand and reading comments to that effect, is the indexing engine. Haven't tried refactoring yet, which is also important. I hear debugging is also faster, which is good. Eclipse's debugger is OK, most of the time, but sometimes grinds to a frustrating stand-still. I think that is caused by the mis-designed communications protocol, e.g. it will try to send a whole stack trace in one go, which is bad for example in the common scenario of recursion gone infinite. I noticed the option of using 'shared-memory' in the IntelliJ debug settings, which might help (but suspiciously not turned on by default?).

So, in summary, trying out IntelliJ can be recommended for Eclipse users, thanks to the ease of getting into it.

Saturday, August 16, 2014

First Database Save/Read Cycle

Just got a test saving an integer, closing database, re-opening, and reading it back working. Whut!

I am implementing a sort of database. Yes, it has to be done; and I have to do it, since apparently it's not been done before -- I mean this way. The simple way; the way based on a simple, versatile foundation.

I believe my reasoning behind this is entirely sound. I'll get back soon with at least some philosophical discussion on why most databases suck, or something more nuanced. It's saturday and dinner-time.

Monday, July 14, 2014

Uh

Wow, two months passed. Let's write something.

So, I haven't been totally idle. Right now I'm just unmotivated and tired of everything, but before that, I was slightly less unmotivated, and spent a week figuring out how to write an allocator for memory mapped bytes. I can't remember what there was to figure out, really. But there's some amount of compromise involved; speed vs size vs simplicity, as always. And the implementation, which is almost done, depending on your definition of done, was fiddlier than expected; as expected. But surprising. Given that I thought I had found an elegant solution. Perhaps I had. Or maybe because programming in Java what should be done in C is not as fun as it sounds. And I am tired.

It's one of these things that you'd think would be easy to find. Well why would I think that, really, am I that demented? Don't you remember that whenever you search the net for an X that you think should exist, all you find is a) stuff that does nothing resembling what you want, b) crap, c) frameworks that do something at least in the ballpark, maybe, or maybe does it in some non-APId component deep inside, but then you would have to work hard for it like one would with a chisel on a block of concrete with a precious marble vase hidden within it, provided that you could even know for a fact that the vase is somewhere in there, d) things for other programming languages, again probably a, b, c, but probably not X? Note that finding a well written, documented solution for X in another language would actually be very useful; I wouldn't mind translating too much, it'd actually be fun, compared to investing time and effort into something that you feel 'ought to' exist. And I am tired or perhaps depressed. Especially something like a memory manager/allocator, since off-heap storage has become rather popular lately in parts of the Java world.

So maybe I'll publish this allocator, or at least a description of the solution, if I can find the energy. As I said, the solution is pretty simple, but the code unfortunately not so simple nor fast. I should optimize and refactor it, after adding more tests. After I try to use it for some small experiments. But I am tired of pretty much everything right now.

I'd like to not be one of the legion of people who put out crap that others find and waste time on and which I'd be ashamed of. If there was a better way to find and filter for library code, it would feel better to release code of mediocre quality. Or one could instead find code of mediocre quality, but appropriate enough to be improved a little, adapted a little, republished, reused. Such a tool would of course be extremely valuable for finding stuff, regardless.

Well blah blah, somebody please make that tool, I'm busy writing blogs.

Friday, May 23, 2014

Today, I Suck Less.

Yep, productivity not bad at all today. Quality of sleep, general mood, and things like that.

Wednesday, May 21, 2014

Hibernate In-Memory Still Slow

I'm beginning to suspect that Hibernate setup with an in-memory is pretty much as slow as regular database Hibernate. Despite being recommended as a useful alternative for fast automatic testing.

Since I am feeble-minded, I think I shall try to look into it a little, instead of accepting the depressing reality. It's just that it's such a hugely soul-killing drag, despite only chipping away 10-20 seconds of spirit every test. Well, multiplication.

Will be updating here, probably.


Tuesday, May 20, 2014

Time for a Walk

Tests. Unpredictable OOMs. Slow. How the f* do you debug such things. Why not on every test? Why can't I just run the things I use, why does everything have to be wired in? Why is hibernate startup so f* slow?

Why am I wasting my... right, there is none.

Time for a walk, maybe the emotional turmoil -- I think mostly nervousness, anxiety, probably from a loss-of-control reaction, some anger, some depression -- will settle.

Friday, May 16, 2014

The Tokenizer Tail Wags The Java Syntax Dog

I'd like to register a complaint: the Java rules for package names are stupid.

Why the _ do the folder names, or components, have to be legal Java identifiers? Most probably because the package name is not designed as a syntactical element all by itself. Or even as a lexeme/tokens of its own, but a sequence of tokens. I suppose the Java syntax is designed as a sequence of lexeme/tokens. Probably under the influence of the long tradition of bottom-up syntax grammars, correct me if I am wrong.

And now, with the Java8 designers trying to reclaim some syntactic space from the past mistakes, another keyword is foreshadowed: underscore.

Warning about single underscore identifier

Already annoyed by Eclipse Luna's (4.4M7) treatment of warning about this (and I haven't found a way to turn it off), I just discovered an even more annoying behavior, which put the annoyance count at two bits, which overflowed into this one post. Unfortunately it's unlikely to leave zero in the annoyance column to the right.

This behavior is that Eclipse won't do the "Move Type to New File..." refactoring as long as this 'warning' is available to make a fuss over. No wait, sorry; apparently now it is an 'error'. This makes no sense at all.

And then for the prize: one can't even rename package names. Presumably because the package name is all retarded, with that un-scannable underscore in it. Maybe it'll be better in the next revision.

A workaround is to comment out any package declaration or import that contains a package name with this terrorist underscore in it. Though that is likely to give other errors, of course...

In fairness, there are probably not many that have discovered the awesome power in naming your packages '_'. But I happen to have it as part of a Brilliant System, so this could get really painful if the Java designers would take this bad idea to completion.

As I started out saying, it makes little sense for packages to have to be 'good' Java names anyway. The requirement could be dropped with no forward compatibility problems at all. Sure, backwards compatibility could be a problem, IOW you may want to be warned when you write code that can't be compiled as Java7 code. OTOH, then why not use a Java(N<8 all="" be="" check="" compiler="" it="" java="" ll="" of="" p="" syntax="" then="" to="" your="">
Do class loaders check class names to not contain keywords, and comply to be identifiers? I don't think it checks resources. And why should it check class names beyond some simple sanity checks? That's only added complexity.

And if no other argument convinces you, how about the fact that there exist other languages, and that the JVM is positioned as and adapted to being multi-lingual, aka polyglot? Why should other languages have to put up with this nonsense?


Wednesday, May 14, 2014

Java 8, Luna, Subclipse

Yep, going to try Java8 already. I installed the JDK a couple of weeks ago, since I was updating Java7 anyway, and found that it would indeed appear as a JRE in Eclipse; but didn't take it further.

But now I am. Downloaded Eclipse Luna, 4.4M7. Tried to changed Java compiler settings to output version 7 class format, but allow Java 8 source. I had somehow got the idea that that should be allowed. And why would you output legacy 7 code as format 8, anyway? But it isn't allowed. So 8 in, 8 out, then. Seems to work fine.

But with J8 output, I had to install Java8 on a target server; so here's how to do that. You probably don't have to use all of it.
nano /etc/hosts # because sudo complained about not resolving hostname
sudo apt-get install software-properties-common # because 'add-apt-repository' wasn't there
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

I also installed Subclipse 1.6. The file/folder status markers were added, but it wouldn't synchronize, "Unable to load default SVN Client", so I tried installing the SvnKit module too. I have the habit to try to install as little as possible, so one thing at a time, although a few restarts are needed. Still no go.

And then I saw the "SVNKit Client Adapter (Not required)", which makes perfect sense; so I installed that, and now these rather old Subclipse modules work inside the latest Eclipse.

So, done and done. Could be easier, but still comparably easy. Java 8 has arrived in my toolchain; to stay, I think. I read that it's very backwards-compatible, source-code wise.

---

Oh, right. Got an OOM during build, so the memory allotment param in eclipse.ini (inside the app) had to be edited too. Changed to "-Xmx1500m" from "-Xmx512m".

---

Ah, trying a lambda expression as first thing, of course. Error: "Lambda expressions are allowed only at source level 1.8 or above". That's nice, it knows about Java8 even at Java7 source setting. There's even a quick tip: "Change project compliance and JRE to 1.8". Well, yes to that, thank you; wow much thoughtful.

And isn't that just cute:
public static void main(String...args) {
   Sam sam = (a, b) -> a + b;
}
interface Sam {
  int bla(int a, int b);
}
---

Trying out what I thought would be the most important feature of Java8, the default (aka defender) methods. Of course, it turns out they don't work as I'd thought.

public class Java8Demo { public static void main(String...args) { Sam sam = (a, b) -> a + b; // SamDefend sd = (a, b) -> a + b; // The target type of this expression must be a functional interface } interface Sam extends SamDefend { int bla(int a, int b); } interface SamDefend { default int bla(int a, int b) { return a + b; } }// Sam sam = new Sam() { // The type new Java8Demo.Sam(){} must implement the inherited abstract method Java8Demo.Sam.bla(int, int)//// @Override//// public int bla(int a, int b) {//// // TODO Auto-generated method stub//// return 0;//// }// };}

Oh #. Blogger/blogspot sucks, especially for blogging software development stuff...why can't I just paste code with formatting intact?


public class Java8Demo {
 public static void main(String...args) {
  Sam sam = (a, b) -> a + b;
  // SamDefend sd = (a, b) -> a + b; // The target type of this expression must be a functional interface
 }
 interface Sam extends SamDefend {
  int bla(int a, int b);
 }
 interface SamDefend {
  default int bla(int a, int b) {
   return a + b;
  }
 }
// Sam sam = new Sam() { // The type new Java8Demo.Sam(){} must implement the inherited abstract method Java8Demo.Sam.bla(int, int)
////  @Override
////  public int bla(int a, int b) {
////   // TODO Auto-generated method stub
////   return 0;
////  }
// };
}


Meh. That's as close as it gets.

Tuesday, May 13, 2014

Close() But No Cigar

The ByteArrayInputStream.close(), it does nothing! And it thus allows reading bytes from the ByteArrayInputStream object after calling close() on it.

Of course someone like me has to make a mistake, closing the ByteArrayInputStream on creation. I did, by leaving a "try-with-resources" in place during refactoring, returning the 'implicitly' closed stream.

Result: 1-2 hours extra debugging, thinking that my code, using XMLStreamReader, tested with ByteArrayInputStream and string literals, had some error causing it to skip prematurely all the way to the end.

An easy fix is to use your own subclass and override close(). Something like this:
/**
* Otherwise, java input stream might return data even when closed. 
* {@link super#close()} does nothing. 
*/
@Override
public void close() throws IOException {
    this.pos = count + 1; // distinct from the 'real' EOF; might be useful.
    super.close(); // does nothing in super, but whatever. 
}

And why doesn't the standard library do this? There seems to be no performance penalty. Well, maybe there is, maybe it's kind of wrong to return EOF (-1) here, maybe it should throw an exception. But is returning bytes after closing better?

Monday, May 12, 2014

Synoptics

Programming Sucks (post)
programming is terrible (blog)

I won't mind at all if links to other output with the same outlook appear in the comments.

Thursday, May 8, 2014

It's Got What Projects Crave: It's Got Resources

I can't help meta-ing, aka thinking about what I do. And so I'm not totally happy with the below post, but what the. I'm thinking maybe I should describe what I think is good, instead of what I think is bad. Though maybe both are ok, maybe the one helps the other. And this text touches on one important facet of complexity, i.e. non-simple-ness, which I have some thoughts on; which thoughts may well materialize as text. Mental note to self: scale-free-ness. But the text is a bit un-simple in itself. Not well structured. Split-brained. Well so what, I'm not a professional writer. The text is at least trying to make a bunch of points. So let it. I can come back later.

---------

Last week I committed with a message like this: "Let's move test data resource files very far from the test source code files: Maven's src/test/resources/". It's an objective description of the change. Though with a small bit of snark. Sometimes, you're morally obliged.

I've been doing software development for a long time. I have, driven by discontentment or frustration, strived to develop at least an idea of what practices make developing easier, even somewhat possible. So my software developer sensibilities have been shaped for a long time. They may certainly need more shaping, but still.

Partaking in a Maven project, these particular sensibilities actually become a liability.

Maybe because the Maven sensibilities, anthropomorphically speaking, have not been shaped by time at all. They were pretty much set a long time ago, perhaps from the start (I'll have to look that up). But the non-existing sensibilities of a stupid tool can and will influence projects and people. Yes, not very difficult to tell Maven to also copy files from /java or whatever, but then half the point of using Maven gets lost, the setting of standards, some standards.

The test/main divide is bad enough, according to my humble sensibilities of course, but the resources/ divide is just sky high on the chart of badness, also according to these humble sensibilities. In fact, you can read 'taste' or something where I say 'sensibilities', it's a bit of a posh word anyway, isn't it.

Why was this layout chosen for Maven from the start? Well, there are some small advantages to it. For instance, you don't have to skip files that are not source-code when compiling. Maybe that was an important performance advantage back in the day, but that's hard to imagine.

Another is that you can have ".java" files be copied verbatim into the jar being built. This could actually be useful.

Polyglot projects could be having java/, scala/ etcetera. On the other hand, that's a bad taste again, it's not really polyglot if you have to have multiple folders, is it? All the source code should go into one source code folder..."src/{main,test}/src/"? "src/{main,test}/tobecompiled/"?

But what about script language source code, e.g. javascript? Well, there you go, it could be either.

This is the old arbitrary code vs. data divide thing living on.

It's also a duplication of structure, a structure that can be twenty folders deep no less.

It also makes it hard to reorganize your code and data together; and such operations AFAIK also are not supported by IDEs, so they can't help you either.

And there's a special wrinkle with Eclipse: it copies files in /java/ as resources, so you will, as I recently and not so recently have, end up with mysterious inconsistencies with tests working on Eclipse, but not in tools correctly following the Maven layout.

It's just so wrong. About 99% wrong.

Black Is The New Productive

This is just such a wonderfully perky headline isn't it; imagine it read by a voice with the intonation of a fifties commercial:

You Thought You Couldn't Be Productive When Feeling Depressed, Just Wait Till You Read This

Imagine somebody depressed sitting in the corner of his own mope, perhaps thinking 'oh no, I can't be productive' (funny already), but then the words of the headline lends a glimmer of hope, and the phrase 'Just Wait' reignites his flame: 'Yes, I can't wait to read This!'. This person obviously has no problem suddenly turning into an optimist. Funny to me, at least. So I may not be clinically depressed.

From my own experience I would theorize that generally, productivity simply drops to a fraction, say, 25%. I am sure you can still be productive, but at a lower level. It might help, though, to take care to remove the kind of obstacles that get you especially hard when you're depressed or unmotivated.

I'd like to maybe write about that. It seems that a big part of being depressed makes it hard to focus. Or, to stay focused once you start thinking. The thoughts wander. So, firstly, keep thoughts from wandering. Or, make it really easy to get back into your work.

Quick feedback is probably a good answer to keep from wandering, and maybe also make it tempting in a gamification sort of way, to keep coming back to just implement one more feature, fix one more bug. E.g. tests must deliver results in seconds. If it takes 20 seconds for setup, thats 20 seconds to wander in.

Allow being consistent, to avoid sliding into long-term thinking. Shouldn't need to be thinking about how to organize code too much.

Need to be learning should be kept to a minimum. For instance, learning a framework. Learning is uphill, and extra steep when depressed.

Need to be debugging is bad, debugging is also mentally straining. Allow only clearly understandable error messages, etcetera.

Things like the above. Actually, kind of makes sense for anybody, not just the depressed. Just being tired is close to being depressed.

Thursday, May 1, 2014

"Question quality is dropping on Stack Overflow"

http://meta.stackoverflow.com/questions/252506/question-quality-is-dropping-on-stack-overflow



There's an interesting discussion going on on the subject of "Question quality is dropping on Stack Overflow". Choice quotes:
"Folks are entering this field not because they have any real drive, love or talent for the craft, [...]""The question quality will continue to decline as long as we continue to reward the bad questions with answers.""The problem is by no means new, btw, as evidenced by this four year old thread. The number of users who are full of it might be, however, [...]""In my view, SO made the jump and became the zero-cost version of Mechanical Turk aeons ago.""How about a probationary period for Questions"
And one answer is the wiser, IMHO: 
This is how gamification works, right?

The rules of Stack Overflow: The Game are as follows.

Your rep is your score.
You want your score to be the highest, because then you WIN. Winning is good!
Downvoting bad questions does nothing to your score. Who cares?
Voting to close bad questions does nothing to your score. Who cares?
Downvoting bad answers, or answers to bad questions, lowers your score. Avoid at all costs!
Posting a quick answer to a trivial question generally nets you an accept, plus maybe a couple drive-by upvotes. Which makes it the best strategy.
The game isn't designed to increase the SNR.

Dislike the game, not the player. The game at Stack Overflow was well enough set up that it could work pretty well for some time. 

Now for my own thoughts...well, sometime later, some sunny day when I get some return for writing here.

Actually, I do have some thoughtful thoughts on this, and I may very well get back with them. This post feels just about the right size and the right single-subject form to end here.


A. Vayner Dead

Just happened upon a piece of information, that makes me rather sad: Aleksey Vayner apparently died about 15 months ago; at what must be a rather young age. Aleksey Vayner was the man behind the 'Impossible is Nothing' video made for a job application, that inadvertently went viral after October 2006; and, later, inspired the name of this blog.

Impossible Is Nothing (video résumé) - Wikipedia, the free encyclopedia

Tuesday, April 29, 2014

Team Heartbeat

I wonder if it shouldn't work pretty well to run a team of developers like a heartbeat network? Perhaps the 25min + break running schedule of the pomodoro technique.

It might solve the problem with being disturbed by notifications, questions, requests. Discipline might or might not be enough; and usually you want to write down your error message or problem right away; to avoid forgetting what it was, and the context.

Of course, this system could be even tighter provided all relevant tools could support it: e.g. support holding notifications and messages that arrive during the pomodoro 25min work interval without annoying the workers out of their focus. On the other hand, with such tool support, or even better, one might not need the centralized heart beat.

Or maybe just turn off Skype's sound. But wait, there are other sounds, e.g. email. So if at least the apps on my computer could be centralized into one notification inbox. Hm, what about web apps? Ah, there seems to be an experimental API for that.

Heartbeat (computing) - Wikipedia, the free encyclopedia
Heartbeat network - Wikipedia, the free encyclopedia
Pomodoro Technique - Wikipedia, the free encyclopedia
How To Use The HTML5 Notification API (Dated? Demo fails.)
http://caniuse.com/#search=notification

Wednesday, April 23, 2014

Big Test Data & JUnit

A good old session of writing-to-clarify coming up.

I have a pretty difficult challenge on my hands. Well, difficult as in non-trivial, non-standard, etcetera. Which is what makes it worth writing about.

I am importing external data into a database. Most of the difficulties are beside this blog post. The subject difficulty is the testing: testing with real data. You can of course do unit tests, and I have so done, that test the details of the formats.

Now, the real data to import is big enough that you don't want to just stick it in a repo. So what can you do instead?

One thing I've done is this: download the data from the source over the internet. This takes some time the first time on a machine, but when the data is downloaded and cached as a file, it's instantly available.

Downloading is also a good test in itself, since the solution will have to automatically check for updated data now and then at a bunch of URLs.

Another thing is to try to cut the data down in size. But that is not so attractive; it's possible to make a mistake; at least in the formats that are not really simple like CSV.

So; moving ahead with the downloading solution, I need to do tests that are certainly not unit tests. JUnit is used, so it'd be nice to make them JUnit tests. This is where the 'non-standard' thing comes in. There seems to be no standard way to mark tests as manual-only in JUnit. The one way I know is to put excludes in maven's surefire. That's kind of clumsy; this should really be part of the actual source code.

So, I cooked up another solution recently, the one posted as 'Spring Plain Java Test'. But this will not be part of the JUnit tests, so as a UI for other developers it's not so good; you'd want them to be able to see these tests as ...tests. And the standard way to do that is to make them JUnit tests so they show up in their GUIs as tests. 

I have no good (practical, standard) solution to all of this.

This is related to a concept of readability, find-ability of projects that have been thinking about a lot, and written some drafts for blog posts, but they are in the cooler for now. Suffice it to say that I think it is a poor bunch of tools, practices and standards that we usually work with and within. 


Tools for the Distributed Team: ETGB Queue

Teamwork is a difficult problem to solve. And I'm not talking about conflicting personalities or whatever; just the bare practicalities of it. For instance, interrupting each other, or not. Waiting on somebody who's forgot to get back to you.

It's very much like multithreading: interrupt(ion)s and context switches often incur a non-trivial cost.

So I often end up thinking about how better adapted tools could help. Imagining tools carefully designed for cooperatively multitasking humans, or perhaps better, 'mostly cooperatively', the nodes are humans, that we're imagining kind of realistically.

And I am thinking about so-called distributed teams.

So, one problem out of many: you've send a question about work ongoing via Skype chat. No reply. You wait. Should you prod your peer again? In 15 minutes? It's hard to miss notifications in Skype, so it's probably not that the message wasn't seen. The coworker might simply be swamped in things to do.

So, that's a common scenario; now how could tools help here? And/or changed practices.

How about ACK support? "I hear you, sorry, later. "

Plus an ETA, or let's make an acronym: Estimated Time When I Can Get Back To You. ETWICGBTY. Estimated time of getting back to you. ETGB?

The awaitee end will of course often get multiple requests. That'd be a Queue; and the tool would of course update the ETGBs for everyone. Requestors should probably only be allowed one spot in the queue each. They should probably only ask for the most important or pressing thing to be done.

The poor overworked awaitee might feel stressed by seeing a row of ETGB promises, but I think that'd be at least one better than getting Skype-pinged every half hour.

Tuesday, April 22, 2014

Spring Plain Java Test

Invented the following as a way to run tests from main() etc without JUnit, which always annoys me with its lack of control (e.g. can't select which tests to run from multiple packages, unless you want to run all or use Suite/SuiteClasses (or, please tell me how!); can't annotate as Ignore to maven, but tell JUnit to run them manually (or tell me how!); can't run tests found with Find References, etc...or maybe one can do that, I'll have to check...), at least when I use it in Eclipse which I use. Took me a while, so I thought it might save some time for somebody, or even myself if I should find myself working in Spring again in the future.

Sorry if the formatting is whack -- I am using blogger.




package jn.spring.test.support;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;

/**
 * If no better solution can be found (I've searched for a couple of hours) to
 * inhibit JUnit tests that are not good as automatic tests, this allows Spring
 * context etc to run from any Java code, e.g. main(). 

 * 

 * 
 * NOTE: maybe configure Maven Surefire excludes could be a way. 

 * 


 * 
 * @author jonasnordin4
 * 
 */
public abstract class PlainJavaSpringTestClassBase {
 
 PlainJavaSpringTestClassBase() {
 }
 
 public void _run() {
  Object tt = this;
  Class testClass = tt.getClass();
  runTestClass(testClass, this);
 }
 
 /**
  * Override to implement a test. 
  */
 public abstract void test();
 
 public static void runTestClass(Class testClass, PlainJavaSpringTestClassBase tt) {
  System.out.println("running...");
  TestContextManager tcm = new TestContextManager(testClass);
  System.out.println("tcm: " + tcm);
  try {
   System.out.println("tcm.prepareTestInstance(tt);...");
   tcm.prepareTestInstance(tt);
   System.out.println("did: tcm.prepareTestInstance(tt);");
   tt.test();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   // e.printStackTrace();
   throw new RuntimeException(e);
  } finally {
     try {
       // this seems to work to clean up. E.g. Spring background threads that keep us from exiting.
       tcm.afterTestClass();
     } catch (Exception e) {

        e.printStackTrace();

     }
     
   }
   
 }
 
 /**
  * No persistence, so set-up runs quickly. 
  * 
  * @author jonasnordin4
  *
  */
 @ContextConfiguration(locations = {
   "classpath*:com/projectname/config/spring-common*.xml",
   // "classpath*:com/projectname/config/spring-cache.xml",
   // "classpath*:com/projectname/config/spring-persistence.xml",
   // "classpath*:com/projectname/config/spring-vfs.xml",
   "classpath*:com/projectname/config/spring-*-test.xml" 
   })
 public abstract static class QuickPlainJavaSpringTest extends
   PlainJavaSpringTestClassBase {
  
 }
 
 @ContextConfiguration(locations = {
   "classpath*:com/projectname/config/spring-common*.xml",
   // "classpath*:com/projectname/config/spring-cache.xml",
    "classpath*:com/projectname/config/spring-persistence.xml",
   // "classpath*:com/projectname/config/spring-vfs.xml",
   "classpath*:com/projectname/config/spring-*-test.xml" 
   })
 public abstract static class PersistencePlainJavaSpringTestClassBase extends
   PlainJavaSpringTestClassBase {
  
  
 }
 
 /**
  * See if this technique works. It seems to work well. 
  * 
  * @author jonasnordin4
  *
  */
 public static class PlainJavaMetaTest {
  
  /**
   * See if '@ContextConfiguration' is inherited (it is). 

   * 

   * 
   * @author jonasnordin4
   *
   */
  public static class TheTestClass extends QuickPlainJavaSpringTest {
   @Override
   public void test() {
    
   }
  }
  
  public void run() {
   final TheTestClass it = new TheTestClass();
   it._run();
  }
  
  public static void main(String...args) {
   new PlainJavaMetaTest().run();
   PersistencePlainJavaSpringTestClassBase p = new PersistencePlainJavaSpringTestClassBase() {
    public void test() {
     
    };
   };
   p._run();
   // System.exit(0); // needed, or some Spring thread lives on. No, see tcm.afterTestClass(); above.
  }
  
 }
}

Monday, April 21, 2014

Back To Write

Have been off the grid for four days. And I haven't worked with the computer, but rather been doing manual, rural work; working the body, resting the mind. Pretty great, I do feel rested.

And I think I now know how to write a few blog posts here: in a non-reactive, simple style. And only write with one fundamental subject in mind; until it achieves some kind of closure: motivation.

(It says something about my vocabulary that I used the words 'reactive' and 'closure', doesn't it.)