repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
rhmoller/embrace
examples/src/main/java/com/giddyplanet/embrace/examples/client/batandball/BouncingBall.java
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Window getWindow() /*-{ // return $wnd; // }-*/;
import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.webapis.*; import com.google.gwt.core.client.GWT; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; import static com.giddyplanet.embrace.examples.client.Examples.getWindow;
package com.giddyplanet.embrace.examples.client.batandball; public class BouncingBall implements Example { private Document doc; private HTMLCanvasElement canvas; private float ballX = 100; private float ballY = 150; private float ballDx = 3; private float ballDy = 2; private Window win; private CanvasRenderingContext2D ctx; @Override public String getId() { return "batandball"; } @Override public String getTitle() { return "animation with requestAnimationFrame()"; } @Override public HTMLElement setup() {
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Window getWindow() /*-{ // return $wnd; // }-*/; // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/batandball/BouncingBall.java import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.webapis.*; import com.google.gwt.core.client.GWT; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; import static com.giddyplanet.embrace.examples.client.Examples.getWindow; package com.giddyplanet.embrace.examples.client.batandball; public class BouncingBall implements Example { private Document doc; private HTMLCanvasElement canvas; private float ballX = 100; private float ballY = 150; private float ballDx = 3; private float ballDy = 2; private Window win; private CanvasRenderingContext2D ctx; @Override public String getId() { return "batandball"; } @Override public String getTitle() { return "animation with requestAnimationFrame()"; } @Override public HTMLElement setup() {
doc = getDocument();
rhmoller/embrace
examples/src/main/java/com/giddyplanet/embrace/examples/client/batandball/BouncingBall.java
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Window getWindow() /*-{ // return $wnd; // }-*/;
import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.webapis.*; import com.google.gwt.core.client.GWT; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; import static com.giddyplanet.embrace.examples.client.Examples.getWindow;
package com.giddyplanet.embrace.examples.client.batandball; public class BouncingBall implements Example { private Document doc; private HTMLCanvasElement canvas; private float ballX = 100; private float ballY = 150; private float ballDx = 3; private float ballDy = 2; private Window win; private CanvasRenderingContext2D ctx; @Override public String getId() { return "batandball"; } @Override public String getTitle() { return "animation with requestAnimationFrame()"; } @Override public HTMLElement setup() { doc = getDocument();
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Window getWindow() /*-{ // return $wnd; // }-*/; // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/batandball/BouncingBall.java import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.webapis.*; import com.google.gwt.core.client.GWT; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; import static com.giddyplanet.embrace.examples.client.Examples.getWindow; package com.giddyplanet.embrace.examples.client.batandball; public class BouncingBall implements Example { private Document doc; private HTMLCanvasElement canvas; private float ballX = 100; private float ballY = 150; private float ballDx = 3; private float ballDy = 2; private Window win; private CanvasRenderingContext2D ctx; @Override public String getId() { return "batandball"; } @Override public String getTitle() { return "animation with requestAnimationFrame()"; } @Override public HTMLElement setup() { doc = getDocument();
win = getWindow();
rhmoller/embrace
examples/src/main/java/com/giddyplanet/embrace/examples/client/observable/ObservableExample.java
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/util/function/UnaryVoidFunction.java // @JsFunction // public interface UnaryVoidFunction<T> { // void apply(T arg); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/;
import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.examples.client.util.function.UnaryVoidFunction; import com.giddyplanet.embrace.webapis.*; import static com.giddyplanet.embrace.examples.client.Examples.getDocument;
package com.giddyplanet.embrace.examples.client.observable; public class ObservableExample implements Example { @Override public String getId() { return "observable"; } @Override public String getTitle() { return "Object.observe (only supported by chrome)"; } @Override public HTMLElement setup() {
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/util/function/UnaryVoidFunction.java // @JsFunction // public interface UnaryVoidFunction<T> { // void apply(T arg); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/observable/ObservableExample.java import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.examples.client.util.function.UnaryVoidFunction; import com.giddyplanet.embrace.webapis.*; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; package com.giddyplanet.embrace.examples.client.observable; public class ObservableExample implements Example { @Override public String getId() { return "observable"; } @Override public String getTitle() { return "Object.observe (only supported by chrome)"; } @Override public HTMLElement setup() {
Document document = getDocument();
rhmoller/embrace
examples/src/main/java/com/giddyplanet/embrace/examples/client/observable/ObservableExample.java
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/util/function/UnaryVoidFunction.java // @JsFunction // public interface UnaryVoidFunction<T> { // void apply(T arg); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/;
import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.examples.client.util.function.UnaryVoidFunction; import com.giddyplanet.embrace.webapis.*; import static com.giddyplanet.embrace.examples.client.Examples.getDocument;
package com.giddyplanet.embrace.examples.client.observable; public class ObservableExample implements Example { @Override public String getId() { return "observable"; } @Override public String getTitle() { return "Object.observe (only supported by chrome)"; } @Override public HTMLElement setup() { Document document = getDocument(); HTMLDivElement div = (HTMLDivElement) document.createElement("div"); Model model = new Model(); model.x = 1; HTMLButtonElement button = (HTMLButtonElement) document.createElement("button"); button.innerHTML = "Bump"; button.addEventListener("click", e -> model.x++); div.appendChild(button); HTMLDivElement status = (HTMLDivElement) document.createElement("div"); status.innerHTML = "Initial value " + model.x;
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/util/function/UnaryVoidFunction.java // @JsFunction // public interface UnaryVoidFunction<T> { // void apply(T arg); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/observable/ObservableExample.java import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.examples.client.util.function.UnaryVoidFunction; import com.giddyplanet.embrace.webapis.*; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; package com.giddyplanet.embrace.examples.client.observable; public class ObservableExample implements Example { @Override public String getId() { return "observable"; } @Override public String getTitle() { return "Object.observe (only supported by chrome)"; } @Override public HTMLElement setup() { Document document = getDocument(); HTMLDivElement div = (HTMLDivElement) document.createElement("div"); Model model = new Model(); model.x = 1; HTMLButtonElement button = (HTMLButtonElement) document.createElement("button"); button.innerHTML = "Bump"; button.addEventListener("click", e -> model.x++); div.appendChild(button); HTMLDivElement status = (HTMLDivElement) document.createElement("div"); status.innerHTML = "Initial value " + model.x;
JsObject.observe(model, (UnaryVoidFunction<String[]>) changes -> status.innerHTML = "Changed to " + model.x, new String[] {"update"});
rhmoller/embrace
tools/src/main/java/com/giddyplanet/embrace/tools/webidl2java/ModelConverter.java
// Path: tools/src/main/java/com/giddyplanet/embrace/tools/model/webidl/Enumeration.java // public class Enumeration implements Definition { // private List<String> values = new ArrayList<>(); // private String name; // // public Enumeration(String name) { // this.name = name; // } // // public void addValue(String text) { // values.add(text); // } // // public String getName() { // return name; // } // // public List<String> getValues() { // return values; // } // }
import com.giddyplanet.embrace.tools.model.java.*; import com.giddyplanet.embrace.tools.model.webidl.*; import com.giddyplanet.embrace.tools.model.webidl.Enumeration; import java.util.*;
} for (Constant constant : idef.getConstants()) { JConstant jc = new JConstant(new JTypeRef(fixType(constant.getType(), true)), constant.getName(), constant.getValue()); java.addConstant(jc); } for (Attribute attribute : idef.getAttributes()) { JField field = new JField(fixName(attribute.getName()), new JTypeRef(fixType(attribute.getType(), false))); java.addField(field); } convertConstructors(java, idef.getConstructors()); convertOperations(java, idef.getOperations()); javaModel.put(name, java); } else if (definition instanceof Callback) { // todo: test for callback String name = ((Callback) definition).getName(); JClass java = new JClass(name); java.setAbstraction(AbstractionLevel.INTERFACE); java.setFunctional(true); JMethod method = new JMethod("execute"); method.setReturnType(new JTypeRef(fixType(((Callback) definition).getReturnType(), true))); List<Argument> arguments = ((Callback) definition).getArguments(); convertArguments(method, arguments); java.addMethod(method); javaModel.put(name, java);
// Path: tools/src/main/java/com/giddyplanet/embrace/tools/model/webidl/Enumeration.java // public class Enumeration implements Definition { // private List<String> values = new ArrayList<>(); // private String name; // // public Enumeration(String name) { // this.name = name; // } // // public void addValue(String text) { // values.add(text); // } // // public String getName() { // return name; // } // // public List<String> getValues() { // return values; // } // } // Path: tools/src/main/java/com/giddyplanet/embrace/tools/webidl2java/ModelConverter.java import com.giddyplanet.embrace.tools.model.java.*; import com.giddyplanet.embrace.tools.model.webidl.*; import com.giddyplanet.embrace.tools.model.webidl.Enumeration; import java.util.*; } for (Constant constant : idef.getConstants()) { JConstant jc = new JConstant(new JTypeRef(fixType(constant.getType(), true)), constant.getName(), constant.getValue()); java.addConstant(jc); } for (Attribute attribute : idef.getAttributes()) { JField field = new JField(fixName(attribute.getName()), new JTypeRef(fixType(attribute.getType(), false))); java.addField(field); } convertConstructors(java, idef.getConstructors()); convertOperations(java, idef.getOperations()); javaModel.put(name, java); } else if (definition instanceof Callback) { // todo: test for callback String name = ((Callback) definition).getName(); JClass java = new JClass(name); java.setAbstraction(AbstractionLevel.INTERFACE); java.setFunctional(true); JMethod method = new JMethod("execute"); method.setReturnType(new JTypeRef(fixType(((Callback) definition).getReturnType(), true))); List<Argument> arguments = ((Callback) definition).getArguments(); convertArguments(method, arguments); java.addMethod(method); javaModel.put(name, java);
} else if (definition instanceof Enumeration) {
rhmoller/embrace
examples/src/main/java/com/giddyplanet/embrace/examples/client/canvas/CanvasExample.java
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public class Examples implements EntryPoint { // private Map<String, Example> examples; // private Document doc; // // // @Override // public void onModuleLoad() { // examples = new HashMap<>(); // addExample(new HelloExample()); // addExample(new EventExample()); // addExample(new CanvasExample()); // addExample(new CanvasTypedArrayExample()); // addExample(new TimerExample()); // addExample(new WebSocketExample()); // addExample(new ObservableExample()); // addExample(new BouncingBall()); // // buildMenu(); // } // // private void buildMenu() { // doc = getDocument(); // // HTMLElement ul = (HTMLElement) doc.createElement("ul"); // for (Map.Entry<String, Example> entry : examples.entrySet()) { // Example example1 = entry.getValue(); // // Element li = doc.createElement("li"); // HTMLAnchorElement a = (HTMLAnchorElement) doc.createElement("a"); // a.href = "#"; // a.innerHTML = example1.getTitle(); // a.setAttribute("data-example", example1.getId()); // // li.appendChild(a); // ul.appendChild(li); // } // ul.style.setProperty("float", "left"); // ul.style.setProperty("margin-right", "2em"); // doc.body.appendChild(ul); // // Element container = doc.createElement("div"); // doc.body.appendChild(container); // // ul.addEventListener("click", (e) -> { // HTMLElement target = (HTMLElement) e.target; // String id = target.getAttribute("data-example"); // Example example = examples.get(id); // // Element old = container.firstElementChild; // if (old != null) { // old.remove(); // } // // HTMLElement root = example.setup(); // container.appendChild(root); // getWindow().setTimeout((UnaryVoidFunction) (t) -> { // example.start(); // }, 0); // }, false); // } // // private void addExample(Example example) { // examples.put(example.getId(), example); // } // // public static native Document getDocument() /*-{ // return $doc; // }-*/; // // public static native Window getWindow() /*-{ // return $wnd; // }-*/; // // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/;
import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.examples.client.Examples; import com.giddyplanet.embrace.webapis.*; import static com.giddyplanet.embrace.examples.client.Examples.getDocument;
package com.giddyplanet.embrace.examples.client.canvas; public class CanvasExample implements Example { @Override public String getId() { return "canvas"; } @Override public String getTitle() { return "2D rendering with canvas"; } @Override public HTMLElement setup() {
// Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Example.java // public interface Example { // // String getId(); // // String getTitle(); // // HTMLElement setup(); // // void start(); // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public class Examples implements EntryPoint { // private Map<String, Example> examples; // private Document doc; // // // @Override // public void onModuleLoad() { // examples = new HashMap<>(); // addExample(new HelloExample()); // addExample(new EventExample()); // addExample(new CanvasExample()); // addExample(new CanvasTypedArrayExample()); // addExample(new TimerExample()); // addExample(new WebSocketExample()); // addExample(new ObservableExample()); // addExample(new BouncingBall()); // // buildMenu(); // } // // private void buildMenu() { // doc = getDocument(); // // HTMLElement ul = (HTMLElement) doc.createElement("ul"); // for (Map.Entry<String, Example> entry : examples.entrySet()) { // Example example1 = entry.getValue(); // // Element li = doc.createElement("li"); // HTMLAnchorElement a = (HTMLAnchorElement) doc.createElement("a"); // a.href = "#"; // a.innerHTML = example1.getTitle(); // a.setAttribute("data-example", example1.getId()); // // li.appendChild(a); // ul.appendChild(li); // } // ul.style.setProperty("float", "left"); // ul.style.setProperty("margin-right", "2em"); // doc.body.appendChild(ul); // // Element container = doc.createElement("div"); // doc.body.appendChild(container); // // ul.addEventListener("click", (e) -> { // HTMLElement target = (HTMLElement) e.target; // String id = target.getAttribute("data-example"); // Example example = examples.get(id); // // Element old = container.firstElementChild; // if (old != null) { // old.remove(); // } // // HTMLElement root = example.setup(); // container.appendChild(root); // getWindow().setTimeout((UnaryVoidFunction) (t) -> { // example.start(); // }, 0); // }, false); // } // // private void addExample(Example example) { // examples.put(example.getId(), example); // } // // public static native Document getDocument() /*-{ // return $doc; // }-*/; // // public static native Window getWindow() /*-{ // return $wnd; // }-*/; // // } // // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/Examples.java // public static native Document getDocument() /*-{ // return $doc; // }-*/; // Path: examples/src/main/java/com/giddyplanet/embrace/examples/client/canvas/CanvasExample.java import com.giddyplanet.embrace.examples.client.Example; import com.giddyplanet.embrace.examples.client.Examples; import com.giddyplanet.embrace.webapis.*; import static com.giddyplanet.embrace.examples.client.Examples.getDocument; package com.giddyplanet.embrace.examples.client.canvas; public class CanvasExample implements Example { @Override public String getId() { return "canvas"; } @Override public String getTitle() { return "2D rendering with canvas"; } @Override public HTMLElement setup() {
Document document = getDocument();
eyp/serfj
src/test/java/net/sf/serfj/RestServletTest.java
// Path: src/main/java/net/sf/serfj/serializers/Base64Serializer.java // public class Base64Serializer implements ObjectSerializer { // // private static final Logger LOGGER = LoggerFactory.getLogger(Base64Serializer.class); // // /** // * Serialize object to an encoded base64 string. // */ // public String serialize(Object object) { // ObjectOutputStream oos = null; // ByteArrayOutputStream bos = null; // try { // bos = new ByteArrayOutputStream(); // oos = new ObjectOutputStream(bos); // oos.writeObject(object); // return new String(Base64.encodeBase64(bos.toByteArray())); // } catch (IOException e) { // LOGGER.error("Can't serialize data on Base 64", e); // throw new IllegalArgumentException(e); // } catch (Exception e) { // LOGGER.error("Can't serialize data on Base 64", e); // throw new IllegalArgumentException(e); // } finally { // try { // if (bos != null) { // bos.close(); // } // } catch (Exception e) { // LOGGER.error("Can't close ObjetInputStream used for serialize data on Base 64", e); // } // } // } // // /** // * Deserialze base 64 encoded string data to Object. // */ // public Object deserialize(String data) { // if ((data == null) || (data.length() == 0)) { // return null; // } // ObjectInputStream ois = null; // ByteArrayInputStream bis = null; // try { // bis = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes())); // ois = new ObjectInputStream(bis); // return ois.readObject(); // } catch (ClassNotFoundException e) { // LOGGER.error("Can't deserialize data from Base64", e); // throw new IllegalArgumentException(e); // } catch (IOException e) { // LOGGER.error("Can't deserialize data from Base64", e); // throw new IllegalArgumentException(e); // } catch (Exception e) { // LOGGER.error("Can't deserialize data from Base64", e); // throw new IllegalArgumentException(e); // } finally { // try { // if (ois != null) { // ois.close(); // } // } catch (Exception e) { // LOGGER.error("Can't close ObjetInputStream used for deserialize data from Base64", e); // } // } // } // // /** // * @see net.sf.serfj.serializers.Serializer#getContentType() // */ // public String getContentType() { // return "application/octect-stream"; // } // // /** // * Returns 'base64' as content-transfer-encoding. // */ // public String getContentTransferEncoding() { // return "base64"; // } // }
import com.meterware.servletunit.ServletRunner; import com.meterware.servletunit.ServletUnitClient; import java.io.ByteArrayInputStream; import java.io.InputStream; import junit.framework.TestCase; import net.sf.serfj.serializers.Base64Serializer; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.HttpNotFoundException; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse;
WebResponse response = sc.getResponse(request); assertNotNull("No response received", response); assertEquals("content type", contentType, response.getContentType()); } catch (HttpNotFoundException e) { assertPage(expectedPage, e); } catch (StringIndexOutOfBoundsException e) { fail("Page not found"); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e); fail(e.getLocalizedMessage()); } } /** * Tests a GET request. Receives an URL to test, and the page that * controller must respond. * * @param requestedUrl * - URL to test. * @param expectedPage * - Expected response from the requested URL. */ private void testGet64(String requestedUrl, String expectedContent, String contentType) { ServletUnitClient sc = sr.newClient(); try { WebRequest request = new GetMethodWebRequest("http://test.meterware.com/" + requestedUrl); WebResponse response = sc.getResponse(request); assertNotNull("No response received", response); assertEquals("content type", contentType, response.getContentType());
// Path: src/main/java/net/sf/serfj/serializers/Base64Serializer.java // public class Base64Serializer implements ObjectSerializer { // // private static final Logger LOGGER = LoggerFactory.getLogger(Base64Serializer.class); // // /** // * Serialize object to an encoded base64 string. // */ // public String serialize(Object object) { // ObjectOutputStream oos = null; // ByteArrayOutputStream bos = null; // try { // bos = new ByteArrayOutputStream(); // oos = new ObjectOutputStream(bos); // oos.writeObject(object); // return new String(Base64.encodeBase64(bos.toByteArray())); // } catch (IOException e) { // LOGGER.error("Can't serialize data on Base 64", e); // throw new IllegalArgumentException(e); // } catch (Exception e) { // LOGGER.error("Can't serialize data on Base 64", e); // throw new IllegalArgumentException(e); // } finally { // try { // if (bos != null) { // bos.close(); // } // } catch (Exception e) { // LOGGER.error("Can't close ObjetInputStream used for serialize data on Base 64", e); // } // } // } // // /** // * Deserialze base 64 encoded string data to Object. // */ // public Object deserialize(String data) { // if ((data == null) || (data.length() == 0)) { // return null; // } // ObjectInputStream ois = null; // ByteArrayInputStream bis = null; // try { // bis = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes())); // ois = new ObjectInputStream(bis); // return ois.readObject(); // } catch (ClassNotFoundException e) { // LOGGER.error("Can't deserialize data from Base64", e); // throw new IllegalArgumentException(e); // } catch (IOException e) { // LOGGER.error("Can't deserialize data from Base64", e); // throw new IllegalArgumentException(e); // } catch (Exception e) { // LOGGER.error("Can't deserialize data from Base64", e); // throw new IllegalArgumentException(e); // } finally { // try { // if (ois != null) { // ois.close(); // } // } catch (Exception e) { // LOGGER.error("Can't close ObjetInputStream used for deserialize data from Base64", e); // } // } // } // // /** // * @see net.sf.serfj.serializers.Serializer#getContentType() // */ // public String getContentType() { // return "application/octect-stream"; // } // // /** // * Returns 'base64' as content-transfer-encoding. // */ // public String getContentTransferEncoding() { // return "base64"; // } // } // Path: src/test/java/net/sf/serfj/RestServletTest.java import com.meterware.servletunit.ServletRunner; import com.meterware.servletunit.ServletUnitClient; import java.io.ByteArrayInputStream; import java.io.InputStream; import junit.framework.TestCase; import net.sf.serfj.serializers.Base64Serializer; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.HttpNotFoundException; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; WebResponse response = sc.getResponse(request); assertNotNull("No response received", response); assertEquals("content type", contentType, response.getContentType()); } catch (HttpNotFoundException e) { assertPage(expectedPage, e); } catch (StringIndexOutOfBoundsException e) { fail("Page not found"); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e); fail(e.getLocalizedMessage()); } } /** * Tests a GET request. Receives an URL to test, and the page that * controller must respond. * * @param requestedUrl * - URL to test. * @param expectedPage * - Expected response from the requested URL. */ private void testGet64(String requestedUrl, String expectedContent, String contentType) { ServletUnitClient sc = sr.newClient(); try { WebRequest request = new GetMethodWebRequest("http://test.meterware.com/" + requestedUrl); WebResponse response = sc.getResponse(request); assertNotNull("No response received", response); assertEquals("content type", contentType, response.getContentType());
Base64Serializer serializer = new Base64Serializer();
eyp/serfj
src/main/java/net/sf/serfj/finders/SerializerFinder.java
// Path: src/main/java/net/sf/serfj/Config.java // public class Config extends SystemConfig { // // /** // * Flag for debug purposes. // */ // protected static final ConfigParam DEBUG = new ConfigParam("debug"); // // /** // * HTTP Encoding. Default is UTF-8 // */ // public static final ConfigParam ENCODING = new ConfigParam("encoding", "UTF-8"); // // /** // * Java main package where the source is located. // */ // public static final ConfigParam MAIN_PACKAGE = new ConfigParam("main.package"); // // /** // * Packages style. // */ // public static final ConfigParam PACKAGES_STYLE = new ConfigParam("packages.style"); // // /** // * Java package where controllers will be located. // */ // public static final ConfigParam ALIAS_CONTROLLERS_PACKAGE = new ConfigParam("alias.controllers.package", "controllers"); // // /** // * Java package where serializers for responses will be located. // */ // public static final ConfigParam ALIAS_SERIALIZERS_PACKAGE = new ConfigParam("alias.serializers.package", "serializers"); // // /** // * Suffix used for controller classes // */ // public static final ConfigParam SUFFIX_CONTROLLER = new ConfigParam("suffix.controllers", "OFF"); // // /** // * Suffix used for serializer classes // */ // public static final ConfigParam SUFFIX_SERIALIZER = new ConfigParam("suffix.serializer", "Serializer"); // // /** // * Directory where the views will be located. // */ // public static final ConfigParam VIEWS_DIRECTORY = new ConfigParam("views.directory", "views"); // // public Config(String filename) throws ConfigFileIOException { // super(filename); // } // }
import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import net.sf.serfj.Config;
/* * Copyright 2010 Eduardo Yáñez Parareda * * 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.sf.serfj.finders; /** * Finds a serializer for a request. It finds a class with the the name * ExtensionResourceNameSerializer in the directory expected depending on the * package style used. Extension could be .xml, .json, .anything, so the finder * will look for JsonResourceNameSerializer, AnythingResourceNameSerializer, * etc...<br/> * <br/> * * There are some default serializers:<br/> * - net.sf.serfj.serializers.JsonSerializer<br/> * - net.sf.serfj.serializers.XmlSerializer<br/> * - net.sf.serfj.serializers.PageSerializer<br/> * <br/> * * that will be used if there aren't any serializers found for a resource. * * @author Eduardo Yáñez */ public class SerializerFinder extends ResourceFinder { protected static final String DEFAULT_SERIALIZERS_PACKAGE = "net.sf.serfj.serializers"; private static final String PAGE_EXTENSION = "page"; private static final String JSON_EXTENSION = "json"; private static final String B64_EXTENSION = "base64"; private static final String XML_EXTENSION = "xml"; private static final String FILE_EXTENSION = "file"; private static Map<String, String> contentType2Extension = new HashMap<String, String>(4); public SerializerFinder(String extension) { super(null, null, (extension == null ? PAGE_EXTENSION : extension), OFF_OPTION, null); this.initExtensionsCache(); }
// Path: src/main/java/net/sf/serfj/Config.java // public class Config extends SystemConfig { // // /** // * Flag for debug purposes. // */ // protected static final ConfigParam DEBUG = new ConfigParam("debug"); // // /** // * HTTP Encoding. Default is UTF-8 // */ // public static final ConfigParam ENCODING = new ConfigParam("encoding", "UTF-8"); // // /** // * Java main package where the source is located. // */ // public static final ConfigParam MAIN_PACKAGE = new ConfigParam("main.package"); // // /** // * Packages style. // */ // public static final ConfigParam PACKAGES_STYLE = new ConfigParam("packages.style"); // // /** // * Java package where controllers will be located. // */ // public static final ConfigParam ALIAS_CONTROLLERS_PACKAGE = new ConfigParam("alias.controllers.package", "controllers"); // // /** // * Java package where serializers for responses will be located. // */ // public static final ConfigParam ALIAS_SERIALIZERS_PACKAGE = new ConfigParam("alias.serializers.package", "serializers"); // // /** // * Suffix used for controller classes // */ // public static final ConfigParam SUFFIX_CONTROLLER = new ConfigParam("suffix.controllers", "OFF"); // // /** // * Suffix used for serializer classes // */ // public static final ConfigParam SUFFIX_SERIALIZER = new ConfigParam("suffix.serializer", "Serializer"); // // /** // * Directory where the views will be located. // */ // public static final ConfigParam VIEWS_DIRECTORY = new ConfigParam("views.directory", "views"); // // public Config(String filename) throws ConfigFileIOException { // super(filename); // } // } // Path: src/main/java/net/sf/serfj/finders/SerializerFinder.java import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import net.sf.serfj.Config; /* * Copyright 2010 Eduardo Yáñez Parareda * * 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.sf.serfj.finders; /** * Finds a serializer for a request. It finds a class with the the name * ExtensionResourceNameSerializer in the directory expected depending on the * package style used. Extension could be .xml, .json, .anything, so the finder * will look for JsonResourceNameSerializer, AnythingResourceNameSerializer, * etc...<br/> * <br/> * * There are some default serializers:<br/> * - net.sf.serfj.serializers.JsonSerializer<br/> * - net.sf.serfj.serializers.XmlSerializer<br/> * - net.sf.serfj.serializers.PageSerializer<br/> * <br/> * * that will be used if there aren't any serializers found for a resource. * * @author Eduardo Yáñez */ public class SerializerFinder extends ResourceFinder { protected static final String DEFAULT_SERIALIZERS_PACKAGE = "net.sf.serfj.serializers"; private static final String PAGE_EXTENSION = "page"; private static final String JSON_EXTENSION = "json"; private static final String B64_EXTENSION = "base64"; private static final String XML_EXTENSION = "xml"; private static final String FILE_EXTENSION = "file"; private static Map<String, String> contentType2Extension = new HashMap<String, String>(4); public SerializerFinder(String extension) { super(null, null, (extension == null ? PAGE_EXTENSION : extension), OFF_OPTION, null); this.initExtensionsCache(); }
public SerializerFinder(Config config, String extension) {
eyp/serfj
src/main/java/net/sf/serfj/ResponseHelper.java
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // // Path: src/main/java/net/sf/serfj/serializers/FileSerializer.java // public class FileSerializer implements Serializer { // private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class); // // /** // * Content type that will be used in the response. // */ // public String getContentType() { // return "application/octet-stream"; // } // // /** // * Write a file to an OuputStream. // * // * @param file File that will be written. // * @param os The target OutputStream. // * @throws IOException if any error happens. // */ // public void sendFile(File file, OutputStream os) throws IOException { // FileInputStream is = null; // BufferedInputStream buf = null;; // try { // is = new FileInputStream(file); // buf = new BufferedInputStream(is); // int readBytes = 0; // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("Writing file..."); // } // while ((readBytes = buf.read()) != -1) { // os.write(readBytes); // } // os.flush(); // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("File written"); // } // } finally { // if (is != null) { // is.close(); // } // if (buf != null) { // buf.close(); // } // } // } // } // // Path: src/main/java/net/sf/serfj/serializers/ObjectSerializer.java // public interface ObjectSerializer extends Serializer { // /** // * Serialize an object in the format that the implementation requires. // * // * @param object // * Object to serialize. // * @return a String with the object serialized. // */ // public String serialize(Object object); // // /** // * Deserialize an object from the format that the implementation requires to // * Java Object. // * // * @param string // * String representation of the object to deserialize. // * @return an Object. // */ // public Object deserialize(String string); // }
import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.annotations.DoNotRenderPage; import net.sf.serfj.config.ConfigFileIOException; import net.sf.serfj.serializers.FileSerializer; import net.sf.serfj.serializers.ObjectSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2010 Eduardo Yáñez Parareda * * 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.sf.serfj; /** * This class allows the developer to render the predefined page for an action, * or to render the page she wants, or serialize an object to JSon, XML, or * whatever as a response. * * @author Eduardo Yáñez */ public class ResponseHelper { private static final Logger LOGGER = LoggerFactory.getLogger(ResponseHelper.class); private ServletContext context; private HttpServletRequest request; private HttpServletResponse response; private UrlInfo urlInfo; private String viewsPath; private String requestedPage; private Object object2Serialize; private Map<String, Object> params; private boolean notRenderPage = false; private File file; private String attachmentFilename; private String contentType; private Config config; /** * Constructor. */ protected ResponseHelper(ServletContext context, HttpServletRequest request, HttpServletResponse response, UrlInfo urlInfo, String viewsPath) { this.context = context; this.request = request; this.response = response; this.urlInfo = urlInfo; this.viewsPath = viewsPath; try { this.config = new Config("/config/serfj.properties");
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // // Path: src/main/java/net/sf/serfj/serializers/FileSerializer.java // public class FileSerializer implements Serializer { // private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class); // // /** // * Content type that will be used in the response. // */ // public String getContentType() { // return "application/octet-stream"; // } // // /** // * Write a file to an OuputStream. // * // * @param file File that will be written. // * @param os The target OutputStream. // * @throws IOException if any error happens. // */ // public void sendFile(File file, OutputStream os) throws IOException { // FileInputStream is = null; // BufferedInputStream buf = null;; // try { // is = new FileInputStream(file); // buf = new BufferedInputStream(is); // int readBytes = 0; // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("Writing file..."); // } // while ((readBytes = buf.read()) != -1) { // os.write(readBytes); // } // os.flush(); // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("File written"); // } // } finally { // if (is != null) { // is.close(); // } // if (buf != null) { // buf.close(); // } // } // } // } // // Path: src/main/java/net/sf/serfj/serializers/ObjectSerializer.java // public interface ObjectSerializer extends Serializer { // /** // * Serialize an object in the format that the implementation requires. // * // * @param object // * Object to serialize. // * @return a String with the object serialized. // */ // public String serialize(Object object); // // /** // * Deserialize an object from the format that the implementation requires to // * Java Object. // * // * @param string // * String representation of the object to deserialize. // * @return an Object. // */ // public Object deserialize(String string); // } // Path: src/main/java/net/sf/serfj/ResponseHelper.java import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.annotations.DoNotRenderPage; import net.sf.serfj.config.ConfigFileIOException; import net.sf.serfj.serializers.FileSerializer; import net.sf.serfj.serializers.ObjectSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2010 Eduardo Yáñez Parareda * * 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.sf.serfj; /** * This class allows the developer to render the predefined page for an action, * or to render the page she wants, or serialize an object to JSon, XML, or * whatever as a response. * * @author Eduardo Yáñez */ public class ResponseHelper { private static final Logger LOGGER = LoggerFactory.getLogger(ResponseHelper.class); private ServletContext context; private HttpServletRequest request; private HttpServletResponse response; private UrlInfo urlInfo; private String viewsPath; private String requestedPage; private Object object2Serialize; private Map<String, Object> params; private boolean notRenderPage = false; private File file; private String attachmentFilename; private String contentType; private Config config; /** * Constructor. */ protected ResponseHelper(ServletContext context, HttpServletRequest request, HttpServletResponse response, UrlInfo urlInfo, String viewsPath) { this.context = context; this.request = request; this.response = response; this.urlInfo = urlInfo; this.viewsPath = viewsPath; try { this.config = new Config("/config/serfj.properties");
} catch (ConfigFileIOException e) {
eyp/serfj
src/main/java/net/sf/serfj/ResponseHelper.java
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // // Path: src/main/java/net/sf/serfj/serializers/FileSerializer.java // public class FileSerializer implements Serializer { // private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class); // // /** // * Content type that will be used in the response. // */ // public String getContentType() { // return "application/octet-stream"; // } // // /** // * Write a file to an OuputStream. // * // * @param file File that will be written. // * @param os The target OutputStream. // * @throws IOException if any error happens. // */ // public void sendFile(File file, OutputStream os) throws IOException { // FileInputStream is = null; // BufferedInputStream buf = null;; // try { // is = new FileInputStream(file); // buf = new BufferedInputStream(is); // int readBytes = 0; // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("Writing file..."); // } // while ((readBytes = buf.read()) != -1) { // os.write(readBytes); // } // os.flush(); // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("File written"); // } // } finally { // if (is != null) { // is.close(); // } // if (buf != null) { // buf.close(); // } // } // } // } // // Path: src/main/java/net/sf/serfj/serializers/ObjectSerializer.java // public interface ObjectSerializer extends Serializer { // /** // * Serialize an object in the format that the implementation requires. // * // * @param object // * Object to serialize. // * @return a String with the object serialized. // */ // public String serialize(Object object); // // /** // * Deserialize an object from the format that the implementation requires to // * Java Object. // * // * @param string // * String representation of the object to deserialize. // * @return an Object. // */ // public Object deserialize(String string); // }
import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.annotations.DoNotRenderPage; import net.sf.serfj.config.ConfigFileIOException; import net.sf.serfj.serializers.FileSerializer; import net.sf.serfj.serializers.ObjectSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
response.setStatus(HttpURLConnection.HTTP_NO_CONTENT); response.getWriter().flush(); } else { if (requestedPage == null) { requestedPage = this.getPage(); } this.forward(); } } else { if (this.object2Serialize == null) { if (this.file != null) { this.sendFile(); } else { LOGGER.warn("There is not object to serialize, returning no content response code: {}", HttpURLConnection.HTTP_NO_CONTENT); response.setCharacterEncoding(this.config.getString(Config.ENCODING)); response.setStatus(HttpURLConnection.HTTP_NO_CONTENT); response.getWriter().flush(); } } else { this.serialize(); } } } } protected void serialize() throws IOException { try { LOGGER.debug("Serializing using {}", urlInfo.getSerializer()); Class<?> clazz = Class.forName(urlInfo.getSerializer()); LOGGER.debug("Creating a new instance of {}", urlInfo.getSerializer());
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // // Path: src/main/java/net/sf/serfj/serializers/FileSerializer.java // public class FileSerializer implements Serializer { // private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class); // // /** // * Content type that will be used in the response. // */ // public String getContentType() { // return "application/octet-stream"; // } // // /** // * Write a file to an OuputStream. // * // * @param file File that will be written. // * @param os The target OutputStream. // * @throws IOException if any error happens. // */ // public void sendFile(File file, OutputStream os) throws IOException { // FileInputStream is = null; // BufferedInputStream buf = null;; // try { // is = new FileInputStream(file); // buf = new BufferedInputStream(is); // int readBytes = 0; // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("Writing file..."); // } // while ((readBytes = buf.read()) != -1) { // os.write(readBytes); // } // os.flush(); // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("File written"); // } // } finally { // if (is != null) { // is.close(); // } // if (buf != null) { // buf.close(); // } // } // } // } // // Path: src/main/java/net/sf/serfj/serializers/ObjectSerializer.java // public interface ObjectSerializer extends Serializer { // /** // * Serialize an object in the format that the implementation requires. // * // * @param object // * Object to serialize. // * @return a String with the object serialized. // */ // public String serialize(Object object); // // /** // * Deserialize an object from the format that the implementation requires to // * Java Object. // * // * @param string // * String representation of the object to deserialize. // * @return an Object. // */ // public Object deserialize(String string); // } // Path: src/main/java/net/sf/serfj/ResponseHelper.java import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.annotations.DoNotRenderPage; import net.sf.serfj.config.ConfigFileIOException; import net.sf.serfj.serializers.FileSerializer; import net.sf.serfj.serializers.ObjectSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; response.setStatus(HttpURLConnection.HTTP_NO_CONTENT); response.getWriter().flush(); } else { if (requestedPage == null) { requestedPage = this.getPage(); } this.forward(); } } else { if (this.object2Serialize == null) { if (this.file != null) { this.sendFile(); } else { LOGGER.warn("There is not object to serialize, returning no content response code: {}", HttpURLConnection.HTTP_NO_CONTENT); response.setCharacterEncoding(this.config.getString(Config.ENCODING)); response.setStatus(HttpURLConnection.HTTP_NO_CONTENT); response.getWriter().flush(); } } else { this.serialize(); } } } } protected void serialize() throws IOException { try { LOGGER.debug("Serializing using {}", urlInfo.getSerializer()); Class<?> clazz = Class.forName(urlInfo.getSerializer()); LOGGER.debug("Creating a new instance of {}", urlInfo.getSerializer());
ObjectSerializer serializer = (ObjectSerializer) clazz.newInstance();
eyp/serfj
src/main/java/net/sf/serfj/ResponseHelper.java
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // // Path: src/main/java/net/sf/serfj/serializers/FileSerializer.java // public class FileSerializer implements Serializer { // private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class); // // /** // * Content type that will be used in the response. // */ // public String getContentType() { // return "application/octet-stream"; // } // // /** // * Write a file to an OuputStream. // * // * @param file File that will be written. // * @param os The target OutputStream. // * @throws IOException if any error happens. // */ // public void sendFile(File file, OutputStream os) throws IOException { // FileInputStream is = null; // BufferedInputStream buf = null;; // try { // is = new FileInputStream(file); // buf = new BufferedInputStream(is); // int readBytes = 0; // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("Writing file..."); // } // while ((readBytes = buf.read()) != -1) { // os.write(readBytes); // } // os.flush(); // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("File written"); // } // } finally { // if (is != null) { // is.close(); // } // if (buf != null) { // buf.close(); // } // } // } // } // // Path: src/main/java/net/sf/serfj/serializers/ObjectSerializer.java // public interface ObjectSerializer extends Serializer { // /** // * Serialize an object in the format that the implementation requires. // * // * @param object // * Object to serialize. // * @return a String with the object serialized. // */ // public String serialize(Object object); // // /** // * Deserialize an object from the format that the implementation requires to // * Java Object. // * // * @param string // * String representation of the object to deserialize. // * @return an Object. // */ // public Object deserialize(String string); // }
import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.annotations.DoNotRenderPage; import net.sf.serfj.config.ConfigFileIOException; import net.sf.serfj.serializers.FileSerializer; import net.sf.serfj.serializers.ObjectSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
response.getWriter().flush(); } } else { this.serialize(); } } } } protected void serialize() throws IOException { try { LOGGER.debug("Serializing using {}", urlInfo.getSerializer()); Class<?> clazz = Class.forName(urlInfo.getSerializer()); LOGGER.debug("Creating a new instance of {}", urlInfo.getSerializer()); ObjectSerializer serializer = (ObjectSerializer) clazz.newInstance(); LOGGER.debug("Calling {}.serialize()", urlInfo.getSerializer()); String serialized = serializer.serialize(this.object2Serialize); LOGGER.debug("Writing object in the response: {}", serialized); this.writeObject(serializer.getContentType(), serialized); } catch (Exception e) { LOGGER.error("Can't serialize object with {} serializer: {}", urlInfo.getSerializer(), e.getLocalizedMessage()); throw new IOException(e.getLocalizedMessage()); } } protected void sendFile() throws IOException { try { LOGGER.debug("Sending file using {}", urlInfo.getSerializer()); Class<?> clazz = Class.forName(urlInfo.getSerializer()); LOGGER.debug("Creating a new instance of {}", urlInfo.getSerializer());
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // // Path: src/main/java/net/sf/serfj/serializers/FileSerializer.java // public class FileSerializer implements Serializer { // private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class); // // /** // * Content type that will be used in the response. // */ // public String getContentType() { // return "application/octet-stream"; // } // // /** // * Write a file to an OuputStream. // * // * @param file File that will be written. // * @param os The target OutputStream. // * @throws IOException if any error happens. // */ // public void sendFile(File file, OutputStream os) throws IOException { // FileInputStream is = null; // BufferedInputStream buf = null;; // try { // is = new FileInputStream(file); // buf = new BufferedInputStream(is); // int readBytes = 0; // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("Writing file..."); // } // while ((readBytes = buf.read()) != -1) { // os.write(readBytes); // } // os.flush(); // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("File written"); // } // } finally { // if (is != null) { // is.close(); // } // if (buf != null) { // buf.close(); // } // } // } // } // // Path: src/main/java/net/sf/serfj/serializers/ObjectSerializer.java // public interface ObjectSerializer extends Serializer { // /** // * Serialize an object in the format that the implementation requires. // * // * @param object // * Object to serialize. // * @return a String with the object serialized. // */ // public String serialize(Object object); // // /** // * Deserialize an object from the format that the implementation requires to // * Java Object. // * // * @param string // * String representation of the object to deserialize. // * @return an Object. // */ // public Object deserialize(String string); // } // Path: src/main/java/net/sf/serfj/ResponseHelper.java import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.annotations.DoNotRenderPage; import net.sf.serfj.config.ConfigFileIOException; import net.sf.serfj.serializers.FileSerializer; import net.sf.serfj.serializers.ObjectSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; response.getWriter().flush(); } } else { this.serialize(); } } } } protected void serialize() throws IOException { try { LOGGER.debug("Serializing using {}", urlInfo.getSerializer()); Class<?> clazz = Class.forName(urlInfo.getSerializer()); LOGGER.debug("Creating a new instance of {}", urlInfo.getSerializer()); ObjectSerializer serializer = (ObjectSerializer) clazz.newInstance(); LOGGER.debug("Calling {}.serialize()", urlInfo.getSerializer()); String serialized = serializer.serialize(this.object2Serialize); LOGGER.debug("Writing object in the response: {}", serialized); this.writeObject(serializer.getContentType(), serialized); } catch (Exception e) { LOGGER.error("Can't serialize object with {} serializer: {}", urlInfo.getSerializer(), e.getLocalizedMessage()); throw new IOException(e.getLocalizedMessage()); } } protected void sendFile() throws IOException { try { LOGGER.debug("Sending file using {}", urlInfo.getSerializer()); Class<?> clazz = Class.forName(urlInfo.getSerializer()); LOGGER.debug("Creating a new instance of {}", urlInfo.getSerializer());
FileSerializer serializer = (FileSerializer) clazz.newInstance();
eyp/serfj
src/main/java/net/sf/serfj/RestServlet.java
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.config.ConfigFileIOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2010 Eduardo Yáñez Parareda * * 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.sf.serfj; /** * Main class. This servlet dispatches REST requests to controllers. It parses * the URL, extracting resources and resources' Ids so developer will be able to * get them in the method's controller. * * @author Eduardo Yáñez * */ public class RestServlet extends HttpServlet { private static final long serialVersionUID = 9209683558191927011L; /** * Log. */ private static final Logger LOGGER = LoggerFactory.getLogger(RestServlet.class); /** * Parameter for supply the HTTP request method that doesn't support the * browsers (PUT and DELETE), but could be set to GET and POST too. */ private static final String HTTP_METHOD_PARAM = "http_method"; /** * Configuration. */ private Config config; /** * URL manager. */ private UrlInspector urlInspector; private ServletHelper helper = new ServletHelper(); /** * Reads configuration from /serfj.properties. * * @throws javax.servlet.ServletException */ @Override public void init() throws ServletException { super.init(); try { config = new Config("/config/serfj.properties");
// Path: src/main/java/net/sf/serfj/config/ConfigFileIOException.java // public class ConfigFileIOException extends Exception { // // private static final long serialVersionUID = 9197319082561488840L; // // /** // * Constructor with a message. // * // * @param msg - Message error. // */ // public ConfigFileIOException(String msg) { // super(msg); // } // } // Path: src/main/java/net/sf/serfj/RestServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.serfj.config.ConfigFileIOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2010 Eduardo Yáñez Parareda * * 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.sf.serfj; /** * Main class. This servlet dispatches REST requests to controllers. It parses * the URL, extracting resources and resources' Ids so developer will be able to * get them in the method's controller. * * @author Eduardo Yáñez * */ public class RestServlet extends HttpServlet { private static final long serialVersionUID = 9209683558191927011L; /** * Log. */ private static final Logger LOGGER = LoggerFactory.getLogger(RestServlet.class); /** * Parameter for supply the HTTP request method that doesn't support the * browsers (PUT and DELETE), but could be set to GET and POST too. */ private static final String HTTP_METHOD_PARAM = "http_method"; /** * Configuration. */ private Config config; /** * URL manager. */ private UrlInspector urlInspector; private ServletHelper helper = new ServletHelper(); /** * Reads configuration from /serfj.properties. * * @throws javax.servlet.ServletException */ @Override public void init() throws ServletException { super.init(); try { config = new Config("/config/serfj.properties");
} catch (ConfigFileIOException e) {
Jdoing/myweb
myweb/src/main/java/com/myweb/annotations/CurrentUser.java
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.myweb.constants.Constants;
package com.myweb.annotations; @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CurrentUser { /** * 当前用户在request中的名字 * * @return */
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // Path: myweb/src/main/java/com/myweb/annotations/CurrentUser.java import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.myweb.constants.Constants; package com.myweb.annotations; @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CurrentUser { /** * 当前用户在request中的名字 * * @return */
String value() default Constants.CURRENT_USER;
Jdoing/myweb
myweb/src/main/java/com/myweb/spring/SysUserFilter.java
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // // Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // }
import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.web.filter.PathMatchingFilter; import com.myweb.constants.Constants; import com.myweb.dao.UserDao; import com.myweb.entity.User;
package com.myweb.spring; public class SysUserFilter extends PathMatchingFilter { @Inject
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // // Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // Path: myweb/src/main/java/com/myweb/spring/SysUserFilter.java import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.web.filter.PathMatchingFilter; import com.myweb.constants.Constants; import com.myweb.dao.UserDao; import com.myweb.entity.User; package com.myweb.spring; public class SysUserFilter extends PathMatchingFilter { @Inject
private UserDao userDao;
Jdoing/myweb
myweb/src/main/java/com/myweb/spring/SysUserFilter.java
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // // Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // }
import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.web.filter.PathMatchingFilter; import com.myweb.constants.Constants; import com.myweb.dao.UserDao; import com.myweb.entity.User;
package com.myweb.spring; public class SysUserFilter extends PathMatchingFilter { @Inject private UserDao userDao; @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { String username = (String) SecurityUtils.getSubject().getPrincipal();
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // // Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // Path: myweb/src/main/java/com/myweb/spring/SysUserFilter.java import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.web.filter.PathMatchingFilter; import com.myweb.constants.Constants; import com.myweb.dao.UserDao; import com.myweb.entity.User; package com.myweb.spring; public class SysUserFilter extends PathMatchingFilter { @Inject private UserDao userDao; @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { String username = (String) SecurityUtils.getSubject().getPrincipal();
User user = userDao.findByUsername(username);
Jdoing/myweb
myweb/src/main/java/com/myweb/spring/SysUserFilter.java
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // // Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // }
import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.web.filter.PathMatchingFilter; import com.myweb.constants.Constants; import com.myweb.dao.UserDao; import com.myweb.entity.User;
package com.myweb.spring; public class SysUserFilter extends PathMatchingFilter { @Inject private UserDao userDao; @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { String username = (String) SecurityUtils.getSubject().getPrincipal(); User user = userDao.findByUsername(username);
// Path: myweb/src/main/java/com/myweb/constants/Constants.java // public class Constants { // public static final String CURRENT_USER = "user"; // } // // Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // Path: myweb/src/main/java/com/myweb/spring/SysUserFilter.java import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.web.filter.PathMatchingFilter; import com.myweb.constants.Constants; import com.myweb.dao.UserDao; import com.myweb.entity.User; package com.myweb.spring; public class SysUserFilter extends PathMatchingFilter { @Inject private UserDao userDao; @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { String username = (String) SecurityUtils.getSubject().getPrincipal(); User user = userDao.findByUsername(username);
request.setAttribute(Constants.CURRENT_USER, user);
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/RoleController.java
// Path: myweb/src/main/java/com/myweb/dao/RoleDao.java // public interface RoleDao extends JpaRepository<Role, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Role.java // @Entity // @Table(name = "sys_role") // public class Role implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // @OneToMany(targetEntity = Permission.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_role_permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", unique = true) ) // private Set<Permission> permissions = new HashSet<>(); // // private String name; // // @Column(unique = true) // private String role; // 角色标识 程序中判断使用,如"admin" // // private String description; // 角色描述,UI界面显示使用 // // public Role() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((role == null) ? 0 : role.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Role other = (Role) obj; // if (role == null) { // if (other.role != null) // return false; // } else if (!role.equals(other.role)) // return false; // return true; // } // // public Set<Permission> getPermissions() { // return permissions; // } // // public void setPermissions(Set<Permission> permissions) { // this.permissions = permissions; // } // // } // // Path: myweb/src/main/java/com/myweb/service/RoleService.java // public interface RoleService { // boolean authorise(Long roleId, Long resourceId, List<Long> operationIds); // // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.RoleDao; import com.myweb.entity.Role; import com.myweb.service.RoleService;
package com.myweb.controller; @Controller @RequestMapping("/api/role") public class RoleController { @Inject
// Path: myweb/src/main/java/com/myweb/dao/RoleDao.java // public interface RoleDao extends JpaRepository<Role, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Role.java // @Entity // @Table(name = "sys_role") // public class Role implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // @OneToMany(targetEntity = Permission.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_role_permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", unique = true) ) // private Set<Permission> permissions = new HashSet<>(); // // private String name; // // @Column(unique = true) // private String role; // 角色标识 程序中判断使用,如"admin" // // private String description; // 角色描述,UI界面显示使用 // // public Role() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((role == null) ? 0 : role.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Role other = (Role) obj; // if (role == null) { // if (other.role != null) // return false; // } else if (!role.equals(other.role)) // return false; // return true; // } // // public Set<Permission> getPermissions() { // return permissions; // } // // public void setPermissions(Set<Permission> permissions) { // this.permissions = permissions; // } // // } // // Path: myweb/src/main/java/com/myweb/service/RoleService.java // public interface RoleService { // boolean authorise(Long roleId, Long resourceId, List<Long> operationIds); // // } // Path: myweb/src/main/java/com/myweb/controller/RoleController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.RoleDao; import com.myweb.entity.Role; import com.myweb.service.RoleService; package com.myweb.controller; @Controller @RequestMapping("/api/role") public class RoleController { @Inject
private RoleDao roleDao;
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/RoleController.java
// Path: myweb/src/main/java/com/myweb/dao/RoleDao.java // public interface RoleDao extends JpaRepository<Role, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Role.java // @Entity // @Table(name = "sys_role") // public class Role implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // @OneToMany(targetEntity = Permission.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_role_permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", unique = true) ) // private Set<Permission> permissions = new HashSet<>(); // // private String name; // // @Column(unique = true) // private String role; // 角色标识 程序中判断使用,如"admin" // // private String description; // 角色描述,UI界面显示使用 // // public Role() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((role == null) ? 0 : role.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Role other = (Role) obj; // if (role == null) { // if (other.role != null) // return false; // } else if (!role.equals(other.role)) // return false; // return true; // } // // public Set<Permission> getPermissions() { // return permissions; // } // // public void setPermissions(Set<Permission> permissions) { // this.permissions = permissions; // } // // } // // Path: myweb/src/main/java/com/myweb/service/RoleService.java // public interface RoleService { // boolean authorise(Long roleId, Long resourceId, List<Long> operationIds); // // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.RoleDao; import com.myweb.entity.Role; import com.myweb.service.RoleService;
package com.myweb.controller; @Controller @RequestMapping("/api/role") public class RoleController { @Inject private RoleDao roleDao; @Inject
// Path: myweb/src/main/java/com/myweb/dao/RoleDao.java // public interface RoleDao extends JpaRepository<Role, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Role.java // @Entity // @Table(name = "sys_role") // public class Role implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // @OneToMany(targetEntity = Permission.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_role_permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", unique = true) ) // private Set<Permission> permissions = new HashSet<>(); // // private String name; // // @Column(unique = true) // private String role; // 角色标识 程序中判断使用,如"admin" // // private String description; // 角色描述,UI界面显示使用 // // public Role() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((role == null) ? 0 : role.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Role other = (Role) obj; // if (role == null) { // if (other.role != null) // return false; // } else if (!role.equals(other.role)) // return false; // return true; // } // // public Set<Permission> getPermissions() { // return permissions; // } // // public void setPermissions(Set<Permission> permissions) { // this.permissions = permissions; // } // // } // // Path: myweb/src/main/java/com/myweb/service/RoleService.java // public interface RoleService { // boolean authorise(Long roleId, Long resourceId, List<Long> operationIds); // // } // Path: myweb/src/main/java/com/myweb/controller/RoleController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.RoleDao; import com.myweb.entity.Role; import com.myweb.service.RoleService; package com.myweb.controller; @Controller @RequestMapping("/api/role") public class RoleController { @Inject private RoleDao roleDao; @Inject
private RoleService roleService;
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/RoleController.java
// Path: myweb/src/main/java/com/myweb/dao/RoleDao.java // public interface RoleDao extends JpaRepository<Role, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Role.java // @Entity // @Table(name = "sys_role") // public class Role implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // @OneToMany(targetEntity = Permission.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_role_permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", unique = true) ) // private Set<Permission> permissions = new HashSet<>(); // // private String name; // // @Column(unique = true) // private String role; // 角色标识 程序中判断使用,如"admin" // // private String description; // 角色描述,UI界面显示使用 // // public Role() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((role == null) ? 0 : role.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Role other = (Role) obj; // if (role == null) { // if (other.role != null) // return false; // } else if (!role.equals(other.role)) // return false; // return true; // } // // public Set<Permission> getPermissions() { // return permissions; // } // // public void setPermissions(Set<Permission> permissions) { // this.permissions = permissions; // } // // } // // Path: myweb/src/main/java/com/myweb/service/RoleService.java // public interface RoleService { // boolean authorise(Long roleId, Long resourceId, List<Long> operationIds); // // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.RoleDao; import com.myweb.entity.Role; import com.myweb.service.RoleService;
package com.myweb.controller; @Controller @RequestMapping("/api/role") public class RoleController { @Inject private RoleDao roleDao; @Inject private RoleService roleService; @RequiresPermissions("role:view") @RequestMapping(value = "/view", method = RequestMethod.GET) public String view() { return "role/role"; } @RequestMapping(value = { "/all", "/list" }, method = RequestMethod.GET) @ResponseBody
// Path: myweb/src/main/java/com/myweb/dao/RoleDao.java // public interface RoleDao extends JpaRepository<Role, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Role.java // @Entity // @Table(name = "sys_role") // public class Role implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // @OneToMany(targetEntity = Permission.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_role_permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", unique = true) ) // private Set<Permission> permissions = new HashSet<>(); // // private String name; // // @Column(unique = true) // private String role; // 角色标识 程序中判断使用,如"admin" // // private String description; // 角色描述,UI界面显示使用 // // public Role() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((role == null) ? 0 : role.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Role other = (Role) obj; // if (role == null) { // if (other.role != null) // return false; // } else if (!role.equals(other.role)) // return false; // return true; // } // // public Set<Permission> getPermissions() { // return permissions; // } // // public void setPermissions(Set<Permission> permissions) { // this.permissions = permissions; // } // // } // // Path: myweb/src/main/java/com/myweb/service/RoleService.java // public interface RoleService { // boolean authorise(Long roleId, Long resourceId, List<Long> operationIds); // // } // Path: myweb/src/main/java/com/myweb/controller/RoleController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.RoleDao; import com.myweb.entity.Role; import com.myweb.service.RoleService; package com.myweb.controller; @Controller @RequestMapping("/api/role") public class RoleController { @Inject private RoleDao roleDao; @Inject private RoleService roleService; @RequiresPermissions("role:view") @RequestMapping(value = "/view", method = RequestMethod.GET) public String view() { return "role/role"; } @RequestMapping(value = { "/all", "/list" }, method = RequestMethod.GET) @ResponseBody
public List<Role> all() {
Jdoing/myweb
myweb/src/main/java/com/myweb/security/realm/UserRealm.java
// Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // // Path: myweb/src/main/java/com/myweb/service/UserService.java // public interface UserService { // // User save(User user); // // Set<String> getStringRoles(String username); // // Set<String> getStringPermissions(String username); // // }
import javax.inject.Inject; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.myweb.dao.UserDao; import com.myweb.entity.User; import com.myweb.service.UserService;
package com.myweb.security.realm; public class UserRealm extends AuthorizingRealm { @Inject
// Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // // Path: myweb/src/main/java/com/myweb/service/UserService.java // public interface UserService { // // User save(User user); // // Set<String> getStringRoles(String username); // // Set<String> getStringPermissions(String username); // // } // Path: myweb/src/main/java/com/myweb/security/realm/UserRealm.java import javax.inject.Inject; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.myweb.dao.UserDao; import com.myweb.entity.User; import com.myweb.service.UserService; package com.myweb.security.realm; public class UserRealm extends AuthorizingRealm { @Inject
private UserService userService;
Jdoing/myweb
myweb/src/main/java/com/myweb/security/realm/UserRealm.java
// Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // // Path: myweb/src/main/java/com/myweb/service/UserService.java // public interface UserService { // // User save(User user); // // Set<String> getStringRoles(String username); // // Set<String> getStringPermissions(String username); // // }
import javax.inject.Inject; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.myweb.dao.UserDao; import com.myweb.entity.User; import com.myweb.service.UserService;
package com.myweb.security.realm; public class UserRealm extends AuthorizingRealm { @Inject private UserService userService; @Inject
// Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // // Path: myweb/src/main/java/com/myweb/service/UserService.java // public interface UserService { // // User save(User user); // // Set<String> getStringRoles(String username); // // Set<String> getStringPermissions(String username); // // } // Path: myweb/src/main/java/com/myweb/security/realm/UserRealm.java import javax.inject.Inject; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.myweb.dao.UserDao; import com.myweb.entity.User; import com.myweb.service.UserService; package com.myweb.security.realm; public class UserRealm extends AuthorizingRealm { @Inject private UserService userService; @Inject
private UserDao userDao;
Jdoing/myweb
myweb/src/main/java/com/myweb/security/realm/UserRealm.java
// Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // // Path: myweb/src/main/java/com/myweb/service/UserService.java // public interface UserService { // // User save(User user); // // Set<String> getStringRoles(String username); // // Set<String> getStringPermissions(String username); // // }
import javax.inject.Inject; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.myweb.dao.UserDao; import com.myweb.entity.User; import com.myweb.service.UserService;
package com.myweb.security.realm; public class UserRealm extends AuthorizingRealm { @Inject private UserService userService; @Inject private UserDao userDao; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 授权 String username = (String) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(userService.getStringRoles(username)); authorizationInfo.setStringPermissions(userService.getStringPermissions(username)); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { // 认证 String username = (String) authenticationToken.getPrincipal();
// Path: myweb/src/main/java/com/myweb/dao/UserDao.java // public interface UserDao extends JpaRepository<User, Long> { // // User findByUsername(String username); // } // // Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // // Path: myweb/src/main/java/com/myweb/service/UserService.java // public interface UserService { // // User save(User user); // // Set<String> getStringRoles(String username); // // Set<String> getStringPermissions(String username); // // } // Path: myweb/src/main/java/com/myweb/security/realm/UserRealm.java import javax.inject.Inject; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.myweb.dao.UserDao; import com.myweb.entity.User; import com.myweb.service.UserService; package com.myweb.security.realm; public class UserRealm extends AuthorizingRealm { @Inject private UserService userService; @Inject private UserDao userDao; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 授权 String username = (String) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(userService.getStringRoles(username)); authorizationInfo.setStringPermissions(userService.getStringPermissions(username)); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { // 认证 String username = (String) authenticationToken.getPrincipal();
User user = userDao.findByUsername(username);
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/OperationController.java
// Path: myweb/src/main/java/com/myweb/dao/OperationDao.java // public interface OperationDao extends JpaRepository<Operation, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Operation.java // @Entity // @Table(name = "sys_operation") // public class Operation implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 操作名称 // // @Column(unique = true) // private String operation;// 操作标识 // // private String description; // // public Operation() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getOperation() { // return operation; // } // // public void setOperation(String operation) { // this.operation = operation; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // Operation operation = (Operation) o; // // if (operation.operation.equals(this.operation)) // return true; // return false; // } // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.OperationDao; import com.myweb.entity.Operation;
package com.myweb.controller; @Controller @RequestMapping("/api/operation") public class OperationController { @Inject
// Path: myweb/src/main/java/com/myweb/dao/OperationDao.java // public interface OperationDao extends JpaRepository<Operation, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Operation.java // @Entity // @Table(name = "sys_operation") // public class Operation implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 操作名称 // // @Column(unique = true) // private String operation;// 操作标识 // // private String description; // // public Operation() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getOperation() { // return operation; // } // // public void setOperation(String operation) { // this.operation = operation; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // Operation operation = (Operation) o; // // if (operation.operation.equals(this.operation)) // return true; // return false; // } // } // Path: myweb/src/main/java/com/myweb/controller/OperationController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.OperationDao; import com.myweb.entity.Operation; package com.myweb.controller; @Controller @RequestMapping("/api/operation") public class OperationController { @Inject
private OperationDao operationDao;
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/OperationController.java
// Path: myweb/src/main/java/com/myweb/dao/OperationDao.java // public interface OperationDao extends JpaRepository<Operation, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Operation.java // @Entity // @Table(name = "sys_operation") // public class Operation implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 操作名称 // // @Column(unique = true) // private String operation;// 操作标识 // // private String description; // // public Operation() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getOperation() { // return operation; // } // // public void setOperation(String operation) { // this.operation = operation; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // Operation operation = (Operation) o; // // if (operation.operation.equals(this.operation)) // return true; // return false; // } // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.OperationDao; import com.myweb.entity.Operation;
package com.myweb.controller; @Controller @RequestMapping("/api/operation") public class OperationController { @Inject private OperationDao operationDao; @RequiresPermissions("operation:view") @RequestMapping(value = "/view", method = RequestMethod.GET) public String view() { return "operation/operation"; } @RequestMapping(value = { "/all", "/list" }, method = RequestMethod.GET) @ResponseBody
// Path: myweb/src/main/java/com/myweb/dao/OperationDao.java // public interface OperationDao extends JpaRepository<Operation, Long> { // // } // // Path: myweb/src/main/java/com/myweb/entity/Operation.java // @Entity // @Table(name = "sys_operation") // public class Operation implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 操作名称 // // @Column(unique = true) // private String operation;// 操作标识 // // private String description; // // public Operation() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getOperation() { // return operation; // } // // public void setOperation(String operation) { // this.operation = operation; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // Operation operation = (Operation) o; // // if (operation.operation.equals(this.operation)) // return true; // return false; // } // } // Path: myweb/src/main/java/com/myweb/controller/OperationController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.OperationDao; import com.myweb.entity.Operation; package com.myweb.controller; @Controller @RequestMapping("/api/operation") public class OperationController { @Inject private OperationDao operationDao; @RequiresPermissions("operation:view") @RequestMapping(value = "/view", method = RequestMethod.GET) public String view() { return "operation/operation"; } @RequestMapping(value = { "/all", "/list" }, method = RequestMethod.GET) @ResponseBody
public List<Operation> getAll() {
Jdoing/myweb
myweb/src/main/java/com/myweb/security/util/PasswordHelper.java
// Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // }
import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.util.ByteSource; import org.springframework.stereotype.Component; import com.myweb.entity.User;
package com.myweb.security.util; @Component public class PasswordHelper { private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); private String algorithmName = "md5"; private int hashIterations = 2; public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) { this.randomNumberGenerator = randomNumberGenerator; } public void setAlgorithmName(String algorithmName) { this.algorithmName = algorithmName; } public void setHashIterations(int hashIterations) { this.hashIterations = hashIterations; }
// Path: myweb/src/main/java/com/myweb/entity/User.java // @Entity // @Table(name = "sys_user") // public class User implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // // 这里不能用CascadeType.ALL // @ManyToMany(targetEntity = Role.class, cascade = CascadeType.MERGE, fetch = FetchType.EAGER) // @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Set<Role> roles = new HashSet<>(); // // @Column(unique = true) // private String username; // 用户名 // // private String password; // 密码 // private String salt; // 加密密码的盐 // private Boolean locked = Boolean.FALSE; // // private String email; // // @Column(name = "create_date") // @Temporal(TemporalType.TIMESTAMP) // private Date createDate = new Date(); // // public User() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getCredentialsSalt() { // return username + salt; // } // // public Boolean getLocked() { // return locked; // } // // public void setLocked(Boolean locked) { // this.locked = locked; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || getClass() != o.getClass()) // return false; // // User user = (User) o; // // if (id != null ? !id.equals(user.id) : user.id != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // } // Path: myweb/src/main/java/com/myweb/security/util/PasswordHelper.java import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.util.ByteSource; import org.springframework.stereotype.Component; import com.myweb.entity.User; package com.myweb.security.util; @Component public class PasswordHelper { private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); private String algorithmName = "md5"; private int hashIterations = 2; public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) { this.randomNumberGenerator = randomNumberGenerator; } public void setAlgorithmName(String algorithmName) { this.algorithmName = algorithmName; } public void setHashIterations(int hashIterations) { this.hashIterations = hashIterations; }
public void encryptPassword(User user) {
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/ResourceController.java
// Path: myweb/src/main/java/com/myweb/dao/ResourceDao.java // public interface ResourceDao extends JpaRepository<Resource, Long> { // List<Resource> findByIdentity(String identity); // } // // Path: myweb/src/main/java/com/myweb/entity/Resource.java // @Entity // @Table(name = "sys_resource") // public class Resource implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 资源名称 // // // @Enumerated(EnumType.STRING) // @Column(unique = true) // private String identity;// 资源类型 // // private String url; // // public Resource() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentity() { // return identity; // } // // public void setIdentity(String identity) { // this.identity = identity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((identity == null) ? 0 : identity.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Resource other = (Resource) obj; // if (identity == null) { // if (other.identity != null) // return false; // } else if (!identity.equals(other.identity)) // return false; // return true; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.ResourceDao; import com.myweb.entity.Resource;
package com.myweb.controller; @Controller @RequestMapping("/api/resource") public class ResourceController { @Inject
// Path: myweb/src/main/java/com/myweb/dao/ResourceDao.java // public interface ResourceDao extends JpaRepository<Resource, Long> { // List<Resource> findByIdentity(String identity); // } // // Path: myweb/src/main/java/com/myweb/entity/Resource.java // @Entity // @Table(name = "sys_resource") // public class Resource implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 资源名称 // // // @Enumerated(EnumType.STRING) // @Column(unique = true) // private String identity;// 资源类型 // // private String url; // // public Resource() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentity() { // return identity; // } // // public void setIdentity(String identity) { // this.identity = identity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((identity == null) ? 0 : identity.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Resource other = (Resource) obj; // if (identity == null) { // if (other.identity != null) // return false; // } else if (!identity.equals(other.identity)) // return false; // return true; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // Path: myweb/src/main/java/com/myweb/controller/ResourceController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.ResourceDao; import com.myweb.entity.Resource; package com.myweb.controller; @Controller @RequestMapping("/api/resource") public class ResourceController { @Inject
private ResourceDao resourceDao;
Jdoing/myweb
myweb/src/main/java/com/myweb/controller/ResourceController.java
// Path: myweb/src/main/java/com/myweb/dao/ResourceDao.java // public interface ResourceDao extends JpaRepository<Resource, Long> { // List<Resource> findByIdentity(String identity); // } // // Path: myweb/src/main/java/com/myweb/entity/Resource.java // @Entity // @Table(name = "sys_resource") // public class Resource implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 资源名称 // // // @Enumerated(EnumType.STRING) // @Column(unique = true) // private String identity;// 资源类型 // // private String url; // // public Resource() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentity() { // return identity; // } // // public void setIdentity(String identity) { // this.identity = identity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((identity == null) ? 0 : identity.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Resource other = (Resource) obj; // if (identity == null) { // if (other.identity != null) // return false; // } else if (!identity.equals(other.identity)) // return false; // return true; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // }
import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.ResourceDao; import com.myweb.entity.Resource;
package com.myweb.controller; @Controller @RequestMapping("/api/resource") public class ResourceController { @Inject private ResourceDao resourceDao; @RequiresPermissions("resource:view") @RequestMapping(value = "/view", method = RequestMethod.GET) public String view() { return "resource/resource"; } @RequestMapping(value = { "/all", "/list" }, method = RequestMethod.GET) @ResponseBody
// Path: myweb/src/main/java/com/myweb/dao/ResourceDao.java // public interface ResourceDao extends JpaRepository<Resource, Long> { // List<Resource> findByIdentity(String identity); // } // // Path: myweb/src/main/java/com/myweb/entity/Resource.java // @Entity // @Table(name = "sys_resource") // public class Resource implements Serializable { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // 编号 // // private String name; // 资源名称 // // // @Enumerated(EnumType.STRING) // @Column(unique = true) // private String identity;// 资源类型 // // private String url; // // public Resource() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentity() { // return identity; // } // // public void setIdentity(String identity) { // this.identity = identity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((identity == null) ? 0 : identity.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Resource other = (Resource) obj; // if (identity == null) { // if (other.identity != null) // return false; // } else if (!identity.equals(other.identity)) // return false; // return true; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // Path: myweb/src/main/java/com/myweb/controller/ResourceController.java import java.util.List; import javax.inject.Inject; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.myweb.dao.ResourceDao; import com.myweb.entity.Resource; package com.myweb.controller; @Controller @RequestMapping("/api/resource") public class ResourceController { @Inject private ResourceDao resourceDao; @RequiresPermissions("resource:view") @RequestMapping(value = "/view", method = RequestMethod.GET) public String view() { return "resource/resource"; } @RequestMapping(value = { "/all", "/list" }, method = RequestMethod.GET) @ResponseBody
public List<Resource> getAll() {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellCursor.java
// Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SelectMapper.java // public interface SelectMapper<T> { // T convert(Cursor cursor); // }
import android.database.Cursor; import android.database.CursorWrapper; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.Nullable; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import com.yarolegovich.wellsql.mapper.SelectMapper; import java.util.Iterator;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 01.12.2015. */ public class WellCursor<T> extends CursorWrapper { private SQLiteDatabase mDb;
// Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SelectMapper.java // public interface SelectMapper<T> { // T convert(Cursor cursor); // } // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellCursor.java import android.database.Cursor; import android.database.CursorWrapper; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.Nullable; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import com.yarolegovich.wellsql.mapper.SelectMapper; import java.util.Iterator; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 01.12.2015. */ public class WellCursor<T> extends CursorWrapper { private SQLiteDatabase mDb;
private SelectMapper<T> mMapper;
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellTableManager.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ public class WellTableManager { private SQLiteDatabase mDb; WellTableManager(SQLiteDatabase db) { mDb = db; }
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellTableManager.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ public class WellTableManager { private SQLiteDatabase mDb; WellTableManager(SQLiteDatabase db) { mDb = db; }
public void createTable(Class<? extends Identifiable> token) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellTableManager.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ public class WellTableManager { private SQLiteDatabase mDb; WellTableManager(SQLiteDatabase db) { mDb = db; } public void createTable(Class<? extends Identifiable> token) {
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellTableManager.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ public class WellTableManager { private SQLiteDatabase mDb; WellTableManager(SQLiteDatabase db) { mDb = db; } public void createTable(Class<? extends Identifiable> token) {
TableClass table = WellSql.tableFor(token);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/SelectQuery.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SelectMapper.java // public interface SelectMapper<T> { // T convert(Cursor cursor); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.IntDef; import android.text.TextUtils; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import com.yarolegovich.wellsql.mapper.SelectMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 19.11.2015. */ @SuppressWarnings("unchecked") public class SelectQuery<T extends Identifiable> implements ConditionClauseConsumer { private static Executor sExecutor = Executors.newSingleThreadExecutor(); private Handler mMainHandler = new Handler(Looper.getMainLooper()); private Class<T> mModel; private SQLiteDatabase mDb; private String[] mProjection; private String mGroupBy; private String mHaving; private String mSortOrder; private String mLimit; private String mSelection; private String[] mSelectionArgs; private SQLiteQueryBuilder mSQLiteQueryBuilder = new SQLiteQueryBuilder(); SelectQuery(SQLiteDatabase db, Class<T> tableClass) {
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SelectMapper.java // public interface SelectMapper<T> { // T convert(Cursor cursor); // } // Path: wellsql/src/main/java/com/yarolegovich/wellsql/SelectQuery.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.IntDef; import android.text.TextUtils; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import com.yarolegovich.wellsql.mapper.SelectMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 19.11.2015. */ @SuppressWarnings("unchecked") public class SelectQuery<T extends Identifiable> implements ConditionClauseConsumer { private static Executor sExecutor = Executors.newSingleThreadExecutor(); private Handler mMainHandler = new Handler(Looper.getMainLooper()); private Class<T> mModel; private SQLiteDatabase mDb; private String[] mProjection; private String mGroupBy; private String mHaving; private String mSortOrder; private String mLimit; private String mSelection; private String[] mSelectionArgs; private SQLiteQueryBuilder mSQLiteQueryBuilder = new SQLiteQueryBuilder(); SelectQuery(SQLiteDatabase db, Class<T> tableClass) {
TableClass table = WellSql.tableFor(tableClass);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/SelectQuery.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SelectMapper.java // public interface SelectMapper<T> { // T convert(Cursor cursor); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.IntDef; import android.text.TextUtils; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import com.yarolegovich.wellsql.mapper.SelectMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors;
} public Map<String, Object> getAsMap() { Cursor cursor = execute(); try { Map<String, Object> result = new HashMap<>(); Bundle bundle = cursor.getExtras(); for (String column : bundle.keySet()) { result.put(column, bundle.get(column)); } return result; } finally { cursor.close(); mDb.close(); } } public void getAsMapAsync(final Callback<Map<String, Object>> callback) { sExecutor.execute(new Runnable() { @Override public void run() { mMainHandler.post(new DeliveryMan<>(getAsMap(), callback)); } }); } public List<T> getAsModel() { return getAsModel(WellSql.mapperFor(mModel)); }
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SelectMapper.java // public interface SelectMapper<T> { // T convert(Cursor cursor); // } // Path: wellsql/src/main/java/com/yarolegovich/wellsql/SelectQuery.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.IntDef; import android.text.TextUtils; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import com.yarolegovich.wellsql.mapper.SelectMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; } public Map<String, Object> getAsMap() { Cursor cursor = execute(); try { Map<String, Object> result = new HashMap<>(); Bundle bundle = cursor.getExtras(); for (String column : bundle.keySet()) { result.put(column, bundle.get(column)); } return result; } finally { cursor.close(); mDb.close(); } } public void getAsMapAsync(final Callback<Map<String, Object>> callback) { sExecutor.execute(new Runnable() { @Override public void run() { mMainHandler.post(new DeliveryMan<>(getAsMap(), callback)); } }); } public List<T> getAsModel() { return getAsModel(WellSql.mapperFor(mModel)); }
public List<T> getAsModel(SelectMapper<T> mapper) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 25.11.2015. */ public interface WellConfig { int getDbVersion(); String getDbName(); OnUpgradeListener getOnUpgradeListener(); OnCreateListener getOnCreateListener(); OnDowngradeListener getOnDowngradeListener(); Context getContext();
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 25.11.2015. */ public interface WellConfig { int getDbVersion(); String getDbName(); OnUpgradeListener getOnUpgradeListener(); OnCreateListener getOnCreateListener(); OnDowngradeListener getOnDowngradeListener(); Context getContext();
<T>SQLiteMapper<T> getMapper(Class<T> token);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 25.11.2015. */ public interface WellConfig { int getDbVersion(); String getDbName(); OnUpgradeListener getOnUpgradeListener(); OnCreateListener getOnCreateListener(); OnDowngradeListener getOnDowngradeListener(); Context getContext(); <T>SQLiteMapper<T> getMapper(Class<T> token);
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 25.11.2015. */ public interface WellConfig { int getDbVersion(); String getDbName(); OnUpgradeListener getOnUpgradeListener(); OnCreateListener getOnCreateListener(); OnDowngradeListener getOnDowngradeListener(); Context getContext(); <T>SQLiteMapper<T> getMapper(Class<T> token);
TableClass getTable(Class<? extends Identifiable> token);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 25.11.2015. */ public interface WellConfig { int getDbVersion(); String getDbName(); OnUpgradeListener getOnUpgradeListener(); OnCreateListener getOnCreateListener(); OnDowngradeListener getOnDowngradeListener(); Context getContext(); <T>SQLiteMapper<T> getMapper(Class<T> token);
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 25.11.2015. */ public interface WellConfig { int getDbVersion(); String getDbName(); OnUpgradeListener getOnUpgradeListener(); OnCreateListener getOnCreateListener(); OnDowngradeListener getOnDowngradeListener(); Context getContext(); <T>SQLiteMapper<T> getMapper(Class<T> token);
TableClass getTable(Class<? extends Identifiable> token);
yarolegovich/wellsql
well-processor/src/main/java/com/yarolegovich/processor/ColumnAnnotatedField.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/ColumnType.java // public abstract class ColumnType { // public static final String BLOB = "BLOB"; // public static final String TEXT = "TEXT"; // public static final String INTEGER = "INTEGER"; // public static final String REAL = "REAL"; // }
import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.ColumnType; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.Unique; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement;
return " UNIQUE"; } else if (simpleName.equals(Check.class.getSimpleName())) { String constraint = Utils.extractValue(mirror, "value", String.class); boolean hasConstraint = !constraint.equals(""); return " CHECK" + (hasConstraint ? " (" + constraint + ")" : ""); } else { return ""; } } public boolean isPrimaryKey() { return isPrimaryKey; } public boolean isAutoincrement() { return isAutoincrement; } public String getFieldName() { return fieldName; } public String getClassName() { return fieldClass; } private static Map<String, String> typeMapping; static { typeMapping = new HashMap<>();
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/ColumnType.java // public abstract class ColumnType { // public static final String BLOB = "BLOB"; // public static final String TEXT = "TEXT"; // public static final String INTEGER = "INTEGER"; // public static final String REAL = "REAL"; // } // Path: well-processor/src/main/java/com/yarolegovich/processor/ColumnAnnotatedField.java import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.ColumnType; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.Unique; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; return " UNIQUE"; } else if (simpleName.equals(Check.class.getSimpleName())) { String constraint = Utils.extractValue(mirror, "value", String.class); boolean hasConstraint = !constraint.equals(""); return " CHECK" + (hasConstraint ? " (" + constraint + ")" : ""); } else { return ""; } } public boolean isPrimaryKey() { return isPrimaryKey; } public boolean isAutoincrement() { return isAutoincrement; } public String getFieldName() { return fieldName; } public String getClassName() { return fieldClass; } private static Map<String, String> typeMapping; static { typeMapping = new HashMap<>();
typeMapping.put(Integer.class.getCanonicalName(), ColumnType.INTEGER);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java
// Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellException.java // public class WellException extends RuntimeException { // public WellException(String detailMessage) { // super(detailMessage); // } // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // }
import android.content.ContentValues; import android.database.Cursor; import com.yarolegovich.wellsql.WellException; import com.yarolegovich.wellsql.core.Mapper; import java.util.HashMap; import java.util.Map;
mMapper = mapper; } @Override public ContentValues toCv(T item) { ContentValues cv = new ContentValues(); Map<String, Object> vals = mMapper.toContentValues(item); for (String key : vals.keySet()) { Object obj = vals.get(key); if (obj instanceof String) { cv.put(key, (String) obj); } else if (obj instanceof Integer) { cv.put(key, (Integer) obj); } else if (obj instanceof Double) { cv.put(key, (Double) obj); } else if (obj instanceof byte[]) { cv.put(key, (byte[]) obj); } else if (obj instanceof Boolean) { cv.put(key, (Boolean) obj); } else if (obj instanceof Byte) { cv.put(key, (Byte) obj); } else if (obj instanceof Float) { cv.put(key, (Float) obj); } else if (obj instanceof Long) { cv.put(key, (Long) obj); } else if (obj instanceof Short) { cv.put(key, (Short) obj); } else if (obj == null) { cv.putNull(key); } else {
// Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellException.java // public class WellException extends RuntimeException { // public WellException(String detailMessage) { // super(detailMessage); // } // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java import android.content.ContentValues; import android.database.Cursor; import com.yarolegovich.wellsql.WellException; import com.yarolegovich.wellsql.core.Mapper; import java.util.HashMap; import java.util.Map; mMapper = mapper; } @Override public ContentValues toCv(T item) { ContentValues cv = new ContentValues(); Map<String, Object> vals = mMapper.toContentValues(item); for (String key : vals.keySet()) { Object obj = vals.get(key); if (obj instanceof String) { cv.put(key, (String) obj); } else if (obj instanceof Integer) { cv.put(key, (Integer) obj); } else if (obj instanceof Double) { cv.put(key, (Double) obj); } else if (obj instanceof byte[]) { cv.put(key, (byte[]) obj); } else if (obj instanceof Boolean) { cv.put(key, (Boolean) obj); } else if (obj instanceof Byte) { cv.put(key, (Byte) obj); } else if (obj instanceof Float) { cv.put(key, (Float) obj); } else if (obj instanceof Long) { cv.put(key, (Long) obj); } else if (obj instanceof Short) { cv.put(key, (Short) obj); } else if (obj == null) { cv.putNull(key); } else {
throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " +
yarolegovich/wellsql
well-sample/src/main/java/com/yarolegovich/wellsample/App.java
// Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java // public class WellSql extends SQLiteOpenHelper { // // private static WellSql sInstance; // // static WellConfig mDbConfig; // // public static void init(WellConfig config) { // mDbConfig = config; // sInstance = new WellSql(config); // } // // @SuppressWarnings("unchecked") // public WellSql(WellConfig config) { // super(config.getContext(), config.getDbName(), null, config.getDbVersion()); // } // // @Override // public void onCreate(SQLiteDatabase db) { // WellConfig.OnCreateListener l = mDbConfig.getOnCreateListener(); // if (l != null) { // l.onCreate(db, new WellTableManager(db)); // } // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // WellConfig.OnUpgradeListener l = mDbConfig.getOnUpgradeListener(); // if (l != null) { // l.onUpgrade(db, new WellTableManager(db), oldVersion, newVersion); // } // } // // @Override // public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { // WellConfig.OnDowngradeListener l = mDbConfig.getOnDowngradeListener(); // if (l != null) { // l.onDowngrade(db, new WellTableManager(db), oldVersion, newVersion); // } // } // // public static <T extends Identifiable> SelectQuery<T> selectUnique(Class<T> token) { // return select(token).uniqueOnly(); // } // // public static <T extends Identifiable> SelectQuery<T> select(Class<T> token) { // return new SelectQuery<>(sInstance.getReadableDatabase(), token); // } // // public static <T extends Identifiable> InsertQuery<T> insert(T item) { // return insert(Collections.singletonList(item)); // } // // public static <T extends Identifiable> InsertQuery<T> insert(List<T> items) { // return new InsertQuery<>(sInstance.getWritableDatabase(), items); // } // // public static <T extends Identifiable> DeleteQuery<T> delete(Class<T> token) { // return new DeleteQuery<>(sInstance.getWritableDatabase(), token); // } // // public static <T extends Identifiable> UpdateQuery<T> update(Class<T> token) { // return new UpdateQuery<>(sInstance.getWritableDatabase(), token); // } // // public static <T extends Identifiable>ResetAutoincrementQuery autoincrementFor(Class<T> token) { // return new ResetAutoincrementQuery(sInstance.getWritableDatabase(), tableFor(token).getTableName()); // } // // public static SQLiteDatabase giveMeReadableDb() { // return sInstance.getReadableDatabase(); // } // // public static SQLiteDatabase giveMeWritableDb() { // return sInstance.getWritableDatabase(); // } // // public static <T> SQLiteMapper<T> mapperFor(Class<T> token) { // SQLiteMapper<T> mapper = mDbConfig.getMapper(token); // if (mapper == null) { // throw new RuntimeException(mDbConfig.getContext() // .getString(R.string.mapper_not_found, token.getSimpleName())); // } // return mapper; // } // // static <T extends Identifiable> TableClass tableFor(Class<T> token) { // TableClass tableClass = mDbConfig.getTable(token); // if (tableClass == null) { // throw new WellException(mDbConfig.getContext() // .getString(R.string.table_not_found, token.getSimpleName())); // } // return tableClass; // } // }
import android.app.Application; import com.wellsql.generated.SuperHeroMapper; import com.wellsql.generated.SuperHeroTable; import com.yarolegovich.wellsql.WellSql;
package com.yarolegovich.wellsample; /** * Created by yarolegovich on 26.11.2015. */ public class App extends Application { @Override public void onCreate() { super.onCreate();
// Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java // public class WellSql extends SQLiteOpenHelper { // // private static WellSql sInstance; // // static WellConfig mDbConfig; // // public static void init(WellConfig config) { // mDbConfig = config; // sInstance = new WellSql(config); // } // // @SuppressWarnings("unchecked") // public WellSql(WellConfig config) { // super(config.getContext(), config.getDbName(), null, config.getDbVersion()); // } // // @Override // public void onCreate(SQLiteDatabase db) { // WellConfig.OnCreateListener l = mDbConfig.getOnCreateListener(); // if (l != null) { // l.onCreate(db, new WellTableManager(db)); // } // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // WellConfig.OnUpgradeListener l = mDbConfig.getOnUpgradeListener(); // if (l != null) { // l.onUpgrade(db, new WellTableManager(db), oldVersion, newVersion); // } // } // // @Override // public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { // WellConfig.OnDowngradeListener l = mDbConfig.getOnDowngradeListener(); // if (l != null) { // l.onDowngrade(db, new WellTableManager(db), oldVersion, newVersion); // } // } // // public static <T extends Identifiable> SelectQuery<T> selectUnique(Class<T> token) { // return select(token).uniqueOnly(); // } // // public static <T extends Identifiable> SelectQuery<T> select(Class<T> token) { // return new SelectQuery<>(sInstance.getReadableDatabase(), token); // } // // public static <T extends Identifiable> InsertQuery<T> insert(T item) { // return insert(Collections.singletonList(item)); // } // // public static <T extends Identifiable> InsertQuery<T> insert(List<T> items) { // return new InsertQuery<>(sInstance.getWritableDatabase(), items); // } // // public static <T extends Identifiable> DeleteQuery<T> delete(Class<T> token) { // return new DeleteQuery<>(sInstance.getWritableDatabase(), token); // } // // public static <T extends Identifiable> UpdateQuery<T> update(Class<T> token) { // return new UpdateQuery<>(sInstance.getWritableDatabase(), token); // } // // public static <T extends Identifiable>ResetAutoincrementQuery autoincrementFor(Class<T> token) { // return new ResetAutoincrementQuery(sInstance.getWritableDatabase(), tableFor(token).getTableName()); // } // // public static SQLiteDatabase giveMeReadableDb() { // return sInstance.getReadableDatabase(); // } // // public static SQLiteDatabase giveMeWritableDb() { // return sInstance.getWritableDatabase(); // } // // public static <T> SQLiteMapper<T> mapperFor(Class<T> token) { // SQLiteMapper<T> mapper = mDbConfig.getMapper(token); // if (mapper == null) { // throw new RuntimeException(mDbConfig.getContext() // .getString(R.string.mapper_not_found, token.getSimpleName())); // } // return mapper; // } // // static <T extends Identifiable> TableClass tableFor(Class<T> token) { // TableClass tableClass = mDbConfig.getTable(token); // if (tableClass == null) { // throw new WellException(mDbConfig.getContext() // .getString(R.string.table_not_found, token.getSimpleName())); // } // return tableClass; // } // } // Path: well-sample/src/main/java/com/yarolegovich/wellsample/App.java import android.app.Application; import com.wellsql.generated.SuperHeroMapper; import com.wellsql.generated.SuperHeroTable; import com.yarolegovich.wellsql.WellSql; package com.yarolegovich.wellsample; /** * Created by yarolegovich on 26.11.2015. */ public class App extends Application { @Override public void onCreate() { super.onCreate();
WellSql.init(new WellConfig(this));
yarolegovich/wellsql
well-processor/src/main/java/com/yarolegovich/processor/TableProcessor.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // }
import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.yarolegovich.wellsql.core.Mapper; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.Unique; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic;
package com.yarolegovich.processor; @AutoService(Processor.class) public class TableProcessor extends AbstractProcessor { private Filer filer; private Messager messager; @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); Utils.init(processingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); FieldSpec tableMap = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Map.class),
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // Path: well-processor/src/main/java/com/yarolegovich/processor/TableProcessor.java import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.yarolegovich.wellsql.core.Mapper; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.Unique; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; package com.yarolegovich.processor; @AutoService(Processor.class) public class TableProcessor extends AbstractProcessor { private Filer filer; private Messager messager; @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); Utils.init(processingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); FieldSpec tableMap = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Map.class),
anyClass, ClassName.get(TableClass.class)),
yarolegovich/wellsql
well-processor/src/main/java/com/yarolegovich/processor/TableProcessor.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // }
import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.yarolegovich.wellsql.core.Mapper; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.Unique; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic;
package com.yarolegovich.processor; @AutoService(Processor.class) public class TableProcessor extends AbstractProcessor { private Filer filer; private Messager messager; @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); Utils.init(processingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); FieldSpec tableMap = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Map.class), anyClass, ClassName.get(TableClass.class)), "tables", Modifier.PRIVATE, Modifier.FINAL).build(); FieldSpec mapperMap = FieldSpec.builder(CodeGenUtils.mapOfParametrized(Map.class,
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // Path: well-processor/src/main/java/com/yarolegovich/processor/TableProcessor.java import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.yarolegovich.wellsql.core.Mapper; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.Unique; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; package com.yarolegovich.processor; @AutoService(Processor.class) public class TableProcessor extends AbstractProcessor { private Filer filer; private Messager messager; @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); Utils.init(processingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); FieldSpec tableMap = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Map.class), anyClass, ClassName.get(TableClass.class)), "tables", Modifier.PRIVATE, Modifier.FINAL).build(); FieldSpec mapperMap = FieldSpec.builder(CodeGenUtils.mapOfParametrized(Map.class,
Class.class, Mapper.class),
yarolegovich/wellsql
well-processor/src/main/java/com/yarolegovich/processor/TableProcessor.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // }
import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.yarolegovich.wellsql.core.Mapper; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.Unique; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic;
} convertBuilder.beginControlFlow(CodeGenUtils.cvGetNotNull(), column.getName()); convertBuilder.addStatement(CodeGenUtils.toConvertStatement(column), column.getName()); convertBuilder.endControlFlow(); } toCvBuilder.addStatement("return cv"); convertBuilder.addStatement("return item"); mapperClassBuilder.addMethod(toCvBuilder.build()); mapperClassBuilder.addMethod(convertBuilder.build()); JavaFile javaFile = JavaFile.builder(CodeGenUtils.PACKAGE, mapperClassBuilder.build()) .build(); try { javaFile.writeTo(filer); } catch (IOException e) { error(tableElement, "Failed to create mapper class: " + e.getMessage()); } return CodeGenUtils.PACKAGE + "." + genClassName; } private void generateLookup(MethodSpec constructor, FieldSpec tableMap, FieldSpec mapperMap) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); TypeSpec.Builder lookupClassBuilder = TypeSpec.classBuilder(CodeGenUtils.LOOKUP_CLASS) .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Mapper.java // public interface Mapper<T> { // Map<String, Object> toContentValues(T item); // T convert(Map<String, Object> cursor); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // Path: well-processor/src/main/java/com/yarolegovich/processor/TableProcessor.java import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.yarolegovich.wellsql.core.Mapper; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.NotNull; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.annotation.Unique; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; } convertBuilder.beginControlFlow(CodeGenUtils.cvGetNotNull(), column.getName()); convertBuilder.addStatement(CodeGenUtils.toConvertStatement(column), column.getName()); convertBuilder.endControlFlow(); } toCvBuilder.addStatement("return cv"); convertBuilder.addStatement("return item"); mapperClassBuilder.addMethod(toCvBuilder.build()); mapperClassBuilder.addMethod(convertBuilder.build()); JavaFile javaFile = JavaFile.builder(CodeGenUtils.PACKAGE, mapperClassBuilder.build()) .build(); try { javaFile.writeTo(filer); } catch (IOException e) { error(tableElement, "Failed to create mapper class: " + e.getMessage()); } return CodeGenUtils.PACKAGE + "." + genClassName; } private void generateLookup(MethodSpec constructor, FieldSpec tableMap, FieldSpec mapperMap) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); TypeSpec.Builder lookupClassBuilder = TypeSpec.classBuilder(CodeGenUtils.LOOKUP_CLASS) .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addSuperinterface(TableLookup.class);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext;
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext;
private TableLookup mGeneratedLookup;
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup;
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup;
private Map<Class<?>, SQLiteMapper<?>> mMappers;
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>)
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>)
Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS);
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>) Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS); mGeneratedLookup = clazz.newInstance(); for (Class<?> token : mGeneratedLookup.getMapperTokens()) {
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>) Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS); mGeneratedLookup = clazz.newInstance(); for (Class<?> token : mGeneratedLookup.getMapperTokens()) {
mMappers.put(token, new MapperAdapter<>(mGeneratedLookup.getMapper(token)));
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>) Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS); mGeneratedLookup = clazz.newInstance(); for (Class<?> token : mGeneratedLookup.getMapperTokens()) { mMappers.put(token, new MapperAdapter<>(mGeneratedLookup.getMapper(token))); } } catch (ClassNotFoundException e) { throw new WellException(mContext.getString(R.string.classes_not_found)); } catch (Exception e) { /* This can't be thrown, because Binder.LOOKUP_CLASS always will be instantiated successfully */ } mMappers.putAll(registerMappers()); } protected Map<Class<?>, SQLiteMapper<?>> registerMappers() { return Collections.emptyMap(); } @Override public OnUpgradeListener getOnUpgradeListener() { return this; } @Override public OnCreateListener getOnCreateListener() { return this; } @Override public OnDowngradeListener getOnDowngradeListener() { return this; } @Override public Context getContext() { return mContext; } @Override public <T> SQLiteMapper<T> getMapper(Class<T> token) { return (SQLiteMapper<T>) mMappers.get(token); } @Override
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>) Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS); mGeneratedLookup = clazz.newInstance(); for (Class<?> token : mGeneratedLookup.getMapperTokens()) { mMappers.put(token, new MapperAdapter<>(mGeneratedLookup.getMapper(token))); } } catch (ClassNotFoundException e) { throw new WellException(mContext.getString(R.string.classes_not_found)); } catch (Exception e) { /* This can't be thrown, because Binder.LOOKUP_CLASS always will be instantiated successfully */ } mMappers.putAll(registerMappers()); } protected Map<Class<?>, SQLiteMapper<?>> registerMappers() { return Collections.emptyMap(); } @Override public OnUpgradeListener getOnUpgradeListener() { return this; } @Override public OnCreateListener getOnCreateListener() { return this; } @Override public OnDowngradeListener getOnDowngradeListener() { return this; } @Override public Context getContext() { return mContext; } @Override public <T> SQLiteMapper<T> getMapper(Class<T> token) { return (SQLiteMapper<T>) mMappers.get(token); } @Override
public TableClass getTable(Class<? extends Identifiable> token) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>) Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS); mGeneratedLookup = clazz.newInstance(); for (Class<?> token : mGeneratedLookup.getMapperTokens()) { mMappers.put(token, new MapperAdapter<>(mGeneratedLookup.getMapper(token))); } } catch (ClassNotFoundException e) { throw new WellException(mContext.getString(R.string.classes_not_found)); } catch (Exception e) { /* This can't be thrown, because Binder.LOOKUP_CLASS always will be instantiated successfully */ } mMappers.putAll(registerMappers()); } protected Map<Class<?>, SQLiteMapper<?>> registerMappers() { return Collections.emptyMap(); } @Override public OnUpgradeListener getOnUpgradeListener() { return this; } @Override public OnCreateListener getOnCreateListener() { return this; } @Override public OnDowngradeListener getOnDowngradeListener() { return this; } @Override public Context getContext() { return mContext; } @Override public <T> SQLiteMapper<T> getMapper(Class<T> token) { return (SQLiteMapper<T>) mMappers.get(token); } @Override
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Binder.java // public abstract class Binder { // public static final String PACKAGE = "com.wellsql.generated"; // public static final String LOOKUP_CLASS = "GeneratedLookup"; // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableLookup.java // public interface TableLookup { // <T>Mapper<T> getMapper(Class<T> token); // TableClass getTable(Class<?> token); // // Set<Class<?>> getMapperTokens(); // Set<Class<?>> getTableTokens(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/MapperAdapter.java // public class MapperAdapter<T> implements SQLiteMapper<T> { // // private Mapper<T> mMapper; // // public MapperAdapter(Mapper<T> mapper) { // mMapper = mapper; // } // // @Override // public ContentValues toCv(T item) { // ContentValues cv = new ContentValues(); // Map<String, Object> vals = mMapper.toContentValues(item); // for (String key : vals.keySet()) { // Object obj = vals.get(key); // if (obj instanceof String) { // cv.put(key, (String) obj); // } else if (obj instanceof Integer) { // cv.put(key, (Integer) obj); // } else if (obj instanceof Double) { // cv.put(key, (Double) obj); // } else if (obj instanceof byte[]) { // cv.put(key, (byte[]) obj); // } else if (obj instanceof Boolean) { // cv.put(key, (Boolean) obj); // } else if (obj instanceof Byte) { // cv.put(key, (Byte) obj); // } else if (obj instanceof Float) { // cv.put(key, (Float) obj); // } else if (obj instanceof Long) { // cv.put(key, (Long) obj); // } else if (obj instanceof Short) { // cv.put(key, (Short) obj); // } else if (obj == null) { // cv.putNull(key); // } else { // throw new WellException("Type " + obj.getClass().getSimpleName() + " unsupported, failed to create ContentValues. " + // "Write custom converter for " + item.getClass().getSimpleName() + " and register " + // "it in WellConfig."); // } // } // return cv; // } // // @Override // public T convert(Cursor item) { // Map<String, Object> map = new HashMap<>(); // for (String column : item.getColumnNames()) { // int columnIndex = item.getColumnIndex(column); // switch (item.getType(columnIndex)) { // case Cursor.FIELD_TYPE_INTEGER: // map.put(column, item.getLong(columnIndex)); // break; // case Cursor.FIELD_TYPE_STRING: // map.put(column, item.getString(columnIndex)); // break; // case Cursor.FIELD_TYPE_FLOAT: // map.put(column, item.getFloat(columnIndex)); // break; // case Cursor.FIELD_TYPE_BLOB: // map.put(column, item.getBlob(columnIndex)); // break; // } // } // return mMapper.convert(map); // } // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/DefaultWellConfig.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.yarolegovich.wellsql.core.Binder; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.core.TableLookup; import com.yarolegovich.wellsql.mapper.MapperAdapter; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public abstract class DefaultWellConfig implements WellConfig, WellConfig.OnUpgradeListener, WellConfig.OnCreateListener, WellConfig.OnDowngradeListener { private Context mContext; private TableLookup mGeneratedLookup; private Map<Class<?>, SQLiteMapper<?>> mMappers; public DefaultWellConfig(Context context) { mContext = context.getApplicationContext(); mMappers = new HashMap<>(); try { Class<? extends TableLookup> clazz = (Class<? extends TableLookup>) Class.forName(Binder.PACKAGE + "." + Binder.LOOKUP_CLASS); mGeneratedLookup = clazz.newInstance(); for (Class<?> token : mGeneratedLookup.getMapperTokens()) { mMappers.put(token, new MapperAdapter<>(mGeneratedLookup.getMapper(token))); } } catch (ClassNotFoundException e) { throw new WellException(mContext.getString(R.string.classes_not_found)); } catch (Exception e) { /* This can't be thrown, because Binder.LOOKUP_CLASS always will be instantiated successfully */ } mMappers.putAll(registerMappers()); } protected Map<Class<?>, SQLiteMapper<?>> registerMappers() { return Collections.emptyMap(); } @Override public OnUpgradeListener getOnUpgradeListener() { return this; } @Override public OnCreateListener getOnCreateListener() { return this; } @Override public OnDowngradeListener getOnDowngradeListener() { return this; } @Override public Context getContext() { return mContext; } @Override public <T> SQLiteMapper<T> getMapper(Class<T> token) { return (SQLiteMapper<T>) mMappers.get(token); } @Override
public TableClass getTable(Class<? extends Identifiable> token) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/InsertQuery.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.List;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public class InsertQuery<T extends Identifiable> {
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/InsertQuery.java import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.List; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public class InsertQuery<T extends Identifiable> {
private TableClass mTable;
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/InsertQuery.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.List;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public class InsertQuery<T extends Identifiable> { private TableClass mTable;
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/InsertQuery.java import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.List; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public class InsertQuery<T extends Identifiable> { private TableClass mTable;
private InsertMapper<T> mMapper;
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List;
@SuppressWarnings("unchecked") public WellSql(WellConfig config) { super(config.getContext(), config.getDbName(), null, config.getDbVersion()); } @Override public void onCreate(SQLiteDatabase db) { WellConfig.OnCreateListener l = mDbConfig.getOnCreateListener(); if (l != null) { l.onCreate(db, new WellTableManager(db)); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { WellConfig.OnUpgradeListener l = mDbConfig.getOnUpgradeListener(); if (l != null) { l.onUpgrade(db, new WellTableManager(db), oldVersion, newVersion); } } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { WellConfig.OnDowngradeListener l = mDbConfig.getOnDowngradeListener(); if (l != null) { l.onDowngrade(db, new WellTableManager(db), oldVersion, newVersion); } }
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List; @SuppressWarnings("unchecked") public WellSql(WellConfig config) { super(config.getContext(), config.getDbName(), null, config.getDbVersion()); } @Override public void onCreate(SQLiteDatabase db) { WellConfig.OnCreateListener l = mDbConfig.getOnCreateListener(); if (l != null) { l.onCreate(db, new WellTableManager(db)); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { WellConfig.OnUpgradeListener l = mDbConfig.getOnUpgradeListener(); if (l != null) { l.onUpgrade(db, new WellTableManager(db), oldVersion, newVersion); } } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { WellConfig.OnDowngradeListener l = mDbConfig.getOnDowngradeListener(); if (l != null) { l.onDowngrade(db, new WellTableManager(db), oldVersion, newVersion); } }
public static <T extends Identifiable> SelectQuery<T> selectUnique(Class<T> token) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List;
} public static <T extends Identifiable> InsertQuery<T> insert(T item) { return insert(Collections.singletonList(item)); } public static <T extends Identifiable> InsertQuery<T> insert(List<T> items) { return new InsertQuery<>(sInstance.getWritableDatabase(), items); } public static <T extends Identifiable> DeleteQuery<T> delete(Class<T> token) { return new DeleteQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable> UpdateQuery<T> update(Class<T> token) { return new UpdateQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable>ResetAutoincrementQuery autoincrementFor(Class<T> token) { return new ResetAutoincrementQuery(sInstance.getWritableDatabase(), tableFor(token).getTableName()); } public static SQLiteDatabase giveMeReadableDb() { return sInstance.getReadableDatabase(); } public static SQLiteDatabase giveMeWritableDb() { return sInstance.getWritableDatabase(); }
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List; } public static <T extends Identifiable> InsertQuery<T> insert(T item) { return insert(Collections.singletonList(item)); } public static <T extends Identifiable> InsertQuery<T> insert(List<T> items) { return new InsertQuery<>(sInstance.getWritableDatabase(), items); } public static <T extends Identifiable> DeleteQuery<T> delete(Class<T> token) { return new DeleteQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable> UpdateQuery<T> update(Class<T> token) { return new UpdateQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable>ResetAutoincrementQuery autoincrementFor(Class<T> token) { return new ResetAutoincrementQuery(sInstance.getWritableDatabase(), tableFor(token).getTableName()); } public static SQLiteDatabase giveMeReadableDb() { return sInstance.getReadableDatabase(); } public static SQLiteDatabase giveMeWritableDb() { return sInstance.getWritableDatabase(); }
public static <T> SQLiteMapper<T> mapperFor(Class<T> token) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List;
public static <T extends Identifiable> DeleteQuery<T> delete(Class<T> token) { return new DeleteQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable> UpdateQuery<T> update(Class<T> token) { return new UpdateQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable>ResetAutoincrementQuery autoincrementFor(Class<T> token) { return new ResetAutoincrementQuery(sInstance.getWritableDatabase(), tableFor(token).getTableName()); } public static SQLiteDatabase giveMeReadableDb() { return sInstance.getReadableDatabase(); } public static SQLiteDatabase giveMeWritableDb() { return sInstance.getWritableDatabase(); } public static <T> SQLiteMapper<T> mapperFor(Class<T> token) { SQLiteMapper<T> mapper = mDbConfig.getMapper(token); if (mapper == null) { throw new RuntimeException(mDbConfig.getContext() .getString(R.string.mapper_not_found, token.getSimpleName())); } return mapper; }
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/TableClass.java // public interface TableClass { // String createStatement(); // String getTableName(); // boolean shouldAutoincrementId(); // Class<?> getModelClass(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/WellSql.java import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.TableClass; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List; public static <T extends Identifiable> DeleteQuery<T> delete(Class<T> token) { return new DeleteQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable> UpdateQuery<T> update(Class<T> token) { return new UpdateQuery<>(sInstance.getWritableDatabase(), token); } public static <T extends Identifiable>ResetAutoincrementQuery autoincrementFor(Class<T> token) { return new ResetAutoincrementQuery(sInstance.getWritableDatabase(), tableFor(token).getTableName()); } public static SQLiteDatabase giveMeReadableDb() { return sInstance.getReadableDatabase(); } public static SQLiteDatabase giveMeWritableDb() { return sInstance.getWritableDatabase(); } public static <T> SQLiteMapper<T> mapperFor(Class<T> token) { SQLiteMapper<T> mapper = mDbConfig.getMapper(token); if (mapper == null) { throw new RuntimeException(mDbConfig.getContext() .getString(R.string.mapper_not_found, token.getSimpleName())); } return mapper; }
static <T extends Identifiable> TableClass tableFor(Class<T> token) {
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/UpdateQuery.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List;
package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public class UpdateQuery<T extends Identifiable> implements ConditionClauseConsumer { private final String WHERE_ID = "_id = ?"; private SQLiteDatabase mDb; private ContentValues mContentValues; private String mTableName; private String mSelection; private String[] mSelectionArgs;
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/UpdateQuery.java import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List; package com.yarolegovich.wellsql; /** * Created by yarolegovich on 26.11.2015. */ @SuppressWarnings("unchecked") public class UpdateQuery<T extends Identifiable> implements ConditionClauseConsumer { private final String WHERE_ID = "_id = ?"; private SQLiteDatabase mDb; private ContentValues mContentValues; private String mTableName; private String mSelection; private String[] mSelectionArgs;
private SQLiteMapper<T> mMapper;
yarolegovich/wellsql
wellsql/src/main/java/com/yarolegovich/wellsql/UpdateQuery.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {}
import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List;
mSelection = WHERE_ID; mSelectionArgs = new String[]{String.valueOf(id)}; return this; } public int replaceWhereId(T item) { return replaceWhereId(Collections.singletonList(item)); } public int replaceWhereId(List<T> items) { mSelection = WHERE_ID; int rowsAffected = 0; try { String[] args = new String[1]; for (T item : items) { args[0] = String.valueOf(item.getId()); ContentValues cv = mMapper.toCv(item); rowsAffected += mDb.update(mTableName, cv, mSelection, args); } } finally { mDb.close(); } return rowsAffected; } public UpdateQuery<T> put(T item) { mContentValues = mMapper.toCv(item); return this; }
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/InsertMapper.java // public interface InsertMapper<T> { // ContentValues toCv(T item); // } // // Path: wellsql/src/main/java/com/yarolegovich/wellsql/mapper/SQLiteMapper.java // public interface SQLiteMapper<T> extends InsertMapper<T>, SelectMapper<T> {} // Path: wellsql/src/main/java/com/yarolegovich/wellsql/UpdateQuery.java import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.mapper.InsertMapper; import com.yarolegovich.wellsql.mapper.SQLiteMapper; import java.util.Collections; import java.util.List; mSelection = WHERE_ID; mSelectionArgs = new String[]{String.valueOf(id)}; return this; } public int replaceWhereId(T item) { return replaceWhereId(Collections.singletonList(item)); } public int replaceWhereId(List<T> items) { mSelection = WHERE_ID; int rowsAffected = 0; try { String[] args = new String[1]; for (T item : items) { args[0] = String.valueOf(item.getId()); ContentValues cv = mMapper.toCv(item); rowsAffected += mDb.update(mTableName, cv, mSelection, args); } } finally { mDb.close(); } return rowsAffected; } public UpdateQuery<T> put(T item) { mContentValues = mMapper.toCv(item); return this; }
public UpdateQuery<T> put(T item, InsertMapper<T> mapper) {
yarolegovich/wellsql
well-sample/src/main/java/com/yarolegovich/wellsample/SuperHero.java
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // }
import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.annotation.Unique; import java.util.Date;
package com.yarolegovich.wellsample; /** * Created by yarolegovich on 27.11.2015. */ @Table @RawConstraints({"UNIQUE (NAME, fought)"})
// Path: well-annotations/src/main/java/com/yarolegovich/wellsql/core/Identifiable.java // public interface Identifiable { // void setId(int id); // int getId(); // } // Path: well-sample/src/main/java/com/yarolegovich/wellsample/SuperHero.java import com.yarolegovich.wellsql.core.Identifiable; import com.yarolegovich.wellsql.core.annotation.Check; import com.yarolegovich.wellsql.core.annotation.Column; import com.yarolegovich.wellsql.core.annotation.PrimaryKey; import com.yarolegovich.wellsql.core.annotation.RawConstraints; import com.yarolegovich.wellsql.core.annotation.Table; import com.yarolegovich.wellsql.core.annotation.Unique; import java.util.Date; package com.yarolegovich.wellsample; /** * Created by yarolegovich on 27.11.2015. */ @Table @RawConstraints({"UNIQUE (NAME, fought)"})
public class SuperHero implements Identifiable {
jMotif/sax-vsm_classic
src/main/java/net/seninp/jmotif/cluster/FurthestFirstStrategy.java
// Path: src/main/java/net/seninp/jmotif/text/CosineDistanceMatrix.java // public class CosineDistanceMatrix { // // /** Distance matrix. */ // private double[][] distances; // // /** Row names. */ // private String[] rows; // // private HashMap<String, Integer> keysToIndex = new HashMap<String, Integer>(); // // private static final String COMMA = ","; // private static final String CR = "\n"; // private static final DecimalFormat df = new DecimalFormat("#0.00000"); // // private static final TextProcessor tp = new TextProcessor(); // // /** // * Builds a distance matrix. // * // * @param tfidf The data to use. // */ // public CosineDistanceMatrix(HashMap<String, HashMap<String, Double>> tfidf) { // // Locale.setDefault(Locale.US); // // rows = tfidf.keySet().toArray(new String[0]); // // Arrays.sort(rows); // // distances = new double[rows.length][rows.length]; // // for (int i = 0; i < rows.length; i++) { // keysToIndex.put(rows[i], i); // for (int j = 0; j < i; j++) { // HashMap<String, Double> vectorA = tfidf.get(rows[i]); // HashMap<String, Double> vectorB = tfidf.get(rows[j]); // double distance = tp.cosineDistance(vectorA, vectorB); // distances[i][j] = distance; // } // } // } // // /** // * Get all the row names - i.e. keys. // * // * @return row names. // */ // public String[] getRows() { // return this.rows; // } // // /** // * Get the distances as matrix. // * // * @return the distance matrix. // */ // public double[][] getDistances() { // return this.distances; // } // // /** // * Prints matrix. // */ // @Override // public String toString() { // // StringBuffer sb = new StringBuffer(); // // sb.append("\"\","); // for (String s : rows) { // sb.append("\"").append(s).append("\"").append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // // for (int i = 0; i < rows.length; i++) { // sb.append("\"").append(rows[i]).append("\","); // for (int j = 0; j < rows.length; j++) { // sb.append(df.format(distances[i][j])).append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // } // // return sb.toString(); // } // // /** // * get the distance value between two keys. // * // * @param keyA first key. // * @param keyB second key. // * @return the distance between vectors. // */ // public double distanceBetween(String keyA, String keyB) { // if (keysToIndex.get(keyA) >= keysToIndex.get(keyB)) { // return distances[keysToIndex.get(keyA)][keysToIndex.get(keyB)]; // } // return distances[keysToIndex.get(keyB)][keysToIndex.get(keyA)]; // } // // /** // * This will subtract all distance values from 1 - so distance becomes inversed - good for // * clustering. // */ // public void transformForHC() { // for (int i = 0; i < distances.length; i++) { // for (int j = 0; j < distances[0].length; j++) { // distances[i][j] = 1.0D - distances[i][j]; // } // } // } // // }
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.Random; import java.util.TreeSet; import net.seninp.jmotif.text.CosineDistanceMatrix;
package net.seninp.jmotif.cluster; public class FurthestFirstStrategy implements StartStrategy { @Override public LinkedHashMap<String, HashMap<String, Double>> getCentroids(Integer num, HashMap<String, HashMap<String, Double>> data) { Random random = new Random(); // need to make distance matrix for all the words in here //
// Path: src/main/java/net/seninp/jmotif/text/CosineDistanceMatrix.java // public class CosineDistanceMatrix { // // /** Distance matrix. */ // private double[][] distances; // // /** Row names. */ // private String[] rows; // // private HashMap<String, Integer> keysToIndex = new HashMap<String, Integer>(); // // private static final String COMMA = ","; // private static final String CR = "\n"; // private static final DecimalFormat df = new DecimalFormat("#0.00000"); // // private static final TextProcessor tp = new TextProcessor(); // // /** // * Builds a distance matrix. // * // * @param tfidf The data to use. // */ // public CosineDistanceMatrix(HashMap<String, HashMap<String, Double>> tfidf) { // // Locale.setDefault(Locale.US); // // rows = tfidf.keySet().toArray(new String[0]); // // Arrays.sort(rows); // // distances = new double[rows.length][rows.length]; // // for (int i = 0; i < rows.length; i++) { // keysToIndex.put(rows[i], i); // for (int j = 0; j < i; j++) { // HashMap<String, Double> vectorA = tfidf.get(rows[i]); // HashMap<String, Double> vectorB = tfidf.get(rows[j]); // double distance = tp.cosineDistance(vectorA, vectorB); // distances[i][j] = distance; // } // } // } // // /** // * Get all the row names - i.e. keys. // * // * @return row names. // */ // public String[] getRows() { // return this.rows; // } // // /** // * Get the distances as matrix. // * // * @return the distance matrix. // */ // public double[][] getDistances() { // return this.distances; // } // // /** // * Prints matrix. // */ // @Override // public String toString() { // // StringBuffer sb = new StringBuffer(); // // sb.append("\"\","); // for (String s : rows) { // sb.append("\"").append(s).append("\"").append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // // for (int i = 0; i < rows.length; i++) { // sb.append("\"").append(rows[i]).append("\","); // for (int j = 0; j < rows.length; j++) { // sb.append(df.format(distances[i][j])).append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // } // // return sb.toString(); // } // // /** // * get the distance value between two keys. // * // * @param keyA first key. // * @param keyB second key. // * @return the distance between vectors. // */ // public double distanceBetween(String keyA, String keyB) { // if (keysToIndex.get(keyA) >= keysToIndex.get(keyB)) { // return distances[keysToIndex.get(keyA)][keysToIndex.get(keyB)]; // } // return distances[keysToIndex.get(keyB)][keysToIndex.get(keyA)]; // } // // /** // * This will subtract all distance values from 1 - so distance becomes inversed - good for // * clustering. // */ // public void transformForHC() { // for (int i = 0; i < distances.length; i++) { // for (int j = 0; j < distances[0].length; j++) { // distances[i][j] = 1.0D - distances[i][j]; // } // } // } // // } // Path: src/main/java/net/seninp/jmotif/cluster/FurthestFirstStrategy.java import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.Random; import java.util.TreeSet; import net.seninp.jmotif.text.CosineDistanceMatrix; package net.seninp.jmotif.cluster; public class FurthestFirstStrategy implements StartStrategy { @Override public LinkedHashMap<String, HashMap<String, Double>> getCentroids(Integer num, HashMap<String, HashMap<String, Double>> data) { Random random = new Random(); // need to make distance matrix for all the words in here //
CosineDistanceMatrix matrix = new CosineDistanceMatrix(data);
jMotif/sax-vsm_classic
src/main/java/net/seninp/jmotif/cluster/HC.java
// Path: src/main/java/net/seninp/jmotif/text/CosineDistanceMatrix.java // public class CosineDistanceMatrix { // // /** Distance matrix. */ // private double[][] distances; // // /** Row names. */ // private String[] rows; // // private HashMap<String, Integer> keysToIndex = new HashMap<String, Integer>(); // // private static final String COMMA = ","; // private static final String CR = "\n"; // private static final DecimalFormat df = new DecimalFormat("#0.00000"); // // private static final TextProcessor tp = new TextProcessor(); // // /** // * Builds a distance matrix. // * // * @param tfidf The data to use. // */ // public CosineDistanceMatrix(HashMap<String, HashMap<String, Double>> tfidf) { // // Locale.setDefault(Locale.US); // // rows = tfidf.keySet().toArray(new String[0]); // // Arrays.sort(rows); // // distances = new double[rows.length][rows.length]; // // for (int i = 0; i < rows.length; i++) { // keysToIndex.put(rows[i], i); // for (int j = 0; j < i; j++) { // HashMap<String, Double> vectorA = tfidf.get(rows[i]); // HashMap<String, Double> vectorB = tfidf.get(rows[j]); // double distance = tp.cosineDistance(vectorA, vectorB); // distances[i][j] = distance; // } // } // } // // /** // * Get all the row names - i.e. keys. // * // * @return row names. // */ // public String[] getRows() { // return this.rows; // } // // /** // * Get the distances as matrix. // * // * @return the distance matrix. // */ // public double[][] getDistances() { // return this.distances; // } // // /** // * Prints matrix. // */ // @Override // public String toString() { // // StringBuffer sb = new StringBuffer(); // // sb.append("\"\","); // for (String s : rows) { // sb.append("\"").append(s).append("\"").append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // // for (int i = 0; i < rows.length; i++) { // sb.append("\"").append(rows[i]).append("\","); // for (int j = 0; j < rows.length; j++) { // sb.append(df.format(distances[i][j])).append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // } // // return sb.toString(); // } // // /** // * get the distance value between two keys. // * // * @param keyA first key. // * @param keyB second key. // * @return the distance between vectors. // */ // public double distanceBetween(String keyA, String keyB) { // if (keysToIndex.get(keyA) >= keysToIndex.get(keyB)) { // return distances[keysToIndex.get(keyA)][keysToIndex.get(keyB)]; // } // return distances[keysToIndex.get(keyB)][keysToIndex.get(keyA)]; // } // // /** // * This will subtract all distance values from 1 - so distance becomes inversed - good for // * clustering. // */ // public void transformForHC() { // for (int i = 0; i < distances.length; i++) { // for (int j = 0; j < distances[0].length; j++) { // distances[i][j] = 1.0D - distances[i][j]; // } // } // } // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Stack; import net.seninp.jmotif.text.CosineDistanceMatrix;
package net.seninp.jmotif.cluster; /** * Hierarchical clustering factory. * * @author psenin * */ public class HC { /** * Implements hierarchical clustering for word bags. * * @param tfidfData The data to cluster. * @param criterion The linkage criterion. * @return The resulting cluster structure. */ public static Cluster Hc(HashMap<String, HashMap<String, Double>> tfidfData, LinkageCriterion criterion) { // pre-compute distances matrix //
// Path: src/main/java/net/seninp/jmotif/text/CosineDistanceMatrix.java // public class CosineDistanceMatrix { // // /** Distance matrix. */ // private double[][] distances; // // /** Row names. */ // private String[] rows; // // private HashMap<String, Integer> keysToIndex = new HashMap<String, Integer>(); // // private static final String COMMA = ","; // private static final String CR = "\n"; // private static final DecimalFormat df = new DecimalFormat("#0.00000"); // // private static final TextProcessor tp = new TextProcessor(); // // /** // * Builds a distance matrix. // * // * @param tfidf The data to use. // */ // public CosineDistanceMatrix(HashMap<String, HashMap<String, Double>> tfidf) { // // Locale.setDefault(Locale.US); // // rows = tfidf.keySet().toArray(new String[0]); // // Arrays.sort(rows); // // distances = new double[rows.length][rows.length]; // // for (int i = 0; i < rows.length; i++) { // keysToIndex.put(rows[i], i); // for (int j = 0; j < i; j++) { // HashMap<String, Double> vectorA = tfidf.get(rows[i]); // HashMap<String, Double> vectorB = tfidf.get(rows[j]); // double distance = tp.cosineDistance(vectorA, vectorB); // distances[i][j] = distance; // } // } // } // // /** // * Get all the row names - i.e. keys. // * // * @return row names. // */ // public String[] getRows() { // return this.rows; // } // // /** // * Get the distances as matrix. // * // * @return the distance matrix. // */ // public double[][] getDistances() { // return this.distances; // } // // /** // * Prints matrix. // */ // @Override // public String toString() { // // StringBuffer sb = new StringBuffer(); // // sb.append("\"\","); // for (String s : rows) { // sb.append("\"").append(s).append("\"").append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // // for (int i = 0; i < rows.length; i++) { // sb.append("\"").append(rows[i]).append("\","); // for (int j = 0; j < rows.length; j++) { // sb.append(df.format(distances[i][j])).append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // } // // return sb.toString(); // } // // /** // * get the distance value between two keys. // * // * @param keyA first key. // * @param keyB second key. // * @return the distance between vectors. // */ // public double distanceBetween(String keyA, String keyB) { // if (keysToIndex.get(keyA) >= keysToIndex.get(keyB)) { // return distances[keysToIndex.get(keyA)][keysToIndex.get(keyB)]; // } // return distances[keysToIndex.get(keyB)][keysToIndex.get(keyA)]; // } // // /** // * This will subtract all distance values from 1 - so distance becomes inversed - good for // * clustering. // */ // public void transformForHC() { // for (int i = 0; i < distances.length; i++) { // for (int j = 0; j < distances[0].length; j++) { // distances[i][j] = 1.0D - distances[i][j]; // } // } // } // // } // Path: src/main/java/net/seninp/jmotif/cluster/HC.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Stack; import net.seninp.jmotif.text.CosineDistanceMatrix; package net.seninp.jmotif.cluster; /** * Hierarchical clustering factory. * * @author psenin * */ public class HC { /** * Implements hierarchical clustering for word bags. * * @param tfidfData The data to cluster. * @param criterion The linkage criterion. * @return The resulting cluster structure. */ public static Cluster Hc(HashMap<String, HashMap<String, Double>> tfidfData, LinkageCriterion criterion) { // pre-compute distances matrix //
CosineDistanceMatrix distanceMatrix = new CosineDistanceMatrix(tfidfData);
jMotif/sax-vsm_classic
src/main/java/net/seninp/jmotif/cluster/Cluster.java
// Path: src/main/java/net/seninp/jmotif/text/CosineDistanceMatrix.java // public class CosineDistanceMatrix { // // /** Distance matrix. */ // private double[][] distances; // // /** Row names. */ // private String[] rows; // // private HashMap<String, Integer> keysToIndex = new HashMap<String, Integer>(); // // private static final String COMMA = ","; // private static final String CR = "\n"; // private static final DecimalFormat df = new DecimalFormat("#0.00000"); // // private static final TextProcessor tp = new TextProcessor(); // // /** // * Builds a distance matrix. // * // * @param tfidf The data to use. // */ // public CosineDistanceMatrix(HashMap<String, HashMap<String, Double>> tfidf) { // // Locale.setDefault(Locale.US); // // rows = tfidf.keySet().toArray(new String[0]); // // Arrays.sort(rows); // // distances = new double[rows.length][rows.length]; // // for (int i = 0; i < rows.length; i++) { // keysToIndex.put(rows[i], i); // for (int j = 0; j < i; j++) { // HashMap<String, Double> vectorA = tfidf.get(rows[i]); // HashMap<String, Double> vectorB = tfidf.get(rows[j]); // double distance = tp.cosineDistance(vectorA, vectorB); // distances[i][j] = distance; // } // } // } // // /** // * Get all the row names - i.e. keys. // * // * @return row names. // */ // public String[] getRows() { // return this.rows; // } // // /** // * Get the distances as matrix. // * // * @return the distance matrix. // */ // public double[][] getDistances() { // return this.distances; // } // // /** // * Prints matrix. // */ // @Override // public String toString() { // // StringBuffer sb = new StringBuffer(); // // sb.append("\"\","); // for (String s : rows) { // sb.append("\"").append(s).append("\"").append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // // for (int i = 0; i < rows.length; i++) { // sb.append("\"").append(rows[i]).append("\","); // for (int j = 0; j < rows.length; j++) { // sb.append(df.format(distances[i][j])).append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // } // // return sb.toString(); // } // // /** // * get the distance value between two keys. // * // * @param keyA first key. // * @param keyB second key. // * @return the distance between vectors. // */ // public double distanceBetween(String keyA, String keyB) { // if (keysToIndex.get(keyA) >= keysToIndex.get(keyB)) { // return distances[keysToIndex.get(keyA)][keysToIndex.get(keyB)]; // } // return distances[keysToIndex.get(keyB)][keysToIndex.get(keyA)]; // } // // /** // * This will subtract all distance values from 1 - so distance becomes inversed - good for // * clustering. // */ // public void transformForHC() { // for (int i = 0; i < distances.length; i++) { // for (int j = 0; j < distances[0].length; j++) { // distances[i][j] = 1.0D - distances[i][j]; // } // } // } // // }
import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.HashMap; import java.util.TreeSet; import net.seninp.jmotif.text.CosineDistanceMatrix;
package net.seninp.jmotif.cluster; /** * Implements a cluster node for SAX terms clustering. * * @author psenin * */ public class Cluster { /** The left sub-cluster. */ public Cluster left = null; /** The right sub-cluster. */ public Cluster right = null; /** The level from the root. */ public int level; /** The distance between left and right sub-clusters. */ public double distanceBetween; /** The keys. Words which are within this cluster. */ private TreeSet<String> keys; /** * Constructor. */ public Cluster() { super(); } /** * Constructor. * * @param key The single name of the cluster. */ public Cluster(String key) { super(); this.keys = new TreeSet<String>(); keys.add(key); } /** * Merging together clusters. * * @param left the left cluster. * @param right the right cluster. * @param distance the distance between clusters. */ public void merge(Cluster left, Cluster right, Double distance) { this.left = left; this.right = right; this.keys = new TreeSet<String>(); this.keys.addAll(left.keys); this.keys.addAll(right.keys); this.distanceBetween = distance; } /** * Compute the distance between words clusters. * * @param otherCluster the other cluster. * @param data this cluster. * @param distanceMatrix the pre-computed distance matrix. * @param criterion the linkage criterion. * @return the distance between clusters based on the distances and the linkage. */ public Double distanceTo(Cluster otherCluster, HashMap<String, HashMap<String, Double>> data,
// Path: src/main/java/net/seninp/jmotif/text/CosineDistanceMatrix.java // public class CosineDistanceMatrix { // // /** Distance matrix. */ // private double[][] distances; // // /** Row names. */ // private String[] rows; // // private HashMap<String, Integer> keysToIndex = new HashMap<String, Integer>(); // // private static final String COMMA = ","; // private static final String CR = "\n"; // private static final DecimalFormat df = new DecimalFormat("#0.00000"); // // private static final TextProcessor tp = new TextProcessor(); // // /** // * Builds a distance matrix. // * // * @param tfidf The data to use. // */ // public CosineDistanceMatrix(HashMap<String, HashMap<String, Double>> tfidf) { // // Locale.setDefault(Locale.US); // // rows = tfidf.keySet().toArray(new String[0]); // // Arrays.sort(rows); // // distances = new double[rows.length][rows.length]; // // for (int i = 0; i < rows.length; i++) { // keysToIndex.put(rows[i], i); // for (int j = 0; j < i; j++) { // HashMap<String, Double> vectorA = tfidf.get(rows[i]); // HashMap<String, Double> vectorB = tfidf.get(rows[j]); // double distance = tp.cosineDistance(vectorA, vectorB); // distances[i][j] = distance; // } // } // } // // /** // * Get all the row names - i.e. keys. // * // * @return row names. // */ // public String[] getRows() { // return this.rows; // } // // /** // * Get the distances as matrix. // * // * @return the distance matrix. // */ // public double[][] getDistances() { // return this.distances; // } // // /** // * Prints matrix. // */ // @Override // public String toString() { // // StringBuffer sb = new StringBuffer(); // // sb.append("\"\","); // for (String s : rows) { // sb.append("\"").append(s).append("\"").append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // // for (int i = 0; i < rows.length; i++) { // sb.append("\"").append(rows[i]).append("\","); // for (int j = 0; j < rows.length; j++) { // sb.append(df.format(distances[i][j])).append(COMMA); // } // sb.delete(sb.length() - 1, sb.length()).append(CR); // } // // return sb.toString(); // } // // /** // * get the distance value between two keys. // * // * @param keyA first key. // * @param keyB second key. // * @return the distance between vectors. // */ // public double distanceBetween(String keyA, String keyB) { // if (keysToIndex.get(keyA) >= keysToIndex.get(keyB)) { // return distances[keysToIndex.get(keyA)][keysToIndex.get(keyB)]; // } // return distances[keysToIndex.get(keyB)][keysToIndex.get(keyA)]; // } // // /** // * This will subtract all distance values from 1 - so distance becomes inversed - good for // * clustering. // */ // public void transformForHC() { // for (int i = 0; i < distances.length; i++) { // for (int j = 0; j < distances[0].length; j++) { // distances[i][j] = 1.0D - distances[i][j]; // } // } // } // // } // Path: src/main/java/net/seninp/jmotif/cluster/Cluster.java import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.HashMap; import java.util.TreeSet; import net.seninp.jmotif.text.CosineDistanceMatrix; package net.seninp.jmotif.cluster; /** * Implements a cluster node for SAX terms clustering. * * @author psenin * */ public class Cluster { /** The left sub-cluster. */ public Cluster left = null; /** The right sub-cluster. */ public Cluster right = null; /** The level from the root. */ public int level; /** The distance between left and right sub-clusters. */ public double distanceBetween; /** The keys. Words which are within this cluster. */ private TreeSet<String> keys; /** * Constructor. */ public Cluster() { super(); } /** * Constructor. * * @param key The single name of the cluster. */ public Cluster(String key) { super(); this.keys = new TreeSet<String>(); keys.add(key); } /** * Merging together clusters. * * @param left the left cluster. * @param right the right cluster. * @param distance the distance between clusters. */ public void merge(Cluster left, Cluster right, Double distance) { this.left = left; this.right = right; this.keys = new TreeSet<String>(); this.keys.addAll(left.keys); this.keys.addAll(right.keys); this.distanceBetween = distance; } /** * Compute the distance between words clusters. * * @param otherCluster the other cluster. * @param data this cluster. * @param distanceMatrix the pre-computed distance matrix. * @param criterion the linkage criterion. * @return the distance between clusters based on the distances and the linkage. */ public Double distanceTo(Cluster otherCluster, HashMap<String, HashMap<String, Double>> data,
CosineDistanceMatrix distanceMatrix, LinkageCriterion criterion) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/TopFieldTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/TopFieldValue.java // public class TopFieldValue extends FieldValue { // private static final TopFieldValue instance = new TopFieldValue(); // // private TopFieldValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static TopFieldValue v() { // return instance; // } // // @Override // public String toString() { // return "top"; // } // // @Override // public Object getValue() { // throw new RuntimeException("Cannot get value for top field value"); // } // }
import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A top field transformer, which maps any {@link FieldValue} to an unknown value. This is a * singleton. */ public class TopFieldTransformer extends FieldTransformer { private static final TopFieldTransformer instance = new TopFieldTransformer(); private TopFieldTransformer() { } /** * Returns the singleton instance for this class. * * @return The singleton instance for this class. */ public static TopFieldTransformer v() { return instance; } @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/TopFieldValue.java // public class TopFieldValue extends FieldValue { // private static final TopFieldValue instance = new TopFieldValue(); // // private TopFieldValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static TopFieldValue v() { // return instance; // } // // @Override // public String toString() { // return "top"; // } // // @Override // public Object getValue() { // throw new RuntimeException("Cannot get value for top field value"); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/TopFieldTransformer.java import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A top field transformer, which maps any {@link FieldValue} to an unknown value. This is a * singleton. */ public class TopFieldTransformer extends FieldTransformer { private static final TopFieldTransformer instance = new TopFieldTransformer(); private TopFieldTransformer() { } /** * Returns the singleton instance for this class. * * @return The singleton instance for this class. */ public static TopFieldTransformer v() { return instance; } @Override
public FieldValue apply(FieldValue fieldValue) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/TopFieldTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/TopFieldValue.java // public class TopFieldValue extends FieldValue { // private static final TopFieldValue instance = new TopFieldValue(); // // private TopFieldValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static TopFieldValue v() { // return instance; // } // // @Override // public String toString() { // return "top"; // } // // @Override // public Object getValue() { // throw new RuntimeException("Cannot get value for top field value"); // } // }
import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A top field transformer, which maps any {@link FieldValue} to an unknown value. This is a * singleton. */ public class TopFieldTransformer extends FieldTransformer { private static final TopFieldTransformer instance = new TopFieldTransformer(); private TopFieldTransformer() { } /** * Returns the singleton instance for this class. * * @return The singleton instance for this class. */ public static TopFieldTransformer v() { return instance; } @Override public FieldValue apply(FieldValue fieldValue) {
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/TopFieldValue.java // public class TopFieldValue extends FieldValue { // private static final TopFieldValue instance = new TopFieldValue(); // // private TopFieldValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static TopFieldValue v() { // return instance; // } // // @Override // public String toString() { // return "top"; // } // // @Override // public Object getValue() { // throw new RuntimeException("Cannot get value for top field value"); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/TopFieldTransformer.java import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A top field transformer, which maps any {@link FieldValue} to an unknown value. This is a * singleton. */ public class TopFieldTransformer extends FieldTransformer { private static final TopFieldTransformer instance = new TopFieldTransformer(); private TopFieldTransformer() { } /** * Returns the singleton instance for this class. * * @return The singleton instance for this class. */ public static TopFieldTransformer v() { return instance; } @Override public FieldValue apply(FieldValue fieldValue) {
return TopFieldValue.v();
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/Remove.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // }
import java.util.HashSet; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A field transformer for remove operations; */ public class Remove extends SetFieldTransformer { public Remove(Object value) { this.remove = new HashSet<>(2); this.remove.add(value); } public Remove(Remove remove1, Remove remove2) { this.remove = new HashSet<>(remove1.remove); this.remove.addAll(remove2.remove); } @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/Remove.java import java.util.HashSet; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A field transformer for remove operations; */ public class Remove extends SetFieldTransformer { public Remove(Object value) { this.remove = new HashSet<>(2); this.remove.add(value); } public Remove(Remove remove1, Remove remove2) { this.remove = new HashSet<>(remove1.remove); this.remove.addAll(remove2.remove); } @Override
public FieldTransformer compose(FieldTransformer secondFieldOperation) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/SequenceElement.java
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // }
import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A element that represents the influence of a modifier after a value composition. This is not be * used in the iterative version of the algorithm. After we encounter a modifier that makes a * reference to another COAL value, we record further transformers for the same field in this * element. */ public class SequenceElement { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Value symbol; private final Stmt stmt; private final String op;
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/SequenceElement.java import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A element that represents the influence of a modifier after a value composition. This is not be * used in the iterative version of the algorithm. After we encounter a modifier that makes a * reference to another COAL value, we record further transformers for the same field in this * element. */ public class SequenceElement { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Value symbol; private final Stmt stmt; private final String op;
private FieldTransformer fieldTransformer;
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/SequenceElement.java
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // }
import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A element that represents the influence of a modifier after a value composition. This is not be * used in the iterative version of the algorithm. After we encounter a modifier that makes a * reference to another COAL value, we record further transformers for the same field in this * element. */ public class SequenceElement { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Value symbol; private final Stmt stmt; private final String op; private FieldTransformer fieldTransformer; public SequenceElement(Value symbol, Stmt stmt, String op) { this.symbol = symbol; this.stmt = stmt; this.op = op;
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/SequenceElement.java import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A element that represents the influence of a modifier after a value composition. This is not be * used in the iterative version of the algorithm. After we encounter a modifier that makes a * reference to another COAL value, we record further transformers for the same field in this * element. */ public class SequenceElement { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Value symbol; private final Stmt stmt; private final String op; private FieldTransformer fieldTransformer; public SequenceElement(Value symbol, Stmt stmt, String op) { this.symbol = symbol; this.stmt = stmt; this.op = op;
this.fieldTransformer = IdentityFieldTransformer.v();
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/SequenceElement.java
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // }
import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A element that represents the influence of a modifier after a value composition. This is not be * used in the iterative version of the algorithm. After we encounter a modifier that makes a * reference to another COAL value, we record further transformers for the same field in this * element. */ public class SequenceElement { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Value symbol; private final Stmt stmt; private final String op; private FieldTransformer fieldTransformer; public SequenceElement(Value symbol, Stmt stmt, String op) { this.symbol = symbol; this.stmt = stmt; this.op = op; this.fieldTransformer = IdentityFieldTransformer.v(); } public void composeWith(FieldTransformer newFieldTransformer) { this.fieldTransformer = this.fieldTransformer.compose(newFieldTransformer); } /** * Generates transformers that represent the influence of this element, including any field * transformer that was encountered after the COAL value composition. * * @param field The field that is modified. * @param solver A propagation solver. * @return The set of field transformers that represent this element. */
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/SequenceElement.java import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A element that represents the influence of a modifier after a value composition. This is not be * used in the iterative version of the algorithm. After we encounter a modifier that makes a * reference to another COAL value, we record further transformers for the same field in this * element. */ public class SequenceElement { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Value symbol; private final Stmt stmt; private final String op; private FieldTransformer fieldTransformer; public SequenceElement(Value symbol, Stmt stmt, String op) { this.symbol = symbol; this.stmt = stmt; this.op = op; this.fieldTransformer = IdentityFieldTransformer.v(); } public void composeWith(FieldTransformer newFieldTransformer) { this.fieldTransformer = this.fieldTransformer.compose(newFieldTransformer); } /** * Generates transformers that represent the influence of this element, including any field * transformer that was encountered after the COAL value composition. * * @param field The field that is modified. * @param solver A propagation solver. * @return The set of field transformers that represent this element. */
public Set<FieldTransformer> makeFinalTransformers(String field, PropagationSolver solver) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/PropagationProblem.java
// Path: src/main/java/edu/psu/cse/siis/coal/transformers/AllTopEdgeFunction.java // public class AllTopEdgeFunction extends AllBottom<BasePropagationValue> { // public AllTopEdgeFunction() { // super(BottomPropagationValue.v()); // } // // @Override // public BasePropagationValue computeTarget(BasePropagationValue source) { // return source; // } // // @Override // public EdgeFunction<BasePropagationValue> joinWith( // EdgeFunction<BasePropagationValue> otherFunction) { // return otherFunction; // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // }
import heros.DefaultSeeds; import heros.EdgeFunction; import heros.EdgeFunctions; import heros.FlowFunction; import heros.FlowFunctions; import heros.JoinLattice; import heros.edgefunc.EdgeIdentity; import heros.template.DefaultIDETabulationProblem; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.NullType; import soot.PointsToAnalysis; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; import edu.psu.cse.siis.coal.transformers.AllTopEdgeFunction; import edu.psu.cse.siis.coal.values.BasePropagationValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * Definition of the IDE problem for MVMF constant propagation. */ public class PropagationProblem extends
// Path: src/main/java/edu/psu/cse/siis/coal/transformers/AllTopEdgeFunction.java // public class AllTopEdgeFunction extends AllBottom<BasePropagationValue> { // public AllTopEdgeFunction() { // super(BottomPropagationValue.v()); // } // // @Override // public BasePropagationValue computeTarget(BasePropagationValue source) { // return source; // } // // @Override // public EdgeFunction<BasePropagationValue> joinWith( // EdgeFunction<BasePropagationValue> otherFunction) { // return otherFunction; // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // Path: src/main/java/edu/psu/cse/siis/coal/PropagationProblem.java import heros.DefaultSeeds; import heros.EdgeFunction; import heros.EdgeFunctions; import heros.FlowFunction; import heros.FlowFunctions; import heros.JoinLattice; import heros.edgefunc.EdgeIdentity; import heros.template.DefaultIDETabulationProblem; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.NullType; import soot.PointsToAnalysis; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; import edu.psu.cse.siis.coal.transformers.AllTopEdgeFunction; import edu.psu.cse.siis.coal.values.BasePropagationValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * Definition of the IDE problem for MVMF constant propagation. */ public class PropagationProblem extends
DefaultIDETabulationProblem<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> {
siis/coal
src/main/java/edu/psu/cse/siis/coal/PropagationProblem.java
// Path: src/main/java/edu/psu/cse/siis/coal/transformers/AllTopEdgeFunction.java // public class AllTopEdgeFunction extends AllBottom<BasePropagationValue> { // public AllTopEdgeFunction() { // super(BottomPropagationValue.v()); // } // // @Override // public BasePropagationValue computeTarget(BasePropagationValue source) { // return source; // } // // @Override // public EdgeFunction<BasePropagationValue> joinWith( // EdgeFunction<BasePropagationValue> otherFunction) { // return otherFunction; // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // }
import heros.DefaultSeeds; import heros.EdgeFunction; import heros.EdgeFunctions; import heros.FlowFunction; import heros.FlowFunctions; import heros.JoinLattice; import heros.edgefunc.EdgeIdentity; import heros.template.DefaultIDETabulationProblem; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.NullType; import soot.PointsToAnalysis; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; import edu.psu.cse.siis.coal.transformers.AllTopEdgeFunction; import edu.psu.cse.siis.coal.values.BasePropagationValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * Definition of the IDE problem for MVMF constant propagation. */ public class PropagationProblem extends DefaultIDETabulationProblem<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> {
// Path: src/main/java/edu/psu/cse/siis/coal/transformers/AllTopEdgeFunction.java // public class AllTopEdgeFunction extends AllBottom<BasePropagationValue> { // public AllTopEdgeFunction() { // super(BottomPropagationValue.v()); // } // // @Override // public BasePropagationValue computeTarget(BasePropagationValue source) { // return source; // } // // @Override // public EdgeFunction<BasePropagationValue> joinWith( // EdgeFunction<BasePropagationValue> otherFunction) { // return otherFunction; // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // Path: src/main/java/edu/psu/cse/siis/coal/PropagationProblem.java import heros.DefaultSeeds; import heros.EdgeFunction; import heros.EdgeFunctions; import heros.FlowFunction; import heros.FlowFunctions; import heros.JoinLattice; import heros.edgefunc.EdgeIdentity; import heros.template.DefaultIDETabulationProblem; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.NullType; import soot.PointsToAnalysis; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; import edu.psu.cse.siis.coal.transformers.AllTopEdgeFunction; import edu.psu.cse.siis.coal.values.BasePropagationValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * Definition of the IDE problem for MVMF constant propagation. */ public class PropagationProblem extends DefaultIDETabulationProblem<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> {
public static final EdgeFunction<BasePropagationValue> ALL_TOP = new AllTopEdgeFunction();
siis/coal
src/main/java/edu/psu/cse/siis/coal/PropagationSceneTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/arguments/StringValueAnalysis.java // public class StringValueAnalysis extends ArgumentValueAnalysis { // private static final String TOP_VALUE = Constants.ANY_STRING; // // /** // * Initializes the string argument value analysis. This should be called before using the // * analysis. // */ // public static void initialize() { // // CCExprVisitor.verbose_level = 20; // // CCVisitor.verbose_level = 20; // // DBG.verbose_level = 20; // ConstraintCollector.globalCollection(new ConstraintCollector.CCModelInterface() { // public boolean isExcludedClass(String class_name) { // return false; // } // }); // } // // @Override // public Set<Object> computeInlineArgumentValues(String[] inlineValues) { // return new HashSet<Object>(Arrays.asList(inlineValues)); // } // // /** // * Returns the string values of a variable used at a given statement. // * // * @param value The value or variable that should be determined. // * @param stmt The statement that uses the variable whose values should be determined. // * @return The set of possible values. // */ // @Override // public Set<Object> computeVariableValues(Value value, Stmt stmt) { // if (value instanceof StringConstant) { // return Collections.singleton((Object) ((StringConstant) value).value.intern()); // } else if (value instanceof NullConstant) { // return Collections.singleton((Object) "<NULL>"); // } else if (value instanceof Local) { // Local local = (Local) value; // // ConstraintCollector constraintCollector = // new ConstraintCollector(new ExceptionalUnitGraph(AnalysisParameters.v().getIcfg() // .getMethodOf(stmt).getActiveBody())); // LanguageConstraints.Box lcb = constraintCollector.getConstraintOfAt(local, stmt); // RecursiveDAGSolverVisitorLC dagvlc = // new RecursiveDAGSolverVisitorLC(5, null, // new RecursiveDAGSolverVisitorLC.MethodReturnValueAnalysisInterface() { // @Override // public Set<Object> getMethodReturnValues(Call call) { // return MethodReturnValueManager.v().getMethodReturnValues(call); // } // }); // // if (dagvlc.solve(lcb)) { // // boolean flag = false; // // if (dagvlc.result.size() == 0 || flag == true) { // // System.out.println("ID: " + lcb.uid); // // // int dbg = 10; // // // while (dbg == 10) { // // System.out.println("Returning " + dagvlc.result); // // System.out.println("Returning.. " + lcb); // // dagvlc.solve(lcb); // // System.out.println("done"); // // // } // // } // // System.out.println("Returning " + dagvlc.result); // return new HashSet<Object>(dagvlc.result); // } else { // return Collections.singleton((Object) TOP_VALUE); // } // } else { // return Collections.singleton((Object) TOP_VALUE); // } // } // // @Override // public Object getTopValue() { // return TOP_VALUE; // } // }
import edu.psu.cse.siis.coal.arguments.StringValueAnalysis; import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Scene; import soot.SceneTransformer; import soot.SootMethod; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * The scene transformer for the propagation problem. */ public class PropagationSceneTransformer extends SceneTransformer { private static final int MAX_ITERATIONS = 15; private final Logger logger = LoggerFactory.getLogger(getClass()); private final ResultBuilder resultBuilder; private final PropagationSceneTransformerPrinter printer; /** * Constructor for the scene transformer. * * @param resultBuilder A {@link ResultBuilder} that describes how the result is generated once * the problem solution is found. * @param printer A {@link PropagationSceneTransformerPrinter} that prints the output of the * analysis when debugging is enabled. If null, nothing gets printed. */ public PropagationSceneTransformer(ResultBuilder resultBuilder, PropagationSceneTransformerPrinter printer) { this.resultBuilder = resultBuilder; this.printer = printer; } @Override protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) { PropagationTimers.v().totalTimer.start(); PropagationTimers.v().misc.start();
// Path: src/main/java/edu/psu/cse/siis/coal/arguments/StringValueAnalysis.java // public class StringValueAnalysis extends ArgumentValueAnalysis { // private static final String TOP_VALUE = Constants.ANY_STRING; // // /** // * Initializes the string argument value analysis. This should be called before using the // * analysis. // */ // public static void initialize() { // // CCExprVisitor.verbose_level = 20; // // CCVisitor.verbose_level = 20; // // DBG.verbose_level = 20; // ConstraintCollector.globalCollection(new ConstraintCollector.CCModelInterface() { // public boolean isExcludedClass(String class_name) { // return false; // } // }); // } // // @Override // public Set<Object> computeInlineArgumentValues(String[] inlineValues) { // return new HashSet<Object>(Arrays.asList(inlineValues)); // } // // /** // * Returns the string values of a variable used at a given statement. // * // * @param value The value or variable that should be determined. // * @param stmt The statement that uses the variable whose values should be determined. // * @return The set of possible values. // */ // @Override // public Set<Object> computeVariableValues(Value value, Stmt stmt) { // if (value instanceof StringConstant) { // return Collections.singleton((Object) ((StringConstant) value).value.intern()); // } else if (value instanceof NullConstant) { // return Collections.singleton((Object) "<NULL>"); // } else if (value instanceof Local) { // Local local = (Local) value; // // ConstraintCollector constraintCollector = // new ConstraintCollector(new ExceptionalUnitGraph(AnalysisParameters.v().getIcfg() // .getMethodOf(stmt).getActiveBody())); // LanguageConstraints.Box lcb = constraintCollector.getConstraintOfAt(local, stmt); // RecursiveDAGSolverVisitorLC dagvlc = // new RecursiveDAGSolverVisitorLC(5, null, // new RecursiveDAGSolverVisitorLC.MethodReturnValueAnalysisInterface() { // @Override // public Set<Object> getMethodReturnValues(Call call) { // return MethodReturnValueManager.v().getMethodReturnValues(call); // } // }); // // if (dagvlc.solve(lcb)) { // // boolean flag = false; // // if (dagvlc.result.size() == 0 || flag == true) { // // System.out.println("ID: " + lcb.uid); // // // int dbg = 10; // // // while (dbg == 10) { // // System.out.println("Returning " + dagvlc.result); // // System.out.println("Returning.. " + lcb); // // dagvlc.solve(lcb); // // System.out.println("done"); // // // } // // } // // System.out.println("Returning " + dagvlc.result); // return new HashSet<Object>(dagvlc.result); // } else { // return Collections.singleton((Object) TOP_VALUE); // } // } else { // return Collections.singleton((Object) TOP_VALUE); // } // } // // @Override // public Object getTopValue() { // return TOP_VALUE; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/PropagationSceneTransformer.java import edu.psu.cse.siis.coal.arguments.StringValueAnalysis; import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Scene; import soot.SceneTransformer; import soot.SootMethod; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * The scene transformer for the propagation problem. */ public class PropagationSceneTransformer extends SceneTransformer { private static final int MAX_ITERATIONS = 15; private final Logger logger = LoggerFactory.getLogger(getClass()); private final ResultBuilder resultBuilder; private final PropagationSceneTransformerPrinter printer; /** * Constructor for the scene transformer. * * @param resultBuilder A {@link ResultBuilder} that describes how the result is generated once * the problem solution is found. * @param printer A {@link PropagationSceneTransformerPrinter} that prints the output of the * analysis when debugging is enabled. If null, nothing gets printed. */ public PropagationSceneTransformer(ResultBuilder resultBuilder, PropagationSceneTransformerPrinter printer) { this.resultBuilder = resultBuilder; this.printer = printer; } @Override protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) { PropagationTimers.v().totalTimer.start(); PropagationTimers.v().misc.start();
StringValueAnalysis.initialize();
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // }
import edu.psu.cse.siis.coal.field.values.FieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * The identity field transformer, which does not modify anything. */ public class IdentityFieldTransformer extends FieldTransformer { private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); private IdentityFieldTransformer() { } @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java import edu.psu.cse.siis.coal.field.values.FieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * The identity field transformer, which does not modify anything. */ public class IdentityFieldTransformer extends FieldTransformer { private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); private IdentityFieldTransformer() { } @Override
public FieldValue apply(FieldValue fieldValue) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/Clear.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A {@link FieldTransformer} for clear operations. This is a singleton, since all clear field * transformers have the same parameters. */ public class Clear extends SetFieldTransformer { private static final Clear instance = new Clear(); public static Clear v() { return instance; } @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/Clear.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A {@link FieldTransformer} for clear operations. This is a singleton, since all clear field * transformers have the same parameters. */ public class Clear extends SetFieldTransformer { private static final Clear instance = new Clear(); public static Clear v() { return instance; } @Override
public FieldTransformer compose(FieldTransformer secondFieldOperation) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.scalar; public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.scalar; public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { @Override
public FieldTransformer makeFieldTransformer(Object value) {
siis/coal
src/test/java/edu/psu/cse/siis/coal/field/transformers/set/SetFieldTransformerTest.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/SetFieldValue.java // public class SetFieldValue extends FieldValue { // private Set<Object> values; // // @Override // public Object getValue() { // return values; // } // // /** // * Adds a set of values to this field value. // * // * @param add A set of values. // */ // public void addAll(Set<Object> add) { // if (add == null) { // return; // } // if (this.values == null) { // this.values = new HashSet<>(add.size()); // } // this.values.addAll(add); // } // // /** // * Removes a set of values from this field value. // * // * @param remove A set of values. // */ // public void removeAll(Set<Object> remove) { // // No need to do anything if there is no value. // if (this.values != null) { // this.values.removeAll(remove); // } // } // // @Override // public String toString() { // if (values == null) { // return "null"; // } // // return Objects.toString(values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // // @Override // public boolean equals(Object other) { // return other instanceof SetFieldValue // && Objects.equals(this.values, ((SetFieldValue) other).values); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.HashSet; import java.util.Set; import org.junit.Test; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.SetFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; public class SetFieldTransformerTest { // private Value value1 = new JimpleLocal("testLocal", null); // private Value value2 = new JimpleLocal("testLocal2", null); // private Stmt stmt = new JAssignStmt(this.value1, this.value2); // private TransformerSequence transformerSequence = Utils.makeTransformerSequence(value1, stmt); @Test public void testApplyWithClear() { Set<Object> expectedValueSet = new HashSet<>(); expectedValueSet.add("addTest1"); expectedValueSet.add("addTest2");
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/SetFieldValue.java // public class SetFieldValue extends FieldValue { // private Set<Object> values; // // @Override // public Object getValue() { // return values; // } // // /** // * Adds a set of values to this field value. // * // * @param add A set of values. // */ // public void addAll(Set<Object> add) { // if (add == null) { // return; // } // if (this.values == null) { // this.values = new HashSet<>(add.size()); // } // this.values.addAll(add); // } // // /** // * Removes a set of values from this field value. // * // * @param remove A set of values. // */ // public void removeAll(Set<Object> remove) { // // No need to do anything if there is no value. // if (this.values != null) { // this.values.removeAll(remove); // } // } // // @Override // public String toString() { // if (values == null) { // return "null"; // } // // return Objects.toString(values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // // @Override // public boolean equals(Object other) { // return other instanceof SetFieldValue // && Objects.equals(this.values, ((SetFieldValue) other).values); // } // // } // Path: src/test/java/edu/psu/cse/siis/coal/field/transformers/set/SetFieldTransformerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.HashSet; import java.util.Set; import org.junit.Test; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.SetFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; public class SetFieldTransformerTest { // private Value value1 = new JimpleLocal("testLocal", null); // private Value value2 = new JimpleLocal("testLocal2", null); // private Stmt stmt = new JAssignStmt(this.value1, this.value2); // private TransformerSequence transformerSequence = Utils.makeTransformerSequence(value1, stmt); @Test public void testApplyWithClear() { Set<Object> expectedValueSet = new HashSet<>(); expectedValueSet.add("addTest1"); expectedValueSet.add("addTest2");
SetFieldValue expectedFieldValue = new SetFieldValue();
siis/coal
src/test/java/edu/psu/cse/siis/coal/field/transformers/set/SetFieldTransformerTest.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/SetFieldValue.java // public class SetFieldValue extends FieldValue { // private Set<Object> values; // // @Override // public Object getValue() { // return values; // } // // /** // * Adds a set of values to this field value. // * // * @param add A set of values. // */ // public void addAll(Set<Object> add) { // if (add == null) { // return; // } // if (this.values == null) { // this.values = new HashSet<>(add.size()); // } // this.values.addAll(add); // } // // /** // * Removes a set of values from this field value. // * // * @param remove A set of values. // */ // public void removeAll(Set<Object> remove) { // // No need to do anything if there is no value. // if (this.values != null) { // this.values.removeAll(remove); // } // } // // @Override // public String toString() { // if (values == null) { // return "null"; // } // // return Objects.toString(values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // // @Override // public boolean equals(Object other) { // return other instanceof SetFieldValue // && Objects.equals(this.values, ((SetFieldValue) other).values); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.HashSet; import java.util.Set; import org.junit.Test; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.SetFieldValue;
// secondFieldTransformer.transformerSequence = transformerSequence; // // FieldTransformer resultFieldTransformer = // firstFieldTransformer.compose(secondFieldTransformer); // // FieldTransformer expectedFieldTransformer = new FieldTransformer(); // expectedFieldTransformer.clear = false; // expectedFieldTransformer.add = new HashSet<>(); // expectedFieldTransformer.add.add("addTestFirst1"); // expectedFieldTransformer.add.add("addTestFirst2"); // expectedFieldTransformer.add.add("addTestFirst3"); // expectedFieldTransformer.add.add("addTest1"); // expectedFieldTransformer.add.add("addTest2"); // expectedFieldTransformer.remove = new HashSet<>(); // expectedFieldTransformer.remove.add("removeTest1"); // expectedFieldTransformer.remove.add("removeTest2"); // expectedFieldTransformer.remove.add("testString2"); // expectedFieldTransformer.remove.add("testString5"); // // List<SequenceElement> sequenceElements = new ArrayList<>(); // sequenceElements.add(new SequenceElement(value1, stmt, Constants.DefaultActions.ADD)); // TransformerSequence expectedTransformerSequence = new TransformerSequence(sequenceElements); // expectedTransformerSequence.addTransformerToSequence(new Add("testComposedAddValue")); // expectedTransformerSequence.addTransformerToSequence(new Remove("testComposedRemoveValue")); // expectedTransformerSequence.addTransformerToSequence(secondFieldTransformer); // expectedFieldTransformer.transformerSequence = transformerSequence; // // assertEquals(expectedFieldTransformer, resultFieldTransformer); // }
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/SetFieldValue.java // public class SetFieldValue extends FieldValue { // private Set<Object> values; // // @Override // public Object getValue() { // return values; // } // // /** // * Adds a set of values to this field value. // * // * @param add A set of values. // */ // public void addAll(Set<Object> add) { // if (add == null) { // return; // } // if (this.values == null) { // this.values = new HashSet<>(add.size()); // } // this.values.addAll(add); // } // // /** // * Removes a set of values from this field value. // * // * @param remove A set of values. // */ // public void removeAll(Set<Object> remove) { // // No need to do anything if there is no value. // if (this.values != null) { // this.values.removeAll(remove); // } // } // // @Override // public String toString() { // if (values == null) { // return "null"; // } // // return Objects.toString(values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // // @Override // public boolean equals(Object other) { // return other instanceof SetFieldValue // && Objects.equals(this.values, ((SetFieldValue) other).values); // } // // } // Path: src/test/java/edu/psu/cse/siis/coal/field/transformers/set/SetFieldTransformerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.HashSet; import java.util.Set; import org.junit.Test; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.SetFieldValue; // secondFieldTransformer.transformerSequence = transformerSequence; // // FieldTransformer resultFieldTransformer = // firstFieldTransformer.compose(secondFieldTransformer); // // FieldTransformer expectedFieldTransformer = new FieldTransformer(); // expectedFieldTransformer.clear = false; // expectedFieldTransformer.add = new HashSet<>(); // expectedFieldTransformer.add.add("addTestFirst1"); // expectedFieldTransformer.add.add("addTestFirst2"); // expectedFieldTransformer.add.add("addTestFirst3"); // expectedFieldTransformer.add.add("addTest1"); // expectedFieldTransformer.add.add("addTest2"); // expectedFieldTransformer.remove = new HashSet<>(); // expectedFieldTransformer.remove.add("removeTest1"); // expectedFieldTransformer.remove.add("removeTest2"); // expectedFieldTransformer.remove.add("testString2"); // expectedFieldTransformer.remove.add("testString5"); // // List<SequenceElement> sequenceElements = new ArrayList<>(); // sequenceElements.add(new SequenceElement(value1, stmt, Constants.DefaultActions.ADD)); // TransformerSequence expectedTransformerSequence = new TransformerSequence(sequenceElements); // expectedTransformerSequence.addTransformerToSequence(new Add("testComposedAddValue")); // expectedTransformerSequence.addTransformerToSequence(new Remove("testComposedRemoveValue")); // expectedTransformerSequence.addTransformerToSequence(secondFieldTransformer); // expectedFieldTransformer.transformerSequence = transformerSequence; // // assertEquals(expectedFieldTransformer, resultFieldTransformer); // }
private void testApplyHelper(boolean clear, FieldValue expectedFieldValue) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/transformers/AllTopEdgeFunction.java
// Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/BottomPropagationValue.java // public final class BottomPropagationValue implements BasePropagationValue { // private static final BottomPropagationValue instance = new BottomPropagationValue(); // // private BottomPropagationValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static BottomPropagationValue v() { // return instance; // } // // @Override // public String toString() { // return "bottom"; // } // }
import heros.EdgeFunction; import heros.edgefunc.AllBottom; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.BottomPropagationValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.transformers; /** * A customized "all top" edge function as required by the IDE solver. This does not actually have * "all top" semantics, we customized it to make it work with the IDE solver in a way compatible * with our propagation values. */ public class AllTopEdgeFunction extends AllBottom<BasePropagationValue> { public AllTopEdgeFunction() {
// Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/BottomPropagationValue.java // public final class BottomPropagationValue implements BasePropagationValue { // private static final BottomPropagationValue instance = new BottomPropagationValue(); // // private BottomPropagationValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static BottomPropagationValue v() { // return instance; // } // // @Override // public String toString() { // return "bottom"; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/transformers/AllTopEdgeFunction.java import heros.EdgeFunction; import heros.edgefunc.AllBottom; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.BottomPropagationValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.transformers; /** * A customized "all top" edge function as required by the IDE solver. This does not actually have * "all top" semantics, we customized it to make it work with the IDE solver in a way compatible * with our propagation values. */ public class AllTopEdgeFunction extends AllBottom<BasePropagationValue> { public AllTopEdgeFunction() {
super(BottomPropagationValue.v());
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/TransformerSequence.java
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // }
import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A sequence of {@link SequenceElement} that represents the influence of several consecutive COAL * value compositions. */ public class TransformerSequence { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<SequenceElement> transformerSequence = null; public TransformerSequence() { } public TransformerSequence(TransformerSequence otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence.transformerSequence); } public TransformerSequence(List<SequenceElement> otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence); } /** * Adds a transformer to the sequence. The transformer is added to the last element. * * @param newFieldTransformer A field transformer. */
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/TransformerSequence.java import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A sequence of {@link SequenceElement} that represents the influence of several consecutive COAL * value compositions. */ public class TransformerSequence { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<SequenceElement> transformerSequence = null; public TransformerSequence() { } public TransformerSequence(TransformerSequence otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence.transformerSequence); } public TransformerSequence(List<SequenceElement> otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence); } /** * Adds a transformer to the sequence. The transformer is added to the last element. * * @param newFieldTransformer A field transformer. */
public void addTransformerToSequence(FieldTransformer newFieldTransformer) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/TransformerSequence.java
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // }
import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A sequence of {@link SequenceElement} that represents the influence of several consecutive COAL * value compositions. */ public class TransformerSequence { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<SequenceElement> transformerSequence = null; public TransformerSequence() { } public TransformerSequence(TransformerSequence otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence.transformerSequence); } public TransformerSequence(List<SequenceElement> otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence); } /** * Adds a transformer to the sequence. The transformer is added to the last element. * * @param newFieldTransformer A field transformer. */ public void addTransformerToSequence(FieldTransformer newFieldTransformer) { this.transformerSequence.get(this.transformerSequence.size() - 1).composeWith( newFieldTransformer); } /** * Concatenate another sequence to this sequence. * * @param transformerSequence A transformer sequence. */ public void addElementsToSequence(TransformerSequence transformerSequence) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.addAll(transformerSequence.transformerSequence); } /** * Adds an element to the sequence. * * @param symbol A symbol (variable) whose type is modeled with COAL. * @param stmt A modifier that references a variable modeled with COAL. * @param op An operation. */ public void addElementToSequence(Value symbol, Stmt stmt, String op) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.add(new SequenceElement(symbol, stmt, op)); } /** * Generates the field transformers that represent the influence of this sequence. * * @param field A field name. * @param solver A propagation solver. * @return The set of field transformers that represent the influence of this sequence. */
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/TransformerSequence.java import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A sequence of {@link SequenceElement} that represents the influence of several consecutive COAL * value compositions. */ public class TransformerSequence { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<SequenceElement> transformerSequence = null; public TransformerSequence() { } public TransformerSequence(TransformerSequence otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence.transformerSequence); } public TransformerSequence(List<SequenceElement> otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence); } /** * Adds a transformer to the sequence. The transformer is added to the last element. * * @param newFieldTransformer A field transformer. */ public void addTransformerToSequence(FieldTransformer newFieldTransformer) { this.transformerSequence.get(this.transformerSequence.size() - 1).composeWith( newFieldTransformer); } /** * Concatenate another sequence to this sequence. * * @param transformerSequence A transformer sequence. */ public void addElementsToSequence(TransformerSequence transformerSequence) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.addAll(transformerSequence.transformerSequence); } /** * Adds an element to the sequence. * * @param symbol A symbol (variable) whose type is modeled with COAL. * @param stmt A modifier that references a variable modeled with COAL. * @param op An operation. */ public void addElementToSequence(Value symbol, Stmt stmt, String op) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.add(new SequenceElement(symbol, stmt, op)); } /** * Generates the field transformers that represent the influence of this sequence. * * @param field A field name. * @param solver A propagation solver. * @return The set of field transformers that represent the influence of this sequence. */
public Set<FieldTransformer> makeFinalFieldTransformers(String field, PropagationSolver solver) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/TransformerSequence.java
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // }
import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A sequence of {@link SequenceElement} that represents the influence of several consecutive COAL * value compositions. */ public class TransformerSequence { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<SequenceElement> transformerSequence = null; public TransformerSequence() { } public TransformerSequence(TransformerSequence otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence.transformerSequence); } public TransformerSequence(List<SequenceElement> otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence); } /** * Adds a transformer to the sequence. The transformer is added to the last element. * * @param newFieldTransformer A field transformer. */ public void addTransformerToSequence(FieldTransformer newFieldTransformer) { this.transformerSequence.get(this.transformerSequence.size() - 1).composeWith( newFieldTransformer); } /** * Concatenate another sequence to this sequence. * * @param transformerSequence A transformer sequence. */ public void addElementsToSequence(TransformerSequence transformerSequence) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.addAll(transformerSequence.transformerSequence); } /** * Adds an element to the sequence. * * @param symbol A symbol (variable) whose type is modeled with COAL. * @param stmt A modifier that references a variable modeled with COAL. * @param op An operation. */ public void addElementToSequence(Value symbol, Stmt stmt, String op) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.add(new SequenceElement(symbol, stmt, op)); } /** * Generates the field transformers that represent the influence of this sequence. * * @param field A field name. * @param solver A propagation solver. * @return The set of field transformers that represent the influence of this sequence. */ public Set<FieldTransformer> makeFinalFieldTransformers(String field, PropagationSolver solver) { Set<FieldTransformer> result =
// Path: src/main/java/edu/psu/cse/siis/coal/PropagationSolver.java // public class PropagationSolver extends // IDESolver<Unit, Value, SootMethod, BasePropagationValue, JimpleBasedInterproceduralCFG> { // // public PropagationSolver(PropagationProblem propagationProblem) { // super(propagationProblem); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/IdentityFieldTransformer.java // public class IdentityFieldTransformer extends FieldTransformer { // private static final IdentityFieldTransformer instance = new IdentityFieldTransformer(); // // private IdentityFieldTransformer() { // } // // @Override // public FieldValue apply(FieldValue fieldValue) { // return fieldValue; // } // // @Override // public FieldTransformer compose(FieldTransformer secondFieldOperation) { // return secondFieldOperation; // } // // @Override // public String toString() { // return "identity"; // } // // public static IdentityFieldTransformer v() { // return instance; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/TransformerSequence.java import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.IdentityFieldTransformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.Stmt; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field; /** * A sequence of {@link SequenceElement} that represents the influence of several consecutive COAL * value compositions. */ public class TransformerSequence { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<SequenceElement> transformerSequence = null; public TransformerSequence() { } public TransformerSequence(TransformerSequence otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence.transformerSequence); } public TransformerSequence(List<SequenceElement> otherTransformerSequence) { this.transformerSequence = new ArrayList<>(otherTransformerSequence); } /** * Adds a transformer to the sequence. The transformer is added to the last element. * * @param newFieldTransformer A field transformer. */ public void addTransformerToSequence(FieldTransformer newFieldTransformer) { this.transformerSequence.get(this.transformerSequence.size() - 1).composeWith( newFieldTransformer); } /** * Concatenate another sequence to this sequence. * * @param transformerSequence A transformer sequence. */ public void addElementsToSequence(TransformerSequence transformerSequence) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.addAll(transformerSequence.transformerSequence); } /** * Adds an element to the sequence. * * @param symbol A symbol (variable) whose type is modeled with COAL. * @param stmt A modifier that references a variable modeled with COAL. * @param op An operation. */ public void addElementToSequence(Value symbol, Stmt stmt, String op) { if (this.transformerSequence == null) { this.transformerSequence = new ArrayList<>(); } this.transformerSequence.add(new SequenceElement(symbol, stmt, op)); } /** * Generates the field transformers that represent the influence of this sequence. * * @param field A field name. * @param solver A propagation solver. * @return The set of field transformers that represent the influence of this sequence. */ public Set<FieldTransformer> makeFinalFieldTransformers(String field, PropagationSolver solver) { Set<FieldTransformer> result =
Collections.singleton((FieldTransformer) IdentityFieldTransformer.v());
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for remove field transformers. */ public class FieldRemoveTransformerFactory extends FieldTransformerFactory { @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for remove field transformers. */ public class FieldRemoveTransformerFactory extends FieldTransformerFactory { @Override
public FieldTransformer makeFieldTransformer(Object value) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/PropagationSceneTransformerFilePrinter.java
// Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // }
import soot.Value; import soot.jimple.toolkits.callgraph.ReachableMethods; import edu.psu.cse.siis.coal.values.BasePropagationValue; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootMethod; import soot.Unit;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * A {@link PropagationSceneTransformerPrinter} that prints to a file. */ public class PropagationSceneTransformerFilePrinter implements PropagationSceneTransformerPrinter { private final String filePath; private final SymbolFilter filter; /** * Constructor for the printer. * * @param filePath The path to the output file. * @param filter A filter to filter out unwanted symbols (e.g., variables or fields whose value * should not be printed). */ public PropagationSceneTransformerFilePrinter(String filePath, SymbolFilter filter) { this.filePath = filePath; this.filter = filter; } @Override public void print(PropagationSolver solver) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); String newLine = System.getProperty("line.separator"); List<MethodOrMethodContext> eps = new ArrayList<MethodOrMethodContext>(Scene.v().getEntryPoints()); ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), eps.iterator(), null); reachableMethods.update(); for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) { SootMethod ep = iter.next().method(); if (!ep.isConcrete() || !ep.hasActiveBody() // || ep.getName().contains("dummy") /* || Model.v().isExcludedClass(ep.getDeclaringClass().getName()) */) { continue; } writer.write(ep.getActiveBody() + newLine); writer.write("----------------------------------------------" + newLine); writer.write("At end of: " + ep.getSignature() + newLine); writer.write("Variables:" + newLine); writer.write("----------------------------------------------" + newLine); for (Unit ret : ep.getActiveBody().getUnits()) {
// Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // Path: src/main/java/edu/psu/cse/siis/coal/PropagationSceneTransformerFilePrinter.java import soot.Value; import soot.jimple.toolkits.callgraph.ReachableMethods; import edu.psu.cse.siis.coal.values.BasePropagationValue; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootMethod; import soot.Unit; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal; /** * A {@link PropagationSceneTransformerPrinter} that prints to a file. */ public class PropagationSceneTransformerFilePrinter implements PropagationSceneTransformerPrinter { private final String filePath; private final SymbolFilter filter; /** * Constructor for the printer. * * @param filePath The path to the output file. * @param filter A filter to filter out unwanted symbols (e.g., variables or fields whose value * should not be printed). */ public PropagationSceneTransformerFilePrinter(String filePath, SymbolFilter filter) { this.filePath = filePath; this.filter = filter; } @Override public void print(PropagationSolver solver) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); String newLine = System.getProperty("line.separator"); List<MethodOrMethodContext> eps = new ArrayList<MethodOrMethodContext>(Scene.v().getEntryPoints()); ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), eps.iterator(), null); reachableMethods.update(); for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) { SootMethod ep = iter.next().method(); if (!ep.isConcrete() || !ep.hasActiveBody() // || ep.getName().contains("dummy") /* || Model.v().isExcludedClass(ep.getDeclaringClass().getName()) */) { continue; } writer.write(ep.getActiveBody() + newLine); writer.write("----------------------------------------------" + newLine); writer.write("At end of: " + ep.getSignature() + newLine); writer.write("Variables:" + newLine); writer.write("----------------------------------------------" + newLine); for (Unit ret : ep.getActiveBody().getUnits()) {
for (Map.Entry<Value, BasePropagationValue> l : solver.resultsAt(ret).entrySet()) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/Internable.java // public interface Internable<T> { // public T intern(); // } // // Path: src/main/java/edu/psu/cse/siis/coal/Pool.java // public class Pool<T> { // private final ConcurrentMap<T, T> pool = new ConcurrentHashMap<>(); // // public T intern(T element) { // T result = pool.putIfAbsent(element, element); // if (result == null) { // return element; // } else { // return result; // } // } // // public Set<T> getValues() { // return new HashSet<T>(pool.values()); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // }
import edu.psu.cse.siis.coal.Internable; import edu.psu.cse.siis.coal.Pool; import edu.psu.cse.siis.coal.field.values.FieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A field transformer, which models the influence of a statement of a single field. */ public abstract class FieldTransformer implements Internable<FieldTransformer> { private static final Pool<FieldTransformer> POOL = new Pool<>(); /** * Applies this field transformer to a {@link FieldValue}. * * @param fieldValue A field value. * @return A field value. */
// Path: src/main/java/edu/psu/cse/siis/coal/Internable.java // public interface Internable<T> { // public T intern(); // } // // Path: src/main/java/edu/psu/cse/siis/coal/Pool.java // public class Pool<T> { // private final ConcurrentMap<T, T> pool = new ConcurrentHashMap<>(); // // public T intern(T element) { // T result = pool.putIfAbsent(element, element); // if (result == null) { // return element; // } else { // return result; // } // } // // public Set<T> getValues() { // return new HashSet<T>(pool.values()); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java import edu.psu.cse.siis.coal.Internable; import edu.psu.cse.siis.coal.Pool; import edu.psu.cse.siis.coal.field.values.FieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A field transformer, which models the influence of a statement of a single field. */ public abstract class FieldTransformer implements Internable<FieldTransformer> { private static final Pool<FieldTransformer> POOL = new Pool<>(); /** * Applies this field transformer to a {@link FieldValue}. * * @param fieldValue A field value. * @return A field value. */
public abstract FieldValue apply(FieldValue fieldValue);
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for add field transformers. */ public class FieldAddTransformerFactory extends FieldTransformerFactory { @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for add field transformers. */ public class FieldAddTransformerFactory extends FieldTransformerFactory { @Override
public FieldTransformer makeFieldTransformer(Object value) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for replace field transformers. */ public class FieldReplaceTransformerFactory extends FieldTransformerFactory { @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for replace field transformers. */ public class FieldReplaceTransformerFactory extends FieldTransformerFactory { @Override
public FieldTransformer makeFieldTransformer(Object value) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/Add.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // }
import java.util.HashSet; import java.util.Set; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A {@link FieldTransformer} for an add operation. */ public class Add extends SetFieldTransformer { @SuppressWarnings("unchecked") public Add(Object value) { this.add = new HashSet<>(2); if (value instanceof Set) { this.add.addAll((Set<Object>) value); } else { this.add.add(value); } } private Add(Add add1, Add add2) { this.add = new HashSet<>(add1.add); this.add.addAll(add2.add); } @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/Add.java import java.util.HashSet; import java.util.Set; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A {@link FieldTransformer} for an add operation. */ public class Add extends SetFieldTransformer { @SuppressWarnings("unchecked") public Add(Object value) { this.add = new HashSet<>(2); if (value instanceof Set) { this.add.addAll((Set<Object>) value); } else { this.add.add(value); } } private Add(Add add1, Add add2) { this.add = new HashSet<>(add1.add); this.add.addAll(add2.add); } @Override
public FieldTransformer compose(FieldTransformer secondFieldOperation) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/ScalarReplace.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/ScalarFieldValue.java // public class ScalarFieldValue extends FieldValue { // private final Object value; // // public ScalarFieldValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <T> T getFieldValue(Class<T> type) { // if (value == null) { // return null; // } // try { // return (T) value; // } catch (ClassCastException classCastException) { // throw new RuntimeException("Could not convert field value " + value + " of type " // + value.getClass() + " to type " + type); // // } // } // // @Override // public Object getValue() { // return value; // } // // @Override // public String toString() { // return Objects.toString(value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public boolean equals(Object other) { // return other instanceof ScalarFieldValue // && Objects.equals(this.value, ((ScalarFieldValue) other).value); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.scalar; public class ScalarReplace extends FieldTransformer { private final Object value; public ScalarReplace(Object newValue) { value = newValue; } @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/ScalarFieldValue.java // public class ScalarFieldValue extends FieldValue { // private final Object value; // // public ScalarFieldValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <T> T getFieldValue(Class<T> type) { // if (value == null) { // return null; // } // try { // return (T) value; // } catch (ClassCastException classCastException) { // throw new RuntimeException("Could not convert field value " + value + " of type " // + value.getClass() + " to type " + type); // // } // } // // @Override // public Object getValue() { // return value; // } // // @Override // public String toString() { // return Objects.toString(value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public boolean equals(Object other) { // return other instanceof ScalarFieldValue // && Objects.equals(this.value, ((ScalarFieldValue) other).value); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/ScalarReplace.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.scalar; public class ScalarReplace extends FieldTransformer { private final Object value; public ScalarReplace(Object newValue) { value = newValue; } @Override
public FieldValue apply(FieldValue fieldValue) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/ScalarReplace.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/ScalarFieldValue.java // public class ScalarFieldValue extends FieldValue { // private final Object value; // // public ScalarFieldValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <T> T getFieldValue(Class<T> type) { // if (value == null) { // return null; // } // try { // return (T) value; // } catch (ClassCastException classCastException) { // throw new RuntimeException("Could not convert field value " + value + " of type " // + value.getClass() + " to type " + type); // // } // } // // @Override // public Object getValue() { // return value; // } // // @Override // public String toString() { // return Objects.toString(value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public boolean equals(Object other) { // return other instanceof ScalarFieldValue // && Objects.equals(this.value, ((ScalarFieldValue) other).value); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.scalar; public class ScalarReplace extends FieldTransformer { private final Object value; public ScalarReplace(Object newValue) { value = newValue; } @Override public FieldValue apply(FieldValue fieldValue) {
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/ScalarFieldValue.java // public class ScalarFieldValue extends FieldValue { // private final Object value; // // public ScalarFieldValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <T> T getFieldValue(Class<T> type) { // if (value == null) { // return null; // } // try { // return (T) value; // } catch (ClassCastException classCastException) { // throw new RuntimeException("Could not convert field value " + value + " of type " // + value.getClass() + " to type " + type); // // } // } // // @Override // public Object getValue() { // return value; // } // // @Override // public String toString() { // return Objects.toString(value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public boolean equals(Object other) { // return other instanceof ScalarFieldValue // && Objects.equals(this.value, ((ScalarFieldValue) other).value); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/ScalarReplace.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.scalar; public class ScalarReplace extends FieldTransformer { private final Object value; public ScalarReplace(Object newValue) { value = newValue; } @Override public FieldValue apply(FieldValue fieldValue) {
return new ScalarFieldValue(value);
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // }
import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for field transformers that add sequence elements. */ public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for field transformers that add sequence elements. */ public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { @Override
public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerManager.java
// Path: src/main/java/edu/psu/cse/siis/coal/Constants.java // public class Constants { // public static final String ANY_STRING = "(.*)"; // public static final String ANY_CLASS = "(.*)"; // public static final int ANY_INT = -1; // public static final int VALUE_LIMIT = 256; // public static final int INSTANCE_INVOKE_BASE_INDEX = -1; // public static final String NULL_STRING = "NULL-CONSTANT"; // // public static class DefaultActions { // public static class Scalar { // public static final String NULL = "null"; // public static final String REPLACE = "replace"; // } // // public static class Set { // public static final String ADD = "add"; // public static final String REMOVE = "remove"; // public static final String CLEAR = "clear"; // public static final String ADD_ALL = "addAll"; // public static final String REPLACE_ALL = "replaceAll"; // } // // public static final String COMPOSE = "compose"; // } // // public static class DefaultArgumentTypes { // public static class Scalar { // public static final String STRING = "String"; // public static final String CLASS = "Class"; // public static final String INT = "int"; // } // // public static class Set { // public static final String STRING = "Set<String>"; // public static final String CLASS = "Set<Class>"; // public static final String INT = "Set<int>"; // } // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java // public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new ScalarReplace(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java // public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // return new AddSequenceElement(symbol, stmt, op); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java // public class FieldAddTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Add(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java // public class FieldClearTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return Clear.v(); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java // public class FieldRemoveTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Remove(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java // public class FieldReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Replace(value); // } // // }
import java.util.HashMap; import java.util.Map; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.field.transformers.scalar.FieldScalarReplaceTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddSequenceElementTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldClearTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldRemoveTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldReplaceTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A manager singleton for field transformers, which is the entry point for generating field * transformers. */ public class FieldTransformerManager { private static FieldTransformerManager instance = new FieldTransformerManager(); private final Map<String, FieldTransformerFactory> fieldTransformerFactoryMap = new HashMap<>(); private FieldTransformerManager() { } /** * Returns the singleton instance for the class. * * @return The singleton instance for this class. */ public static FieldTransformerManager v() { return instance; } /** * Registers a field transformer factory for a given operation. * * @param action An operation that can be performed on fields. * @param fieldTransformerFactory A field transformer factory for the operation. */ public void registerFieldTransformerFactory(String action, FieldTransformerFactory fieldTransformerFactory) { fieldTransformerFactoryMap.put(action, fieldTransformerFactory); } /** * Registers the field transformer factories for the field operations that are supported by COAL * by default. Operations that are supported by default are add, remove, clear, replace and value * composition. */ public void registerDefaultFieldTransformerFactories() {
// Path: src/main/java/edu/psu/cse/siis/coal/Constants.java // public class Constants { // public static final String ANY_STRING = "(.*)"; // public static final String ANY_CLASS = "(.*)"; // public static final int ANY_INT = -1; // public static final int VALUE_LIMIT = 256; // public static final int INSTANCE_INVOKE_BASE_INDEX = -1; // public static final String NULL_STRING = "NULL-CONSTANT"; // // public static class DefaultActions { // public static class Scalar { // public static final String NULL = "null"; // public static final String REPLACE = "replace"; // } // // public static class Set { // public static final String ADD = "add"; // public static final String REMOVE = "remove"; // public static final String CLEAR = "clear"; // public static final String ADD_ALL = "addAll"; // public static final String REPLACE_ALL = "replaceAll"; // } // // public static final String COMPOSE = "compose"; // } // // public static class DefaultArgumentTypes { // public static class Scalar { // public static final String STRING = "String"; // public static final String CLASS = "Class"; // public static final String INT = "int"; // } // // public static class Set { // public static final String STRING = "Set<String>"; // public static final String CLASS = "Set<Class>"; // public static final String INT = "Set<int>"; // } // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java // public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new ScalarReplace(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java // public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // return new AddSequenceElement(symbol, stmt, op); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java // public class FieldAddTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Add(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java // public class FieldClearTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return Clear.v(); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java // public class FieldRemoveTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Remove(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java // public class FieldReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Replace(value); // } // // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerManager.java import java.util.HashMap; import java.util.Map; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.field.transformers.scalar.FieldScalarReplaceTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddSequenceElementTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldClearTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldRemoveTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldReplaceTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A manager singleton for field transformers, which is the entry point for generating field * transformers. */ public class FieldTransformerManager { private static FieldTransformerManager instance = new FieldTransformerManager(); private final Map<String, FieldTransformerFactory> fieldTransformerFactoryMap = new HashMap<>(); private FieldTransformerManager() { } /** * Returns the singleton instance for the class. * * @return The singleton instance for this class. */ public static FieldTransformerManager v() { return instance; } /** * Registers a field transformer factory for a given operation. * * @param action An operation that can be performed on fields. * @param fieldTransformerFactory A field transformer factory for the operation. */ public void registerFieldTransformerFactory(String action, FieldTransformerFactory fieldTransformerFactory) { fieldTransformerFactoryMap.put(action, fieldTransformerFactory); } /** * Registers the field transformer factories for the field operations that are supported by COAL * by default. Operations that are supported by default are add, remove, clear, replace and value * composition. */ public void registerDefaultFieldTransformerFactories() {
registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD,
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerManager.java
// Path: src/main/java/edu/psu/cse/siis/coal/Constants.java // public class Constants { // public static final String ANY_STRING = "(.*)"; // public static final String ANY_CLASS = "(.*)"; // public static final int ANY_INT = -1; // public static final int VALUE_LIMIT = 256; // public static final int INSTANCE_INVOKE_BASE_INDEX = -1; // public static final String NULL_STRING = "NULL-CONSTANT"; // // public static class DefaultActions { // public static class Scalar { // public static final String NULL = "null"; // public static final String REPLACE = "replace"; // } // // public static class Set { // public static final String ADD = "add"; // public static final String REMOVE = "remove"; // public static final String CLEAR = "clear"; // public static final String ADD_ALL = "addAll"; // public static final String REPLACE_ALL = "replaceAll"; // } // // public static final String COMPOSE = "compose"; // } // // public static class DefaultArgumentTypes { // public static class Scalar { // public static final String STRING = "String"; // public static final String CLASS = "Class"; // public static final String INT = "int"; // } // // public static class Set { // public static final String STRING = "Set<String>"; // public static final String CLASS = "Set<Class>"; // public static final String INT = "Set<int>"; // } // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java // public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new ScalarReplace(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java // public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // return new AddSequenceElement(symbol, stmt, op); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java // public class FieldAddTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Add(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java // public class FieldClearTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return Clear.v(); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java // public class FieldRemoveTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Remove(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java // public class FieldReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Replace(value); // } // // }
import java.util.HashMap; import java.util.Map; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.field.transformers.scalar.FieldScalarReplaceTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddSequenceElementTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldClearTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldRemoveTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldReplaceTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A manager singleton for field transformers, which is the entry point for generating field * transformers. */ public class FieldTransformerManager { private static FieldTransformerManager instance = new FieldTransformerManager(); private final Map<String, FieldTransformerFactory> fieldTransformerFactoryMap = new HashMap<>(); private FieldTransformerManager() { } /** * Returns the singleton instance for the class. * * @return The singleton instance for this class. */ public static FieldTransformerManager v() { return instance; } /** * Registers a field transformer factory for a given operation. * * @param action An operation that can be performed on fields. * @param fieldTransformerFactory A field transformer factory for the operation. */ public void registerFieldTransformerFactory(String action, FieldTransformerFactory fieldTransformerFactory) { fieldTransformerFactoryMap.put(action, fieldTransformerFactory); } /** * Registers the field transformer factories for the field operations that are supported by COAL * by default. Operations that are supported by default are add, remove, clear, replace and value * composition. */ public void registerDefaultFieldTransformerFactories() { registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD,
// Path: src/main/java/edu/psu/cse/siis/coal/Constants.java // public class Constants { // public static final String ANY_STRING = "(.*)"; // public static final String ANY_CLASS = "(.*)"; // public static final int ANY_INT = -1; // public static final int VALUE_LIMIT = 256; // public static final int INSTANCE_INVOKE_BASE_INDEX = -1; // public static final String NULL_STRING = "NULL-CONSTANT"; // // public static class DefaultActions { // public static class Scalar { // public static final String NULL = "null"; // public static final String REPLACE = "replace"; // } // // public static class Set { // public static final String ADD = "add"; // public static final String REMOVE = "remove"; // public static final String CLEAR = "clear"; // public static final String ADD_ALL = "addAll"; // public static final String REPLACE_ALL = "replaceAll"; // } // // public static final String COMPOSE = "compose"; // } // // public static class DefaultArgumentTypes { // public static class Scalar { // public static final String STRING = "String"; // public static final String CLASS = "Class"; // public static final String INT = "int"; // } // // public static class Set { // public static final String STRING = "Set<String>"; // public static final String CLASS = "Set<Class>"; // public static final String INT = "Set<int>"; // } // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java // public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new ScalarReplace(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java // public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // return new AddSequenceElement(symbol, stmt, op); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java // public class FieldAddTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Add(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java // public class FieldClearTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return Clear.v(); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java // public class FieldRemoveTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Remove(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java // public class FieldReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Replace(value); // } // // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerManager.java import java.util.HashMap; import java.util.Map; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.field.transformers.scalar.FieldScalarReplaceTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddSequenceElementTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldClearTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldRemoveTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldReplaceTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A manager singleton for field transformers, which is the entry point for generating field * transformers. */ public class FieldTransformerManager { private static FieldTransformerManager instance = new FieldTransformerManager(); private final Map<String, FieldTransformerFactory> fieldTransformerFactoryMap = new HashMap<>(); private FieldTransformerManager() { } /** * Returns the singleton instance for the class. * * @return The singleton instance for this class. */ public static FieldTransformerManager v() { return instance; } /** * Registers a field transformer factory for a given operation. * * @param action An operation that can be performed on fields. * @param fieldTransformerFactory A field transformer factory for the operation. */ public void registerFieldTransformerFactory(String action, FieldTransformerFactory fieldTransformerFactory) { fieldTransformerFactoryMap.put(action, fieldTransformerFactory); } /** * Registers the field transformer factories for the field operations that are supported by COAL * by default. Operations that are supported by default are add, remove, clear, replace and value * composition. */ public void registerDefaultFieldTransformerFactories() { registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD,
new FieldAddTransformerFactory());
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerManager.java
// Path: src/main/java/edu/psu/cse/siis/coal/Constants.java // public class Constants { // public static final String ANY_STRING = "(.*)"; // public static final String ANY_CLASS = "(.*)"; // public static final int ANY_INT = -1; // public static final int VALUE_LIMIT = 256; // public static final int INSTANCE_INVOKE_BASE_INDEX = -1; // public static final String NULL_STRING = "NULL-CONSTANT"; // // public static class DefaultActions { // public static class Scalar { // public static final String NULL = "null"; // public static final String REPLACE = "replace"; // } // // public static class Set { // public static final String ADD = "add"; // public static final String REMOVE = "remove"; // public static final String CLEAR = "clear"; // public static final String ADD_ALL = "addAll"; // public static final String REPLACE_ALL = "replaceAll"; // } // // public static final String COMPOSE = "compose"; // } // // public static class DefaultArgumentTypes { // public static class Scalar { // public static final String STRING = "String"; // public static final String CLASS = "Class"; // public static final String INT = "int"; // } // // public static class Set { // public static final String STRING = "Set<String>"; // public static final String CLASS = "Set<Class>"; // public static final String INT = "Set<int>"; // } // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java // public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new ScalarReplace(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java // public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // return new AddSequenceElement(symbol, stmt, op); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java // public class FieldAddTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Add(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java // public class FieldClearTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return Clear.v(); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java // public class FieldRemoveTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Remove(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java // public class FieldReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Replace(value); // } // // }
import java.util.HashMap; import java.util.Map; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.field.transformers.scalar.FieldScalarReplaceTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddSequenceElementTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldClearTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldRemoveTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldReplaceTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A manager singleton for field transformers, which is the entry point for generating field * transformers. */ public class FieldTransformerManager { private static FieldTransformerManager instance = new FieldTransformerManager(); private final Map<String, FieldTransformerFactory> fieldTransformerFactoryMap = new HashMap<>(); private FieldTransformerManager() { } /** * Returns the singleton instance for the class. * * @return The singleton instance for this class. */ public static FieldTransformerManager v() { return instance; } /** * Registers a field transformer factory for a given operation. * * @param action An operation that can be performed on fields. * @param fieldTransformerFactory A field transformer factory for the operation. */ public void registerFieldTransformerFactory(String action, FieldTransformerFactory fieldTransformerFactory) { fieldTransformerFactoryMap.put(action, fieldTransformerFactory); } /** * Registers the field transformer factories for the field operations that are supported by COAL * by default. Operations that are supported by default are add, remove, clear, replace and value * composition. */ public void registerDefaultFieldTransformerFactories() { registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD, new FieldAddTransformerFactory()); registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD_ALL, new FieldAddTransformerFactory()); registerFieldTransformerFactory(Constants.DefaultActions.Set.REMOVE,
// Path: src/main/java/edu/psu/cse/siis/coal/Constants.java // public class Constants { // public static final String ANY_STRING = "(.*)"; // public static final String ANY_CLASS = "(.*)"; // public static final int ANY_INT = -1; // public static final int VALUE_LIMIT = 256; // public static final int INSTANCE_INVOKE_BASE_INDEX = -1; // public static final String NULL_STRING = "NULL-CONSTANT"; // // public static class DefaultActions { // public static class Scalar { // public static final String NULL = "null"; // public static final String REPLACE = "replace"; // } // // public static class Set { // public static final String ADD = "add"; // public static final String REMOVE = "remove"; // public static final String CLEAR = "clear"; // public static final String ADD_ALL = "addAll"; // public static final String REPLACE_ALL = "replaceAll"; // } // // public static final String COMPOSE = "compose"; // } // // public static class DefaultArgumentTypes { // public static class Scalar { // public static final String STRING = "String"; // public static final String CLASS = "Class"; // public static final String INT = "int"; // } // // public static class Set { // public static final String STRING = "Set<String>"; // public static final String CLASS = "Set<Class>"; // public static final String INT = "Set<int>"; // } // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/scalar/FieldScalarReplaceTransformerFactory.java // public class FieldScalarReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new ScalarReplace(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddSequenceElementTransformerFactory.java // public class FieldAddSequenceElementTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // return new AddSequenceElement(symbol, stmt, op); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldAddTransformerFactory.java // public class FieldAddTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Add(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java // public class FieldClearTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return Clear.v(); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldRemoveTransformerFactory.java // public class FieldRemoveTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Remove(value); // } // // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldReplaceTransformerFactory.java // public class FieldReplaceTransformerFactory extends FieldTransformerFactory { // // @Override // public FieldTransformer makeFieldTransformer(Object value) { // return new Replace(value); // } // // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerManager.java import java.util.HashMap; import java.util.Map; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.field.transformers.scalar.FieldScalarReplaceTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddSequenceElementTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldAddTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldClearTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldRemoveTransformerFactory; import edu.psu.cse.siis.coal.field.transformers.set.FieldReplaceTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A manager singleton for field transformers, which is the entry point for generating field * transformers. */ public class FieldTransformerManager { private static FieldTransformerManager instance = new FieldTransformerManager(); private final Map<String, FieldTransformerFactory> fieldTransformerFactoryMap = new HashMap<>(); private FieldTransformerManager() { } /** * Returns the singleton instance for the class. * * @return The singleton instance for this class. */ public static FieldTransformerManager v() { return instance; } /** * Registers a field transformer factory for a given operation. * * @param action An operation that can be performed on fields. * @param fieldTransformerFactory A field transformer factory for the operation. */ public void registerFieldTransformerFactory(String action, FieldTransformerFactory fieldTransformerFactory) { fieldTransformerFactoryMap.put(action, fieldTransformerFactory); } /** * Registers the field transformer factories for the field operations that are supported by COAL * by default. Operations that are supported by default are add, remove, clear, replace and value * composition. */ public void registerDefaultFieldTransformerFactories() { registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD, new FieldAddTransformerFactory()); registerFieldTransformerFactory(Constants.DefaultActions.Set.ADD_ALL, new FieldAddTransformerFactory()); registerFieldTransformerFactory(Constants.DefaultActions.Set.REMOVE,
new FieldRemoveTransformerFactory());
siis/coal
src/main/java/edu/psu/cse/siis/coal/transformers/TopPropagationTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/TopPropagationValue.java // public final class TopPropagationValue implements BasePropagationValue { // private static final TopPropagationValue instance = new TopPropagationValue(); // // private TopPropagationValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static TopPropagationValue v() { // return instance; // } // // @Override // public String toString() { // return "top"; // } // }
import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.TopPropagationValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.transformers; /** * A "top" transformer, which maps everything to a "top" value. This is a singleton. */ public class TopPropagationTransformer extends AllTop<BasePropagationValue> { private static TopPropagationTransformer instance = new TopPropagationTransformer(); /** * Returns the singleton instance for this class. * * @return The singleton instance for this class. */ public static TopPropagationTransformer v() { return instance; } private TopPropagationTransformer() {
// Path: src/main/java/edu/psu/cse/siis/coal/values/BasePropagationValue.java // public interface BasePropagationValue { // } // // Path: src/main/java/edu/psu/cse/siis/coal/values/TopPropagationValue.java // public final class TopPropagationValue implements BasePropagationValue { // private static final TopPropagationValue instance = new TopPropagationValue(); // // private TopPropagationValue() { // } // // /** // * Returns the singleton instance for this class. // * // * @return The singleton instance for this class. // */ // public static TopPropagationValue v() { // return instance; // } // // @Override // public String toString() { // return "top"; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/transformers/TopPropagationTransformer.java import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.TopPropagationValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.transformers; /** * A "top" transformer, which maps everything to a "top" value. This is a singleton. */ public class TopPropagationTransformer extends AllTop<BasePropagationValue> { private static TopPropagationTransformer instance = new TopPropagationTransformer(); /** * Returns the singleton instance for this class. * * @return The singleton instance for this class. */ public static TopPropagationTransformer v() { return instance; } private TopPropagationTransformer() {
super(TopPropagationValue.v());
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // }
import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for clear field transformers. */ public class FieldClearTransformerFactory extends FieldTransformerFactory { @Override
// Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformer.java // public abstract class FieldTransformer implements Internable<FieldTransformer> { // private static final Pool<FieldTransformer> POOL = new Pool<>(); // // /** // * Applies this field transformer to a {@link FieldValue}. // * // * @param fieldValue A field value. // * @return A field value. // */ // public abstract FieldValue apply(FieldValue fieldValue); // // /** // * Composes this field transformer with another one. // * // * @param secondFieldOperation A field transformer. // * @return The result of composing this field transformer with the argument transformer. // */ // public abstract FieldTransformer compose(FieldTransformer secondFieldOperation); // // @Override // public FieldTransformer intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/FieldTransformerFactory.java // public abstract class FieldTransformerFactory { // // /** // * Returns a field transformer for a given COAL argument value. Most subclasses should override // * this method. // * // * @param value An argument value. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Object value) { // throw new RuntimeException("makeFieldTransformer(value) not implemented in factory " // + this.getClass().toString()); // } // // /** // * Returns a field transformer for a given variable, a given statement and an operation. // * // * At the moment, this is not used. // * // * @param symbol A COAL symbol (variable). // * @param stmt A COAL modifier. // * @param op An operation to be performed on a field. // * @return A field transformer. // */ // public FieldTransformer makeFieldTransformer(Value symbol, Stmt stmt, String op) { // throw new RuntimeException("makeFieldTransformer(symbol, stmt) not implemented in factory " // + this.getClass().toString()); // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/set/FieldClearTransformerFactory.java import edu.psu.cse.siis.coal.field.transformers.FieldTransformer; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerFactory; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers.set; /** * A factory for clear field transformers. */ public class FieldClearTransformerFactory extends FieldTransformerFactory { @Override
public FieldTransformer makeFieldTransformer(Object value) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/NullFieldTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/NullFieldValue.java // public class NullFieldValue extends FieldValue { // private static NullFieldValue instance = new NullFieldValue(); // // private NullFieldValue() { // } // // public static NullFieldValue v() { // return instance; // } // // @Override // public Object getValue() { // return null; // } // // @Override // public String toString() { // return "null"; // } // }
import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.NullFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A {@link FieldTransformer} that replaces values with null. This can be applied to any field type. */ public class NullFieldTransformer extends FieldTransformer { private static NullFieldTransformer instance = new NullFieldTransformer(); private NullFieldTransformer() { } public static NullFieldTransformer v() { return instance; }
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/NullFieldValue.java // public class NullFieldValue extends FieldValue { // private static NullFieldValue instance = new NullFieldValue(); // // private NullFieldValue() { // } // // public static NullFieldValue v() { // return instance; // } // // @Override // public Object getValue() { // return null; // } // // @Override // public String toString() { // return "null"; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/NullFieldTransformer.java import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.NullFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A {@link FieldTransformer} that replaces values with null. This can be applied to any field type. */ public class NullFieldTransformer extends FieldTransformer { private static NullFieldTransformer instance = new NullFieldTransformer(); private NullFieldTransformer() { } public static NullFieldTransformer v() { return instance; }
public FieldValue apply(FieldValue fieldValue) {
siis/coal
src/main/java/edu/psu/cse/siis/coal/field/transformers/NullFieldTransformer.java
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/NullFieldValue.java // public class NullFieldValue extends FieldValue { // private static NullFieldValue instance = new NullFieldValue(); // // private NullFieldValue() { // } // // public static NullFieldValue v() { // return instance; // } // // @Override // public Object getValue() { // return null; // } // // @Override // public String toString() { // return "null"; // } // }
import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.NullFieldValue;
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A {@link FieldTransformer} that replaces values with null. This can be applied to any field type. */ public class NullFieldTransformer extends FieldTransformer { private static NullFieldTransformer instance = new NullFieldTransformer(); private NullFieldTransformer() { } public static NullFieldTransformer v() { return instance; } public FieldValue apply(FieldValue fieldValue) {
// Path: src/main/java/edu/psu/cse/siis/coal/field/values/FieldValue.java // public abstract class FieldValue implements Internable<FieldValue> { // private static final Pool<FieldValue> POOL = new Pool<>(); // // /** // * Returns the value represented by this field value. // * // * @return The value represented by this field value. // */ // public abstract Object getValue(); // // /** // * Determines if the field value makes a reference to another COAL value. In other words, this // * determines if the field value is not completely resolved. // * // * @return True if the field value makes a reference to another COAL value. // */ // public boolean hasTransformerSequence() { // return false; // } // // @Override // public FieldValue intern() { // return POOL.intern(this); // } // } // // Path: src/main/java/edu/psu/cse/siis/coal/field/values/NullFieldValue.java // public class NullFieldValue extends FieldValue { // private static NullFieldValue instance = new NullFieldValue(); // // private NullFieldValue() { // } // // public static NullFieldValue v() { // return instance; // } // // @Override // public Object getValue() { // return null; // } // // @Override // public String toString() { // return "null"; // } // } // Path: src/main/java/edu/psu/cse/siis/coal/field/transformers/NullFieldTransformer.java import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.NullFieldValue; /* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * 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 edu.psu.cse.siis.coal.field.transformers; /** * A {@link FieldTransformer} that replaces values with null. This can be applied to any field type. */ public class NullFieldTransformer extends FieldTransformer { private static NullFieldTransformer instance = new NullFieldTransformer(); private NullFieldTransformer() { } public static NullFieldTransformer v() { return instance; } public FieldValue apply(FieldValue fieldValue) {
return NullFieldValue.v();
census-instrumentation/opencensus-java
contrib/log_correlation/stackdriver/src/main/java/io/opencensus/contrib/logcorrelation/stackdriver/OpenCensusTraceLoggingEnhancer.java
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java // public class ContextHandleUtils { // // // No instance of this class. // private ContextHandleUtils() {} // // private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); // private static final ContextManager CONTEXT_MANAGER = // loadContextManager(ContextManager.class.getClassLoader()); // // private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { // try { // return Provider.createInstance( // Class.forName( // "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", // /*initialize=*/ true, // classLoader), // ContextManager.class); // } catch (ClassNotFoundException e) { // LOGGER.log( // Level.FINE, // "Couldn't load full implementation for OpenTelemetry context manager, now loading " // + "original implementation.", // e); // } // return new ContextManagerImpl(); // } // // public static ContextHandle currentContext() { // return CONTEXT_MANAGER.currentContext(); // } // // /** // * Creates a new {@code ContextHandle} with the given value set. // * // * @param context the parent {@code ContextHandle}. // * @param span the value to be set. // * @return a new context with the given value set. // */ // public static ContextHandle withValue( // ContextHandle context, @javax.annotation.Nullable Span span) { // return CONTEXT_MANAGER.withValue(context, span); // } // // /** // * Returns the value from the specified {@code ContextHandle}. // * // * @param context the specified {@code ContextHandle}. // * @return the value from the specified {@code ContextHandle}. // */ // public static Span getValue(ContextHandle context) { // return CONTEXT_MANAGER.getValue(context); // } // // /** // * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}. // * // * @return The context, or null if not a GRPC backed context handle. // */ // @Nullable // public static Context tryExtractGrpcContext(ContextHandle handle) { // if (handle instanceof ContextHandleImpl) { // return ((ContextHandleImpl) handle).getContext(); // } // // TODO: see if we can do something for the OpenTelemetry shim. // return null; // } // }
import com.google.cloud.ServiceOptions; import com.google.cloud.logging.LogEntry; import com.google.cloud.logging.LoggingEnhancer; import io.opencensus.trace.Span; import io.opencensus.trace.SpanContext; import io.opencensus.trace.TraceId; import io.opencensus.trace.unsafe.ContextHandleUtils; import java.util.logging.LogManager; import javax.annotation.Nullable;
@Nullable private static String lookUpProjectId() { String projectIdProperty = lookUpProperty(PROJECT_ID_PROPERTY_NAME); return projectIdProperty == null || projectIdProperty.isEmpty() ? ServiceOptions.getDefaultProjectId() : projectIdProperty; } // An OpenCensusTraceLoggingEnhancer property can be set with a logging property or a system // property. @Nullable private static String lookUpProperty(String name) { String property = LogManager.getLogManager().getProperty(name); return property == null || property.isEmpty() ? System.getProperty(name) : property; } // visible for testing @Nullable String getProjectId() { return projectId; } // This method avoids getting the current span when the feature is disabled, for efficiency. @Override public void enhanceLogEntry(LogEntry.Builder builder) { addTracingData(tracePrefix, getCurrentSpanContext(), builder); } private static SpanContext getCurrentSpanContext() {
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java // public class ContextHandleUtils { // // // No instance of this class. // private ContextHandleUtils() {} // // private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); // private static final ContextManager CONTEXT_MANAGER = // loadContextManager(ContextManager.class.getClassLoader()); // // private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { // try { // return Provider.createInstance( // Class.forName( // "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", // /*initialize=*/ true, // classLoader), // ContextManager.class); // } catch (ClassNotFoundException e) { // LOGGER.log( // Level.FINE, // "Couldn't load full implementation for OpenTelemetry context manager, now loading " // + "original implementation.", // e); // } // return new ContextManagerImpl(); // } // // public static ContextHandle currentContext() { // return CONTEXT_MANAGER.currentContext(); // } // // /** // * Creates a new {@code ContextHandle} with the given value set. // * // * @param context the parent {@code ContextHandle}. // * @param span the value to be set. // * @return a new context with the given value set. // */ // public static ContextHandle withValue( // ContextHandle context, @javax.annotation.Nullable Span span) { // return CONTEXT_MANAGER.withValue(context, span); // } // // /** // * Returns the value from the specified {@code ContextHandle}. // * // * @param context the specified {@code ContextHandle}. // * @return the value from the specified {@code ContextHandle}. // */ // public static Span getValue(ContextHandle context) { // return CONTEXT_MANAGER.getValue(context); // } // // /** // * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}. // * // * @return The context, or null if not a GRPC backed context handle. // */ // @Nullable // public static Context tryExtractGrpcContext(ContextHandle handle) { // if (handle instanceof ContextHandleImpl) { // return ((ContextHandleImpl) handle).getContext(); // } // // TODO: see if we can do something for the OpenTelemetry shim. // return null; // } // } // Path: contrib/log_correlation/stackdriver/src/main/java/io/opencensus/contrib/logcorrelation/stackdriver/OpenCensusTraceLoggingEnhancer.java import com.google.cloud.ServiceOptions; import com.google.cloud.logging.LogEntry; import com.google.cloud.logging.LoggingEnhancer; import io.opencensus.trace.Span; import io.opencensus.trace.SpanContext; import io.opencensus.trace.TraceId; import io.opencensus.trace.unsafe.ContextHandleUtils; import java.util.logging.LogManager; import javax.annotation.Nullable; @Nullable private static String lookUpProjectId() { String projectIdProperty = lookUpProperty(PROJECT_ID_PROPERTY_NAME); return projectIdProperty == null || projectIdProperty.isEmpty() ? ServiceOptions.getDefaultProjectId() : projectIdProperty; } // An OpenCensusTraceLoggingEnhancer property can be set with a logging property or a system // property. @Nullable private static String lookUpProperty(String name) { String property = LogManager.getLogManager().getProperty(name); return property == null || property.isEmpty() ? System.getProperty(name) : property; } // visible for testing @Nullable String getProjectId() { return projectId; } // This method avoids getting the current span when the feature is disabled, for efficiency. @Override public void enhanceLogEntry(LogEntry.Builder builder) { addTracingData(tracePrefix, getCurrentSpanContext(), builder); } private static SpanContext getCurrentSpanContext() {
Span span = ContextHandleUtils.getValue(ContextHandleUtils.currentContext());
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java
// Path: api/src/main/java/io/opencensus/trace/ContextHandle.java // public interface ContextHandle { // // ContextHandle attach(); // // void detach(ContextHandle contextHandle); // } // // Path: api/src/main/java/io/opencensus/trace/ContextManager.java // public interface ContextManager { // // ContextHandle currentContext(); // // ContextHandle withValue(ContextHandle contextHandle, @javax.annotation.Nullable Span span); // // Span getValue(ContextHandle contextHandle); // }
import io.grpc.Context; import io.opencensus.internal.Provider; import io.opencensus.trace.ContextHandle; import io.opencensus.trace.ContextManager; import io.opencensus.trace.Span; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable;
/* * Copyright 2016-17, OpenCensus Authors * * 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 io.opencensus.trace.unsafe; public class ContextHandleUtils { // No instance of this class. private ContextHandleUtils() {} private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName());
// Path: api/src/main/java/io/opencensus/trace/ContextHandle.java // public interface ContextHandle { // // ContextHandle attach(); // // void detach(ContextHandle contextHandle); // } // // Path: api/src/main/java/io/opencensus/trace/ContextManager.java // public interface ContextManager { // // ContextHandle currentContext(); // // ContextHandle withValue(ContextHandle contextHandle, @javax.annotation.Nullable Span span); // // Span getValue(ContextHandle contextHandle); // } // Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java import io.grpc.Context; import io.opencensus.internal.Provider; import io.opencensus.trace.ContextHandle; import io.opencensus.trace.ContextManager; import io.opencensus.trace.Span; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /* * Copyright 2016-17, OpenCensus Authors * * 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 io.opencensus.trace.unsafe; public class ContextHandleUtils { // No instance of this class. private ContextHandleUtils() {} private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName());
private static final ContextManager CONTEXT_MANAGER =
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java
// Path: api/src/main/java/io/opencensus/trace/ContextHandle.java // public interface ContextHandle { // // ContextHandle attach(); // // void detach(ContextHandle contextHandle); // } // // Path: api/src/main/java/io/opencensus/trace/ContextManager.java // public interface ContextManager { // // ContextHandle currentContext(); // // ContextHandle withValue(ContextHandle contextHandle, @javax.annotation.Nullable Span span); // // Span getValue(ContextHandle contextHandle); // }
import io.grpc.Context; import io.opencensus.internal.Provider; import io.opencensus.trace.ContextHandle; import io.opencensus.trace.ContextManager; import io.opencensus.trace.Span; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable;
/* * Copyright 2016-17, OpenCensus Authors * * 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 io.opencensus.trace.unsafe; public class ContextHandleUtils { // No instance of this class. private ContextHandleUtils() {} private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); private static final ContextManager CONTEXT_MANAGER = loadContextManager(ContextManager.class.getClassLoader()); private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { try { return Provider.createInstance( Class.forName( "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", /*initialize=*/ true, classLoader), ContextManager.class); } catch (ClassNotFoundException e) { LOGGER.log( Level.FINE, "Couldn't load full implementation for OpenTelemetry context manager, now loading " + "original implementation.", e); } return new ContextManagerImpl(); }
// Path: api/src/main/java/io/opencensus/trace/ContextHandle.java // public interface ContextHandle { // // ContextHandle attach(); // // void detach(ContextHandle contextHandle); // } // // Path: api/src/main/java/io/opencensus/trace/ContextManager.java // public interface ContextManager { // // ContextHandle currentContext(); // // ContextHandle withValue(ContextHandle contextHandle, @javax.annotation.Nullable Span span); // // Span getValue(ContextHandle contextHandle); // } // Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java import io.grpc.Context; import io.opencensus.internal.Provider; import io.opencensus.trace.ContextHandle; import io.opencensus.trace.ContextManager; import io.opencensus.trace.Span; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /* * Copyright 2016-17, OpenCensus Authors * * 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 io.opencensus.trace.unsafe; public class ContextHandleUtils { // No instance of this class. private ContextHandleUtils() {} private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); private static final ContextManager CONTEXT_MANAGER = loadContextManager(ContextManager.class.getClassLoader()); private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { try { return Provider.createInstance( Class.forName( "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", /*initialize=*/ true, classLoader), ContextManager.class); } catch (ClassNotFoundException e) { LOGGER.log( Level.FINE, "Couldn't load full implementation for OpenTelemetry context manager, now loading " + "original implementation.", e); } return new ContextManagerImpl(); }
public static ContextHandle currentContext() {
census-instrumentation/opencensus-java
contrib/log_correlation/log4j2/src/main/java/io/opencensus/contrib/logcorrelation/log4j2/ContextDataUtils.java
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java // public class ContextHandleUtils { // // // No instance of this class. // private ContextHandleUtils() {} // // private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); // private static final ContextManager CONTEXT_MANAGER = // loadContextManager(ContextManager.class.getClassLoader()); // // private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { // try { // return Provider.createInstance( // Class.forName( // "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", // /*initialize=*/ true, // classLoader), // ContextManager.class); // } catch (ClassNotFoundException e) { // LOGGER.log( // Level.FINE, // "Couldn't load full implementation for OpenTelemetry context manager, now loading " // + "original implementation.", // e); // } // return new ContextManagerImpl(); // } // // public static ContextHandle currentContext() { // return CONTEXT_MANAGER.currentContext(); // } // // /** // * Creates a new {@code ContextHandle} with the given value set. // * // * @param context the parent {@code ContextHandle}. // * @param span the value to be set. // * @return a new context with the given value set. // */ // public static ContextHandle withValue( // ContextHandle context, @javax.annotation.Nullable Span span) { // return CONTEXT_MANAGER.withValue(context, span); // } // // /** // * Returns the value from the specified {@code ContextHandle}. // * // * @param context the specified {@code ContextHandle}. // * @return the value from the specified {@code ContextHandle}. // */ // public static Span getValue(ContextHandle context) { // return CONTEXT_MANAGER.getValue(context); // } // // /** // * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}. // * // * @return The context, or null if not a GRPC backed context handle. // */ // @Nullable // public static Context tryExtractGrpcContext(ContextHandle handle) { // if (handle instanceof ContextHandleImpl) { // return ((ContextHandleImpl) handle).getContext(); // } // // TODO: see if we can do something for the OpenTelemetry shim. // return null; // } // }
import io.opencensus.trace.Span; import io.opencensus.trace.SpanContext; import io.opencensus.trace.unsafe.ContextHandleUtils; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.spi.ReadOnlyThreadContextMap; import org.apache.logging.log4j.util.SortedArrayStringMap; import org.apache.logging.log4j.util.StringMap;
} static StringMap getContextAndTracingData() { SpanContext spanContext = getCurrentSpanContext(); ReadOnlyThreadContextMap context = ThreadContext.getThreadContextMap(); SortedArrayStringMap stringMap; if (context == null) { stringMap = new SortedArrayStringMap(ThreadContext.getImmutableContext()); } else { StringMap contextData = context.getReadOnlyContextData(); stringMap = new SortedArrayStringMap(contextData.size() + 3); stringMap.putAll(contextData); } // TODO(sebright): Move the calls to TraceId.toLowerBase16() and SpanId.toLowerBase16() out of // the critical path by wrapping the trace and span IDs in objects that call toLowerBase16() in // their toString() methods, after there is a fix for // https://github.com/census-instrumentation/opencensus-java/issues/1436. stringMap.putValue( OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY, spanContext.getTraceId().toLowerBase16()); stringMap.putValue( OpenCensusTraceContextDataInjector.SPAN_ID_CONTEXT_KEY, spanContext.getSpanId().toLowerBase16()); stringMap.putValue( OpenCensusTraceContextDataInjector.TRACE_SAMPLED_CONTEXT_KEY, spanContext.getTraceOptions().isSampled() ? "true" : "false"); return stringMap; } private static SpanContext getCurrentSpanContext() {
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java // public class ContextHandleUtils { // // // No instance of this class. // private ContextHandleUtils() {} // // private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); // private static final ContextManager CONTEXT_MANAGER = // loadContextManager(ContextManager.class.getClassLoader()); // // private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { // try { // return Provider.createInstance( // Class.forName( // "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", // /*initialize=*/ true, // classLoader), // ContextManager.class); // } catch (ClassNotFoundException e) { // LOGGER.log( // Level.FINE, // "Couldn't load full implementation for OpenTelemetry context manager, now loading " // + "original implementation.", // e); // } // return new ContextManagerImpl(); // } // // public static ContextHandle currentContext() { // return CONTEXT_MANAGER.currentContext(); // } // // /** // * Creates a new {@code ContextHandle} with the given value set. // * // * @param context the parent {@code ContextHandle}. // * @param span the value to be set. // * @return a new context with the given value set. // */ // public static ContextHandle withValue( // ContextHandle context, @javax.annotation.Nullable Span span) { // return CONTEXT_MANAGER.withValue(context, span); // } // // /** // * Returns the value from the specified {@code ContextHandle}. // * // * @param context the specified {@code ContextHandle}. // * @return the value from the specified {@code ContextHandle}. // */ // public static Span getValue(ContextHandle context) { // return CONTEXT_MANAGER.getValue(context); // } // // /** // * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}. // * // * @return The context, or null if not a GRPC backed context handle. // */ // @Nullable // public static Context tryExtractGrpcContext(ContextHandle handle) { // if (handle instanceof ContextHandleImpl) { // return ((ContextHandleImpl) handle).getContext(); // } // // TODO: see if we can do something for the OpenTelemetry shim. // return null; // } // } // Path: contrib/log_correlation/log4j2/src/main/java/io/opencensus/contrib/logcorrelation/log4j2/ContextDataUtils.java import io.opencensus.trace.Span; import io.opencensus.trace.SpanContext; import io.opencensus.trace.unsafe.ContextHandleUtils; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.spi.ReadOnlyThreadContextMap; import org.apache.logging.log4j.util.SortedArrayStringMap; import org.apache.logging.log4j.util.StringMap; } static StringMap getContextAndTracingData() { SpanContext spanContext = getCurrentSpanContext(); ReadOnlyThreadContextMap context = ThreadContext.getThreadContextMap(); SortedArrayStringMap stringMap; if (context == null) { stringMap = new SortedArrayStringMap(ThreadContext.getImmutableContext()); } else { StringMap contextData = context.getReadOnlyContextData(); stringMap = new SortedArrayStringMap(contextData.size() + 3); stringMap.putAll(contextData); } // TODO(sebright): Move the calls to TraceId.toLowerBase16() and SpanId.toLowerBase16() out of // the critical path by wrapping the trace and span IDs in objects that call toLowerBase16() in // their toString() methods, after there is a fix for // https://github.com/census-instrumentation/opencensus-java/issues/1436. stringMap.putValue( OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY, spanContext.getTraceId().toLowerBase16()); stringMap.putValue( OpenCensusTraceContextDataInjector.SPAN_ID_CONTEXT_KEY, spanContext.getSpanId().toLowerBase16()); stringMap.putValue( OpenCensusTraceContextDataInjector.TRACE_SAMPLED_CONTEXT_KEY, spanContext.getTraceOptions().isSampled() ? "true" : "false"); return stringMap; } private static SpanContext getCurrentSpanContext() {
Span span = ContextHandleUtils.getValue(ContextHandleUtils.currentContext());
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/CurrentSpanUtils.java
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java // public class ContextHandleUtils { // // // No instance of this class. // private ContextHandleUtils() {} // // private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); // private static final ContextManager CONTEXT_MANAGER = // loadContextManager(ContextManager.class.getClassLoader()); // // private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { // try { // return Provider.createInstance( // Class.forName( // "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", // /*initialize=*/ true, // classLoader), // ContextManager.class); // } catch (ClassNotFoundException e) { // LOGGER.log( // Level.FINE, // "Couldn't load full implementation for OpenTelemetry context manager, now loading " // + "original implementation.", // e); // } // return new ContextManagerImpl(); // } // // public static ContextHandle currentContext() { // return CONTEXT_MANAGER.currentContext(); // } // // /** // * Creates a new {@code ContextHandle} with the given value set. // * // * @param context the parent {@code ContextHandle}. // * @param span the value to be set. // * @return a new context with the given value set. // */ // public static ContextHandle withValue( // ContextHandle context, @javax.annotation.Nullable Span span) { // return CONTEXT_MANAGER.withValue(context, span); // } // // /** // * Returns the value from the specified {@code ContextHandle}. // * // * @param context the specified {@code ContextHandle}. // * @return the value from the specified {@code ContextHandle}. // */ // public static Span getValue(ContextHandle context) { // return CONTEXT_MANAGER.getValue(context); // } // // /** // * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}. // * // * @return The context, or null if not a GRPC backed context handle. // */ // @Nullable // public static Context tryExtractGrpcContext(ContextHandle handle) { // if (handle instanceof ContextHandleImpl) { // return ((ContextHandleImpl) handle).getContext(); // } // // TODO: see if we can do something for the OpenTelemetry shim. // return null; // } // }
import io.opencensus.common.Scope; import io.opencensus.trace.unsafe.ContextHandleUtils; import java.util.concurrent.Callable; import javax.annotation.Nullable;
/* * Copyright 2017, OpenCensus Authors * * 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 io.opencensus.trace; /** Util methods/functionality to interact with the {@link Span} in the {@link io.grpc.Context}. */ final class CurrentSpanUtils { // No instance of this class. private CurrentSpanUtils() {} /** * Returns The {@link Span} from the current context. * * @return The {@code Span} from the current context. */ @Nullable static Span getCurrentSpan() {
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java // public class ContextHandleUtils { // // // No instance of this class. // private ContextHandleUtils() {} // // private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName()); // private static final ContextManager CONTEXT_MANAGER = // loadContextManager(ContextManager.class.getClassLoader()); // // private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) { // try { // return Provider.createInstance( // Class.forName( // "io.opentelemetry.opencensusshim.OpenTelemetryContextManager", // /*initialize=*/ true, // classLoader), // ContextManager.class); // } catch (ClassNotFoundException e) { // LOGGER.log( // Level.FINE, // "Couldn't load full implementation for OpenTelemetry context manager, now loading " // + "original implementation.", // e); // } // return new ContextManagerImpl(); // } // // public static ContextHandle currentContext() { // return CONTEXT_MANAGER.currentContext(); // } // // /** // * Creates a new {@code ContextHandle} with the given value set. // * // * @param context the parent {@code ContextHandle}. // * @param span the value to be set. // * @return a new context with the given value set. // */ // public static ContextHandle withValue( // ContextHandle context, @javax.annotation.Nullable Span span) { // return CONTEXT_MANAGER.withValue(context, span); // } // // /** // * Returns the value from the specified {@code ContextHandle}. // * // * @param context the specified {@code ContextHandle}. // * @return the value from the specified {@code ContextHandle}. // */ // public static Span getValue(ContextHandle context) { // return CONTEXT_MANAGER.getValue(context); // } // // /** // * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}. // * // * @return The context, or null if not a GRPC backed context handle. // */ // @Nullable // public static Context tryExtractGrpcContext(ContextHandle handle) { // if (handle instanceof ContextHandleImpl) { // return ((ContextHandleImpl) handle).getContext(); // } // // TODO: see if we can do something for the OpenTelemetry shim. // return null; // } // } // Path: api/src/main/java/io/opencensus/trace/CurrentSpanUtils.java import io.opencensus.common.Scope; import io.opencensus.trace.unsafe.ContextHandleUtils; import java.util.concurrent.Callable; import javax.annotation.Nullable; /* * Copyright 2017, OpenCensus Authors * * 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 io.opencensus.trace; /** Util methods/functionality to interact with the {@link Span} in the {@link io.grpc.Context}. */ final class CurrentSpanUtils { // No instance of this class. private CurrentSpanUtils() {} /** * Returns The {@link Span} from the current context. * * @return The {@code Span} from the current context. */ @Nullable static Span getCurrentSpan() {
return ContextHandleUtils.getValue(ContextHandleUtils.currentContext());
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final Duration DEFAULT_DEADLINE = Duration.create(60, 0); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final String DEFAULT_PROJECT_ID = // Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource(); // // Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java // @ExperimentalApi // public final class OpenCensusLibraryInformation { // // /** // * The current version of the OpenCensus Java library. // * // * @since 0.8 // */ // public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION // // private OpenCensusLibraryInformation() {} // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE; import com.google.api.MonitoredResource; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.cloud.monitoring.v3.stub.MetricServiceStub; import com.google.common.annotations.VisibleForTesting; import io.opencensus.common.Duration; import io.opencensus.common.OpenCensusLibraryInformation; import io.opencensus.exporter.metrics.util.IntervalMetricReader; import io.opencensus.exporter.metrics.util.MetricReader; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; import io.opencensus.metrics.Metrics; import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe;
/* * Copyright 2017, OpenCensus Authors * * 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 io.opencensus.exporter.stats.stackdriver; /** * Exporter to Stackdriver Monitoring Client API v3. * * <p>Example of usage on Google Cloud VMs: * * <pre><code> * public static void main(String[] args) { * StackdriverStatsExporter.createAndRegister( * StackdriverStatsConfiguration * .builder() * .setProjectId("MyStackdriverProjectId") * .setExportInterval(Duration.fromMillis(100000)) * .build()); * ... // Do work. * } * </code></pre> * * @since 0.9 */ @ThreadSafe public final class StackdriverStatsExporter { @VisibleForTesting static final Object monitor = new Object(); @GuardedBy("monitor") @Nullable private static StackdriverStatsExporter instance = null; @GuardedBy("monitor") @Nullable private static MetricServiceClient metricServiceClient = null; private static final String EXPORTER_SPAN_NAME = "ExportMetricsToStackdriver"; // See io.grpc.internal.GrpcUtil.USER_AGENT_KEY private static final String USER_AGENT_KEY = "user-agent"; private static final String USER_AGENT =
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final Duration DEFAULT_DEADLINE = Duration.create(60, 0); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final String DEFAULT_PROJECT_ID = // Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource(); // // Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java // @ExperimentalApi // public final class OpenCensusLibraryInformation { // // /** // * The current version of the OpenCensus Java library. // * // * @since 0.8 // */ // public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION // // private OpenCensusLibraryInformation() {} // } // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE; import com.google.api.MonitoredResource; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.cloud.monitoring.v3.stub.MetricServiceStub; import com.google.common.annotations.VisibleForTesting; import io.opencensus.common.Duration; import io.opencensus.common.OpenCensusLibraryInformation; import io.opencensus.exporter.metrics.util.IntervalMetricReader; import io.opencensus.exporter.metrics.util.MetricReader; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; import io.opencensus.metrics.Metrics; import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; /* * Copyright 2017, OpenCensus Authors * * 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 io.opencensus.exporter.stats.stackdriver; /** * Exporter to Stackdriver Monitoring Client API v3. * * <p>Example of usage on Google Cloud VMs: * * <pre><code> * public static void main(String[] args) { * StackdriverStatsExporter.createAndRegister( * StackdriverStatsConfiguration * .builder() * .setProjectId("MyStackdriverProjectId") * .setExportInterval(Duration.fromMillis(100000)) * .build()); * ... // Do work. * } * </code></pre> * * @since 0.9 */ @ThreadSafe public final class StackdriverStatsExporter { @VisibleForTesting static final Object monitor = new Object(); @GuardedBy("monitor") @Nullable private static StackdriverStatsExporter instance = null; @GuardedBy("monitor") @Nullable private static MetricServiceClient metricServiceClient = null; private static final String EXPORTER_SPAN_NAME = "ExportMetricsToStackdriver"; // See io.grpc.internal.GrpcUtil.USER_AGENT_KEY private static final String USER_AGENT_KEY = "user-agent"; private static final String USER_AGENT =
"opencensus-java/" + OpenCensusLibraryInformation.VERSION;
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final Duration DEFAULT_DEADLINE = Duration.create(60, 0); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final String DEFAULT_PROJECT_ID = // Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource(); // // Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java // @ExperimentalApi // public final class OpenCensusLibraryInformation { // // /** // * The current version of the OpenCensus Java library. // * // * @since 0.8 // */ // public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION // // private OpenCensusLibraryInformation() {} // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE; import com.google.api.MonitoredResource; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.cloud.monitoring.v3.stub.MetricServiceStub; import com.google.common.annotations.VisibleForTesting; import io.opencensus.common.Duration; import io.opencensus.common.OpenCensusLibraryInformation; import io.opencensus.exporter.metrics.util.IntervalMetricReader; import io.opencensus.exporter.metrics.util.MetricReader; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; import io.opencensus.metrics.Metrics; import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe;
.setMetricProducerManager( Metrics.getExportComponent().getMetricProducerManager()) .setSpanName(EXPORTER_SPAN_NAME) .build()), intervalMetricReaderOptionsBuilder.build()); } /** * Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials, * with default Monitored Resource. * * <p>Only one Stackdriver exporter can be created. * * @param credentials a credentials used to authenticate API calls. * @param projectId the cloud project id. * @param exportInterval the interval between pushing stats to StackDriver. * @throws IllegalStateException if a Stackdriver exporter already exists. * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. * @since 0.9 */ @Deprecated public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId, Duration exportInterval) throws IOException { checkNotNull(credentials, "credentials"); checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( credentials, projectId, exportInterval,
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final Duration DEFAULT_DEADLINE = Duration.create(60, 0); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final String DEFAULT_PROJECT_ID = // Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource(); // // Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java // @ExperimentalApi // public final class OpenCensusLibraryInformation { // // /** // * The current version of the OpenCensus Java library. // * // * @since 0.8 // */ // public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION // // private OpenCensusLibraryInformation() {} // } // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE; import com.google.api.MonitoredResource; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.cloud.monitoring.v3.stub.MetricServiceStub; import com.google.common.annotations.VisibleForTesting; import io.opencensus.common.Duration; import io.opencensus.common.OpenCensusLibraryInformation; import io.opencensus.exporter.metrics.util.IntervalMetricReader; import io.opencensus.exporter.metrics.util.MetricReader; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; import io.opencensus.metrics.Metrics; import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; .setMetricProducerManager( Metrics.getExportComponent().getMetricProducerManager()) .setSpanName(EXPORTER_SPAN_NAME) .build()), intervalMetricReaderOptionsBuilder.build()); } /** * Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials, * with default Monitored Resource. * * <p>Only one Stackdriver exporter can be created. * * @param credentials a credentials used to authenticate API calls. * @param projectId the cloud project id. * @param exportInterval the interval between pushing stats to StackDriver. * @throws IllegalStateException if a Stackdriver exporter already exists. * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. * @since 0.9 */ @Deprecated public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId, Duration exportInterval) throws IOException { checkNotNull(credentials, "credentials"); checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( credentials, projectId, exportInterval,
DEFAULT_RESOURCE,
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final Duration DEFAULT_DEADLINE = Duration.create(60, 0); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final String DEFAULT_PROJECT_ID = // Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource(); // // Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java // @ExperimentalApi // public final class OpenCensusLibraryInformation { // // /** // * The current version of the OpenCensus Java library. // * // * @since 0.8 // */ // public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION // // private OpenCensusLibraryInformation() {} // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE; import com.google.api.MonitoredResource; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.cloud.monitoring.v3.stub.MetricServiceStub; import com.google.common.annotations.VisibleForTesting; import io.opencensus.common.Duration; import io.opencensus.common.OpenCensusLibraryInformation; import io.opencensus.exporter.metrics.util.IntervalMetricReader; import io.opencensus.exporter.metrics.util.MetricReader; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; import io.opencensus.metrics.Metrics; import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe;
intervalMetricReaderOptionsBuilder.build()); } /** * Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials, * with default Monitored Resource. * * <p>Only one Stackdriver exporter can be created. * * @param credentials a credentials used to authenticate API calls. * @param projectId the cloud project id. * @param exportInterval the interval between pushing stats to StackDriver. * @throws IllegalStateException if a Stackdriver exporter already exists. * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. * @since 0.9 */ @Deprecated public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId, Duration exportInterval) throws IOException { checkNotNull(credentials, "credentials"); checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( credentials, projectId, exportInterval, DEFAULT_RESOURCE, null, null, DEFAULT_CONSTANT_LABELS,
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final Duration DEFAULT_DEADLINE = Duration.create(60, 0); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final String DEFAULT_PROJECT_ID = // Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); // // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java // static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource(); // // Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java // @ExperimentalApi // public final class OpenCensusLibraryInformation { // // /** // * The current version of the OpenCensus Java library. // * // * @since 0.8 // */ // public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION // // private OpenCensusLibraryInformation() {} // } // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID; import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE; import com.google.api.MonitoredResource; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.cloud.monitoring.v3.stub.MetricServiceStub; import com.google.common.annotations.VisibleForTesting; import io.opencensus.common.Duration; import io.opencensus.common.OpenCensusLibraryInformation; import io.opencensus.exporter.metrics.util.IntervalMetricReader; import io.opencensus.exporter.metrics.util.MetricReader; import io.opencensus.metrics.LabelKey; import io.opencensus.metrics.LabelValue; import io.opencensus.metrics.Metrics; import java.io.IOException; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; intervalMetricReaderOptionsBuilder.build()); } /** * Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials, * with default Monitored Resource. * * <p>Only one Stackdriver exporter can be created. * * @param credentials a credentials used to authenticate API calls. * @param projectId the cloud project id. * @param exportInterval the interval between pushing stats to StackDriver. * @throws IllegalStateException if a Stackdriver exporter already exists. * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. * @since 0.9 */ @Deprecated public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId, Duration exportInterval) throws IOException { checkNotNull(credentials, "credentials"); checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( credentials, projectId, exportInterval, DEFAULT_RESOURCE, null, null, DEFAULT_CONSTANT_LABELS,
DEFAULT_DEADLINE,