SQLClass.java
/***************************************************************************
Copyright 2012 Emily Estes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/
package net.metanotion.sqlc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.metanotion.functor.Block;
import net.metanotion.util.Dispatcher;
import net.metanotion.util.Message;
public final class SQLClass implements Block<Iterable<Object>,Object>, Dispatcher<Object, Map.Entry<String,Iterable<Object>>> {
private final String name;
private final boolean isPublic;
private final Map<String,SQLMethod> methods;
public SQLClass(String name, boolean isPublic, Map<String,SQLMethod> methods) {
this.name = name;
this.isPublic = isPublic;
this.methods = methods;
}
public boolean isPublic() { return isPublic; }
public String getName() { return name; }
public SQLMethod[] getMethods() {
final ArrayList<SQLMethod> list = new ArrayList<SQLMethod>();
for(Map.Entry<String,SQLMethod> m: methods.entrySet()) {
list.add(m.getValue());
}
return list.toArray(new SQLMethod[list.size()]);
}
@Override public Object eval(Iterable<Object> params) throws Exception {
final ArrayList<Object> list = new ArrayList<>();
for(final Object o: params) { list.add(o); }
final SQLMethod m = methods.get(list.get(0).toString());
return m.eval(list.subList(1, list.size()));
}
private static final class M implements Message<Object> {
private final SQLMethod m;
private final Iterable<Object> params;
public M(final SQLMethod m, final Iterable<Object> params) {
this.m = m;
this.params = params;
}
@Override public Object call(final Object o) {
try {
return m.eval(params);
} catch (final Exception e) { throw new RuntimeException(e); }
}
@Override public Class<Object> receiverType() { return Object.class; }
}
public Map<String,Iterable<String>> getMethodMap() {
final HashMap<String,Iterable<String>> map = new HashMap<String,Iterable<String>>();
for(final Map.Entry<String,SQLMethod> method: methods.entrySet()) {
final ArrayList<String> params = new ArrayList<String>();
for(String p: method.getValue().pList) { params.add(p); }
map.put(method.getKey(),params);
}
return map;
}
@Override public Message<Object> dispatch(final Map.Entry<String,Iterable<Object>> data) {
final Iterable<Object> v = data.getValue();
final SQLMethod m = methods.get(data.getKey());
return new M(m, v);
}
}