How can I provide a pseudo file system for r.js? - java

Ok, so r.js can run on Rhino. Which is great.
To do the stuff it needs to do.
On rhino it basically uses java.io.File, java.io.FileOutputStream and java.io.FileInputStream to achieve the filesystem modifications that it needs to do.
(Background: I am working on delivering a better development experience for Maven based Java/Javascript developers. Being Maven, there is the power of convention and the power of being opinionated. You can see the progress at jszip.org.)
So what I want to do is have the on-disk structure appear by magic as a virtual file system.
So on disk we will have a structure like so:
/
/module1/src/main/js/controllers/controller.js
/module2/src/main/js/models/model.js
/module3/src/main/js/views/view.js
/webapp/src/build/js/profile.js
/webapp/src/main/js/main.js
/webapp/src/main/webapp/index.html
The /webapp/src/build/js/profile.js should look something like this:
({
appDir: "src",
baseUrl:".",
dir: "target",
optimize: "closure",
modules:[
{
name:"main"
}
]
})
Such that
when r.js asks for new File("src/main.js") I will actually give it new File("/webapp/src/main/js/main.js")
when it asks for new File("profile.js") I will give it new File("/webapp/src/build/js/profile.js")
when it asks for new File("controllers/controller.js") I will give it new File("/module1/src/main/js/controllers/controller.js")
when it asks for new File("target") I will give it new File("/webapp/target/webapp-1.0-SNAPSHOT").
I have no issue writing the three mock classes required, i.e. the ones to use in place of java.io.File, java.io.FileInputStream and java.io.FileOutputStream,
Some questions such as this have answers that point to things like ClassShutter, which I can see I could use like this:
context.setClassShutter(new ClassShutter() {
public boolean visibleToScripts(String fullClassName) {
if (File.class.getName().equals(fullClassName)) return false;
if (FileOutputStream.class.getName().equals(fullClassName)) return false;
if (FileInputStream.class.getName().equals(fullClassName)) return false;
return true;
}
});
To hide the original implementations.
The problem is then getting Rhino to resolve the sandboxed equivalents... I keep on getting
TypeError: [JavaPackage java.io.File] is not a function, it is object.
Even if I prefix the call with a prior execution of java.io.File = org.jszip.rhino.SandboxFile map my sandboxed implementation over the now missing java.io.File
I could even consider using search and replace on the loaded r.js file just prior to compiling it... but I feel there must be a better way.
Does anyone have any hints?

Ok, after much experimentation, this seems to be the way to do this:
Scriptable scope = context.newObject(global);
scope.setPrototype(global);
scope.setParentScope(null);
NativeJavaTopPackage $packages = (NativeJavaTopPackage) global.get("Packages");
NativeJavaPackage $java = (NativeJavaPackage) $packages.get("java");
NativeJavaPackage $java_io = (NativeJavaPackage) $java.get("io");
ProxyNativeJavaPackage proxy$java = new ProxyNativeJavaPackage($java);
ProxyNativeJavaPackage proxy$java_io = new ProxyNativeJavaPackage($java_io);
proxy$java_io.put("File", scope, get(scope, "Packages." + PseudoFile.class.getName()));
proxy$java_io.put("FileInputStream", scope,
get(scope, "Packages." + PseudoFileInputStream.class.getName()));
proxy$java_io.put("FileOutputStream", scope,
get(scope, "Packages." + PseudoFileOutputStream.class.getName()));
proxy$java.put("io", scope, proxy$java_io);
scope.put("java", scope, proxy$java);
There is a helper method:
private static Object get(Scriptable scope, String name) {
Scriptable cur = scope;
for (String part : StringUtils.split(name, ".")) {
Object next = cur.get(part, scope);
if (next instanceof Scriptable) {
cur = (Scriptable) next;
} else {
return null;
}
}
return cur;
}
And where ProxyNativeJavaPackage is something like
public class ProxyNativeJavaPackage extends ScriptableObject implements Serializable {
static final long serialVersionUID = 1L;
protected final NativeJavaPackage delegate;
private final Map<String, Object> mutations = new HashMap<String, Object>();
public ProxyNativeJavaPackage(NativeJavaPackage delegate) {
delegate.getClass();
this.delegate = delegate;
}
#Override
public String getClassName() {
return delegate.getClassName();
}
#Override
public boolean has(String id, Scriptable start) {
return mutations.containsKey(id) ? mutations.get(id) != null : delegate.has(id, start);
}
#Override
public boolean has(int index, Scriptable start) {
return delegate.has(index, start);
}
#Override
public void put(String id, Scriptable start, Object value) {
mutations.put(id, value);
}
#Override
public void put(int index, Scriptable start, Object value) {
delegate.put(index, start, value);
}
#Override
public Object get(String id, Scriptable start) {
if (mutations.containsKey(id)) {
return mutations.get(id);
}
return delegate.get(id, start);
}
#Override
public Object get(int index, Scriptable start) {
return delegate.get(index, start);
}
#Override
public Object getDefaultValue(Class<?> ignored) {
return toString();
}
#Override
public String toString() {
return delegate.toString();
}
#Override
public boolean equals(Object obj) {
if (obj instanceof ProxyNativeJavaPackage) {
ProxyNativeJavaPackage that = (ProxyNativeJavaPackage) obj;
return delegate.equals(that.delegate) && mutations.equals(that.mutations);
}
return false;
}
#Override
public int hashCode() {
return delegate.hashCode();
}
}
That still leaves the original classes at Packages.java.io.File etc, but for the r.js requirement this is sufficient, and it should be possible for others to extend this trick to the general case.

Related

Which pattern or method to use when calling a regex check method in multiple if statements?

I created a factory pattern in my class.
In this class I injected classes which implements Command interface based on incoming String parameter.
Factory class
#Component
#RequiredArgsConstructor
public class CommandFactory {
private final ACommand aCommand;
private final BCommand bCommand;
private final CCommand cCommand;
private final DCommand dCommand;
private final ECommand eCommand;
private final FCommand fCommand;
public Command createCommand(String content) {
if (aCommand.isMatching(content)) {
return aCommand;
} else if (bCommand.isMatching(content)) {
return bCommand;
} else if (cCommand.isMatching(content)) {
return cCommand;
} else if (dCommand.isMatching(content)) {
return dCommand;
} else if (eCommand.isMatching(content)) {
return eCommand;
} else if (fCommand.isMatching(content)) {
return fCommand;
} else {
return null;
}
}
In isMatching() method there are different regex'es and I try to figure out how this incoming String should be processed.
I am looking for a cleaner way to get rid of these sequential if statements. Because whenever I create a new class into this factory I add another if statement.
Maybe Stream can help?
Stream<Command> stream = Stream.of(aCommand, bCommand, cCommand ...);
return stream.filter(x -> x.isMatching(content)).findFirst().orElse(null);
Now every time you add a new class, you just add a new object to the first line.
If you want to get rid of the sequential if statements you can use streams (like user Sweeper suggested) or loops and I would also suggest to return and optional which makes null handling clearer for the client.
Here are two suggested options to get rid of if else repetitions one with loops another with streams:
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class CommandPatternExample {
private List<Command> candidates = Arrays.asList(new ACommand(), new BCommand(), new CCommand());
public Optional<Command> createCommand(String content) {
for(Command command : candidates) {
if(command.isMatching(content)) {
return Optional.of(command);
}
}
return Optional.empty();
}
public Optional<Command> createCommandStream(String content) {
return candidates.stream().filter(c -> c.isMatching(content)).findFirst();
}
}
interface Command<T> {
void execute(T obj);
boolean isMatching(String s);
}
class ACommand implements Command<String> {
#Override
public void execute(String obj) {
}
#Override
public boolean isMatching(String s) {
return "A".equals(s);
}
}
class BCommand implements Command<String> {
#Override
public void execute(String obj) {
}
#Override
public boolean isMatching(String s) {
return "B".equals(s);
}
}
class CCommand implements Command<String> {
#Override
public void execute(String obj) {
}
#Override
public boolean isMatching(String s) {
return "C".equals(s);
}
}
Map might be a good idea. Meaning if you place your command instances into a map as values where your key would be something that you could match against incoming String. Then instead of sequential search with Efficiency O(n) you can get much better performance O(1). This is a short answer.
Besides that There is an open source java library MgntUtils (wriiten by me) that contains some utility called "Self-instantiating factories" Basically it manages and the Factory for you. All you will need to do is to create a class that implements a certain interface and the utility will add it for you into a map based factory. It might be useful to you. Here is the link to an article that explains about the utilities in the library as well as where to get the library (Github and Maven central). In the article look for the paragraph "Lifecycle management (Self-instantiating factories)". Also library comes with a detailed written javadoc and code example for that feature.

How to add a hook to save event for existing DataObject in NetBeans?

I want to make some processing every time when a particular DataObject is saved. If I understand NetBeans IDE API correctly, there is an Savable interface that can be used to implement saving options for custom editors. The problem here is that I do not want to implement my own editor, nor DataObject. I have a MIME type that is edited by a default Gsf editor (the common scripting language api) and has a GsfDataObject (I expect with the DOSavable). I want to keep all that way, just to add a hook, maybe a callback method or something, that would be called every time a save is done upon a given GsfDataObject (and I want a default save action be called, I dont want to override it).
So far I came to this simple solution but it seems ugly (it is more or less inspired by http://wiki.netbeans.org/DevFaqListenForSaveEvents ):
// I have a FileObject fobj
final DataObject dobj = DataObject.find(fobj);
dobj.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(DataObject.PROP_MODIFIED)) {
if (!((Boolean) evt.getOldValue()) & ((Boolean) evt.getNewValue())) {
System.out.println(">>>> here it gets modified");
} else {
System.out.println(">>>> here the data object gets saved");
}
}
}
});
However, this is not called only when the save is done, but also when the file gets modified, but then the modifications are reverted by Ctrl + Z. It only checks whether the data object changes its state from modified to unmodified. Is there a way to hook to a save event only?
P.S.: I tried to call new SJDOSavable(dobj).add(); in the moment when the DataObject gets modified and then to remove it in the other branch. However, the handleSave method does not get called. SJDOSavable class is a simple Savable implemented according to DOSavable from the DataSystems API:
private static final class SJDOSavable extends AbstractSavable implements Icon {
final DataObject obj;
public SJDOSavable(DataObject obj) {
this.obj = obj;
}
#Override
public String findDisplayName() {
return obj.getNodeDelegate().getDisplayName();
}
#Override
protected void handleSave() throws IOException {
System.out.println(">>>>> but this does not get called");
}
#Override
public boolean equals(Object other) {
if (other instanceof SJDOSavable) {
SJDOSavable dos = (SJDOSavable) other;
return obj.equals(dos.obj);
}
return false;
}
#Override
public int hashCode() {
return obj.hashCode();
}
final void remove() {
unregister();
}
final void add() {
register();
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
icon().paintIcon(c, g, x, y);
}
#Override
public int getIconWidth() {
return icon().getIconWidth();
}
#Override
public int getIconHeight() {
return icon().getIconHeight();
}
private Icon icon() {
return ImageUtilities.image2Icon(obj.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16));
}
}
Did you try this ?
http://wiki.netbeans.org/DevFaqListenForSaveEvents
Also if you want to listen to global Save events, it seems you can do that now.
https://netbeans.org/bugzilla/show_bug.cgi?id=140719

Wrap/Proxy Boilerplate from Methods

I'm not a Java specialist and wondering if I could wrap Methods that are only different in their middle to stop having boilerplatecode like this:
public boolean storeAnimals(Cage cage, Collection<Anmial> animals, IConfiguration configuration) {
checkPrerequisite(cage);
String cagePath = cage.getPath();
AnimalStorage animalStore = AnimalStorage.openFile(cage, configuration);
//***/
do_sth_very_special
//***/
animalStore.closeFile();
return true;
}
public Collection<Anmial> getRedAnimals(Cage cage, IConfiguration configuration) {
checkPrerequisite(cage);
String cagePath = cage.getPath();
File animalStore = AnimalStorage.openFile(cage, configuration);
//***/
do_sth_very_special
//***/
animalStore.closeFile();
return result;
}
Since java doesn't present a kind of closure, you could use an interface for it. In this case you could do something like:
public Collection<Anmial> commonMethod(Cage cage, IConfiguration configuration, Runnable runnable) {
checkPrerequisite(cage);
String cagePath = cage.getPath();
File animalStore = AnimalStorage.openFile(cage, configuration);
//***/
runnable.run();
//***/
animalStore.closeFile();
return result;
}
and you method would be something like:
public boolean storeAnimals(Cage cage, Collection<Anmial> animals, IConfiguration configuration) {
commonMethod(cage, animals, configuration, new Runnable() {
public void run() {
System.out.println("something special");
}
});
return true;
}
of course the Runnable interface was taken just to exemplify the idea, you could implement an interface for your needs. If you need that the inner code accesses some variables defined outside you can pass it as parameters, and if the outside code needs to access some variables defined inside you could return them from the invocation.
You could define a generic interface like:
public interface Executable<ReturnType, ParameterType> {
ReturnType execute(ParameterType parameter);
}
In case you need more parameters to execute the code, you could build a class containing all needed fields for the code execution. The same could be applied to the result.
This would be the idea to return a list of string:
new Executable<List<String>, Void>() {
public List<String> execute(Void void) {
// something special
return new ArrayList<String>();
}
}
ParameterObject could be used to solve the problem when you need to give more objects to the execution. Suppose you have one Integer and a boolean that needs to be given to the execution, this means you will have a class holding an Integer and a boolean like:
public class MyParameter {
private boolean b;
private Integer i;
public MyParameter(Integer i, boolean b) {
this.b = b;
this.i = i;
}
// getters
}
new Executable<Void, MyParameter>() {
public Void execute(MyParameter params) {
// something special
System.out.println(params.getI());
return null;
}
}

Can overriding be an effective replacement for an if statement in lazy initialization and in general?

I'm trying to mimic the following abstract class, designed to enable only one lazy initialization, without using logic statements. I'm ignoring the synchronization elements necessary for thread safety for simplicity's sake.
abstract class Thunk<T>
{
private boolean initiated = false;
private T value;
public T get()
{
if(!initiated) // not using (value == null)
{
value = compute();
initiated = true;
}
return value;
}
abstract protected T compute();
}
Can an instance of the following abstract class be hacked by a child to initialize the same variable more than once?
abstract class Thunk<T>
{
private T value;
private Computer<T> computer;
public Thunk()
{
computer = new Computer<T>(this);
}
public T get()
{
value = computer.getValue();
return value;
}
abstract protected T compute();
private class Computer<T>
{
private static final String TAG = "Computer";
private Thunk<T> thunk;
private T value;
private Computer<T> computer;
public Computer(Thunk<T> thunk)
{
Log.d(TAG, "constructed");
this.thunk = thunk;
computer = this;
}
public T getValue()
{
Log.d(TAG + ".getValue()", "");
value = computer.computeValue();
return value;
}
protected T computeValue()
{
Log.d(TAG + ".computeValue()", "");
value = thunk.compute();
computer = new DumbComputer<T>(thunk, value);
return value;
}
//this is for maximal encapsulation
private class DumbComputer<T> extends Computer<T>
{
private static final String TAG = "DumbComputer";
private T value;
public DumbComputer(Thunk<T> thunk, T value)
{
super(thunk);
Log.d(TAG + ".contructed()", "booki");
this.value = value;
}
//overriding so that value will be calculated only once.
#Override
protected T computeValue()
{
Log.d(TAG + ".computeValue()", "");
return value;
}
}
}
}
Yes, by overriding the get method.
To fix that you can make the get into a final method. That will prevent overriding and give you singleton-like behaviour.
Note that the code you have written is not thread safe.
You could achieve thread safety by making the method synchronized (don't worry about performance until you know you gave a problem and that the method is the hotspot, because slow correct code is better than fast incorrect code, and the JVM is very good at optimising locks. If you find a specific lock for this class to be excessively hot, you can use a number of tricks to speed it up... but don't worry about that just yet)
Also worth pointing out the resource holder inner class pattern for lazy init (not applicable to your use case as this class need. It be used for only singletons) can be used if you wan the best lazy init of singletons.
update (responding to comment as comments don't support formatting)
Do this:
abstract class Thunk<T>
{
private boolean initiated = false;
private T value;
public synchronized final T get()
{
if(!initiated) // not using (value == null)
{
value = compute();
initiated = true;
}
return value;
}
abstract protected T compute();
}
That is the simplest code that can possibly work. Don't even dream of trying to "improve" that code. It can be improved, but the improvements will differ depending on how the class is being used, and the complexity of the improvement will hide what your code is trying to do. Start with the simplest thing that can work, and go from there.
Keep It Simple Stupid
And don't solve problems you don't have yet
The pattern
public final void f() {
...
X x = ...;
g(x);
...
}
abstract protected void g(X x);
is quite usefull in contractual programming:
to impose a behaviour (body of f), and
to provide a local context (x).
A behaviour often is realized by holding a state (like your initiated).
So yes, it is fine for lazy evaluation. Though lazy evaluation can be achieved on field level, for instance by the seldom seen jewel Future<>.
Your second example does not work as (probably) intended, as you create a new DumbComputer each time you call Thunk.get. You can achieve your goal as follows (but I do not think it's good design, and I really do not see where the advantage compared to an easier solution shuld be):
abstract class Thunk<T> {
T value;
Computer<T> computer;
protected abstract T doCompute ();
private interface Computer<T> {
Computer getComputer ();
T compute ();
}
public Thunk<T> () {
// initialize computer with a calculating one
computer = new Computer<T> () {
Computer getComputer () {
// return a dumb computer
return new Computer<T> () {
Computer getComputer () { return this; }
T compute () { return value; }
}
}
T compute () { value = doCompute (); return value; }
};
}
public T getValue () {
T v = computer.compute (); computer = computer.getComputer (); return v;
}
}

Applying a custom CharTokenizer in Solr4

I just wrote a custom CharTokenizer, and I want to use it in my Solr server.
In Solr3, I could just extend TokenizerFactory and return my CharTokenizer in the create method, but TokenizerFactory does not exist in Solr4.
So, I was noticed that I should replace TokenizerFactory with TokenFilterFactory, but in this case, I cannot return my custom CharTokenizer, because the parameters don't match.
I also search for some documentation, but looks like there is nothing really useful about that out there.
So, how can I make it works?
Example:
public class MyCustomTokenizer extends CharTokenizer {
char anotherSpace = 24;
public MyCustomTokenizer(Version matchVersion, Reader in) {
super(matchVersion, in);
}
protected boolean isTokenChar(int c) {
return !Character.isWhitespace(c) && isToken((char) c);
}
private boolean isToken(char c) {
if (c == anotherSpace || c == ',') {
return false;
}
return true;
}
}
public class MyCustomTokenizerFactory extends TokenFilterFactory {
public void init(Map<String, String> args) {
super.init(args);
assureMatchVersion();
}
#Override
public TokenStream create(TokenStream input) {
// sh*t happens here
return new MyCustomTokenizer(luceneMatchVersion, input);
}
}
Thanks in advance.
The best way to check for implementation is looking the Source code of an existing Tokenizer in Lucene.
Example :-
WhitespaceTokenizer
WhitespaceTokenizerFactory

Categories