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
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/ClientApplication.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/CustomException.java // public class CustomException extends Exception implements IsSerializable{ // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java // public interface TestService extends RemoteService{ // // /** // * Adds two integers together and return result // * @param a // * @param b // * @return // */ // int add(int a, int b); // // /** // * Set a session attribute and return old value // * @param name // * @param value // * @return // */ // String replaceAttribute(String name, String value); // // /** // * Set a session attribute and return old value. Should use // * an alternative implementation to access the servlet session. // * @param name // * @param value // * @return // */ // String replaceAttributeAlt(String name, String value); // // /** // * Throws an exceptions that has been declared in the interface} // * @throws CustomException // */ // void throwDeclaredException() throws CustomException; // // /** // * Throws an exceptions that has not been declared in the interface} // * @throws RuntimeException // */ // void throwUndeclaredException(); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link GWTSerialisableObject} // */ // // GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link JavaSerialisableObject} // */ // // JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o); // // /** // * Returns a random number. // * @return // */ // Integer getRandomNumber(); // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java // public interface TestServiceAsync { // // void add(int a, int b, AsyncCallback<Integer> callback); // // void throwDeclaredException(AsyncCallback<Void> callback); // // void throwUndeclaredException(AsyncCallback<Object> callback); // // void replaceAttribute(String name, String value, AsyncCallback<String> callback); // // void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); // // void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback); // // void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback); // // void getRandomNumber(AsyncCallback<Integer> callback); // // }
import java.io.Serializable; import java.util.Date; import org.gwtwidgets.server.spring.test.common.CustomException; import org.gwtwidgets.server.spring.test.common.TestService; import org.gwtwidgets.server.spring.test.common.TestServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel;
String testUrls[] = { "../handler/service", "../handler/tx", "../handler/pojo", "../handler/extended", "../exporter/service", "../exporter/tx", "../exporter/pojo", "../exporter/extended", "../annotation/service", "../exporter/pojo", "../exporter/pojo", "../exporter/pojo" }; String testLabel[] = { "GWTHandler with RPC service", "GWTHandler with transaction RPC service", "GWTHandler with POJO service", "GWTHandler with extending service", "GWTRPCServiceExporter with RPC service", "GWTRPCServiceExporter transaction RPC service", "GWTRPCServiceExporter POJO service", "GWTRPCServiceExporter extending service", "Annotated service", "GWTRPCServiceExporter POJO service" }; int testIndex = 0; String newRandomString() { return "" + Math.random(); } void log(String text) { HTML html = new HTML("(" + testIndex + ") " + text); currentPanel.add(html); html.getElement().scrollIntoView(); } void fail(String text, Throwable t) { log("<span class='error' style='color:red'>" + text + "</span>"); if (t != null) log("<pre>" + t + "</pre>"); GWT.log(text, t); throw (t == null ? new RuntimeException("Test failed") : new RuntimeException(t)); }
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/CustomException.java // public class CustomException extends Exception implements IsSerializable{ // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java // public interface TestService extends RemoteService{ // // /** // * Adds two integers together and return result // * @param a // * @param b // * @return // */ // int add(int a, int b); // // /** // * Set a session attribute and return old value // * @param name // * @param value // * @return // */ // String replaceAttribute(String name, String value); // // /** // * Set a session attribute and return old value. Should use // * an alternative implementation to access the servlet session. // * @param name // * @param value // * @return // */ // String replaceAttributeAlt(String name, String value); // // /** // * Throws an exceptions that has been declared in the interface} // * @throws CustomException // */ // void throwDeclaredException() throws CustomException; // // /** // * Throws an exceptions that has not been declared in the interface} // * @throws RuntimeException // */ // void throwUndeclaredException(); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link GWTSerialisableObject} // */ // // GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link JavaSerialisableObject} // */ // // JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o); // // /** // * Returns a random number. // * @return // */ // Integer getRandomNumber(); // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java // public interface TestServiceAsync { // // void add(int a, int b, AsyncCallback<Integer> callback); // // void throwDeclaredException(AsyncCallback<Void> callback); // // void throwUndeclaredException(AsyncCallback<Object> callback); // // void replaceAttribute(String name, String value, AsyncCallback<String> callback); // // void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); // // void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback); // // void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback); // // void getRandomNumber(AsyncCallback<Integer> callback); // // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/ClientApplication.java import java.io.Serializable; import java.util.Date; import org.gwtwidgets.server.spring.test.common.CustomException; import org.gwtwidgets.server.spring.test.common.TestService; import org.gwtwidgets.server.spring.test.common.TestServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel; String testUrls[] = { "../handler/service", "../handler/tx", "../handler/pojo", "../handler/extended", "../exporter/service", "../exporter/tx", "../exporter/pojo", "../exporter/extended", "../annotation/service", "../exporter/pojo", "../exporter/pojo", "../exporter/pojo" }; String testLabel[] = { "GWTHandler with RPC service", "GWTHandler with transaction RPC service", "GWTHandler with POJO service", "GWTHandler with extending service", "GWTRPCServiceExporter with RPC service", "GWTRPCServiceExporter transaction RPC service", "GWTRPCServiceExporter POJO service", "GWTRPCServiceExporter extending service", "Annotated service", "GWTRPCServiceExporter POJO service" }; int testIndex = 0; String newRandomString() { return "" + Math.random(); } void log(String text) { HTML html = new HTML("(" + testIndex + ") " + text); currentPanel.add(html); html.getElement().scrollIntoView(); } void fail(String text, Throwable t) { log("<span class='error' style='color:red'>" + text + "</span>"); if (t != null) log("<pre>" + t + "</pre>"); GWT.log(text, t); throw (t == null ? new RuntimeException("Test failed") : new RuntimeException(t)); }
TestServiceAsync getService() {
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/ClientApplication.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/CustomException.java // public class CustomException extends Exception implements IsSerializable{ // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java // public interface TestService extends RemoteService{ // // /** // * Adds two integers together and return result // * @param a // * @param b // * @return // */ // int add(int a, int b); // // /** // * Set a session attribute and return old value // * @param name // * @param value // * @return // */ // String replaceAttribute(String name, String value); // // /** // * Set a session attribute and return old value. Should use // * an alternative implementation to access the servlet session. // * @param name // * @param value // * @return // */ // String replaceAttributeAlt(String name, String value); // // /** // * Throws an exceptions that has been declared in the interface} // * @throws CustomException // */ // void throwDeclaredException() throws CustomException; // // /** // * Throws an exceptions that has not been declared in the interface} // * @throws RuntimeException // */ // void throwUndeclaredException(); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link GWTSerialisableObject} // */ // // GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link JavaSerialisableObject} // */ // // JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o); // // /** // * Returns a random number. // * @return // */ // Integer getRandomNumber(); // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java // public interface TestServiceAsync { // // void add(int a, int b, AsyncCallback<Integer> callback); // // void throwDeclaredException(AsyncCallback<Void> callback); // // void throwUndeclaredException(AsyncCallback<Object> callback); // // void replaceAttribute(String name, String value, AsyncCallback<String> callback); // // void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); // // void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback); // // void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback); // // void getRandomNumber(AsyncCallback<Integer> callback); // // }
import java.io.Serializable; import java.util.Date; import org.gwtwidgets.server.spring.test.common.CustomException; import org.gwtwidgets.server.spring.test.common.TestService; import org.gwtwidgets.server.spring.test.common.TestServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel;
"../exporter/service", "../exporter/tx", "../exporter/pojo", "../exporter/extended", "../annotation/service", "../exporter/pojo", "../exporter/pojo", "../exporter/pojo" }; String testLabel[] = { "GWTHandler with RPC service", "GWTHandler with transaction RPC service", "GWTHandler with POJO service", "GWTHandler with extending service", "GWTRPCServiceExporter with RPC service", "GWTRPCServiceExporter transaction RPC service", "GWTRPCServiceExporter POJO service", "GWTRPCServiceExporter extending service", "Annotated service", "GWTRPCServiceExporter POJO service" }; int testIndex = 0; String newRandomString() { return "" + Math.random(); } void log(String text) { HTML html = new HTML("(" + testIndex + ") " + text); currentPanel.add(html); html.getElement().scrollIntoView(); } void fail(String text, Throwable t) { log("<span class='error' style='color:red'>" + text + "</span>"); if (t != null) log("<pre>" + t + "</pre>"); GWT.log(text, t); throw (t == null ? new RuntimeException("Test failed") : new RuntimeException(t)); } TestServiceAsync getService() {
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/CustomException.java // public class CustomException extends Exception implements IsSerializable{ // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java // public interface TestService extends RemoteService{ // // /** // * Adds two integers together and return result // * @param a // * @param b // * @return // */ // int add(int a, int b); // // /** // * Set a session attribute and return old value // * @param name // * @param value // * @return // */ // String replaceAttribute(String name, String value); // // /** // * Set a session attribute and return old value. Should use // * an alternative implementation to access the servlet session. // * @param name // * @param value // * @return // */ // String replaceAttributeAlt(String name, String value); // // /** // * Throws an exceptions that has been declared in the interface} // * @throws CustomException // */ // void throwDeclaredException() throws CustomException; // // /** // * Throws an exceptions that has not been declared in the interface} // * @throws RuntimeException // */ // void throwUndeclaredException(); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link GWTSerialisableObject} // */ // // GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link JavaSerialisableObject} // */ // // JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o); // // /** // * Returns a random number. // * @return // */ // Integer getRandomNumber(); // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java // public interface TestServiceAsync { // // void add(int a, int b, AsyncCallback<Integer> callback); // // void throwDeclaredException(AsyncCallback<Void> callback); // // void throwUndeclaredException(AsyncCallback<Object> callback); // // void replaceAttribute(String name, String value, AsyncCallback<String> callback); // // void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); // // void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback); // // void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback); // // void getRandomNumber(AsyncCallback<Integer> callback); // // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/ClientApplication.java import java.io.Serializable; import java.util.Date; import org.gwtwidgets.server.spring.test.common.CustomException; import org.gwtwidgets.server.spring.test.common.TestService; import org.gwtwidgets.server.spring.test.common.TestServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel; "../exporter/service", "../exporter/tx", "../exporter/pojo", "../exporter/extended", "../annotation/service", "../exporter/pojo", "../exporter/pojo", "../exporter/pojo" }; String testLabel[] = { "GWTHandler with RPC service", "GWTHandler with transaction RPC service", "GWTHandler with POJO service", "GWTHandler with extending service", "GWTRPCServiceExporter with RPC service", "GWTRPCServiceExporter transaction RPC service", "GWTRPCServiceExporter POJO service", "GWTRPCServiceExporter extending service", "Annotated service", "GWTRPCServiceExporter POJO service" }; int testIndex = 0; String newRandomString() { return "" + Math.random(); } void log(String text) { HTML html = new HTML("(" + testIndex + ") " + text); currentPanel.add(html); html.getElement().scrollIntoView(); } void fail(String text, Throwable t) { log("<span class='error' style='color:red'>" + text + "</span>"); if (t != null) log("<pre>" + t + "</pre>"); GWT.log(text, t); throw (t == null ? new RuntimeException("Test failed") : new RuntimeException(t)); } TestServiceAsync getService() {
TestServiceAsync service = (TestServiceAsync) GWT.create(TestService.class);
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/ClientApplication.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/CustomException.java // public class CustomException extends Exception implements IsSerializable{ // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java // public interface TestService extends RemoteService{ // // /** // * Adds two integers together and return result // * @param a // * @param b // * @return // */ // int add(int a, int b); // // /** // * Set a session attribute and return old value // * @param name // * @param value // * @return // */ // String replaceAttribute(String name, String value); // // /** // * Set a session attribute and return old value. Should use // * an alternative implementation to access the servlet session. // * @param name // * @param value // * @return // */ // String replaceAttributeAlt(String name, String value); // // /** // * Throws an exceptions that has been declared in the interface} // * @throws CustomException // */ // void throwDeclaredException() throws CustomException; // // /** // * Throws an exceptions that has not been declared in the interface} // * @throws RuntimeException // */ // void throwUndeclaredException(); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link GWTSerialisableObject} // */ // // GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link JavaSerialisableObject} // */ // // JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o); // // /** // * Returns a random number. // * @return // */ // Integer getRandomNumber(); // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java // public interface TestServiceAsync { // // void add(int a, int b, AsyncCallback<Integer> callback); // // void throwDeclaredException(AsyncCallback<Void> callback); // // void throwUndeclaredException(AsyncCallback<Object> callback); // // void replaceAttribute(String name, String value, AsyncCallback<String> callback); // // void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); // // void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback); // // void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback); // // void getRandomNumber(AsyncCallback<Integer> callback); // // }
import java.io.Serializable; import java.util.Date; import org.gwtwidgets.server.spring.test.common.CustomException; import org.gwtwidgets.server.spring.test.common.TestService; import org.gwtwidgets.server.spring.test.common.TestServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel;
log("Test5: Testing for exception translation."); TestServiceAsync testRequest = getService(); testRequest.throwUndeclaredException((new AsyncCallback<Object>() { public void onFailure(Throwable exception) { if (!(exception instanceof Serializable)) { fail("Test5 failed, expected a SerializableException.", exception); return; } log("Test5 success"); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { public void execute() { testCustomException(); } }); } public void onSuccess(Object result) { fail("Test5 failed, expected a SerializableException.", null); } })); } // check void testCustomException() { log("Test5b: Testing for custom exception serialisability."); TestServiceAsync testRequest = getService(); testRequest.throwDeclaredException((new AsyncCallback<Void>() { public void onFailure(Throwable exception) {
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/CustomException.java // public class CustomException extends Exception implements IsSerializable{ // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java // public interface TestService extends RemoteService{ // // /** // * Adds two integers together and return result // * @param a // * @param b // * @return // */ // int add(int a, int b); // // /** // * Set a session attribute and return old value // * @param name // * @param value // * @return // */ // String replaceAttribute(String name, String value); // // /** // * Set a session attribute and return old value. Should use // * an alternative implementation to access the servlet session. // * @param name // * @param value // * @return // */ // String replaceAttributeAlt(String name, String value); // // /** // * Throws an exceptions that has been declared in the interface} // * @throws CustomException // */ // void throwDeclaredException() throws CustomException; // // /** // * Throws an exceptions that has not been declared in the interface} // * @throws RuntimeException // */ // void throwUndeclaredException(); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link GWTSerialisableObject} // */ // // GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); // // /** // * @param o Object argument. Will turn string to lower case and increment number by 1 // * @return Testing {@link JavaSerialisableObject} // */ // // JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o); // // /** // * Returns a random number. // * @return // */ // Integer getRandomNumber(); // // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java // public interface TestServiceAsync { // // void add(int a, int b, AsyncCallback<Integer> callback); // // void throwDeclaredException(AsyncCallback<Void> callback); // // void throwUndeclaredException(AsyncCallback<Object> callback); // // void replaceAttribute(String name, String value, AsyncCallback<String> callback); // // void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); // // void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback); // // void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback); // // void getRandomNumber(AsyncCallback<Integer> callback); // // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/ClientApplication.java import java.io.Serializable; import java.util.Date; import org.gwtwidgets.server.spring.test.common.CustomException; import org.gwtwidgets.server.spring.test.common.TestService; import org.gwtwidgets.server.spring.test.common.TestServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel; log("Test5: Testing for exception translation."); TestServiceAsync testRequest = getService(); testRequest.throwUndeclaredException((new AsyncCallback<Object>() { public void onFailure(Throwable exception) { if (!(exception instanceof Serializable)) { fail("Test5 failed, expected a SerializableException.", exception); return; } log("Test5 success"); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { public void execute() { testCustomException(); } }); } public void onSuccess(Object result) { fail("Test5 failed, expected a SerializableException.", null); } })); } // check void testCustomException() { log("Test5b: Testing for custom exception serialisability."); TestServiceAsync testRequest = getService(); testRequest.throwDeclaredException((new AsyncCallback<Void>() { public void onFailure(Throwable exception) {
if (!(exception instanceof CustomException)) {
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // }
import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.RemoteService; import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject;
/* * 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 org.gwtwidgets.server.spring.test.common; /** * Declares three methods which our test service will expose. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestService extends RemoteService{ /** * Adds two integers together and return result * @param a * @param b * @return */ int add(int a, int b); /** * Set a session attribute and return old value * @param name * @param value * @return */ String replaceAttribute(String name, String value); /** * Set a session attribute and return old value. Should use * an alternative implementation to access the servlet session. * @param name * @param value * @return */ String replaceAttributeAlt(String name, String value); /** * Throws an exceptions that has been declared in the interface} * @throws CustomException */ void throwDeclaredException() throws CustomException; /** * Throws an exceptions that has not been declared in the interface} * @throws RuntimeException */ void throwUndeclaredException(); /** * @param o Object argument. Will turn string to lower case and increment number by 1 * @return Testing {@link GWTSerialisableObject} */
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.RemoteService; import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject; /* * 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 org.gwtwidgets.server.spring.test.common; /** * Declares three methods which our test service will expose. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestService extends RemoteService{ /** * Adds two integers together and return result * @param a * @param b * @return */ int add(int a, int b); /** * Set a session attribute and return old value * @param name * @param value * @return */ String replaceAttribute(String name, String value); /** * Set a session attribute and return old value. Should use * an alternative implementation to access the servlet session. * @param name * @param value * @return */ String replaceAttributeAlt(String name, String value); /** * Throws an exceptions that has been declared in the interface} * @throws CustomException */ void throwDeclaredException() throws CustomException; /** * Throws an exceptions that has not been declared in the interface} * @throws RuntimeException */ void throwUndeclaredException(); /** * @param o Object argument. Will turn string to lower case and increment number by 1 * @return Testing {@link GWTSerialisableObject} */
GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o);
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // }
import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.RemoteService; import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject;
/* * 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 org.gwtwidgets.server.spring.test.common; /** * Declares three methods which our test service will expose. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestService extends RemoteService{ /** * Adds two integers together and return result * @param a * @param b * @return */ int add(int a, int b); /** * Set a session attribute and return old value * @param name * @param value * @return */ String replaceAttribute(String name, String value); /** * Set a session attribute and return old value. Should use * an alternative implementation to access the servlet session. * @param name * @param value * @return */ String replaceAttributeAlt(String name, String value); /** * Throws an exceptions that has been declared in the interface} * @throws CustomException */ void throwDeclaredException() throws CustomException; /** * Throws an exceptions that has not been declared in the interface} * @throws RuntimeException */ void throwUndeclaredException(); /** * @param o Object argument. Will turn string to lower case and increment number by 1 * @return Testing {@link GWTSerialisableObject} */ GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); /** * @param o Object argument. Will turn string to lower case and increment number by 1 * @return Testing {@link JavaSerialisableObject} */
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestService.java import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.RemoteService; import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject; /* * 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 org.gwtwidgets.server.spring.test.common; /** * Declares three methods which our test service will expose. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestService extends RemoteService{ /** * Adds two integers together and return result * @param a * @param b * @return */ int add(int a, int b); /** * Set a session attribute and return old value * @param name * @param value * @return */ String replaceAttribute(String name, String value); /** * Set a session attribute and return old value. Should use * an alternative implementation to access the servlet session. * @param name * @param value * @return */ String replaceAttributeAlt(String name, String value); /** * Throws an exceptions that has been declared in the interface} * @throws CustomException */ void throwDeclaredException() throws CustomException; /** * Throws an exceptions that has not been declared in the interface} * @throws RuntimeException */ void throwUndeclaredException(); /** * @param o Object argument. Will turn string to lower case and increment number by 1 * @return Testing {@link GWTSerialisableObject} */ GWTSerialisableObject getGWTSerialisableObject(GWTSerialisableObject o); /** * @param o Object argument. Will turn string to lower case and increment number by 1 * @return Testing {@link JavaSerialisableObject} */
JavaSerialisableObject getJavaSerialisableObject(JavaSerialisableObject o);
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // }
import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject; import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.AsyncCallback;
/* * 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 org.gwtwidgets.server.spring.test.common; /** * Asynchronous version of the {@link TestService} service. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestServiceAsync { void add(int a, int b, AsyncCallback<Integer> callback); void throwDeclaredException(AsyncCallback<Void> callback); void throwUndeclaredException(AsyncCallback<Object> callback); void replaceAttribute(String name, String value, AsyncCallback<String> callback); void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback);
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject; import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.AsyncCallback; /* * 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 org.gwtwidgets.server.spring.test.common; /** * Asynchronous version of the {@link TestService} service. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestServiceAsync { void add(int a, int b, AsyncCallback<Integer> callback); void throwDeclaredException(AsyncCallback<Void> callback); void throwUndeclaredException(AsyncCallback<Object> callback); void replaceAttribute(String name, String value, AsyncCallback<String> callback); void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback);
void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback);
ggeorgovassilis/gwt-sl
test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // }
import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject; import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.AsyncCallback;
/* * 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 org.gwtwidgets.server.spring.test.common; /** * Asynchronous version of the {@link TestService} service. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestServiceAsync { void add(int a, int b, AsyncCallback<Integer> callback); void throwDeclaredException(AsyncCallback<Void> callback); void throwUndeclaredException(AsyncCallback<Object> callback); void replaceAttribute(String name, String value, AsyncCallback<String> callback); void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback);
// Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/GWTSerialisableObject.java // public class GWTSerialisableObject implements IsSerializable { // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/client/JavaSerialisableObject.java // public class JavaSerialisableObject implements Serializable { // private static final long serialVersionUID = -9112367310814219457L; // private int number; // private String string; // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getString() { // return string; // } // // public void setString(String string) { // this.string = string; // } // } // Path: test-webapp/src/main/java/org/gwtwidgets/server/spring/test/common/TestServiceAsync.java import org.gwtwidgets.server.spring.test.client.GWTSerialisableObject; import org.gwtwidgets.server.spring.test.client.JavaSerialisableObject; import com.google.gwt.user.client.rpc.AsyncCallback; /* * 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 org.gwtwidgets.server.spring.test.common; /** * Asynchronous version of the {@link TestService} service. * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public interface TestServiceAsync { void add(int a, int b, AsyncCallback<Integer> callback); void throwDeclaredException(AsyncCallback<Void> callback); void throwUndeclaredException(AsyncCallback<Object> callback); void replaceAttribute(String name, String value, AsyncCallback<String> callback); void replaceAttributeAlt(String name, String value, AsyncCallback<String> callback); void getGWTSerialisableObject(GWTSerialisableObject o, AsyncCallback<GWTSerialisableObject> callback);
void getJavaSerialisableObject(JavaSerialisableObject o, AsyncCallback<JavaSerialisableObject> callback);
ggeorgovassilis/gwt-sl
test-webapp/src/test/java/org/gwtwidgets/server/spring/test/BaseTest.java
// Path: gwt-sl/src/main/java/org/gwtwidgets/server/spring/ServletUtils.java // public class ServletUtils { // // private static ThreadLocal<HttpServletResponse> servletResponse = new ThreadLocal<HttpServletResponse>(); // // /** // * Adjusts HTTP headers so that browsers won't cache response. // * @param response // * For more background see <a href="http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index2.html">this</a>. // */ // public static void disableResponseCaching(HttpServletResponse response) { // response.setHeader("Expires", "Sat, 1 January 2000 12:00:00 GMT"); // response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // response.setHeader("Pragma", "no-cache"); // } // // /** // * Return the request which invokes the service. Valid only if used in the // * dispatching thread. // * @return the servlet request // */ // public static HttpServletRequest getRequest() { // return // ((ServletRequestAttributes) // RequestContextHolder.getRequestAttributes()).getRequest(); // } // // /** // * Return the response which accompanies the request. Valid only if used in // * the dispatching thread. // * // * @return the servlet response // */ // public static HttpServletResponse getResponse() { // return servletResponse.get(); // } // // /** // * Assign the current servlet request to a thread local variable. Valid only // * if used inside the invoking thread scope. // * @deprecated Does not perform any operation // * @param request Set the request // */ // public static void setRequest(HttpServletRequest request) { // throw new RuntimeException("setRequest has been deprecated"); // } // // /** // * Assign the current servlet response to a thread local variable. Valid // * only if used inside the invoking thread scope. // * // * @param response Set the response // */ // public static void setResponse(HttpServletResponse response) { // servletResponse.set(response); // } // // }
import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.gwtwidgets.server.spring.ServletUtils; import org.junit.Before; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;
/* * 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 org.gwtwidgets.server.spring.test; /** * Abstract basis test for unit tests * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public abstract class BaseTest{ protected String readResource(String resource) throws Exception { URL url = getClass().getClassLoader().getResource(resource); if (url == null) url = ClassLoader.getSystemResource(resource); if (url == null) url = ClassLoader.getSystemClassLoader().getResource(resource); URLConnection conn = url.openConnection(); byte[] b = new byte[conn.getContentLength()]; InputStream in = conn.getInputStream(); in.read(b); in.close(); return new String(b, "UTF-8"); } @Before public void setUp() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); // need to override our own request RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
// Path: gwt-sl/src/main/java/org/gwtwidgets/server/spring/ServletUtils.java // public class ServletUtils { // // private static ThreadLocal<HttpServletResponse> servletResponse = new ThreadLocal<HttpServletResponse>(); // // /** // * Adjusts HTTP headers so that browsers won't cache response. // * @param response // * For more background see <a href="http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index2.html">this</a>. // */ // public static void disableResponseCaching(HttpServletResponse response) { // response.setHeader("Expires", "Sat, 1 January 2000 12:00:00 GMT"); // response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // response.setHeader("Pragma", "no-cache"); // } // // /** // * Return the request which invokes the service. Valid only if used in the // * dispatching thread. // * @return the servlet request // */ // public static HttpServletRequest getRequest() { // return // ((ServletRequestAttributes) // RequestContextHolder.getRequestAttributes()).getRequest(); // } // // /** // * Return the response which accompanies the request. Valid only if used in // * the dispatching thread. // * // * @return the servlet response // */ // public static HttpServletResponse getResponse() { // return servletResponse.get(); // } // // /** // * Assign the current servlet request to a thread local variable. Valid only // * if used inside the invoking thread scope. // * @deprecated Does not perform any operation // * @param request Set the request // */ // public static void setRequest(HttpServletRequest request) { // throw new RuntimeException("setRequest has been deprecated"); // } // // /** // * Assign the current servlet response to a thread local variable. Valid // * only if used inside the invoking thread scope. // * // * @param response Set the response // */ // public static void setResponse(HttpServletResponse response) { // servletResponse.set(response); // } // // } // Path: test-webapp/src/test/java/org/gwtwidgets/server/spring/test/BaseTest.java import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.gwtwidgets.server.spring.ServletUtils; import org.junit.Before; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; /* * 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 org.gwtwidgets.server.spring.test; /** * Abstract basis test for unit tests * @author George Georgovassilis, g.georgovassilis[at]gmail.com * */ public abstract class BaseTest{ protected String readResource(String resource) throws Exception { URL url = getClass().getClassLoader().getResource(resource); if (url == null) url = ClassLoader.getSystemResource(resource); if (url == null) url = ClassLoader.getSystemClassLoader().getResource(resource); URLConnection conn = url.openConnection(); byte[] b = new byte[conn.getContentLength()]; InputStream in = conn.getInputStream(); in.read(b); in.close(); return new String(b, "UTF-8"); } @Before public void setUp() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); // need to override our own request RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
ServletUtils.setResponse(response);
ggeorgovassilis/gwt-sl
test-webapp/src/test/java/org/gwtwidgets/server/spring/test/ReflectionUtilsTest.java
// Path: gwt-sl/src/main/java/org/gwtwidgets/server/spring/ReflectionUtils.java // public class ReflectionUtils { // // /** // * Return array of all interfaces that are implemented by clazz and extend // * {@link RemoteService}. // * // * @param clazz Class to scan for interfaces // * @return Array of interfaces. May be empty but never null. // */ // @SuppressWarnings("unchecked") // public static Class<RemoteService>[] getExposedInterfaces(Class<?> clazz) { // Set<Class<?>> interfaces = getInterfaces(clazz); // for (Iterator<Class<?>> ite = interfaces.iterator(); ite.hasNext();) { // Class<?> c = ite.next(); // if (!isExposed(c)) // ite.remove(); // } // return interfaces.toArray(new Class[interfaces.size()]); // } // // /** // * Adds elements of an array to a set. The JRE 1.5 does include a similar // * method in the Collections class, but that breaks GWT-SL 1.4 // * compatibility. // * // * @param set Set of classes // * @param elements Elements in this array will be added to the set // */ // public static void addAll(Set<Class<?>> set, Class<?>[] elements) { // for (Class<?> element : elements) // set.add(element); // } // // /** // * Return all interfaces that are implemented by this class, traversing // * super classes and super interfaces. // * // * @param c Class to scan // * @return Set of classes. May be empty but not null. // */ // public static Set<Class<?>> getInterfaces(Class<?> c) { // Class<?> interfaces[] = c.getInterfaces(); // Set<Class<?>> classes = new HashSet<Class<?>>(); // if (interfaces == null) // return classes; // addAll(classes, interfaces); // for (Class<?> cl : interfaces) { // classes.addAll(getInterfaces(cl)); // } // Class<?> superClass = c.getSuperclass(); // if (superClass != null) { // classes.addAll(getInterfaces(superClass)); // } // return classes; // } // // private static boolean isExposed(Class<?> c) { // return RemoteService.class.isAssignableFrom(c); // } // // /** // * Will try to find method in 'serviceInterfaces' and if found, will attempt // * to return a method with the same signature from 'service', otherwise an // * exception is thrown. If 'serviceInterfaces' is a zero-sized array, the // * interface check is omitted and the method is looked up directly on the // * object. // * // * @param target // * Object to search method on // * @param serviceInterfaces // * The requested method must exist on at least one of the // * interfaces // * @param method Method to look for // * @return Method on 'service' or else a {@link NoSuchMethodException} is // * thrown // * @throws NoSuchMethodException If method can't be found on target // */ // public static Method getRPCMethod(Object target, Class<?>[] serviceInterfaces, Method method) throws NoSuchMethodException { // if (serviceInterfaces.length == 0) // return target.getClass().getMethod(method.getName(), method.getParameterTypes()); // for (Class<?> serviceInterface : serviceInterfaces) // try { // Method template = serviceInterface.getMethod(method.getName(), method.getParameterTypes()); // return target.getClass().getMethod(template.getName(), template.getParameterTypes()); // } catch (NoSuchMethodException e) { // } // throw new NoSuchMethodException(method.toString()); // } // // /* // * This is from the AnnotationUtils class of the Springframework (2.5+) in // * the core packag. This code is licensed under the Apache v2 license. // */ // public static <A extends Annotation> A findAnnotation(Class<?> clazz, // Class<A> annotationType) { // A annotation = clazz.getAnnotation(annotationType); // if (annotation != null) { // return annotation; // } // for (Class<?> ifc : clazz.getInterfaces()) { // annotation = findAnnotation(ifc, annotationType); // if (annotation != null) { // return annotation; // } // } // Class<?> superClass = clazz.getSuperclass(); // if (superClass == null || superClass == Object.class) { // return null; // } // return findAnnotation(superClass, annotationType); // } // // // }
import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import org.gwtwidgets.server.spring.ReflectionUtils; import org.junit.Test; import com.google.gwt.user.client.rpc.RemoteService; import static org.junit.Assert.* ;/**
System.out.println("I did something"); } } public static class CGLibProxy implements MethodInterceptor { public static MyAbstractTestClass newInstance(final Class<?> clazz) { try { final Enhancer e = new Enhancer(); e.setSuperclass(clazz); e.setCallback(new CGLibProxy()); return (MyAbstractTestClass) e.create(); } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } } public Object intercept(Object target, Method method, Object[] arguments, MethodProxy proxy) throws Throwable { System.out.println("I intercepted something - " + method.getName()); return method.invoke(target, arguments); } } @Test public void testGetInterfaces() { MyAbstractTestClass instance = CGLibProxy.newInstance(MyTestClass.class); assertTrue(instance instanceof RemoteService);
// Path: gwt-sl/src/main/java/org/gwtwidgets/server/spring/ReflectionUtils.java // public class ReflectionUtils { // // /** // * Return array of all interfaces that are implemented by clazz and extend // * {@link RemoteService}. // * // * @param clazz Class to scan for interfaces // * @return Array of interfaces. May be empty but never null. // */ // @SuppressWarnings("unchecked") // public static Class<RemoteService>[] getExposedInterfaces(Class<?> clazz) { // Set<Class<?>> interfaces = getInterfaces(clazz); // for (Iterator<Class<?>> ite = interfaces.iterator(); ite.hasNext();) { // Class<?> c = ite.next(); // if (!isExposed(c)) // ite.remove(); // } // return interfaces.toArray(new Class[interfaces.size()]); // } // // /** // * Adds elements of an array to a set. The JRE 1.5 does include a similar // * method in the Collections class, but that breaks GWT-SL 1.4 // * compatibility. // * // * @param set Set of classes // * @param elements Elements in this array will be added to the set // */ // public static void addAll(Set<Class<?>> set, Class<?>[] elements) { // for (Class<?> element : elements) // set.add(element); // } // // /** // * Return all interfaces that are implemented by this class, traversing // * super classes and super interfaces. // * // * @param c Class to scan // * @return Set of classes. May be empty but not null. // */ // public static Set<Class<?>> getInterfaces(Class<?> c) { // Class<?> interfaces[] = c.getInterfaces(); // Set<Class<?>> classes = new HashSet<Class<?>>(); // if (interfaces == null) // return classes; // addAll(classes, interfaces); // for (Class<?> cl : interfaces) { // classes.addAll(getInterfaces(cl)); // } // Class<?> superClass = c.getSuperclass(); // if (superClass != null) { // classes.addAll(getInterfaces(superClass)); // } // return classes; // } // // private static boolean isExposed(Class<?> c) { // return RemoteService.class.isAssignableFrom(c); // } // // /** // * Will try to find method in 'serviceInterfaces' and if found, will attempt // * to return a method with the same signature from 'service', otherwise an // * exception is thrown. If 'serviceInterfaces' is a zero-sized array, the // * interface check is omitted and the method is looked up directly on the // * object. // * // * @param target // * Object to search method on // * @param serviceInterfaces // * The requested method must exist on at least one of the // * interfaces // * @param method Method to look for // * @return Method on 'service' or else a {@link NoSuchMethodException} is // * thrown // * @throws NoSuchMethodException If method can't be found on target // */ // public static Method getRPCMethod(Object target, Class<?>[] serviceInterfaces, Method method) throws NoSuchMethodException { // if (serviceInterfaces.length == 0) // return target.getClass().getMethod(method.getName(), method.getParameterTypes()); // for (Class<?> serviceInterface : serviceInterfaces) // try { // Method template = serviceInterface.getMethod(method.getName(), method.getParameterTypes()); // return target.getClass().getMethod(template.getName(), template.getParameterTypes()); // } catch (NoSuchMethodException e) { // } // throw new NoSuchMethodException(method.toString()); // } // // /* // * This is from the AnnotationUtils class of the Springframework (2.5+) in // * the core packag. This code is licensed under the Apache v2 license. // */ // public static <A extends Annotation> A findAnnotation(Class<?> clazz, // Class<A> annotationType) { // A annotation = clazz.getAnnotation(annotationType); // if (annotation != null) { // return annotation; // } // for (Class<?> ifc : clazz.getInterfaces()) { // annotation = findAnnotation(ifc, annotationType); // if (annotation != null) { // return annotation; // } // } // Class<?> superClass = clazz.getSuperclass(); // if (superClass == null || superClass == Object.class) { // return null; // } // return findAnnotation(superClass, annotationType); // } // // // } // Path: test-webapp/src/test/java/org/gwtwidgets/server/spring/test/ReflectionUtilsTest.java import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import org.gwtwidgets.server.spring.ReflectionUtils; import org.junit.Test; import com.google.gwt.user.client.rpc.RemoteService; import static org.junit.Assert.* ;/** System.out.println("I did something"); } } public static class CGLibProxy implements MethodInterceptor { public static MyAbstractTestClass newInstance(final Class<?> clazz) { try { final Enhancer e = new Enhancer(); e.setSuperclass(clazz); e.setCallback(new CGLibProxy()); return (MyAbstractTestClass) e.create(); } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } } public Object intercept(Object target, Method method, Object[] arguments, MethodProxy proxy) throws Throwable { System.out.println("I intercepted something - " + method.getName()); return method.invoke(target, arguments); } } @Test public void testGetInterfaces() { MyAbstractTestClass instance = CGLibProxy.newInstance(MyTestClass.class); assertTrue(instance instanceof RemoteService);
assertTrue(ReflectionUtils.getExposedInterfaces(instance.getClass()).length == 1);
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/inventories/containers/ContainerRefinery.java
// Path: src/main/java/buildcraftAdditions/inventories/slots/SlotFake.java // public class SlotFake extends Slot { // // public SlotFake(IInventory inventory, int x, int y, int id) { // super(inventory, x, y, id); // } // // @Override // public void onSlotChange(ItemStack stack, ItemStack stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack, int stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack) { // // } // // @Override // public void onPickupFromSlot(EntityPlayer player, ItemStack stack) { // // } // // @Override // public boolean isItemValid(ItemStack stack) { // return false; // } // // @Override // public ItemStack getStack() { // return null; // } // // @Override // public boolean getHasStack() { // return false; // } // // @Override // public void putStack(ItemStack stack) { // // } // // @Override // public void onSlotChanged() { // // } // // @Override // public int getSlotStackLimit() { // return 64; // } // // @Override // public ItemStack decrStackSize(int amount) { // return null; // } // // @Override // public boolean isSlotInInventory(IInventory inventory, int slot) { // return true; // } // // @Override // public boolean canTakeStack(EntityPlayer player) { // return false; // } // // // @Override // public int getSlotIndex() { // return 0; // } // }
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraftAdditions.inventories.slots.SlotFake; import buildcraftAdditions.tileEntities.TileRefinery;
else inventory.output.setFluid(null); break; default: break; } } @Override protected void addPlayerInventory(int x, int y) { } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { return null; } @Override public ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) { return null; } @Override protected Slot addSlotToContainer(Slot slot) { return null; } @Override public Slot getSlot(int id) {
// Path: src/main/java/buildcraftAdditions/inventories/slots/SlotFake.java // public class SlotFake extends Slot { // // public SlotFake(IInventory inventory, int x, int y, int id) { // super(inventory, x, y, id); // } // // @Override // public void onSlotChange(ItemStack stack, ItemStack stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack, int stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack) { // // } // // @Override // public void onPickupFromSlot(EntityPlayer player, ItemStack stack) { // // } // // @Override // public boolean isItemValid(ItemStack stack) { // return false; // } // // @Override // public ItemStack getStack() { // return null; // } // // @Override // public boolean getHasStack() { // return false; // } // // @Override // public void putStack(ItemStack stack) { // // } // // @Override // public void onSlotChanged() { // // } // // @Override // public int getSlotStackLimit() { // return 64; // } // // @Override // public ItemStack decrStackSize(int amount) { // return null; // } // // @Override // public boolean isSlotInInventory(IInventory inventory, int slot) { // return true; // } // // @Override // public boolean canTakeStack(EntityPlayer player) { // return false; // } // // // @Override // public int getSlotIndex() { // return 0; // } // } // Path: src/main/java/buildcraftAdditions/inventories/containers/ContainerRefinery.java import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraftAdditions.inventories.slots.SlotFake; import buildcraftAdditions.tileEntities.TileRefinery; else inventory.output.setFluid(null); break; default: break; } } @Override protected void addPlayerInventory(int x, int y) { } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { return null; } @Override public ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) { return null; } @Override protected Slot addSlotToContainer(Slot slot) { return null; } @Override public Slot getSlot(int id) {
return new SlotFake(null, -5, -5, 0);
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/reference/ArmorLoader.java
// Path: src/main/java/buildcraftAdditions/armour/ItemHoverBoots.java // public class ItemHoverBoots extends ItemPoweredArmor implements IHUD { // // public ItemHoverBoots() { // super("hoverBoots", 3); // } // // private void tagTest(ItemStack stack) { // if (stack.stackTagCompound == null) // stack.stackTagCompound = new NBTTagCompound(); // if (!stack.stackTagCompound.hasKey("enabled")) // stack.stackTagCompound.setBoolean("enabled", true); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // tagTest(itemStack); // if (itemStack.stackTagCompound.getBoolean("enabled")) { // player.fallDistance = 0; // if (player.motionY < -0 && !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 30, true) == 30) { // if (player.isSneaking()) { // player.motionY /= 1.1; // } else { // player.motionY = 0; // backpack.extractEnergy(stack, 30, false); // } // } // } // } // } // } // // @Override // public String getInfo(ItemStack stack) { // return EnumChatFormatting.GOLD + Utils.localize("hud.boots") + " " + (stack.stackTagCompound.getBoolean("enabled") ? EnumChatFormatting.GREEN + Utils.localize("hud.enabled") : EnumChatFormatting.DARK_RED + Utils.localize("hud.dissabled")); // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelHoverBoots.INSTANCE; // } // } // // Path: src/main/java/buildcraftAdditions/armour/ItemRocketPants.java // public class ItemRocketPants extends ItemPoweredArmor { // private static final int // MAX_LIFT = 6, // FLY_POWER = 60, // SPEED_POWER = 20; // // public static IIcon icon; // // public ItemRocketPants() { // super("rocketPants", 2); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // setDamage(itemStack, 0); // if (FlightTracker.wantsToFly(player) || !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 40, true) == 40) { // if (FlightTracker.wantsToMove(player)) { // player.moveFlying(0, .2f, .2f); // } // player.motionX *= 1.025; // player.motionZ *= 1.025; // backpack.extractEnergy(stack, SPEED_POWER, false); // if (player.motionY < MAX_LIFT && FlightTracker.wantsToFly(player)) { // backpack.extractEnergy(stack, FLY_POWER, false); // player.motionY += 0.1; // player.fallDistance = 0; // } // } // } // } // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelRocketPants.INSTANCE; // } // // @Override // public void registerIcons(IIconRegister register) { // icon = RenderUtils.registerIcon(register, "rocketPants"); // } // // @Override // public IIcon getIcon(ItemStack stack, int pass) { // return icon; // } // // @Override // public IIcon getIconFromDamage(int damage) { // return icon; // } // }
import buildcraftAdditions.armour.ItemHoverBoots; import buildcraftAdditions.armour.ItemKineticBackpack; import buildcraftAdditions.armour.ItemRocketPants; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack;
package buildcraftAdditions.reference; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ArmorLoader { public static ItemArmor kineticBackpack; public static ItemArmor rocketPants; public static ItemArmor hoverBoots; public static void loadArmor() { kineticBackpack = new ItemKineticBackpack();
// Path: src/main/java/buildcraftAdditions/armour/ItemHoverBoots.java // public class ItemHoverBoots extends ItemPoweredArmor implements IHUD { // // public ItemHoverBoots() { // super("hoverBoots", 3); // } // // private void tagTest(ItemStack stack) { // if (stack.stackTagCompound == null) // stack.stackTagCompound = new NBTTagCompound(); // if (!stack.stackTagCompound.hasKey("enabled")) // stack.stackTagCompound.setBoolean("enabled", true); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // tagTest(itemStack); // if (itemStack.stackTagCompound.getBoolean("enabled")) { // player.fallDistance = 0; // if (player.motionY < -0 && !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 30, true) == 30) { // if (player.isSneaking()) { // player.motionY /= 1.1; // } else { // player.motionY = 0; // backpack.extractEnergy(stack, 30, false); // } // } // } // } // } // } // // @Override // public String getInfo(ItemStack stack) { // return EnumChatFormatting.GOLD + Utils.localize("hud.boots") + " " + (stack.stackTagCompound.getBoolean("enabled") ? EnumChatFormatting.GREEN + Utils.localize("hud.enabled") : EnumChatFormatting.DARK_RED + Utils.localize("hud.dissabled")); // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelHoverBoots.INSTANCE; // } // } // // Path: src/main/java/buildcraftAdditions/armour/ItemRocketPants.java // public class ItemRocketPants extends ItemPoweredArmor { // private static final int // MAX_LIFT = 6, // FLY_POWER = 60, // SPEED_POWER = 20; // // public static IIcon icon; // // public ItemRocketPants() { // super("rocketPants", 2); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // setDamage(itemStack, 0); // if (FlightTracker.wantsToFly(player) || !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 40, true) == 40) { // if (FlightTracker.wantsToMove(player)) { // player.moveFlying(0, .2f, .2f); // } // player.motionX *= 1.025; // player.motionZ *= 1.025; // backpack.extractEnergy(stack, SPEED_POWER, false); // if (player.motionY < MAX_LIFT && FlightTracker.wantsToFly(player)) { // backpack.extractEnergy(stack, FLY_POWER, false); // player.motionY += 0.1; // player.fallDistance = 0; // } // } // } // } // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelRocketPants.INSTANCE; // } // // @Override // public void registerIcons(IIconRegister register) { // icon = RenderUtils.registerIcon(register, "rocketPants"); // } // // @Override // public IIcon getIcon(ItemStack stack, int pass) { // return icon; // } // // @Override // public IIcon getIconFromDamage(int damage) { // return icon; // } // } // Path: src/main/java/buildcraftAdditions/reference/ArmorLoader.java import buildcraftAdditions.armour.ItemHoverBoots; import buildcraftAdditions.armour.ItemKineticBackpack; import buildcraftAdditions.armour.ItemRocketPants; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; package buildcraftAdditions.reference; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ArmorLoader { public static ItemArmor kineticBackpack; public static ItemArmor rocketPants; public static ItemArmor hoverBoots; public static void loadArmor() { kineticBackpack = new ItemKineticBackpack();
rocketPants = new ItemRocketPants();
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/reference/ArmorLoader.java
// Path: src/main/java/buildcraftAdditions/armour/ItemHoverBoots.java // public class ItemHoverBoots extends ItemPoweredArmor implements IHUD { // // public ItemHoverBoots() { // super("hoverBoots", 3); // } // // private void tagTest(ItemStack stack) { // if (stack.stackTagCompound == null) // stack.stackTagCompound = new NBTTagCompound(); // if (!stack.stackTagCompound.hasKey("enabled")) // stack.stackTagCompound.setBoolean("enabled", true); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // tagTest(itemStack); // if (itemStack.stackTagCompound.getBoolean("enabled")) { // player.fallDistance = 0; // if (player.motionY < -0 && !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 30, true) == 30) { // if (player.isSneaking()) { // player.motionY /= 1.1; // } else { // player.motionY = 0; // backpack.extractEnergy(stack, 30, false); // } // } // } // } // } // } // // @Override // public String getInfo(ItemStack stack) { // return EnumChatFormatting.GOLD + Utils.localize("hud.boots") + " " + (stack.stackTagCompound.getBoolean("enabled") ? EnumChatFormatting.GREEN + Utils.localize("hud.enabled") : EnumChatFormatting.DARK_RED + Utils.localize("hud.dissabled")); // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelHoverBoots.INSTANCE; // } // } // // Path: src/main/java/buildcraftAdditions/armour/ItemRocketPants.java // public class ItemRocketPants extends ItemPoweredArmor { // private static final int // MAX_LIFT = 6, // FLY_POWER = 60, // SPEED_POWER = 20; // // public static IIcon icon; // // public ItemRocketPants() { // super("rocketPants", 2); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // setDamage(itemStack, 0); // if (FlightTracker.wantsToFly(player) || !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 40, true) == 40) { // if (FlightTracker.wantsToMove(player)) { // player.moveFlying(0, .2f, .2f); // } // player.motionX *= 1.025; // player.motionZ *= 1.025; // backpack.extractEnergy(stack, SPEED_POWER, false); // if (player.motionY < MAX_LIFT && FlightTracker.wantsToFly(player)) { // backpack.extractEnergy(stack, FLY_POWER, false); // player.motionY += 0.1; // player.fallDistance = 0; // } // } // } // } // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelRocketPants.INSTANCE; // } // // @Override // public void registerIcons(IIconRegister register) { // icon = RenderUtils.registerIcon(register, "rocketPants"); // } // // @Override // public IIcon getIcon(ItemStack stack, int pass) { // return icon; // } // // @Override // public IIcon getIconFromDamage(int damage) { // return icon; // } // }
import buildcraftAdditions.armour.ItemHoverBoots; import buildcraftAdditions.armour.ItemKineticBackpack; import buildcraftAdditions.armour.ItemRocketPants; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack;
package buildcraftAdditions.reference; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ArmorLoader { public static ItemArmor kineticBackpack; public static ItemArmor rocketPants; public static ItemArmor hoverBoots; public static void loadArmor() { kineticBackpack = new ItemKineticBackpack(); rocketPants = new ItemRocketPants();
// Path: src/main/java/buildcraftAdditions/armour/ItemHoverBoots.java // public class ItemHoverBoots extends ItemPoweredArmor implements IHUD { // // public ItemHoverBoots() { // super("hoverBoots", 3); // } // // private void tagTest(ItemStack stack) { // if (stack.stackTagCompound == null) // stack.stackTagCompound = new NBTTagCompound(); // if (!stack.stackTagCompound.hasKey("enabled")) // stack.stackTagCompound.setBoolean("enabled", true); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // tagTest(itemStack); // if (itemStack.stackTagCompound.getBoolean("enabled")) { // player.fallDistance = 0; // if (player.motionY < -0 && !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 30, true) == 30) { // if (player.isSneaking()) { // player.motionY /= 1.1; // } else { // player.motionY = 0; // backpack.extractEnergy(stack, 30, false); // } // } // } // } // } // } // // @Override // public String getInfo(ItemStack stack) { // return EnumChatFormatting.GOLD + Utils.localize("hud.boots") + " " + (stack.stackTagCompound.getBoolean("enabled") ? EnumChatFormatting.GREEN + Utils.localize("hud.enabled") : EnumChatFormatting.DARK_RED + Utils.localize("hud.dissabled")); // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelHoverBoots.INSTANCE; // } // } // // Path: src/main/java/buildcraftAdditions/armour/ItemRocketPants.java // public class ItemRocketPants extends ItemPoweredArmor { // private static final int // MAX_LIFT = 6, // FLY_POWER = 60, // SPEED_POWER = 20; // // public static IIcon icon; // // public ItemRocketPants() { // super("rocketPants", 2); // } // // @Override // public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { // setDamage(itemStack, 0); // if (FlightTracker.wantsToFly(player) || !player.onGround) { // ItemStack stack = player.getCurrentArmor(2); // if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) { // ItemKineticBackpack backpack = (ItemKineticBackpack) stack.getItem(); // if (backpack.extractEnergy(stack, 40, true) == 40) { // if (FlightTracker.wantsToMove(player)) { // player.moveFlying(0, .2f, .2f); // } // player.motionX *= 1.025; // player.motionZ *= 1.025; // backpack.extractEnergy(stack, SPEED_POWER, false); // if (player.motionY < MAX_LIFT && FlightTracker.wantsToFly(player)) { // backpack.extractEnergy(stack, FLY_POWER, false); // player.motionY += 0.1; // player.fallDistance = 0; // } // } // } // } // } // // @SideOnly(Side.CLIENT) // @Override // public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { // return ModelRocketPants.INSTANCE; // } // // @Override // public void registerIcons(IIconRegister register) { // icon = RenderUtils.registerIcon(register, "rocketPants"); // } // // @Override // public IIcon getIcon(ItemStack stack, int pass) { // return icon; // } // // @Override // public IIcon getIconFromDamage(int damage) { // return icon; // } // } // Path: src/main/java/buildcraftAdditions/reference/ArmorLoader.java import buildcraftAdditions.armour.ItemHoverBoots; import buildcraftAdditions.armour.ItemKineticBackpack; import buildcraftAdditions.armour.ItemRocketPants; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; package buildcraftAdditions.reference; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ArmorLoader { public static ItemArmor kineticBackpack; public static ItemArmor rocketPants; public static ItemArmor hoverBoots; public static void loadArmor() { kineticBackpack = new ItemKineticBackpack(); rocketPants = new ItemRocketPants();
hoverBoots = new ItemHoverBoots();
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/inventories/containers/ContainerCoolingTower.java
// Path: src/main/java/buildcraftAdditions/inventories/slots/SlotFake.java // public class SlotFake extends Slot { // // public SlotFake(IInventory inventory, int x, int y, int id) { // super(inventory, x, y, id); // } // // @Override // public void onSlotChange(ItemStack stack, ItemStack stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack, int stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack) { // // } // // @Override // public void onPickupFromSlot(EntityPlayer player, ItemStack stack) { // // } // // @Override // public boolean isItemValid(ItemStack stack) { // return false; // } // // @Override // public ItemStack getStack() { // return null; // } // // @Override // public boolean getHasStack() { // return false; // } // // @Override // public void putStack(ItemStack stack) { // // } // // @Override // public void onSlotChanged() { // // } // // @Override // public int getSlotStackLimit() { // return 64; // } // // @Override // public ItemStack decrStackSize(int amount) { // return null; // } // // @Override // public boolean isSlotInInventory(IInventory inventory, int slot) { // return true; // } // // @Override // public boolean canTakeStack(EntityPlayer player) { // return false; // } // // // @Override // public int getSlotIndex() { // return 0; // } // }
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraftAdditions.inventories.slots.SlotFake; import buildcraftAdditions.tileEntities.TileCoolingTower;
else inventory.coolant.setFluid(null); break; default: break; } } @Override protected void addPlayerInventory(int x, int y) { } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { return null; } @Override public ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) { return null; } @Override protected Slot addSlotToContainer(Slot slot) { return null; } @Override public Slot getSlot(int id) {
// Path: src/main/java/buildcraftAdditions/inventories/slots/SlotFake.java // public class SlotFake extends Slot { // // public SlotFake(IInventory inventory, int x, int y, int id) { // super(inventory, x, y, id); // } // // @Override // public void onSlotChange(ItemStack stack, ItemStack stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack, int stack2) { // // } // // @Override // protected void onCrafting(ItemStack stack) { // // } // // @Override // public void onPickupFromSlot(EntityPlayer player, ItemStack stack) { // // } // // @Override // public boolean isItemValid(ItemStack stack) { // return false; // } // // @Override // public ItemStack getStack() { // return null; // } // // @Override // public boolean getHasStack() { // return false; // } // // @Override // public void putStack(ItemStack stack) { // // } // // @Override // public void onSlotChanged() { // // } // // @Override // public int getSlotStackLimit() { // return 64; // } // // @Override // public ItemStack decrStackSize(int amount) { // return null; // } // // @Override // public boolean isSlotInInventory(IInventory inventory, int slot) { // return true; // } // // @Override // public boolean canTakeStack(EntityPlayer player) { // return false; // } // // // @Override // public int getSlotIndex() { // return 0; // } // } // Path: src/main/java/buildcraftAdditions/inventories/containers/ContainerCoolingTower.java import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraftAdditions.inventories.slots.SlotFake; import buildcraftAdditions.tileEntities.TileCoolingTower; else inventory.coolant.setFluid(null); break; default: break; } } @Override protected void addPlayerInventory(int x, int y) { } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { return null; } @Override public ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) { return null; } @Override protected Slot addSlotToContainer(Slot slot) { return null; } @Override public Slot getSlot(int id) {
return new SlotFake(null, -5, -5, 0);
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/armour/ItemRocketPants.java
// Path: src/main/java/buildcraftAdditions/listeners/FlightTracker.java // public class FlightTracker { // private static final HashMap<UUID, Boolean> // jumpers = new HashMap<UUID, Boolean>(), // movers = new HashMap<UUID, Boolean>(); // // // public static boolean wantsToFly(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!jumpers.containsKey(player.getGameProfile().getId())) // jumpers.put(player.getGameProfile().getId(), false); // return jumpers.get(player.getGameProfile().getId()); // } // // public static boolean wantsToMove(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!movers.containsKey(player.getGameProfile().getId())) // movers.put(player.getGameProfile().getId(), false); // return movers.get(player.getGameProfile().getId()); // } // // public static void setJumping(EntityPlayer player, boolean newStatus) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // jumpers.put(player.getGameProfile().getId(), newStatus); // sync(player); // } // // public static void setMoving(EntityPlayer player, boolean moving) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // movers.put(player.getGameProfile().getId(), moving); // sync(player); // } // // private static void sync(EntityPlayer player) { // if (player == null || player.worldObj == null) // return; // if (player.worldObj.isRemote) // PacketHandler.instance.sendToServer(new MessageFlightSync(wantsToFly(player), wantsToMove(player))); // } // } // // Path: src/main/java/buildcraftAdditions/reference/ArmorLoader.java // public class ArmorLoader { // public static ItemArmor kineticBackpack; // public static ItemArmor rocketPants; // public static ItemArmor hoverBoots; // // public static void loadArmor() { // kineticBackpack = new ItemKineticBackpack(); // rocketPants = new ItemRocketPants(); // hoverBoots = new ItemHoverBoots(); // // } // // public static void addRecipes() { // GameRegistry.addRecipe(new ItemStack(kineticBackpack), "PLP", "PPP", "PPP", 'P', ItemLoader.conductivePlate, 'L', Items.leather); // GameRegistry.addRecipe(new ItemStack(BlockLoader.backpackStand), "III", " I ", "III", 'I', Items.iron_ingot); // GameRegistry.addRecipe(new ItemStack(rocketPants), "P P", "ITI", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // GameRegistry.addRecipe(new ItemStack(hoverBoots), "P P", "I I", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // } // }
import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import buildcraftAdditions.client.models.ModelRocketPants; import buildcraftAdditions.listeners.FlightTracker; import buildcraftAdditions.reference.ArmorLoader; import buildcraftAdditions.utils.RenderUtils;
package buildcraftAdditions.armour; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ItemRocketPants extends ItemPoweredArmor { private static final int MAX_LIFT = 6, FLY_POWER = 60, SPEED_POWER = 20; public static IIcon icon; public ItemRocketPants() { super("rocketPants", 2); } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { setDamage(itemStack, 0);
// Path: src/main/java/buildcraftAdditions/listeners/FlightTracker.java // public class FlightTracker { // private static final HashMap<UUID, Boolean> // jumpers = new HashMap<UUID, Boolean>(), // movers = new HashMap<UUID, Boolean>(); // // // public static boolean wantsToFly(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!jumpers.containsKey(player.getGameProfile().getId())) // jumpers.put(player.getGameProfile().getId(), false); // return jumpers.get(player.getGameProfile().getId()); // } // // public static boolean wantsToMove(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!movers.containsKey(player.getGameProfile().getId())) // movers.put(player.getGameProfile().getId(), false); // return movers.get(player.getGameProfile().getId()); // } // // public static void setJumping(EntityPlayer player, boolean newStatus) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // jumpers.put(player.getGameProfile().getId(), newStatus); // sync(player); // } // // public static void setMoving(EntityPlayer player, boolean moving) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // movers.put(player.getGameProfile().getId(), moving); // sync(player); // } // // private static void sync(EntityPlayer player) { // if (player == null || player.worldObj == null) // return; // if (player.worldObj.isRemote) // PacketHandler.instance.sendToServer(new MessageFlightSync(wantsToFly(player), wantsToMove(player))); // } // } // // Path: src/main/java/buildcraftAdditions/reference/ArmorLoader.java // public class ArmorLoader { // public static ItemArmor kineticBackpack; // public static ItemArmor rocketPants; // public static ItemArmor hoverBoots; // // public static void loadArmor() { // kineticBackpack = new ItemKineticBackpack(); // rocketPants = new ItemRocketPants(); // hoverBoots = new ItemHoverBoots(); // // } // // public static void addRecipes() { // GameRegistry.addRecipe(new ItemStack(kineticBackpack), "PLP", "PPP", "PPP", 'P', ItemLoader.conductivePlate, 'L', Items.leather); // GameRegistry.addRecipe(new ItemStack(BlockLoader.backpackStand), "III", " I ", "III", 'I', Items.iron_ingot); // GameRegistry.addRecipe(new ItemStack(rocketPants), "P P", "ITI", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // GameRegistry.addRecipe(new ItemStack(hoverBoots), "P P", "I I", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // } // } // Path: src/main/java/buildcraftAdditions/armour/ItemRocketPants.java import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import buildcraftAdditions.client.models.ModelRocketPants; import buildcraftAdditions.listeners.FlightTracker; import buildcraftAdditions.reference.ArmorLoader; import buildcraftAdditions.utils.RenderUtils; package buildcraftAdditions.armour; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ItemRocketPants extends ItemPoweredArmor { private static final int MAX_LIFT = 6, FLY_POWER = 60, SPEED_POWER = 20; public static IIcon icon; public ItemRocketPants() { super("rocketPants", 2); } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { setDamage(itemStack, 0);
if (FlightTracker.wantsToFly(player) || !player.onGround) {
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/armour/ItemRocketPants.java
// Path: src/main/java/buildcraftAdditions/listeners/FlightTracker.java // public class FlightTracker { // private static final HashMap<UUID, Boolean> // jumpers = new HashMap<UUID, Boolean>(), // movers = new HashMap<UUID, Boolean>(); // // // public static boolean wantsToFly(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!jumpers.containsKey(player.getGameProfile().getId())) // jumpers.put(player.getGameProfile().getId(), false); // return jumpers.get(player.getGameProfile().getId()); // } // // public static boolean wantsToMove(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!movers.containsKey(player.getGameProfile().getId())) // movers.put(player.getGameProfile().getId(), false); // return movers.get(player.getGameProfile().getId()); // } // // public static void setJumping(EntityPlayer player, boolean newStatus) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // jumpers.put(player.getGameProfile().getId(), newStatus); // sync(player); // } // // public static void setMoving(EntityPlayer player, boolean moving) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // movers.put(player.getGameProfile().getId(), moving); // sync(player); // } // // private static void sync(EntityPlayer player) { // if (player == null || player.worldObj == null) // return; // if (player.worldObj.isRemote) // PacketHandler.instance.sendToServer(new MessageFlightSync(wantsToFly(player), wantsToMove(player))); // } // } // // Path: src/main/java/buildcraftAdditions/reference/ArmorLoader.java // public class ArmorLoader { // public static ItemArmor kineticBackpack; // public static ItemArmor rocketPants; // public static ItemArmor hoverBoots; // // public static void loadArmor() { // kineticBackpack = new ItemKineticBackpack(); // rocketPants = new ItemRocketPants(); // hoverBoots = new ItemHoverBoots(); // // } // // public static void addRecipes() { // GameRegistry.addRecipe(new ItemStack(kineticBackpack), "PLP", "PPP", "PPP", 'P', ItemLoader.conductivePlate, 'L', Items.leather); // GameRegistry.addRecipe(new ItemStack(BlockLoader.backpackStand), "III", " I ", "III", 'I', Items.iron_ingot); // GameRegistry.addRecipe(new ItemStack(rocketPants), "P P", "ITI", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // GameRegistry.addRecipe(new ItemStack(hoverBoots), "P P", "I I", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // } // }
import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import buildcraftAdditions.client.models.ModelRocketPants; import buildcraftAdditions.listeners.FlightTracker; import buildcraftAdditions.reference.ArmorLoader; import buildcraftAdditions.utils.RenderUtils;
package buildcraftAdditions.armour; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ItemRocketPants extends ItemPoweredArmor { private static final int MAX_LIFT = 6, FLY_POWER = 60, SPEED_POWER = 20; public static IIcon icon; public ItemRocketPants() { super("rocketPants", 2); } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { setDamage(itemStack, 0); if (FlightTracker.wantsToFly(player) || !player.onGround) { ItemStack stack = player.getCurrentArmor(2);
// Path: src/main/java/buildcraftAdditions/listeners/FlightTracker.java // public class FlightTracker { // private static final HashMap<UUID, Boolean> // jumpers = new HashMap<UUID, Boolean>(), // movers = new HashMap<UUID, Boolean>(); // // // public static boolean wantsToFly(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!jumpers.containsKey(player.getGameProfile().getId())) // jumpers.put(player.getGameProfile().getId(), false); // return jumpers.get(player.getGameProfile().getId()); // } // // public static boolean wantsToMove(EntityPlayer player) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return false; // if (!movers.containsKey(player.getGameProfile().getId())) // movers.put(player.getGameProfile().getId(), false); // return movers.get(player.getGameProfile().getId()); // } // // public static void setJumping(EntityPlayer player, boolean newStatus) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // jumpers.put(player.getGameProfile().getId(), newStatus); // sync(player); // } // // public static void setMoving(EntityPlayer player, boolean moving) { // if (player == null || player.getGameProfile() == null || player.getGameProfile().getId() == null) // return; // movers.put(player.getGameProfile().getId(), moving); // sync(player); // } // // private static void sync(EntityPlayer player) { // if (player == null || player.worldObj == null) // return; // if (player.worldObj.isRemote) // PacketHandler.instance.sendToServer(new MessageFlightSync(wantsToFly(player), wantsToMove(player))); // } // } // // Path: src/main/java/buildcraftAdditions/reference/ArmorLoader.java // public class ArmorLoader { // public static ItemArmor kineticBackpack; // public static ItemArmor rocketPants; // public static ItemArmor hoverBoots; // // public static void loadArmor() { // kineticBackpack = new ItemKineticBackpack(); // rocketPants = new ItemRocketPants(); // hoverBoots = new ItemHoverBoots(); // // } // // public static void addRecipes() { // GameRegistry.addRecipe(new ItemStack(kineticBackpack), "PLP", "PPP", "PPP", 'P', ItemLoader.conductivePlate, 'L', Items.leather); // GameRegistry.addRecipe(new ItemStack(BlockLoader.backpackStand), "III", " I ", "III", 'I', Items.iron_ingot); // GameRegistry.addRecipe(new ItemStack(rocketPants), "P P", "ITI", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // GameRegistry.addRecipe(new ItemStack(hoverBoots), "P P", "I I", "T T", 'P', ItemLoader.lightPlating, 'I', Items.iron_ingot, 'T', ItemLoader.thruster); // } // } // Path: src/main/java/buildcraftAdditions/armour/ItemRocketPants.java import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import buildcraftAdditions.client.models.ModelRocketPants; import buildcraftAdditions.listeners.FlightTracker; import buildcraftAdditions.reference.ArmorLoader; import buildcraftAdditions.utils.RenderUtils; package buildcraftAdditions.armour; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class ItemRocketPants extends ItemPoweredArmor { private static final int MAX_LIFT = 6, FLY_POWER = 60, SPEED_POWER = 20; public static IIcon icon; public ItemRocketPants() { super("rocketPants", 2); } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { setDamage(itemStack, 0); if (FlightTracker.wantsToFly(player) || !player.onGround) { ItemStack stack = player.getCurrentArmor(2);
if (stack != null && stack.getItem() == ArmorLoader.kineticBackpack) {
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/blocks/BlockTest.java
// Path: src/main/java/buildcraftAdditions/multiBlocks/TestingPatern.java // public class TestingPatern { // // public static void build(Location location) { // HashMap<String, Block> blocks = new HashMap<String, Block>(); // ForgeDirection directions[] = new ForgeDirection[]{ForgeDirection.NORTH, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, // ForgeDirection.SOUTH, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.NORTH, // ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.SOUTH, ForgeDirection.DOWN, // ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, // ForgeDirection.EAST, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.NORTH, ForgeDirection.UP, ForgeDirection.UP, // ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN}; // int length = directions.length; // String identifiers[] = new String[length]; // int rotation = 3; // directions = RotationUtils.rotateDirections(rotation, directions); // Arrays.fill(identifiers, "walls"); // blocks.put("walls", BlockLoader.coolingTowerWalls); // blocks.put("valve", BlockLoader.coolingTowerValve); // blocks.put("air", Blocks.air); // identifiers[3] = "valve"; // identifiers[6] = "valve"; // for (int t = 7; t < 10; t++) // identifiers[t] = "air"; // identifiers[10] = "valve"; // for (int t = 0; t < length; t++) { // location.move(directions[t]); // location.setBlock(blocks.get(identifiers[t])); // } // } // }
import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import cpw.mods.fml.common.registry.GameRegistry; import buildcraftAdditions.BuildcraftAdditions; import buildcraftAdditions.multiBlocks.TestingPatern; import buildcraftAdditions.utils.Location;
package buildcraftAdditions.blocks; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class BlockTest extends Block { public BlockTest() { super(Material.iron); setBlockName("testBlock"); setBlockTextureName("bcadditions:testBlock"); setCreativeTab(BuildcraftAdditions.bcadditions); GameRegistry.registerBlock(this, "testingBlock"); } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) {
// Path: src/main/java/buildcraftAdditions/multiBlocks/TestingPatern.java // public class TestingPatern { // // public static void build(Location location) { // HashMap<String, Block> blocks = new HashMap<String, Block>(); // ForgeDirection directions[] = new ForgeDirection[]{ForgeDirection.NORTH, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, // ForgeDirection.SOUTH, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.NORTH, // ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.SOUTH, ForgeDirection.DOWN, // ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.UP, // ForgeDirection.EAST, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.NORTH, ForgeDirection.UP, ForgeDirection.UP, // ForgeDirection.UP, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN, ForgeDirection.DOWN}; // int length = directions.length; // String identifiers[] = new String[length]; // int rotation = 3; // directions = RotationUtils.rotateDirections(rotation, directions); // Arrays.fill(identifiers, "walls"); // blocks.put("walls", BlockLoader.coolingTowerWalls); // blocks.put("valve", BlockLoader.coolingTowerValve); // blocks.put("air", Blocks.air); // identifiers[3] = "valve"; // identifiers[6] = "valve"; // for (int t = 7; t < 10; t++) // identifiers[t] = "air"; // identifiers[10] = "valve"; // for (int t = 0; t < length; t++) { // location.move(directions[t]); // location.setBlock(blocks.get(identifiers[t])); // } // } // } // Path: src/main/java/buildcraftAdditions/blocks/BlockTest.java import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import cpw.mods.fml.common.registry.GameRegistry; import buildcraftAdditions.BuildcraftAdditions; import buildcraftAdditions.multiBlocks.TestingPatern; import buildcraftAdditions.utils.Location; package buildcraftAdditions.blocks; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class BlockTest extends Block { public BlockTest() { super(Material.iron); setBlockName("testBlock"); setBlockTextureName("bcadditions:testBlock"); setCreativeTab(BuildcraftAdditions.bcadditions); GameRegistry.registerBlock(this, "testingBlock"); } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) {
TestingPatern.build(new Location(world, x, y, z));
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/utils/Utils.java
// Path: src/main/java/buildcraftAdditions/reference/enums/EnumMachineUpgrades.java // public enum EnumMachineUpgrades { // // AUTO_OUTPUT("upgradeAutoEject", false), // EFFICIENCY_1("upgradeEfficiency1", false), // EFFICIENCY_2("upgradeEfficiency2", false), // EFFICIENCY_3("upgradeEfficiency3", false), // SPEED_1("upgradeSpeed1", false), // SPEED_2("upgradeSpeed2", false), // SPEED_3("upgradeSpeed3", false), // AUTO_IMPORT("upgradeAutoImport", false); // // private final String tag; // private final boolean multipleInstalls; // private final ResourceLocation texture; // // private EnumMachineUpgrades(String tag, boolean multipleInstalls) { // this.tag = tag; // this.multipleInstalls = multipleInstalls; // texture = new ResourceLocation(Variables.MOD.ID, "textures/items/upgrades/" + tag.substring(7).toLowerCase() + ".png"); // } // // public String getTag() { // return tag; // } // // public boolean canBeInstalledMultipleTimes() { // return multipleInstalls; // } // // public ItemStack getItemStack() { // return new ItemStack(ItemLoader.upgrade, 1, ordinal()); // } // // public ResourceLocation getTexture() { // return texture; // } // // public String getTextureName() { // return "upgrades/" + tag.substring(7).toLowerCase(); // } // // // }
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Sets; import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import buildcraft.api.transport.IInjectable; import buildcraftAdditions.api.configurableOutput.EnumPriority; import buildcraftAdditions.api.configurableOutput.SideConfiguration; import buildcraftAdditions.reference.enums.EnumMachineUpgrades; import buildcraftAdditions.tileEntities.interfaces.IUpgradableMachine;
color += EnumChatFormatting.YELLOW; else if (percent >= 30) color += EnumChatFormatting.GOLD; else if (percent >= 15) color += EnumChatFormatting.RED; else color += EnumChatFormatting.DARK_RED; return color + percent + "%"; } public static String colorText(String text, EnumChatFormatting color) { return ("" + color + text).trim(); } public static String decapitalizeFirstChar(String string) { return !Strings.isNullOrEmpty(string) ? Character.toLowerCase(string.charAt(0)) + string.substring(1) : null; } public static void dropInventory(World world, int x, int y, int z) { TileEntity tile = world.getTileEntity(x, y, z); if (tile != null) { if (tile instanceof IInventory) { IInventory inventory = (IInventory) tile; for (int i = 0; i < inventory.getSizeInventory(); i++) { dropItemstack(world, x, y, z, inventory.getStackInSlot(i)); inventory.setInventorySlotContents(i, null); } } if (tile instanceof IUpgradableMachine) { IUpgradableMachine machine = (IUpgradableMachine) tile;
// Path: src/main/java/buildcraftAdditions/reference/enums/EnumMachineUpgrades.java // public enum EnumMachineUpgrades { // // AUTO_OUTPUT("upgradeAutoEject", false), // EFFICIENCY_1("upgradeEfficiency1", false), // EFFICIENCY_2("upgradeEfficiency2", false), // EFFICIENCY_3("upgradeEfficiency3", false), // SPEED_1("upgradeSpeed1", false), // SPEED_2("upgradeSpeed2", false), // SPEED_3("upgradeSpeed3", false), // AUTO_IMPORT("upgradeAutoImport", false); // // private final String tag; // private final boolean multipleInstalls; // private final ResourceLocation texture; // // private EnumMachineUpgrades(String tag, boolean multipleInstalls) { // this.tag = tag; // this.multipleInstalls = multipleInstalls; // texture = new ResourceLocation(Variables.MOD.ID, "textures/items/upgrades/" + tag.substring(7).toLowerCase() + ".png"); // } // // public String getTag() { // return tag; // } // // public boolean canBeInstalledMultipleTimes() { // return multipleInstalls; // } // // public ItemStack getItemStack() { // return new ItemStack(ItemLoader.upgrade, 1, ordinal()); // } // // public ResourceLocation getTexture() { // return texture; // } // // public String getTextureName() { // return "upgrades/" + tag.substring(7).toLowerCase(); // } // // // } // Path: src/main/java/buildcraftAdditions/utils/Utils.java import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Sets; import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import buildcraft.api.transport.IInjectable; import buildcraftAdditions.api.configurableOutput.EnumPriority; import buildcraftAdditions.api.configurableOutput.SideConfiguration; import buildcraftAdditions.reference.enums.EnumMachineUpgrades; import buildcraftAdditions.tileEntities.interfaces.IUpgradableMachine; color += EnumChatFormatting.YELLOW; else if (percent >= 30) color += EnumChatFormatting.GOLD; else if (percent >= 15) color += EnumChatFormatting.RED; else color += EnumChatFormatting.DARK_RED; return color + percent + "%"; } public static String colorText(String text, EnumChatFormatting color) { return ("" + color + text).trim(); } public static String decapitalizeFirstChar(String string) { return !Strings.isNullOrEmpty(string) ? Character.toLowerCase(string.charAt(0)) + string.substring(1) : null; } public static void dropInventory(World world, int x, int y, int z) { TileEntity tile = world.getTileEntity(x, y, z); if (tile != null) { if (tile instanceof IInventory) { IInventory inventory = (IInventory) tile; for (int i = 0; i < inventory.getSizeInventory(); i++) { dropItemstack(world, x, y, z, inventory.getStackInSlot(i)); inventory.setInventorySlotContents(i, null); } } if (tile instanceof IUpgradableMachine) { IUpgradableMachine machine = (IUpgradableMachine) tile;
Set<EnumMachineUpgrades> upgrades = machine.getInstalledUpgrades();
enasequence/cramtools
src/main/java/net/sf/cram/fasta/BGZF_ReferenceSequenceFile.java
// Path: src/main/java/net/sf/cram/AlignmentSliceQuery.java // public class AlignmentSliceQuery { // public String sequence; // public int sequenceId; // public int start; // public int end = Integer.MAX_VALUE; // // public AlignmentSliceQuery(String spec) { // String[] chunks = spec.split(":"); // // sequence = chunks[0]; // // if (chunks.length > 1) { // chunks = chunks[1].split("-"); // start = Integer.valueOf(chunks[0]); // if (chunks.length == 2) // end = Integer.valueOf(chunks[1]); // } // // } // // @Override // public String toString() { // StringBuffer sb = new StringBuffer(sequence); // if (start > 1 || end < Integer.MAX_VALUE) // sb.append(":").append(start); // if (end < Integer.MAX_VALUE) // sb.append("-").append(end); // return sb.toString(); // } // }
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Scanner; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.cram.io.InputStreamUtils; import htsjdk.samtools.reference.ReferenceSequence; import htsjdk.samtools.reference.ReferenceSequenceFile; import htsjdk.samtools.seekablestream.SeekableFileStream; import htsjdk.samtools.util.BlockCompressedInputStream; import htsjdk.samtools.util.Log; import net.sf.cram.AlignmentSliceQuery; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.converters.FileConverter;
bufPos += entry.getBasesPerLine(); is.skip(lineBreakLen); } // read the rest of the last incomplete line: while ((b = (byte) is.read()) != -1 && bufPos < len && b != '\r' && b != '\n') data[bufPos++] = b; return new ReferenceSequence(entry.getName(), entry.getIndex(), data); } public static void main(String[] args) throws FileNotFoundException { Params params = new Params(); JCommander jc = new JCommander(params); jc.setProgramName("bquery"); try { jc.parse(args); } catch (Exception e) { jc.usage(); return; } if (params.file == null) { jc.usage(); return; } BGZF_ReferenceSequenceFile rsf = new BGZF_ReferenceSequenceFile(params.file); for (String stringQuery : params.queries) {
// Path: src/main/java/net/sf/cram/AlignmentSliceQuery.java // public class AlignmentSliceQuery { // public String sequence; // public int sequenceId; // public int start; // public int end = Integer.MAX_VALUE; // // public AlignmentSliceQuery(String spec) { // String[] chunks = spec.split(":"); // // sequence = chunks[0]; // // if (chunks.length > 1) { // chunks = chunks[1].split("-"); // start = Integer.valueOf(chunks[0]); // if (chunks.length == 2) // end = Integer.valueOf(chunks[1]); // } // // } // // @Override // public String toString() { // StringBuffer sb = new StringBuffer(sequence); // if (start > 1 || end < Integer.MAX_VALUE) // sb.append(":").append(start); // if (end < Integer.MAX_VALUE) // sb.append("-").append(end); // return sb.toString(); // } // } // Path: src/main/java/net/sf/cram/fasta/BGZF_ReferenceSequenceFile.java import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Scanner; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.cram.io.InputStreamUtils; import htsjdk.samtools.reference.ReferenceSequence; import htsjdk.samtools.reference.ReferenceSequenceFile; import htsjdk.samtools.seekablestream.SeekableFileStream; import htsjdk.samtools.util.BlockCompressedInputStream; import htsjdk.samtools.util.Log; import net.sf.cram.AlignmentSliceQuery; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.converters.FileConverter; bufPos += entry.getBasesPerLine(); is.skip(lineBreakLen); } // read the rest of the last incomplete line: while ((b = (byte) is.read()) != -1 && bufPos < len && b != '\r' && b != '\n') data[bufPos++] = b; return new ReferenceSequence(entry.getName(), entry.getIndex(), data); } public static void main(String[] args) throws FileNotFoundException { Params params = new Params(); JCommander jc = new JCommander(params); jc.setProgramName("bquery"); try { jc.parse(args); } catch (Exception e) { jc.usage(); return; } if (params.file == null) { jc.usage(); return; } BGZF_ReferenceSequenceFile rsf = new BGZF_ReferenceSequenceFile(params.file); for (String stringQuery : params.queries) {
AlignmentSliceQuery q = new AlignmentSliceQuery(stringQuery);
enasequence/cramtools
src/main/java/net/sf/cram/DownloadReferences.java
// Path: src/main/java/net/sf/cram/CramTools.java // public static class LevelConverter implements IStringConverter<Log.LogLevel> { // // @Override // public Log.LogLevel convert(String s) { // return Log.LogLevel.valueOf(s.toUpperCase()); // } // // }
import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.cram.build.CramIO; import htsjdk.samtools.cram.structure.CramHeader; import htsjdk.samtools.util.Log; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPOutputStream; import net.sf.cram.CramTools.LevelConverter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.converters.FileConverter;
private static void copy(InputStream in, OutputStream out, int lineLength) throws IOException { int count; byte[] buffer = new byte[8192]; int posInLine = 0, posInBuf = 0; while ((count = in.read(buffer)) > -1) { posInBuf = 0; while (posInBuf < count) { for (; posInLine < lineLength && posInBuf < count; posInLine++) { out.write(buffer[posInBuf++]); } if (posInLine >= lineLength) { posInLine = 0; out.write('\n'); } } } if (posInLine > 0) out.write('\n'); } private static InputStream getInputStreamForMD5(String md5) throws IOException { String urlString = String.format("http://www.ebi.ac.uk/ena/cram/md5/%s", md5); URL url = new URL(urlString); return url.openStream(); } @Parameters(commandDescription = "Download reference sequences.") static class Params {
// Path: src/main/java/net/sf/cram/CramTools.java // public static class LevelConverter implements IStringConverter<Log.LogLevel> { // // @Override // public Log.LogLevel convert(String s) { // return Log.LogLevel.valueOf(s.toUpperCase()); // } // // } // Path: src/main/java/net/sf/cram/DownloadReferences.java import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.cram.build.CramIO; import htsjdk.samtools.cram.structure.CramHeader; import htsjdk.samtools.util.Log; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPOutputStream; import net.sf.cram.CramTools.LevelConverter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.converters.FileConverter; private static void copy(InputStream in, OutputStream out, int lineLength) throws IOException { int count; byte[] buffer = new byte[8192]; int posInLine = 0, posInBuf = 0; while ((count = in.read(buffer)) > -1) { posInBuf = 0; while (posInBuf < count) { for (; posInLine < lineLength && posInBuf < count; posInLine++) { out.write(buffer[posInBuf++]); } if (posInLine >= lineLength) { posInLine = 0; out.write('\n'); } } } if (posInLine > 0) out.write('\n'); } private static InputStream getInputStreamForMD5(String md5) throws IOException { String urlString = String.format("http://www.ebi.ac.uk/ena/cram/md5/%s", md5); URL url = new URL(urlString); return url.openStream(); } @Parameters(commandDescription = "Download reference sequences.") static class Params {
@Parameter(names = { "-l", "--log-level" }, description = "Change log level: DEBUG, INFO, WARNING, ERROR.", converter = LevelConverter.class)
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/notificationprovider/NotificationBroadcaster.java
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/ProcessedNotification.java // public class ProcessedNotification { // private final StatusBarNotification contentNotification; // private StatusBarNotification metadataNotification; // private final SharedPreferences appPreferences; // private boolean updateNotification; // private boolean subsequentNotification; // private String title; // private String text; // // public ProcessedNotification(StatusBarNotification contentNotification, SharedPreferences appPreferences) { // this.contentNotification = contentNotification; // this.metadataNotification = contentNotification; // this.appPreferences = appPreferences; // updateNotification = false; // subsequentNotification = false; // text = ""; // title = ""; // } // // /** // * @return notification that contains content of the message // */ // public StatusBarNotification getContentNotification() { // return contentNotification; // } // // public SharedPreferences getAppPreferences() { // return appPreferences; // } // // public boolean isUpdateNotification() { // return updateNotification; // } // // public void setUpdateNotification(boolean updateNotification) { // this.updateNotification = updateNotification; // } // // public boolean isSubsequentNotification() { // return subsequentNotification; // } // // public void setSubsequentNotification(boolean subsequentNotification) { // this.subsequentNotification = subsequentNotification; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // /** // * @return notification that contains the metadata of the message (vibration pattern etc.) // */ // public StatusBarNotification getMetadataNotification() { // return metadataNotification; // } // // public void setMetadataNotification(StatusBarNotification metadataNotification) { // this.metadataNotification = metadataNotification; // } // // public boolean containsSameNotification(StatusBarNotification other) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { // return contentNotification.getKey().equals(other.getKey()); // } else { // return (contentNotification.getPackageName().equals(other.getPackageName()) && // (contentNotification.getId() == other.getId()) && // ((contentNotification.getTag() != null && contentNotification.getTag().equals(other.getTag())) || (contentNotification.getTag() == null && other.getTag() == null))); // } // } // }
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import com.matejdro.wearvibrationcenter.notification.ProcessedNotification;
package com.matejdro.wearvibrationcenter.notificationprovider; public class NotificationBroadcaster { private Context context; private NotificationBroadcastMediator mediator; public NotificationBroadcaster(Context context) { this.context = context; Intent intent = new Intent(); intent.setComponent(NotificationProviderConstants.TARGET_COMPONENT); intent.setAction(NotificationProviderConstants.ACTION_NOTIFICATION_SENDER); context.bindService(intent, connection, Context.BIND_AUTO_CREATE); } public void onDestroy() { context.unbindService(connection); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mediator = ((NotificationBroadcastMediator.MediatorBinder) service).getMediator(); } @Override public void onServiceDisconnected(ComponentName name) { mediator = null; } };
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/ProcessedNotification.java // public class ProcessedNotification { // private final StatusBarNotification contentNotification; // private StatusBarNotification metadataNotification; // private final SharedPreferences appPreferences; // private boolean updateNotification; // private boolean subsequentNotification; // private String title; // private String text; // // public ProcessedNotification(StatusBarNotification contentNotification, SharedPreferences appPreferences) { // this.contentNotification = contentNotification; // this.metadataNotification = contentNotification; // this.appPreferences = appPreferences; // updateNotification = false; // subsequentNotification = false; // text = ""; // title = ""; // } // // /** // * @return notification that contains content of the message // */ // public StatusBarNotification getContentNotification() { // return contentNotification; // } // // public SharedPreferences getAppPreferences() { // return appPreferences; // } // // public boolean isUpdateNotification() { // return updateNotification; // } // // public void setUpdateNotification(boolean updateNotification) { // this.updateNotification = updateNotification; // } // // public boolean isSubsequentNotification() { // return subsequentNotification; // } // // public void setSubsequentNotification(boolean subsequentNotification) { // this.subsequentNotification = subsequentNotification; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // /** // * @return notification that contains the metadata of the message (vibration pattern etc.) // */ // public StatusBarNotification getMetadataNotification() { // return metadataNotification; // } // // public void setMetadataNotification(StatusBarNotification metadataNotification) { // this.metadataNotification = metadataNotification; // } // // public boolean containsSameNotification(StatusBarNotification other) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { // return contentNotification.getKey().equals(other.getKey()); // } else { // return (contentNotification.getPackageName().equals(other.getPackageName()) && // (contentNotification.getId() == other.getId()) && // ((contentNotification.getTag() != null && contentNotification.getTag().equals(other.getTag())) || (contentNotification.getTag() == null && other.getTag() == null))); // } // } // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notificationprovider/NotificationBroadcaster.java import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import com.matejdro.wearvibrationcenter.notification.ProcessedNotification; package com.matejdro.wearvibrationcenter.notificationprovider; public class NotificationBroadcaster { private Context context; private NotificationBroadcastMediator mediator; public NotificationBroadcaster(Context context) { this.context = context; Intent intent = new Intent(); intent.setComponent(NotificationProviderConstants.TARGET_COMPONENT); intent.setAction(NotificationProviderConstants.ACTION_NOTIFICATION_SENDER); context.bindService(intent, connection, Context.BIND_AUTO_CREATE); } public void onDestroy() { context.unbindService(connection); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mediator = ((NotificationBroadcastMediator.MediatorBinder) service).getMediator(); } @Override public void onServiceDisconnected(ComponentName name) { mediator = null; } };
public void onNewNotification(ProcessedNotification notification) {
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/WearVibrationCenter.java
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/CrashlyticsExceptionWearHandler.java // public class CrashlyticsExceptionWearHandler implements ExceptionWearHandler{ // @Override // /** // * Exception handler with Crashlytics support, also it will be shown in logcat. // */ // public void handleException(Throwable throwable, DataMap map) { // Timber.d("HandleException %s", throwable); // Crashlytics.setBool("wear_exception", true); // Crashlytics.setString("board", map.getString("board")); // Crashlytics.setString("fingerprint", map.getString("fingerprint")); // Crashlytics.setString("model", map.getString("model")); // Crashlytics.setString("manufacturer", map.getString("manufacturer")); // Crashlytics.setString("product", map.getString("product")); // Crashlytics.setString("api_level", map.getString("api_level")); // // Crashlytics.logException(throwable); // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/TimberCrashlytics.java // public class TimberCrashlytics extends Timber.Tree { // @Override // protected void log(int priority, String tag, String message, Throwable t) { // if (t != null) { // Crashlytics.log(priority, tag, message); // Crashlytics.logException(t); // } // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/VibrationCenterChannels.java // @TargetApi(Build.VERSION_CODES.O) // public class VibrationCenterChannels { // public static String CHANNEL_TEMPORARY_MUTE = "TEMPORARY_MUTE"; // // public static void init(Context context) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // return; // } // // NotificationManager notificationManager = (NotificationManager) // context.getSystemService(Context.NOTIFICATION_SERVICE); // assert notificationManager != null; // // NotificationChannel channel = new NotificationChannel( // CHANNEL_TEMPORARY_MUTE, // context.getString(R.string.temporary_mute_channel_name), // NotificationManager.IMPORTANCE_MIN // ); // notificationManager.createNotificationChannel(channel); // // } // }
import android.app.Application; import android.content.pm.ApplicationInfo; import com.crashlytics.android.Crashlytics; import com.matejdro.wearutils.logging.FileLogger; import com.matejdro.wearvibrationcenter.logging.CrashlyticsExceptionWearHandler; import com.matejdro.wearvibrationcenter.logging.TimberCrashlytics; import com.matejdro.wearvibrationcenter.notification.VibrationCenterChannels; import io.fabric.sdk.android.Fabric; import pl.tajchert.exceptionwear.ExceptionDataListenerService; import timber.log.Timber;
package com.matejdro.wearvibrationcenter; public class WearVibrationCenter extends Application { @Override public void onCreate() { super.onCreate(); Timber.setAppTag("WearVibrationCenter"); boolean isDebuggable = (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (!isDebuggable) { Fabric.with(this, new Crashlytics());
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/CrashlyticsExceptionWearHandler.java // public class CrashlyticsExceptionWearHandler implements ExceptionWearHandler{ // @Override // /** // * Exception handler with Crashlytics support, also it will be shown in logcat. // */ // public void handleException(Throwable throwable, DataMap map) { // Timber.d("HandleException %s", throwable); // Crashlytics.setBool("wear_exception", true); // Crashlytics.setString("board", map.getString("board")); // Crashlytics.setString("fingerprint", map.getString("fingerprint")); // Crashlytics.setString("model", map.getString("model")); // Crashlytics.setString("manufacturer", map.getString("manufacturer")); // Crashlytics.setString("product", map.getString("product")); // Crashlytics.setString("api_level", map.getString("api_level")); // // Crashlytics.logException(throwable); // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/TimberCrashlytics.java // public class TimberCrashlytics extends Timber.Tree { // @Override // protected void log(int priority, String tag, String message, Throwable t) { // if (t != null) { // Crashlytics.log(priority, tag, message); // Crashlytics.logException(t); // } // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/VibrationCenterChannels.java // @TargetApi(Build.VERSION_CODES.O) // public class VibrationCenterChannels { // public static String CHANNEL_TEMPORARY_MUTE = "TEMPORARY_MUTE"; // // public static void init(Context context) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // return; // } // // NotificationManager notificationManager = (NotificationManager) // context.getSystemService(Context.NOTIFICATION_SERVICE); // assert notificationManager != null; // // NotificationChannel channel = new NotificationChannel( // CHANNEL_TEMPORARY_MUTE, // context.getString(R.string.temporary_mute_channel_name), // NotificationManager.IMPORTANCE_MIN // ); // notificationManager.createNotificationChannel(channel); // // } // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/WearVibrationCenter.java import android.app.Application; import android.content.pm.ApplicationInfo; import com.crashlytics.android.Crashlytics; import com.matejdro.wearutils.logging.FileLogger; import com.matejdro.wearvibrationcenter.logging.CrashlyticsExceptionWearHandler; import com.matejdro.wearvibrationcenter.logging.TimberCrashlytics; import com.matejdro.wearvibrationcenter.notification.VibrationCenterChannels; import io.fabric.sdk.android.Fabric; import pl.tajchert.exceptionwear.ExceptionDataListenerService; import timber.log.Timber; package com.matejdro.wearvibrationcenter; public class WearVibrationCenter extends Application { @Override public void onCreate() { super.onCreate(); Timber.setAppTag("WearVibrationCenter"); boolean isDebuggable = (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (!isDebuggable) { Fabric.with(this, new Crashlytics());
Timber.plant(new TimberCrashlytics());
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/WearVibrationCenter.java
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/CrashlyticsExceptionWearHandler.java // public class CrashlyticsExceptionWearHandler implements ExceptionWearHandler{ // @Override // /** // * Exception handler with Crashlytics support, also it will be shown in logcat. // */ // public void handleException(Throwable throwable, DataMap map) { // Timber.d("HandleException %s", throwable); // Crashlytics.setBool("wear_exception", true); // Crashlytics.setString("board", map.getString("board")); // Crashlytics.setString("fingerprint", map.getString("fingerprint")); // Crashlytics.setString("model", map.getString("model")); // Crashlytics.setString("manufacturer", map.getString("manufacturer")); // Crashlytics.setString("product", map.getString("product")); // Crashlytics.setString("api_level", map.getString("api_level")); // // Crashlytics.logException(throwable); // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/TimberCrashlytics.java // public class TimberCrashlytics extends Timber.Tree { // @Override // protected void log(int priority, String tag, String message, Throwable t) { // if (t != null) { // Crashlytics.log(priority, tag, message); // Crashlytics.logException(t); // } // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/VibrationCenterChannels.java // @TargetApi(Build.VERSION_CODES.O) // public class VibrationCenterChannels { // public static String CHANNEL_TEMPORARY_MUTE = "TEMPORARY_MUTE"; // // public static void init(Context context) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // return; // } // // NotificationManager notificationManager = (NotificationManager) // context.getSystemService(Context.NOTIFICATION_SERVICE); // assert notificationManager != null; // // NotificationChannel channel = new NotificationChannel( // CHANNEL_TEMPORARY_MUTE, // context.getString(R.string.temporary_mute_channel_name), // NotificationManager.IMPORTANCE_MIN // ); // notificationManager.createNotificationChannel(channel); // // } // }
import android.app.Application; import android.content.pm.ApplicationInfo; import com.crashlytics.android.Crashlytics; import com.matejdro.wearutils.logging.FileLogger; import com.matejdro.wearvibrationcenter.logging.CrashlyticsExceptionWearHandler; import com.matejdro.wearvibrationcenter.logging.TimberCrashlytics; import com.matejdro.wearvibrationcenter.notification.VibrationCenterChannels; import io.fabric.sdk.android.Fabric; import pl.tajchert.exceptionwear.ExceptionDataListenerService; import timber.log.Timber;
package com.matejdro.wearvibrationcenter; public class WearVibrationCenter extends Application { @Override public void onCreate() { super.onCreate(); Timber.setAppTag("WearVibrationCenter"); boolean isDebuggable = (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (!isDebuggable) { Fabric.with(this, new Crashlytics()); Timber.plant(new TimberCrashlytics());
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/CrashlyticsExceptionWearHandler.java // public class CrashlyticsExceptionWearHandler implements ExceptionWearHandler{ // @Override // /** // * Exception handler with Crashlytics support, also it will be shown in logcat. // */ // public void handleException(Throwable throwable, DataMap map) { // Timber.d("HandleException %s", throwable); // Crashlytics.setBool("wear_exception", true); // Crashlytics.setString("board", map.getString("board")); // Crashlytics.setString("fingerprint", map.getString("fingerprint")); // Crashlytics.setString("model", map.getString("model")); // Crashlytics.setString("manufacturer", map.getString("manufacturer")); // Crashlytics.setString("product", map.getString("product")); // Crashlytics.setString("api_level", map.getString("api_level")); // // Crashlytics.logException(throwable); // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/TimberCrashlytics.java // public class TimberCrashlytics extends Timber.Tree { // @Override // protected void log(int priority, String tag, String message, Throwable t) { // if (t != null) { // Crashlytics.log(priority, tag, message); // Crashlytics.logException(t); // } // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/VibrationCenterChannels.java // @TargetApi(Build.VERSION_CODES.O) // public class VibrationCenterChannels { // public static String CHANNEL_TEMPORARY_MUTE = "TEMPORARY_MUTE"; // // public static void init(Context context) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // return; // } // // NotificationManager notificationManager = (NotificationManager) // context.getSystemService(Context.NOTIFICATION_SERVICE); // assert notificationManager != null; // // NotificationChannel channel = new NotificationChannel( // CHANNEL_TEMPORARY_MUTE, // context.getString(R.string.temporary_mute_channel_name), // NotificationManager.IMPORTANCE_MIN // ); // notificationManager.createNotificationChannel(channel); // // } // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/WearVibrationCenter.java import android.app.Application; import android.content.pm.ApplicationInfo; import com.crashlytics.android.Crashlytics; import com.matejdro.wearutils.logging.FileLogger; import com.matejdro.wearvibrationcenter.logging.CrashlyticsExceptionWearHandler; import com.matejdro.wearvibrationcenter.logging.TimberCrashlytics; import com.matejdro.wearvibrationcenter.notification.VibrationCenterChannels; import io.fabric.sdk.android.Fabric; import pl.tajchert.exceptionwear.ExceptionDataListenerService; import timber.log.Timber; package com.matejdro.wearvibrationcenter; public class WearVibrationCenter extends Application { @Override public void onCreate() { super.onCreate(); Timber.setAppTag("WearVibrationCenter"); boolean isDebuggable = (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (!isDebuggable) { Fabric.with(this, new Crashlytics()); Timber.plant(new TimberCrashlytics());
ExceptionDataListenerService.setHandler(new CrashlyticsExceptionWearHandler());
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/WearVibrationCenter.java
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/CrashlyticsExceptionWearHandler.java // public class CrashlyticsExceptionWearHandler implements ExceptionWearHandler{ // @Override // /** // * Exception handler with Crashlytics support, also it will be shown in logcat. // */ // public void handleException(Throwable throwable, DataMap map) { // Timber.d("HandleException %s", throwable); // Crashlytics.setBool("wear_exception", true); // Crashlytics.setString("board", map.getString("board")); // Crashlytics.setString("fingerprint", map.getString("fingerprint")); // Crashlytics.setString("model", map.getString("model")); // Crashlytics.setString("manufacturer", map.getString("manufacturer")); // Crashlytics.setString("product", map.getString("product")); // Crashlytics.setString("api_level", map.getString("api_level")); // // Crashlytics.logException(throwable); // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/TimberCrashlytics.java // public class TimberCrashlytics extends Timber.Tree { // @Override // protected void log(int priority, String tag, String message, Throwable t) { // if (t != null) { // Crashlytics.log(priority, tag, message); // Crashlytics.logException(t); // } // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/VibrationCenterChannels.java // @TargetApi(Build.VERSION_CODES.O) // public class VibrationCenterChannels { // public static String CHANNEL_TEMPORARY_MUTE = "TEMPORARY_MUTE"; // // public static void init(Context context) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // return; // } // // NotificationManager notificationManager = (NotificationManager) // context.getSystemService(Context.NOTIFICATION_SERVICE); // assert notificationManager != null; // // NotificationChannel channel = new NotificationChannel( // CHANNEL_TEMPORARY_MUTE, // context.getString(R.string.temporary_mute_channel_name), // NotificationManager.IMPORTANCE_MIN // ); // notificationManager.createNotificationChannel(channel); // // } // }
import android.app.Application; import android.content.pm.ApplicationInfo; import com.crashlytics.android.Crashlytics; import com.matejdro.wearutils.logging.FileLogger; import com.matejdro.wearvibrationcenter.logging.CrashlyticsExceptionWearHandler; import com.matejdro.wearvibrationcenter.logging.TimberCrashlytics; import com.matejdro.wearvibrationcenter.notification.VibrationCenterChannels; import io.fabric.sdk.android.Fabric; import pl.tajchert.exceptionwear.ExceptionDataListenerService; import timber.log.Timber;
package com.matejdro.wearvibrationcenter; public class WearVibrationCenter extends Application { @Override public void onCreate() { super.onCreate(); Timber.setAppTag("WearVibrationCenter"); boolean isDebuggable = (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (!isDebuggable) { Fabric.with(this, new Crashlytics()); Timber.plant(new TimberCrashlytics()); ExceptionDataListenerService.setHandler(new CrashlyticsExceptionWearHandler()); } Timber.plant(new Timber.AndroidDebugTree(isDebuggable)); FileLogger fileLogger = FileLogger.getInstance(this); fileLogger.activate(); Timber.plant(fileLogger);
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/CrashlyticsExceptionWearHandler.java // public class CrashlyticsExceptionWearHandler implements ExceptionWearHandler{ // @Override // /** // * Exception handler with Crashlytics support, also it will be shown in logcat. // */ // public void handleException(Throwable throwable, DataMap map) { // Timber.d("HandleException %s", throwable); // Crashlytics.setBool("wear_exception", true); // Crashlytics.setString("board", map.getString("board")); // Crashlytics.setString("fingerprint", map.getString("fingerprint")); // Crashlytics.setString("model", map.getString("model")); // Crashlytics.setString("manufacturer", map.getString("manufacturer")); // Crashlytics.setString("product", map.getString("product")); // Crashlytics.setString("api_level", map.getString("api_level")); // // Crashlytics.logException(throwable); // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/logging/TimberCrashlytics.java // public class TimberCrashlytics extends Timber.Tree { // @Override // protected void log(int priority, String tag, String message, Throwable t) { // if (t != null) { // Crashlytics.log(priority, tag, message); // Crashlytics.logException(t); // } // } // } // // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/notification/VibrationCenterChannels.java // @TargetApi(Build.VERSION_CODES.O) // public class VibrationCenterChannels { // public static String CHANNEL_TEMPORARY_MUTE = "TEMPORARY_MUTE"; // // public static void init(Context context) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // return; // } // // NotificationManager notificationManager = (NotificationManager) // context.getSystemService(Context.NOTIFICATION_SERVICE); // assert notificationManager != null; // // NotificationChannel channel = new NotificationChannel( // CHANNEL_TEMPORARY_MUTE, // context.getString(R.string.temporary_mute_channel_name), // NotificationManager.IMPORTANCE_MIN // ); // notificationManager.createNotificationChannel(channel); // // } // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/WearVibrationCenter.java import android.app.Application; import android.content.pm.ApplicationInfo; import com.crashlytics.android.Crashlytics; import com.matejdro.wearutils.logging.FileLogger; import com.matejdro.wearvibrationcenter.logging.CrashlyticsExceptionWearHandler; import com.matejdro.wearvibrationcenter.logging.TimberCrashlytics; import com.matejdro.wearvibrationcenter.notification.VibrationCenterChannels; import io.fabric.sdk.android.Fabric; import pl.tajchert.exceptionwear.ExceptionDataListenerService; import timber.log.Timber; package com.matejdro.wearvibrationcenter; public class WearVibrationCenter extends Application { @Override public void onCreate() { super.onCreate(); Timber.setAppTag("WearVibrationCenter"); boolean isDebuggable = (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (!isDebuggable) { Fabric.with(this, new Crashlytics()); Timber.plant(new TimberCrashlytics()); ExceptionDataListenerService.setHandler(new CrashlyticsExceptionWearHandler()); } Timber.plant(new Timber.AndroidDebugTree(isDebuggable)); FileLogger fileLogger = FileLogger.getInstance(this); fileLogger.activate(); Timber.plant(fileLogger);
VibrationCenterChannels.init(this);
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/ui/GlobalSettingsFragment.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // }
import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import androidx.annotation.NonNull; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearutils.logging.LogRetrievalTask; import com.matejdro.wearutils.preferences.legacy.CustomStoragePreferenceFragment; import com.matejdro.wearutils.preferencesync.PreferencePusher; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.CommPaths; import de.psdev.licensesdialog.LicensesDialog;
.build() .show(); return true; } }); findPreference("donateButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=THRX5EMUNBZE6")); startActivity(intent); return true; } }); if (canTransmitSettingsAutomatically()) { googleApiClient = new GoogleApiClient.Builder(getActivity()) .addApi(Wearable.API) .build(); googleApiClient.connect(); } } @Override public void onStop() { super.onStop(); if (canTransmitSettingsAutomatically() && googleApiClient != null && googleApiClient.isConnected()) {
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/ui/GlobalSettingsFragment.java import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import androidx.annotation.NonNull; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearutils.logging.LogRetrievalTask; import com.matejdro.wearutils.preferences.legacy.CustomStoragePreferenceFragment; import com.matejdro.wearutils.preferencesync.PreferencePusher; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.CommPaths; import de.psdev.licensesdialog.LicensesDialog; .build() .show(); return true; } }); findPreference("donateButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=THRX5EMUNBZE6")); startActivity(intent); return true; } }); if (canTransmitSettingsAutomatically()) { googleApiClient = new GoogleApiClient.Builder(getActivity()) .addApi(Wearable.API) .build(); googleApiClient.connect(); } } @Override public void onStop() { super.onStop(); if (canTransmitSettingsAutomatically() && googleApiClient != null && googleApiClient.isConnected()) {
PreferencePusher.INSTANCE.pushPreferences(googleApiClient, getPreferenceManager().getSharedPreferences(), CommPaths.PREFERENCES_PREFIX, false);
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/tasker/TaskerGlobalSettingsActivity.java
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/ui/GlobalSettingsFragment.java // public class GlobalSettingsFragment extends CustomStoragePreferenceFragment implements TitleUtils.TitledFragment { // private GoogleApiClient googleApiClient; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // addPreferencesFromResource(R.xml.global_settings); // // try { // findPreference("version").setSummary(getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName); // } catch (PackageManager.NameNotFoundException ignored) { // } // // findPreference("supportButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // sendLogs(); // return true; // } // }); // // findPreference("licenses").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // // @Override // public boolean onPreferenceClick(Preference preference) { // new LicensesDialog.Builder(getActivity()) // .setNotices(R.raw.notices) // .setIncludeOwnLicense(true) // .build() // .show(); // return true; // } // }); // // findPreference("donateButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=THRX5EMUNBZE6")); // startActivity(intent); // return true; // } // }); // // if (canTransmitSettingsAutomatically()) { // googleApiClient = new GoogleApiClient.Builder(getActivity()) // .addApi(Wearable.API) // .build(); // // googleApiClient.connect(); // } // } // // @Override // public void onStop() { // super.onStop(); // // if (canTransmitSettingsAutomatically() && googleApiClient != null && googleApiClient.isConnected()) { // PreferencePusher.INSTANCE.pushPreferences(googleApiClient, getPreferenceManager().getSharedPreferences(), CommPaths.PREFERENCES_PREFIX, false); // } // } // // @Override // public String getTitle() { // return getString(R.string.global_settings); // } // // @SuppressWarnings("SameReturnValue") // protected boolean canTransmitSettingsAutomatically() { // return true; // } // // private void sendLogs() { // new LogRetrievalTask(getActivity(), // CommPaths.COMMAND_SEND_LOGS, // "matejdro+support@gmail.com", // "com.matejdro.wearvibrationcenter.logs").execute((Void) null); // } // // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] // grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // // if (permissions.length > 0 && // permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && // grantResults[0] == PackageManager.PERMISSION_GRANTED) { // sendLogs(); // } // } // }
import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.matejdro.wearutils.tasker.TaskerPreferenceActivity; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.ui.GlobalSettingsFragment;
setContentView(R.layout.activity_single_fragment); getFragmentManager() .beginTransaction() .replace(R.id.content_frame, new TaskerGlobalSettingsFragment()) .commit(); super.onCreate(savedInstanceState); } @Override protected boolean onPreviousTaskerOptionsLoaded(Bundle taskerOptions) { if (taskerOptions.getInt("action", Integer.MAX_VALUE) != TaskerActions.ACTION_GLOBAL_SETTINGS) { return false; } return super.onPreviousTaskerOptionsLoaded(taskerOptions); } @Nullable @Override protected SharedPreferences getOriginalValues() { return PreferenceManager.getDefaultSharedPreferences(this); } @Override protected void onPreSave(Bundle settingsBundle, Intent taskerIntent) { settingsBundle.putInt("action", TaskerActions.ACTION_GLOBAL_SETTINGS); }
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/ui/GlobalSettingsFragment.java // public class GlobalSettingsFragment extends CustomStoragePreferenceFragment implements TitleUtils.TitledFragment { // private GoogleApiClient googleApiClient; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // addPreferencesFromResource(R.xml.global_settings); // // try { // findPreference("version").setSummary(getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName); // } catch (PackageManager.NameNotFoundException ignored) { // } // // findPreference("supportButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // sendLogs(); // return true; // } // }); // // findPreference("licenses").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // // @Override // public boolean onPreferenceClick(Preference preference) { // new LicensesDialog.Builder(getActivity()) // .setNotices(R.raw.notices) // .setIncludeOwnLicense(true) // .build() // .show(); // return true; // } // }); // // findPreference("donateButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=THRX5EMUNBZE6")); // startActivity(intent); // return true; // } // }); // // if (canTransmitSettingsAutomatically()) { // googleApiClient = new GoogleApiClient.Builder(getActivity()) // .addApi(Wearable.API) // .build(); // // googleApiClient.connect(); // } // } // // @Override // public void onStop() { // super.onStop(); // // if (canTransmitSettingsAutomatically() && googleApiClient != null && googleApiClient.isConnected()) { // PreferencePusher.INSTANCE.pushPreferences(googleApiClient, getPreferenceManager().getSharedPreferences(), CommPaths.PREFERENCES_PREFIX, false); // } // } // // @Override // public String getTitle() { // return getString(R.string.global_settings); // } // // @SuppressWarnings("SameReturnValue") // protected boolean canTransmitSettingsAutomatically() { // return true; // } // // private void sendLogs() { // new LogRetrievalTask(getActivity(), // CommPaths.COMMAND_SEND_LOGS, // "matejdro+support@gmail.com", // "com.matejdro.wearvibrationcenter.logs").execute((Void) null); // } // // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] // grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // // if (permissions.length > 0 && // permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && // grantResults[0] == PackageManager.PERMISSION_GRANTED) { // sendLogs(); // } // } // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/tasker/TaskerGlobalSettingsActivity.java import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.matejdro.wearutils.tasker.TaskerPreferenceActivity; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.ui.GlobalSettingsFragment; setContentView(R.layout.activity_single_fragment); getFragmentManager() .beginTransaction() .replace(R.id.content_frame, new TaskerGlobalSettingsFragment()) .commit(); super.onCreate(savedInstanceState); } @Override protected boolean onPreviousTaskerOptionsLoaded(Bundle taskerOptions) { if (taskerOptions.getInt("action", Integer.MAX_VALUE) != TaskerActions.ACTION_GLOBAL_SETTINGS) { return false; } return super.onPreviousTaskerOptionsLoaded(taskerOptions); } @Nullable @Override protected SharedPreferences getOriginalValues() { return PreferenceManager.getDefaultSharedPreferences(this); } @Override protected void onPreSave(Bundle settingsBundle, Intent taskerIntent) { settingsBundle.putInt("action", TaskerActions.ACTION_GLOBAL_SETTINGS); }
public static class TaskerGlobalSettingsFragment extends GlobalSettingsFragment
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/TimedMuteActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/TimedMuteCommand.java // public class TimedMuteCommand implements Parcelable { // private final int muteDurationMinutes; // // public TimedMuteCommand(int muteDurationMinutes) { // this.muteDurationMinutes = muteDurationMinutes; // } // // public int getMuteDurationMinutes() { // return muteDurationMinutes; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.muteDurationMinutes); // } // // protected TimedMuteCommand(Parcel in) { // this.muteDurationMinutes = in.readInt(); // } // // public static final Parcelable.Creator<TimedMuteCommand> CREATOR = new Parcelable.Creator<TimedMuteCommand>() { // @Override // public TimedMuteCommand createFromParcel(Parcel source) { // return new TimedMuteCommand(source); // } // // @Override // public TimedMuteCommand[] newArray(int size) { // return new TimedMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.common.TimedMuteCommand; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
package com.matejdro.wearvibrationcenter.mutepicker; public class TimedMuteActivity extends Activity { private WearableRecyclerView recycler; private ProgressBar progressBar; private List<String> muteIntervals; private List<String> storedMuteIntervals; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_loading); muteIntervals = new ArrayList<>(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/TimedMuteCommand.java // public class TimedMuteCommand implements Parcelable { // private final int muteDurationMinutes; // // public TimedMuteCommand(int muteDurationMinutes) { // this.muteDurationMinutes = muteDurationMinutes; // } // // public int getMuteDurationMinutes() { // return muteDurationMinutes; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.muteDurationMinutes); // } // // protected TimedMuteCommand(Parcel in) { // this.muteDurationMinutes = in.readInt(); // } // // public static final Parcelable.Creator<TimedMuteCommand> CREATOR = new Parcelable.Creator<TimedMuteCommand>() { // @Override // public TimedMuteCommand createFromParcel(Parcel source) { // return new TimedMuteCommand(source); // } // // @Override // public TimedMuteCommand[] newArray(int size) { // return new TimedMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/TimedMuteActivity.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.common.TimedMuteCommand; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; package com.matejdro.wearvibrationcenter.mutepicker; public class TimedMuteActivity extends Activity { private WearableRecyclerView recycler; private ProgressBar progressBar; private List<String> muteIntervals; private List<String> storedMuteIntervals; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_loading); muteIntervals = new ArrayList<>(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
storedMuteIntervals = Preferences.getStringList(preferences, GlobalSettings.MUTE_INTERVALS);
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/TimedMuteActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/TimedMuteCommand.java // public class TimedMuteCommand implements Parcelable { // private final int muteDurationMinutes; // // public TimedMuteCommand(int muteDurationMinutes) { // this.muteDurationMinutes = muteDurationMinutes; // } // // public int getMuteDurationMinutes() { // return muteDurationMinutes; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.muteDurationMinutes); // } // // protected TimedMuteCommand(Parcel in) { // this.muteDurationMinutes = in.readInt(); // } // // public static final Parcelable.Creator<TimedMuteCommand> CREATOR = new Parcelable.Creator<TimedMuteCommand>() { // @Override // public TimedMuteCommand createFromParcel(Parcel source) { // return new TimedMuteCommand(source); // } // // @Override // public TimedMuteCommand[] newArray(int size) { // return new TimedMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.common.TimedMuteCommand; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
} catch (NumberFormatException ignored) { } } new MuteExecutor(duration).execute((Void) null); } private class MuteExecutor extends AsyncTask<Void, Void, Boolean> { private final int muteDurationMinutes; public MuteExecutor(int muteDurationMinutes) { this.muteDurationMinutes = muteDurationMinutes; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... params) { GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TimedMuteActivity.this) .addApi(Wearable.API) .build(); googleApiClient.blockingConnect(); SingleMessageReceiver ackReceiver = new SingleMessageReceiver(googleApiClient,
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/TimedMuteCommand.java // public class TimedMuteCommand implements Parcelable { // private final int muteDurationMinutes; // // public TimedMuteCommand(int muteDurationMinutes) { // this.muteDurationMinutes = muteDurationMinutes; // } // // public int getMuteDurationMinutes() { // return muteDurationMinutes; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.muteDurationMinutes); // } // // protected TimedMuteCommand(Parcel in) { // this.muteDurationMinutes = in.readInt(); // } // // public static final Parcelable.Creator<TimedMuteCommand> CREATOR = new Parcelable.Creator<TimedMuteCommand>() { // @Override // public TimedMuteCommand createFromParcel(Parcel source) { // return new TimedMuteCommand(source); // } // // @Override // public TimedMuteCommand[] newArray(int size) { // return new TimedMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/TimedMuteActivity.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.common.TimedMuteCommand; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; } catch (NumberFormatException ignored) { } } new MuteExecutor(duration).execute((Void) null); } private class MuteExecutor extends AsyncTask<Void, Void, Boolean> { private final int muteDurationMinutes; public MuteExecutor(int muteDurationMinutes) { this.muteDurationMinutes = muteDurationMinutes; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... params) { GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TimedMuteActivity.this) .addApi(Wearable.API) .build(); googleApiClient.blockingConnect(); SingleMessageReceiver ackReceiver = new SingleMessageReceiver(googleApiClient,
Uri.parse("wear://*" + CommPaths.COMMAND_RECEIVAL_ACKNOWLEDGMENT),
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/TimedMuteActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/TimedMuteCommand.java // public class TimedMuteCommand implements Parcelable { // private final int muteDurationMinutes; // // public TimedMuteCommand(int muteDurationMinutes) { // this.muteDurationMinutes = muteDurationMinutes; // } // // public int getMuteDurationMinutes() { // return muteDurationMinutes; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.muteDurationMinutes); // } // // protected TimedMuteCommand(Parcel in) { // this.muteDurationMinutes = in.readInt(); // } // // public static final Parcelable.Creator<TimedMuteCommand> CREATOR = new Parcelable.Creator<TimedMuteCommand>() { // @Override // public TimedMuteCommand createFromParcel(Parcel source) { // return new TimedMuteCommand(source); // } // // @Override // public TimedMuteCommand[] newArray(int size) { // return new TimedMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.common.TimedMuteCommand; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
new MuteExecutor(duration).execute((Void) null); } private class MuteExecutor extends AsyncTask<Void, Void, Boolean> { private final int muteDurationMinutes; public MuteExecutor(int muteDurationMinutes) { this.muteDurationMinutes = muteDurationMinutes; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... params) { GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TimedMuteActivity.this) .addApi(Wearable.API) .build(); googleApiClient.blockingConnect(); SingleMessageReceiver ackReceiver = new SingleMessageReceiver(googleApiClient, Uri.parse("wear://*" + CommPaths.COMMAND_RECEIVAL_ACKNOWLEDGMENT), MessageApi.FILTER_LITERAL);
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/TimedMuteCommand.java // public class TimedMuteCommand implements Parcelable { // private final int muteDurationMinutes; // // public TimedMuteCommand(int muteDurationMinutes) { // this.muteDurationMinutes = muteDurationMinutes; // } // // public int getMuteDurationMinutes() { // return muteDurationMinutes; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.muteDurationMinutes); // } // // protected TimedMuteCommand(Parcel in) { // this.muteDurationMinutes = in.readInt(); // } // // public static final Parcelable.Creator<TimedMuteCommand> CREATOR = new Parcelable.Creator<TimedMuteCommand>() { // @Override // public TimedMuteCommand createFromParcel(Parcel source) { // return new TimedMuteCommand(source); // } // // @Override // public TimedMuteCommand[] newArray(int size) { // return new TimedMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/TimedMuteActivity.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.common.TimedMuteCommand; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; new MuteExecutor(duration).execute((Void) null); } private class MuteExecutor extends AsyncTask<Void, Void, Boolean> { private final int muteDurationMinutes; public MuteExecutor(int muteDurationMinutes) { this.muteDurationMinutes = muteDurationMinutes; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... params) { GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TimedMuteActivity.this) .addApi(Wearable.API) .build(); googleApiClient.blockingConnect(); SingleMessageReceiver ackReceiver = new SingleMessageReceiver(googleApiClient, Uri.parse("wear://*" + CommPaths.COMMAND_RECEIVAL_ACKNOWLEDGMENT), MessageApi.FILTER_LITERAL);
TimedMuteCommand command = new TimedMuteCommand(muteDurationMinutes);
matejdro/WearVibrationCenter
mobile/src/main/java/com/matejdro/wearvibrationcenter/tasker/TaskerActionPickerActivity.java
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/preferences/PerAppSettings.java // public class PerAppSettings { // public static final String VIRTUAL_APP_DEFAULT_SETTINGS = "com.matejdro.wearvibrationcenter.virtual.default"; // // public static final EnumPreferenceDefinition<VibrationType> VIBRATION_TYPE = new EnumPreferenceDefinition<>("vibration_type", VibrationType.REGULAR); // public static final PreferenceDefinition<long[]> VIBRATION_PATTERN = new SimplePreferenceDefinition<>("vibration_pattern", new long[] { 0, 500, 250, 500, 250, 500, 1000 }); // public static final PreferenceDefinition<Boolean> TURN_SCREEN_ON = new SimplePreferenceDefinition<>("turn_screen_on", false); // // public static final PreferenceDefinition<Boolean> ONLY_VIBRATE_ORIGINAL_VIBRATING = new SimplePreferenceDefinition<>("only_vibrate_original_vibrating", true); // public static final PreferenceDefinition<Boolean> RESPECT_ZEN_MODE = new SimplePreferenceDefinition<>("setting_respect_zen_mode", false); // // public static final PreferenceDefinition<Integer> MIN_VIBRATION_INTERVAL = new SimplePreferenceDefinition<>("min_vibration_interval", 5000); // public static final PreferenceDefinition<Boolean> NO_UPDATE_VIBRATIONS = new SimplePreferenceDefinition<>("setting_no_update_vibration", false); // public static final PreferenceDefinition<Boolean> NO_SUBSEQUENT_NOTIFICATION_VIBRATIONS = new SimplePreferenceDefinition<>("setting_no_subsequent_notification_vibration", false); // public static final PreferenceDefinition<Boolean> NO_VIBRATIONS_SCREEN_ON = new SimplePreferenceDefinition<>("no_vibration_screen_on", false); // public static final PreferenceDefinition<Boolean> IGNORE_LOCAL_ONLY = new SimplePreferenceDefinition<>("ignore_local_only", false); // public static final PreferenceDefinition<Boolean> ALLOW_PERSISTENT = new SimplePreferenceDefinition<>("allow_persistent", false); // // public static final PreferenceDefinition<Boolean> RESPECT_THETAER_MODE = new SimplePreferenceDefinition<>("respect_theater_mode", true); // public static final PreferenceDefinition<Boolean> RESPECT_CHARGING = new SimplePreferenceDefinition<>("respect_charging", true); // // public static final PreferenceDefinition<List<String>> EXCLUDING_REGEX = new SimplePreferenceDefinition<>("excluding_regex", null); // public static final PreferenceDefinition<List<String>> INCLUDING_REGEX = new SimplePreferenceDefinition<>("including_regex", null); // public static final PreferenceDefinition<List<String>> ALARM_REGEX = new SimplePreferenceDefinition<>("alarm_regex", null); // // public static final PreferenceDefinition<Integer> SNOOZE_DURATION = new SimplePreferenceDefinition<>("snooze_duration", 10 * 60); // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import com.matejdro.wearutils.tasker.LocaleConstants; import com.matejdro.wearutils.tasker.TaskerSetupActivity; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.PerAppSettings;
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TASKER_ACTION_REQUEST && resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); return; } super.onActivityResult(requestCode, resultCode, data); } @Override public void onBackPressed() { setResult(RESULT_CANCELED); super.onBackPressed(); } public void startAlarm(View view) { startActivityForResult(new Intent(this, StartAlarmPreferenceActivity.class), TASKER_ACTION_REQUEST); } public void changeGlobalSettings(View view) { startActivityForResult(new Intent(this, TaskerGlobalSettingsActivity.class), TASKER_ACTION_REQUEST); } public void changeDefaultAppSettings(View view) { Intent appSettingsActivityIntent = new Intent(this, TaskerAppSettingsActivity.class);
// Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/preferences/PerAppSettings.java // public class PerAppSettings { // public static final String VIRTUAL_APP_DEFAULT_SETTINGS = "com.matejdro.wearvibrationcenter.virtual.default"; // // public static final EnumPreferenceDefinition<VibrationType> VIBRATION_TYPE = new EnumPreferenceDefinition<>("vibration_type", VibrationType.REGULAR); // public static final PreferenceDefinition<long[]> VIBRATION_PATTERN = new SimplePreferenceDefinition<>("vibration_pattern", new long[] { 0, 500, 250, 500, 250, 500, 1000 }); // public static final PreferenceDefinition<Boolean> TURN_SCREEN_ON = new SimplePreferenceDefinition<>("turn_screen_on", false); // // public static final PreferenceDefinition<Boolean> ONLY_VIBRATE_ORIGINAL_VIBRATING = new SimplePreferenceDefinition<>("only_vibrate_original_vibrating", true); // public static final PreferenceDefinition<Boolean> RESPECT_ZEN_MODE = new SimplePreferenceDefinition<>("setting_respect_zen_mode", false); // // public static final PreferenceDefinition<Integer> MIN_VIBRATION_INTERVAL = new SimplePreferenceDefinition<>("min_vibration_interval", 5000); // public static final PreferenceDefinition<Boolean> NO_UPDATE_VIBRATIONS = new SimplePreferenceDefinition<>("setting_no_update_vibration", false); // public static final PreferenceDefinition<Boolean> NO_SUBSEQUENT_NOTIFICATION_VIBRATIONS = new SimplePreferenceDefinition<>("setting_no_subsequent_notification_vibration", false); // public static final PreferenceDefinition<Boolean> NO_VIBRATIONS_SCREEN_ON = new SimplePreferenceDefinition<>("no_vibration_screen_on", false); // public static final PreferenceDefinition<Boolean> IGNORE_LOCAL_ONLY = new SimplePreferenceDefinition<>("ignore_local_only", false); // public static final PreferenceDefinition<Boolean> ALLOW_PERSISTENT = new SimplePreferenceDefinition<>("allow_persistent", false); // // public static final PreferenceDefinition<Boolean> RESPECT_THETAER_MODE = new SimplePreferenceDefinition<>("respect_theater_mode", true); // public static final PreferenceDefinition<Boolean> RESPECT_CHARGING = new SimplePreferenceDefinition<>("respect_charging", true); // // public static final PreferenceDefinition<List<String>> EXCLUDING_REGEX = new SimplePreferenceDefinition<>("excluding_regex", null); // public static final PreferenceDefinition<List<String>> INCLUDING_REGEX = new SimplePreferenceDefinition<>("including_regex", null); // public static final PreferenceDefinition<List<String>> ALARM_REGEX = new SimplePreferenceDefinition<>("alarm_regex", null); // // public static final PreferenceDefinition<Integer> SNOOZE_DURATION = new SimplePreferenceDefinition<>("snooze_duration", 10 * 60); // } // Path: mobile/src/main/java/com/matejdro/wearvibrationcenter/tasker/TaskerActionPickerActivity.java import android.content.Intent; import android.os.Bundle; import android.view.View; import com.matejdro.wearutils.tasker.LocaleConstants; import com.matejdro.wearutils.tasker.TaskerSetupActivity; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.preferences.PerAppSettings; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TASKER_ACTION_REQUEST && resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); return; } super.onActivityResult(requestCode, resultCode, data); } @Override public void onBackPressed() { setResult(RESULT_CANCELED); super.onBackPressed(); } public void startAlarm(View view) { startActivityForResult(new Intent(this, StartAlarmPreferenceActivity.class), TASKER_ACTION_REQUEST); } public void changeGlobalSettings(View view) { startActivityForResult(new Intent(this, TaskerGlobalSettingsActivity.class), TASKER_ACTION_REQUEST); } public void changeDefaultAppSettings(View view) { Intent appSettingsActivityIntent = new Intent(this, TaskerAppSettingsActivity.class);
appSettingsActivityIntent.putExtra(TaskerAppSettingsActivity.EXTRA_SHOW_APP, PerAppSettings.VIRTUAL_APP_DEFAULT_SETTINGS);
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/AppMuteActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AppMuteCommand.java // public class AppMuteCommand implements Parcelable { // private final int appIndex; // // public AppMuteCommand(int appIndex) { // this.appIndex = appIndex; // } // // public int getAppIndex() { // return appIndex; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.appIndex); // } // // protected AppMuteCommand(Parcel in) { // this.appIndex = in.readInt(); // } // // public static final Parcelable.Creator<AppMuteCommand> CREATOR = new Parcelable.Creator<AppMuteCommand>() { // @Override // public AppMuteCommand createFromParcel(Parcel source) { // return new AppMuteCommand(source); // } // // @Override // public AppMuteCommand[] newArray(int size) { // return new AppMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalWatchPreferences.java // public class GlobalWatchPreferences { // public static final PreferenceDefinition<Boolean> DO_NOT_ASK_APP_MUTE_CONFIRM = new SimplePreferenceDefinition<>("do_not_ask_app_mute_confirm", false); // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearremotelist.parcelables.CompressedParcelableBitmap; import com.matejdro.wearremotelist.parcelables.StringParcelableWraper; import com.matejdro.wearremotelist.receiverside.RemoteList; import com.matejdro.wearremotelist.receiverside.RemoteListListener; import com.matejdro.wearremotelist.receiverside.RemoteListManager; import com.matejdro.wearremotelist.receiverside.conn.WatchSingleConnection; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.AppMuteCommand; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.preferences.GlobalWatchPreferences; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
@Override protected void onStop() { listConnection.disconnect(); googleApiClient.disconnect(); super.onStop(); } private void showLoading() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); emptyNotice.setVisibility(View.GONE); } private void showList() { progressBar.setVisibility(View.GONE); recycler.setVisibility(View.VISIBLE); emptyNotice.setVisibility(View.GONE); } private void showEmptyNotice() { progressBar.setVisibility(View.GONE); recycler.setVisibility(View.GONE); emptyNotice.setVisibility(View.VISIBLE); } private void itemSelected(int position) {
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AppMuteCommand.java // public class AppMuteCommand implements Parcelable { // private final int appIndex; // // public AppMuteCommand(int appIndex) { // this.appIndex = appIndex; // } // // public int getAppIndex() { // return appIndex; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.appIndex); // } // // protected AppMuteCommand(Parcel in) { // this.appIndex = in.readInt(); // } // // public static final Parcelable.Creator<AppMuteCommand> CREATOR = new Parcelable.Creator<AppMuteCommand>() { // @Override // public AppMuteCommand createFromParcel(Parcel source) { // return new AppMuteCommand(source); // } // // @Override // public AppMuteCommand[] newArray(int size) { // return new AppMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalWatchPreferences.java // public class GlobalWatchPreferences { // public static final PreferenceDefinition<Boolean> DO_NOT_ASK_APP_MUTE_CONFIRM = new SimplePreferenceDefinition<>("do_not_ask_app_mute_confirm", false); // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/AppMuteActivity.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearremotelist.parcelables.CompressedParcelableBitmap; import com.matejdro.wearremotelist.parcelables.StringParcelableWraper; import com.matejdro.wearremotelist.receiverside.RemoteList; import com.matejdro.wearremotelist.receiverside.RemoteListListener; import com.matejdro.wearremotelist.receiverside.RemoteListManager; import com.matejdro.wearremotelist.receiverside.conn.WatchSingleConnection; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.AppMuteCommand; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.preferences.GlobalWatchPreferences; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @Override protected void onStop() { listConnection.disconnect(); googleApiClient.disconnect(); super.onStop(); } private void showLoading() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); emptyNotice.setVisibility(View.GONE); } private void showList() { progressBar.setVisibility(View.GONE); recycler.setVisibility(View.VISIBLE); emptyNotice.setVisibility(View.GONE); } private void showEmptyNotice() { progressBar.setVisibility(View.GONE); recycler.setVisibility(View.GONE); emptyNotice.setVisibility(View.VISIBLE); } private void itemSelected(int position) {
if (Preferences.getBoolean(preferences, GlobalWatchPreferences.DO_NOT_ASK_APP_MUTE_CONFIRM)) {
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/AppMuteActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AppMuteCommand.java // public class AppMuteCommand implements Parcelable { // private final int appIndex; // // public AppMuteCommand(int appIndex) { // this.appIndex = appIndex; // } // // public int getAppIndex() { // return appIndex; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.appIndex); // } // // protected AppMuteCommand(Parcel in) { // this.appIndex = in.readInt(); // } // // public static final Parcelable.Creator<AppMuteCommand> CREATOR = new Parcelable.Creator<AppMuteCommand>() { // @Override // public AppMuteCommand createFromParcel(Parcel source) { // return new AppMuteCommand(source); // } // // @Override // public AppMuteCommand[] newArray(int size) { // return new AppMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalWatchPreferences.java // public class GlobalWatchPreferences { // public static final PreferenceDefinition<Boolean> DO_NOT_ASK_APP_MUTE_CONFIRM = new SimplePreferenceDefinition<>("do_not_ask_app_mute_confirm", false); // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearremotelist.parcelables.CompressedParcelableBitmap; import com.matejdro.wearremotelist.parcelables.StringParcelableWraper; import com.matejdro.wearremotelist.receiverside.RemoteList; import com.matejdro.wearremotelist.receiverside.RemoteListListener; import com.matejdro.wearremotelist.receiverside.RemoteListManager; import com.matejdro.wearremotelist.receiverside.conn.WatchSingleConnection; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.AppMuteCommand; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.preferences.GlobalWatchPreferences; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
progressBar.setVisibility(View.GONE); recycler.setVisibility(View.GONE); emptyNotice.setVisibility(View.VISIBLE); } private void itemSelected(int position) { if (Preferences.getBoolean(preferences, GlobalWatchPreferences.DO_NOT_ASK_APP_MUTE_CONFIRM)) { muteApp(position); return; } positionPendingConfirmation = position; Intent confirmationIntent = new Intent(this, AppMuteConfirmationActivity.class); confirmationIntent.putExtra(AppMuteConfirmationActivity.EXTRA_APP_NAME, textList.get(position).getString()); startActivityForResult(confirmationIntent, CONFIRMATION_REQUEST_CODE); } private void muteApp(int position) { new MuteExecutor(position).execute((Void) null); } @Override public void onConnected(@Nullable Bundle bundle) { listConnection = new WatchSingleConnection(googleApiClient); RemoteListManager listManager = new RemoteListManager(listConnection, this);
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AppMuteCommand.java // public class AppMuteCommand implements Parcelable { // private final int appIndex; // // public AppMuteCommand(int appIndex) { // this.appIndex = appIndex; // } // // public int getAppIndex() { // return appIndex; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.appIndex); // } // // protected AppMuteCommand(Parcel in) { // this.appIndex = in.readInt(); // } // // public static final Parcelable.Creator<AppMuteCommand> CREATOR = new Parcelable.Creator<AppMuteCommand>() { // @Override // public AppMuteCommand createFromParcel(Parcel source) { // return new AppMuteCommand(source); // } // // @Override // public AppMuteCommand[] newArray(int size) { // return new AppMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalWatchPreferences.java // public class GlobalWatchPreferences { // public static final PreferenceDefinition<Boolean> DO_NOT_ASK_APP_MUTE_CONFIRM = new SimplePreferenceDefinition<>("do_not_ask_app_mute_confirm", false); // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/AppMuteActivity.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearremotelist.parcelables.CompressedParcelableBitmap; import com.matejdro.wearremotelist.parcelables.StringParcelableWraper; import com.matejdro.wearremotelist.receiverside.RemoteList; import com.matejdro.wearremotelist.receiverside.RemoteListListener; import com.matejdro.wearremotelist.receiverside.RemoteListManager; import com.matejdro.wearremotelist.receiverside.conn.WatchSingleConnection; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.AppMuteCommand; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.preferences.GlobalWatchPreferences; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; progressBar.setVisibility(View.GONE); recycler.setVisibility(View.GONE); emptyNotice.setVisibility(View.VISIBLE); } private void itemSelected(int position) { if (Preferences.getBoolean(preferences, GlobalWatchPreferences.DO_NOT_ASK_APP_MUTE_CONFIRM)) { muteApp(position); return; } positionPendingConfirmation = position; Intent confirmationIntent = new Intent(this, AppMuteConfirmationActivity.class); confirmationIntent.putExtra(AppMuteConfirmationActivity.EXTRA_APP_NAME, textList.get(position).getString()); startActivityForResult(confirmationIntent, CONFIRMATION_REQUEST_CODE); } private void muteApp(int position) { new MuteExecutor(position).execute((Void) null); } @Override public void onConnected(@Nullable Bundle bundle) { listConnection = new WatchSingleConnection(googleApiClient); RemoteListManager listManager = new RemoteListManager(listConnection, this);
textList = listManager.createRemoteList(CommPaths.LIST_ACTIVE_APPS_NAMES, StringParcelableWraper.CREATOR, 1000, 40);
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/AppMuteActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AppMuteCommand.java // public class AppMuteCommand implements Parcelable { // private final int appIndex; // // public AppMuteCommand(int appIndex) { // this.appIndex = appIndex; // } // // public int getAppIndex() { // return appIndex; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.appIndex); // } // // protected AppMuteCommand(Parcel in) { // this.appIndex = in.readInt(); // } // // public static final Parcelable.Creator<AppMuteCommand> CREATOR = new Parcelable.Creator<AppMuteCommand>() { // @Override // public AppMuteCommand createFromParcel(Parcel source) { // return new AppMuteCommand(source); // } // // @Override // public AppMuteCommand[] newArray(int size) { // return new AppMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalWatchPreferences.java // public class GlobalWatchPreferences { // public static final PreferenceDefinition<Boolean> DO_NOT_ASK_APP_MUTE_CONFIRM = new SimplePreferenceDefinition<>("do_not_ask_app_mute_confirm", false); // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearremotelist.parcelables.CompressedParcelableBitmap; import com.matejdro.wearremotelist.parcelables.StringParcelableWraper; import com.matejdro.wearremotelist.receiverside.RemoteList; import com.matejdro.wearremotelist.receiverside.RemoteListListener; import com.matejdro.wearremotelist.receiverside.RemoteListManager; import com.matejdro.wearremotelist.receiverside.conn.WatchSingleConnection; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.AppMuteCommand; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.preferences.GlobalWatchPreferences; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
muteApp(positionPendingConfirmation); } } private class MuteExecutor extends AsyncTask<Void, Void, Boolean> { private final int appIndex; public MuteExecutor(int appIndex) { this.appIndex = appIndex; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... params) { GoogleApiClient googleApiClient = new GoogleApiClient.Builder(AppMuteActivity.this) .addApi(Wearable.API) .build(); googleApiClient.blockingConnect(); SingleMessageReceiver ackReceiver = new SingleMessageReceiver(googleApiClient, Uri.parse("wear://*" + CommPaths.COMMAND_RECEIVAL_ACKNOWLEDGMENT), MessageApi.FILTER_LITERAL);
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AppMuteCommand.java // public class AppMuteCommand implements Parcelable { // private final int appIndex; // // public AppMuteCommand(int appIndex) { // this.appIndex = appIndex; // } // // public int getAppIndex() { // return appIndex; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.appIndex); // } // // protected AppMuteCommand(Parcel in) { // this.appIndex = in.readInt(); // } // // public static final Parcelable.Creator<AppMuteCommand> CREATOR = new Parcelable.Creator<AppMuteCommand>() { // @Override // public AppMuteCommand createFromParcel(Parcel source) { // return new AppMuteCommand(source); // } // // @Override // public AppMuteCommand[] newArray(int size) { // return new AppMuteCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalWatchPreferences.java // public class GlobalWatchPreferences { // public static final PreferenceDefinition<Boolean> DO_NOT_ASK_APP_MUTE_CONFIRM = new SimplePreferenceDefinition<>("do_not_ask_app_mute_confirm", false); // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/AppMuteActivity.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.view.DefaultOffsettingHelper; import android.support.wearable.view.WearableRecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Wearable; import com.matejdro.wearremotelist.parcelables.CompressedParcelableBitmap; import com.matejdro.wearremotelist.parcelables.StringParcelableWraper; import com.matejdro.wearremotelist.receiverside.RemoteList; import com.matejdro.wearremotelist.receiverside.RemoteListListener; import com.matejdro.wearremotelist.receiverside.RemoteListManager; import com.matejdro.wearremotelist.receiverside.conn.WatchSingleConnection; import com.matejdro.wearutils.messages.MessagingUtils; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.messages.SingleMessageReceiver; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.AppMuteCommand; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearvibrationcenter.preferences.GlobalWatchPreferences; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; muteApp(positionPendingConfirmation); } } private class MuteExecutor extends AsyncTask<Void, Void, Boolean> { private final int appIndex; public MuteExecutor(int appIndex) { this.appIndex = appIndex; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); recycler.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... params) { GoogleApiClient googleApiClient = new GoogleApiClient.Builder(AppMuteActivity.this) .addApi(Wearable.API) .build(); googleApiClient.blockingConnect(); SingleMessageReceiver ackReceiver = new SingleMessageReceiver(googleApiClient, Uri.parse("wear://*" + CommPaths.COMMAND_RECEIVAL_ACKNOWLEDGMENT), MessageApi.FILTER_LITERAL);
AppMuteCommand command = new AppMuteCommand(appIndex);
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/AlarmActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AlarmCommand.java // public class AlarmCommand implements Parcelable, InterruptionCommand { // private final String text; // private final long[] vibrationPattern; // private final byte[] backgroundBitmap; // private final byte[] icon; // private final int snoozeDuration; // private final boolean doNotVibrateInTheater; // private final boolean doNotVibrateOnCharger; // // public AlarmCommand(LiteAlarmCommand liteAlarmCommand, byte[] backgroundBitmap, byte[] icon) { // this(liteAlarmCommand.getText(), // liteAlarmCommand.getVibrationPattern(), // backgroundBitmap, // icon, // liteAlarmCommand.getSnoozeDuration(), // liteAlarmCommand.shouldNotVibrateInTheater(), // liteAlarmCommand.shouldNotVibrateOnCharger()); // } // // public AlarmCommand(String text, long[] vibrationPattern, byte[] backgroundBitmap, byte[] icon, int snoozeDuration, boolean doNotVibrateInTheater, boolean doNotVibrateOnCharger) { // this.text = text; // this.vibrationPattern = vibrationPattern; // this.backgroundBitmap = backgroundBitmap; // this.icon = icon; // this.snoozeDuration = snoozeDuration; // this.doNotVibrateInTheater = doNotVibrateInTheater; // this.doNotVibrateOnCharger = doNotVibrateOnCharger; // } // // public String getText() { // return text; // } // // public byte[] getBackgroundBitmap() { // return backgroundBitmap; // } // // public boolean shouldNotVibrateInTheater() { // return doNotVibrateInTheater; // } // // public boolean shouldNotVibrateOnCharger() { // return doNotVibrateOnCharger; // } // // public byte[] getIcon() { // return icon; // } // // public long[] getVibrationPattern() { // return vibrationPattern; // } // // public int getSnoozeDuration() { // return snoozeDuration; // } // // @Override public int describeContents() { // return 0; // } // // @Override public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.text); // dest.writeLongArray(this.vibrationPattern); // dest.writeByteArray(this.backgroundBitmap); // dest.writeByteArray(this.icon); // dest.writeInt(this.snoozeDuration); // dest.writeByte(this.doNotVibrateInTheater ? (byte) 1 : (byte) 0); // dest.writeByte(this.doNotVibrateOnCharger ? (byte) 1 : (byte) 0); // } // // protected AlarmCommand(Parcel in) { // this.text = in.readString(); // this.vibrationPattern = in.createLongArray(); // this.backgroundBitmap = in.createByteArray(); // this.icon = in.createByteArray(); // this.snoozeDuration = in.readInt(); // this.doNotVibrateInTheater = in.readByte() != 0; // this.doNotVibrateOnCharger = in.readByte() != 0; // } // // public static final Creator<AlarmCommand> CREATOR = new Creator<AlarmCommand>() { // @Override public AlarmCommand createFromParcel(Parcel source) { // return new AlarmCommand(source); // } // // @Override public AlarmCommand[] newArray(int size) { // return new AlarmCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.activity.WearableActivity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.miscutils.BitmapUtils; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.common.AlarmCommand; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import timber.log.Timber;
package com.matejdro.wearvibrationcenter; public class AlarmActivity extends WearableActivity implements View.OnTouchListener { public static final String EXTRA_ALARM_COMMAND_BYTES = "AlarmCommandBytes"; public static final String EXTRA_ALARM_TEXT = "Text"; private int displayWidth; private FrameLayout rootLayout; private FrameLayout movableLayout; private FrameLayout centerMovableLayout; private ImageView leftMovableCircle; private ImageView rightMovableCircle; private ImageView backgroundImage; private ImageView iconImage; private TextView titleBox; private int leftCircleStartPosition; private int rightCircleStartPosition; private int moveStartX = 0; private int lastMoveX = 0; private boolean resumed = false; private boolean dismissed = false;
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/AlarmCommand.java // public class AlarmCommand implements Parcelable, InterruptionCommand { // private final String text; // private final long[] vibrationPattern; // private final byte[] backgroundBitmap; // private final byte[] icon; // private final int snoozeDuration; // private final boolean doNotVibrateInTheater; // private final boolean doNotVibrateOnCharger; // // public AlarmCommand(LiteAlarmCommand liteAlarmCommand, byte[] backgroundBitmap, byte[] icon) { // this(liteAlarmCommand.getText(), // liteAlarmCommand.getVibrationPattern(), // backgroundBitmap, // icon, // liteAlarmCommand.getSnoozeDuration(), // liteAlarmCommand.shouldNotVibrateInTheater(), // liteAlarmCommand.shouldNotVibrateOnCharger()); // } // // public AlarmCommand(String text, long[] vibrationPattern, byte[] backgroundBitmap, byte[] icon, int snoozeDuration, boolean doNotVibrateInTheater, boolean doNotVibrateOnCharger) { // this.text = text; // this.vibrationPattern = vibrationPattern; // this.backgroundBitmap = backgroundBitmap; // this.icon = icon; // this.snoozeDuration = snoozeDuration; // this.doNotVibrateInTheater = doNotVibrateInTheater; // this.doNotVibrateOnCharger = doNotVibrateOnCharger; // } // // public String getText() { // return text; // } // // public byte[] getBackgroundBitmap() { // return backgroundBitmap; // } // // public boolean shouldNotVibrateInTheater() { // return doNotVibrateInTheater; // } // // public boolean shouldNotVibrateOnCharger() { // return doNotVibrateOnCharger; // } // // public byte[] getIcon() { // return icon; // } // // public long[] getVibrationPattern() { // return vibrationPattern; // } // // public int getSnoozeDuration() { // return snoozeDuration; // } // // @Override public int describeContents() { // return 0; // } // // @Override public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.text); // dest.writeLongArray(this.vibrationPattern); // dest.writeByteArray(this.backgroundBitmap); // dest.writeByteArray(this.icon); // dest.writeInt(this.snoozeDuration); // dest.writeByte(this.doNotVibrateInTheater ? (byte) 1 : (byte) 0); // dest.writeByte(this.doNotVibrateOnCharger ? (byte) 1 : (byte) 0); // } // // protected AlarmCommand(Parcel in) { // this.text = in.readString(); // this.vibrationPattern = in.createLongArray(); // this.backgroundBitmap = in.createByteArray(); // this.icon = in.createByteArray(); // this.snoozeDuration = in.readInt(); // this.doNotVibrateInTheater = in.readByte() != 0; // this.doNotVibrateOnCharger = in.readByte() != 0; // } // // public static final Creator<AlarmCommand> CREATOR = new Creator<AlarmCommand>() { // @Override public AlarmCommand createFromParcel(Parcel source) { // return new AlarmCommand(source); // } // // @Override public AlarmCommand[] newArray(int size) { // return new AlarmCommand[size]; // } // }; // } // // Path: common/src/main/java/com/matejdro/wearvibrationcenter/preferences/GlobalSettings.java // public class GlobalSettings { // public static final PreferenceDefinition<Boolean> ENABLE_VIBRATIONS = new SimplePreferenceDefinition<>("enable_vibrations", true); // public static final PreferenceDefinition<Integer> ALARM_TIMEOUT = new SimplePreferenceDefinition<>("alarm_timeout", 60); // public static final PreferenceDefinition<List<String>> MUTE_INTERVALS = new SimplePreferenceDefinition<>("mute_intervals", Arrays.asList("10", "20", "30", "60", "120")); // public static final EnumPreferenceDefinition<ZenModeChange> TIMED_MUTE_ZEN_CHANGE = new EnumPreferenceDefinition<>("timed_mute_zen", ZenModeChange.ALARMS); // public static final PreferenceDefinition<Integer> PROCESSING_DELAY = new SimplePreferenceDefinition<>("processing_delay", 2000); // // // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/AlarmActivity.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.support.wearable.activity.ConfirmationActivity; import android.support.wearable.activity.WearableActivity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.matejdro.wearutils.messages.ParcelPacker; import com.matejdro.wearutils.miscutils.BitmapUtils; import com.matejdro.wearutils.preferences.definition.Preferences; import com.matejdro.wearvibrationcenter.common.AlarmCommand; import com.matejdro.wearvibrationcenter.preferences.GlobalSettings; import timber.log.Timber; package com.matejdro.wearvibrationcenter; public class AlarmActivity extends WearableActivity implements View.OnTouchListener { public static final String EXTRA_ALARM_COMMAND_BYTES = "AlarmCommandBytes"; public static final String EXTRA_ALARM_TEXT = "Text"; private int displayWidth; private FrameLayout rootLayout; private FrameLayout movableLayout; private FrameLayout centerMovableLayout; private ImageView leftMovableCircle; private ImageView rightMovableCircle; private ImageView backgroundImage; private ImageView iconImage; private TextView titleBox; private int leftCircleStartPosition; private int rightCircleStartPosition; private int moveStartX = 0; private int lastMoveX = 0; private boolean resumed = false; private boolean dismissed = false;
private AlarmCommand alarmCommand;
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/GlobalPreferenceReceiverService.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // }
import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearutils.preferencesync.PreferenceReceiverService;
package com.matejdro.wearvibrationcenter; public class GlobalPreferenceReceiverService extends PreferenceReceiverService { public GlobalPreferenceReceiverService() {
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/GlobalPreferenceReceiverService.java import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.matejdro.wearvibrationcenter.common.CommPaths; import com.matejdro.wearutils.preferencesync.PreferenceReceiverService; package com.matejdro.wearvibrationcenter; public class GlobalPreferenceReceiverService extends PreferenceReceiverService { public GlobalPreferenceReceiverService() {
super(CommPaths.PREFERENCES_PREFIX);
matejdro/WearVibrationCenter
wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/MuteModeActivity.java
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.wearable.CapabilityApi; import com.matejdro.wearutils.companionnotice.WearCompanionWatchActivity; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.CommPaths;
package com.matejdro.wearvibrationcenter.mutepicker; public class MuteModeActivity extends WearCompanionWatchActivity implements GoogleApiClient.ConnectionCallbacks, ResultCallback<CapabilityApi.GetCapabilityResult> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mute_mode); } public void openTimedMute(View view) { startActivity(new Intent(this, TimedMuteActivity.class)); finish(); } public void openAppMute(View view) { startActivity(new Intent(this, AppMuteActivity.class)); finish(); } @Override public String getPhoneAppPresenceCapability() {
// Path: common/src/main/java/com/matejdro/wearvibrationcenter/common/CommPaths.java // public interface CommPaths // { // String PHONE_APP_CAPABILITY = "VibrationCenterPhone"; // String WATCH_APP_CAPABILITY = "VibrationCenterWatch"; // // String COMMAND_VIBRATE = "/Command/Vibrate"; // String COMMAND_ALARM = "/Command/Alarm"; // String COMMAND_APP_MUTE = "/Command/AppMute"; // String COMMAND_TIMED_MUTE = "/Command/TimedMute"; // String COMMAND_SEND_LOGS = "/Command/SendLogs"; // // String COMMAND_RECEIVAL_ACKNOWLEDGMENT = "/Ack"; // // String CHANNEL_LOGS = "/Channel/Logs"; // // String LIST_ACTIVE_APPS_NAMES = "/List/ActiveApps/Names"; // String LIST_ACTIVE_APPS_ICONS = "/List/ActiveApps/Icons"; // // String ASSET_ICON = "Icon"; // String ASSET_BACKGROUND = "Background"; // // String PREFERENCES_PREFIX = "/Preferences"; // } // Path: wear/src/main/java/com/matejdro/wearvibrationcenter/mutepicker/MuteModeActivity.java import android.content.Intent; import android.os.Bundle; import android.view.View; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.wearable.CapabilityApi; import com.matejdro.wearutils.companionnotice.WearCompanionWatchActivity; import com.matejdro.wearvibrationcenter.R; import com.matejdro.wearvibrationcenter.common.CommPaths; package com.matejdro.wearvibrationcenter.mutepicker; public class MuteModeActivity extends WearCompanionWatchActivity implements GoogleApiClient.ConnectionCallbacks, ResultCallback<CapabilityApi.GetCapabilityResult> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mute_mode); } public void openTimedMute(View view) { startActivity(new Intent(this, TimedMuteActivity.class)); finish(); } public void openAppMute(View view) { startActivity(new Intent(this, AppMuteActivity.class)); finish(); } @Override public String getPhoneAppPresenceCapability() {
return CommPaths.PHONE_APP_CAPABILITY;
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserIntTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserIntTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "foo", "poiuytd", "Odwdw0", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("5", Collections.singletonList(5)), Arguments.of("5,999,-55", Arrays.asList(5, 999, -55)) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<Integer> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofInt().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofInt().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofInt().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserIntTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserIntTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "foo", "poiuytd", "Odwdw0", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("5", Collections.singletonList(5)), Arguments.of("5,999,-55", Arrays.asList(5, 999, -55)) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<Integer> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofInt().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofInt().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofInt().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterMultipleValueParser.ofInt().parse(argument));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserByteTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserByteTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "foo", "poiuytd", "Odwdw0", "129", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("5", Collections.singletonList((byte) 5)), Arguments.of("5,127,-55", Arrays.asList((byte) 5, (byte) 127, (byte) -55)) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<Byte> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofByte().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofByte().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofByte().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserByteTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserByteTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "foo", "poiuytd", "Odwdw0", "129", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("5", Collections.singletonList((byte) 5)), Arguments.of("5,127,-55", Arrays.asList((byte) 5, (byte) 127, (byte) -55)) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<Byte> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofByte().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofByte().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofByte().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterMultipleValueParser.ofByte().parse(argument));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserLocalDateTimeTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.time.format.DateTimeParseException;
Assertions.assertEquals(date2, FilterParser.ofDateTime().parse(correctFormatDate2)); Assertions.assertEquals(date3, FilterParser.ofDateTime().parse(correctFormatDate3)); // Later could add more default "correct" datetime values but very minimal -> still keep ISO // Assertions.assertEquals(date1, FilterParser.ofDateTime().parse("2017-10-20 14:46")); // Assertions.assertEquals(date2, FilterParser.ofDateTime().parse("2017-10-25 10:30:45")); } @Test void parseThrows() { Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("2017-04-06")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("poiuytd")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("Odwdw0")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("O")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(date1, FilterParser.ofDateTime().parseWithApiException(correctFormatDate1)); Assertions.assertEquals(date2, FilterParser.ofDateTime().parseWithApiException(correctFormatDate2)); Assertions.assertEquals(date3, FilterParser.ofDateTime().parseWithApiException(correctFormatDate3)); // Later could add more default "correct" datetime values but very minimal -> still keep ISO // Assertions.assertEquals(date1, FilterParser.ofDateTime().parseWithApiException("2017-10-20 14:46")); // Assertions.assertEquals(date2, FilterParser.ofDateTime().parseWithApiException("2017-10-25 10:30:45")); } @Test void parseWithApiExceptionThrows() {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserLocalDateTimeTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.time.format.DateTimeParseException; Assertions.assertEquals(date2, FilterParser.ofDateTime().parse(correctFormatDate2)); Assertions.assertEquals(date3, FilterParser.ofDateTime().parse(correctFormatDate3)); // Later could add more default "correct" datetime values but very minimal -> still keep ISO // Assertions.assertEquals(date1, FilterParser.ofDateTime().parse("2017-10-20 14:46")); // Assertions.assertEquals(date2, FilterParser.ofDateTime().parse("2017-10-25 10:30:45")); } @Test void parseThrows() { Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("2017-04-06")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("poiuytd")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("Odwdw0")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse("O")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDateTime().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(date1, FilterParser.ofDateTime().parseWithApiException(correctFormatDate1)); Assertions.assertEquals(date2, FilterParser.ofDateTime().parseWithApiException(correctFormatDate2)); Assertions.assertEquals(date3, FilterParser.ofDateTime().parseWithApiException(correctFormatDate3)); // Later could add more default "correct" datetime values but very minimal -> still keep ISO // Assertions.assertEquals(date1, FilterParser.ofDateTime().parseWithApiException("2017-10-20 14:46")); // Assertions.assertEquals(date2, FilterParser.ofDateTime().parseWithApiException("2017-10-25 10:30:45")); } @Test void parseWithApiExceptionThrows() {
Assertions.assertThrows(FilteringApiException.class, () -> FilterParser.ofDateTime().parseWithApiException("2017-04-06"));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/FilteringJooqTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParser.java // @FunctionalInterface // public interface FilterParser<R> { // // /** // * @param value Value to be parsed // * @return Value parsed and transform to generic value // * @throws RuntimeException When parsing failed if implementation does not swallow exception // */ // @NotNull // R parse(final String value); // // /** // * @param value Value to be parsed // * @param parser Custom parser function // * @return Value parsed and transform to generic value // * @throws FilteringApiException If an error occurred at parsing // * @deprecated No sure it is useful, if need to define a new parser then better to create the class and etc // */ // default R parseWithApiException(final String value, final Function<String, R> parser) throws FilteringApiException { // try { // return parser.apply(value); // } catch (Exception e) { // throw new FilteringApiException("Could not parse value (" + value + ") to " + this.getClass().getSimpleName()); // } // } // // /** // * @param value Value to be parsed // * @return Value parsed and transform to generic value // * @throws FilteringApiException If an error occurred at parsing // */ // default R parseWithApiException(final String value) throws FilteringApiException { // try { // return parse(value); // } catch (Exception e) { // throw new FilteringApiException("Could not parse value (" + value + ") to " + this.getClass().getSimpleName()); // } // } // // /** // * @param value Value to be parsed // * @param defaultValue Default value returned if parse throws an exception // * @return Value parsed and transform to generic value // */ // default R parseOrDefault(final String value, final R defaultValue) { // try { // return parse(value); // } catch (Exception e) { // return defaultValue; // } // } // // /** // * @param value Value to be parsed // * @param defaultValue Default value returned if parse throws an exception // * @return Value parsed and transform to generic value // */ // default R parseOrDefault(final String value, final Supplier<R> defaultValue) { // try { // return parse(value); // } catch (Exception e) { // return defaultValue.get(); // } // } // // /** // * @return Parser to change string to Integer // */ // static FilterParser<Integer> ofInt() { // return FilterParserInteger.INSTANCE; // } // // /** // * @return Parser to change string to LocalDate // */ // static FilterParser<LocalDate> ofDate() { // return FilterParserDate.INSTANCE; // } // // /** // * @return Parser to change string to LocalTime // */ // static FilterParser<LocalTime> ofTime() { // return FilterParserTime.INSTANCE; // } // // /** // * @return Parser to change string to LocalDateTime // */ // static FilterParser<LocalDateTime> ofDateTime() { // return FilterParserDateTime.INSTANCE; // } // // /** // * A parser that does not parse. An identity string // * // * @return A parser that does not parse value // */ // static FilterParser<String> ofIdentity() { // return FilterParserIdentity.INSTANCE; // } // // /** // * @return Parser to change string to Byte // */ // static FilterParser<Byte> ofByte() { // return FilterParserByte.INSTANCE; // } // // // TODO To see if meaningful to have a "fake" parser that returns a value predefined // // static <T> FilterParser<T> of(final T value) { // // return FilterParse; // // } // // }
import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.filter.parser.FilterParser; import org.jooq.Condition; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.sql.Time; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream;
private static List<FilterValue> createFilterValueTrueConditionByKeys(final String... keys) { if (keys.length < 1) throw new IllegalArgumentException("Cannot have keys length < 1"); return Arrays.stream(keys) .map(key -> Filter.of(key, DSL::trueCondition)) .collect(Collectors.toList()); } @BeforeEach void setUp() { filteringJooqImpl1 = new FilteringJooqImpl1(); } @AfterEach void teardDown() { } @ParameterizedTest @MethodSource("goodMapConditionAndResult") void buildConditions(final Map<String, String> params, final List<FilterValue> filterValues, final Condition expectedCondition) { filteringJooqImpl1.getFilterValues().addAll(filterValues); final Condition condition = filteringJooqImpl1.buildConditions(params); Assertions.assertEquals(expectedCondition, condition); } @ParameterizedTest @MethodSource("incompleteMapOfFilterMultipleKeys") void buildConditionsThrowsByDefaultForMissingKeyMultiple(final Map<String, String> params, final List<FilterValue> filterValues) { filteringJooqImpl1.getFilterValues().addAll(filterValues);
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParser.java // @FunctionalInterface // public interface FilterParser<R> { // // /** // * @param value Value to be parsed // * @return Value parsed and transform to generic value // * @throws RuntimeException When parsing failed if implementation does not swallow exception // */ // @NotNull // R parse(final String value); // // /** // * @param value Value to be parsed // * @param parser Custom parser function // * @return Value parsed and transform to generic value // * @throws FilteringApiException If an error occurred at parsing // * @deprecated No sure it is useful, if need to define a new parser then better to create the class and etc // */ // default R parseWithApiException(final String value, final Function<String, R> parser) throws FilteringApiException { // try { // return parser.apply(value); // } catch (Exception e) { // throw new FilteringApiException("Could not parse value (" + value + ") to " + this.getClass().getSimpleName()); // } // } // // /** // * @param value Value to be parsed // * @return Value parsed and transform to generic value // * @throws FilteringApiException If an error occurred at parsing // */ // default R parseWithApiException(final String value) throws FilteringApiException { // try { // return parse(value); // } catch (Exception e) { // throw new FilteringApiException("Could not parse value (" + value + ") to " + this.getClass().getSimpleName()); // } // } // // /** // * @param value Value to be parsed // * @param defaultValue Default value returned if parse throws an exception // * @return Value parsed and transform to generic value // */ // default R parseOrDefault(final String value, final R defaultValue) { // try { // return parse(value); // } catch (Exception e) { // return defaultValue; // } // } // // /** // * @param value Value to be parsed // * @param defaultValue Default value returned if parse throws an exception // * @return Value parsed and transform to generic value // */ // default R parseOrDefault(final String value, final Supplier<R> defaultValue) { // try { // return parse(value); // } catch (Exception e) { // return defaultValue.get(); // } // } // // /** // * @return Parser to change string to Integer // */ // static FilterParser<Integer> ofInt() { // return FilterParserInteger.INSTANCE; // } // // /** // * @return Parser to change string to LocalDate // */ // static FilterParser<LocalDate> ofDate() { // return FilterParserDate.INSTANCE; // } // // /** // * @return Parser to change string to LocalTime // */ // static FilterParser<LocalTime> ofTime() { // return FilterParserTime.INSTANCE; // } // // /** // * @return Parser to change string to LocalDateTime // */ // static FilterParser<LocalDateTime> ofDateTime() { // return FilterParserDateTime.INSTANCE; // } // // /** // * A parser that does not parse. An identity string // * // * @return A parser that does not parse value // */ // static FilterParser<String> ofIdentity() { // return FilterParserIdentity.INSTANCE; // } // // /** // * @return Parser to change string to Byte // */ // static FilterParser<Byte> ofByte() { // return FilterParserByte.INSTANCE; // } // // // TODO To see if meaningful to have a "fake" parser that returns a value predefined // // static <T> FilterParser<T> of(final T value) { // // return FilterParse; // // } // // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/FilteringJooqTest.java import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.filter.parser.FilterParser; import org.jooq.Condition; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.sql.Time; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; private static List<FilterValue> createFilterValueTrueConditionByKeys(final String... keys) { if (keys.length < 1) throw new IllegalArgumentException("Cannot have keys length < 1"); return Arrays.stream(keys) .map(key -> Filter.of(key, DSL::trueCondition)) .collect(Collectors.toList()); } @BeforeEach void setUp() { filteringJooqImpl1 = new FilteringJooqImpl1(); } @AfterEach void teardDown() { } @ParameterizedTest @MethodSource("goodMapConditionAndResult") void buildConditions(final Map<String, String> params, final List<FilterValue> filterValues, final Condition expectedCondition) { filteringJooqImpl1.getFilterValues().addAll(filterValues); final Condition condition = filteringJooqImpl1.buildConditions(params); Assertions.assertEquals(expectedCondition, condition); } @ParameterizedTest @MethodSource("incompleteMapOfFilterMultipleKeys") void buildConditionsThrowsByDefaultForMissingKeyMultiple(final Map<String, String> params, final List<FilterValue> filterValues) { filteringJooqImpl1.getFilterValues().addAll(filterValues);
Assertions.assertThrows(FilteringApiException.class, () -> filteringJooqImpl1.buildConditions(params));
Blackdread/filter-sort-jooq-api
src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParser.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.function.Function; import java.util.function.Supplier;
package org.blackdread.filtersortjooqapi.filter.parser; /** * Created by Yoann CAPLAIN on 2017/8/28. */ @FunctionalInterface public interface FilterParser<R> { /** * @param value Value to be parsed * @return Value parsed and transform to generic value * @throws RuntimeException When parsing failed if implementation does not swallow exception */ @NotNull R parse(final String value); /** * @param value Value to be parsed * @param parser Custom parser function * @return Value parsed and transform to generic value * @throws FilteringApiException If an error occurred at parsing * @deprecated No sure it is useful, if need to define a new parser then better to create the class and etc */
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParser.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.function.Function; import java.util.function.Supplier; package org.blackdread.filtersortjooqapi.filter.parser; /** * Created by Yoann CAPLAIN on 2017/8/28. */ @FunctionalInterface public interface FilterParser<R> { /** * @param value Value to be parsed * @return Value parsed and transform to generic value * @throws RuntimeException When parsing failed if implementation does not swallow exception */ @NotNull R parse(final String value); /** * @param value Value to be parsed * @param parser Custom parser function * @return Value parsed and transform to generic value * @throws FilteringApiException If an error occurred at parsing * @deprecated No sure it is useful, if need to define a new parser then better to create the class and etc */
default R parseWithApiException(final String value, final Function<String, R> parser) throws FilteringApiException {
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserLocalTimeTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalTime; import java.time.format.DateTimeParseException;
private static final String correctFormatTime1 = "14:46"; private static final String correctFormatTime2 = "10:30:45"; private static final String correctFormatTime3 = "10:30:45.000001233"; @Test void parse() { Assertions.assertEquals(time1, FilterParser.ofTime().parse(correctFormatTime1)); Assertions.assertEquals(time2, FilterParser.ofTime().parse(correctFormatTime2)); Assertions.assertEquals(time3, FilterParser.ofTime().parse(correctFormatTime3)); } @Test void parseThrows() { Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("12 43")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("12:23 45")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("Odwdw0")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("O")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("87")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(time1, FilterParser.ofTime().parseWithApiException(correctFormatTime1)); Assertions.assertEquals(time2, FilterParser.ofTime().parseWithApiException(correctFormatTime2)); Assertions.assertEquals(time3, FilterParser.ofTime().parseWithApiException(correctFormatTime3)); } @Test void parseWithApiExceptionThrows() {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserLocalTimeTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalTime; import java.time.format.DateTimeParseException; private static final String correctFormatTime1 = "14:46"; private static final String correctFormatTime2 = "10:30:45"; private static final String correctFormatTime3 = "10:30:45.000001233"; @Test void parse() { Assertions.assertEquals(time1, FilterParser.ofTime().parse(correctFormatTime1)); Assertions.assertEquals(time2, FilterParser.ofTime().parse(correctFormatTime2)); Assertions.assertEquals(time3, FilterParser.ofTime().parse(correctFormatTime3)); } @Test void parseThrows() { Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("12 43")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("12:23 45")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("Odwdw0")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("O")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse("87")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofTime().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(time1, FilterParser.ofTime().parseWithApiException(correctFormatTime1)); Assertions.assertEquals(time2, FilterParser.ofTime().parseWithApiException(correctFormatTime2)); Assertions.assertEquals(time3, FilterParser.ofTime().parseWithApiException(correctFormatTime3)); } @Test void parseWithApiExceptionThrows() {
Assertions.assertThrows(FilteringApiException.class, () -> FilterParser.ofTime().parseWithApiException("12 43"));
Blackdread/filter-sort-jooq-api
src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParser.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List;
package org.blackdread.filtersortjooqapi.filter.parser; /** * Created by Yoann CAPLAIN on 2017/8/28. */ @FunctionalInterface public interface FilterMultipleValueParser<R> { /** * @param value Contains at least one value, many are split with a token * @param token Token to split value (Has to have the form of a <b>java regex</b>) * @return List of parsed values * @throws RuntimeException When parsing failed if implementation does not swallow exception */ List<R> parse(final String value, final String token); /** * Parse many elements with default token of ',' * * @param value Value to parse * @return List of values parsed in value parameter * @throws RuntimeException When parsing failed if implementation does not swallow exception */ default List<R> parse(final String value) { return parse(value, ","); } /** * Parse many elements with default token of ',' * * @param value Value to parse * @param expectedElements Number of expected elements that list will contain * @return List of values parsed in value parameter * @throws FilteringApiException If expected size is different from returned list size */ default List<R> parse(final String value, final int expectedElements) { final List<R> parse = parse(value, ","); if (parse.size() != expectedElements)
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParser.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; package org.blackdread.filtersortjooqapi.filter.parser; /** * Created by Yoann CAPLAIN on 2017/8/28. */ @FunctionalInterface public interface FilterMultipleValueParser<R> { /** * @param value Contains at least one value, many are split with a token * @param token Token to split value (Has to have the form of a <b>java regex</b>) * @return List of parsed values * @throws RuntimeException When parsing failed if implementation does not swallow exception */ List<R> parse(final String value, final String token); /** * Parse many elements with default token of ',' * * @param value Value to parse * @return List of values parsed in value parameter * @throws RuntimeException When parsing failed if implementation does not swallow exception */ default List<R> parse(final String value) { return parse(value, ","); } /** * Parse many elements with default token of ',' * * @param value Value to parse * @param expectedElements Number of expected elements that list will contain * @return List of values parsed in value parameter * @throws FilteringApiException If expected size is different from returned list size */ default List<R> parse(final String value, final int expectedElements) { final List<R> parse = parse(value, ","); if (parse.size() != expectedElements)
throw new FilteringApiException("Expected " + expectedElements + " selection only.");
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserDateTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserDateTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "2017-04-04 ", "2017-04-04T12:12:12", "2017-04-04T12:OO:O0", "2017", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("2017-04-04", Collections.singletonList(LocalDate.of(2017, 4, 4))), Arguments.of("2017-04-04,2017-05-04,2017-12-25", Arrays.asList( LocalDate.of(2017, 4, 4), LocalDate.of(2017, 5, 4), LocalDate.of(2017, 12, 25) )) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<LocalDate> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofDate().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofDate().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofDate().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserDateTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserDateTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "2017-04-04 ", "2017-04-04T12:12:12", "2017-04-04T12:OO:O0", "2017", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("2017-04-04", Collections.singletonList(LocalDate.of(2017, 4, 4))), Arguments.of("2017-04-04,2017-05-04,2017-12-25", Arrays.asList( LocalDate.of(2017, 4, 4), LocalDate.of(2017, 5, 4), LocalDate.of(2017, 12, 25) )) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<LocalDate> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofDate().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofDate().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofDate().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterMultipleValueParser.ofDate().parse(argument));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserIdentityTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserIdentityTest { static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("5", Collections.singletonList("5")), Arguments.of("5,999,-55,)(*&^%$,djoaihdouawd,][][poouia sdasd a ad", Arrays.asList("5,999,-55,)(*&^%$,djoaihdouawd,][][poouia sdasd a ad".split(","))) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<String> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofIdentity().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument, ",")); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parseWithExpectedElements(final String argument, final List<String> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument, expected.size())); Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument, ",", expected.size())); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parseWithExpectedElementsThrows2(final String argument, final List<String> expected) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserIdentityTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserIdentityTest { static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("5", Collections.singletonList("5")), Arguments.of("5,999,-55,)(*&^%$,djoaihdouawd,][][poouia sdasd a ad", Arrays.asList("5,999,-55,)(*&^%$,djoaihdouawd,][][poouia sdasd a ad".split(","))) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<String> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofIdentity().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument, ",")); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parseWithExpectedElements(final String argument, final List<String> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument, expected.size())); Assertions.assertEquals(expected, FilterMultipleValueParser.ofIdentity().parse(argument, ",", expected.size())); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parseWithExpectedElementsThrows2(final String argument, final List<String> expected) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterMultipleValueParser.ofIdentity().parse(argument, 929292));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/sort/SortingJooqTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.jooq.SortField; import org.jooq.SortOrder; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Sort; import java.sql.Timestamp; import java.util.Collection;
package org.blackdread.filtersortjooqapi.sort; /** * Created by Yoann CAPLAIN on 2017/10/23. */ class SortingJooqTest { private SortingJooqImpl1 sortingJooqImpl1; @BeforeEach void setUp() { sortingJooqImpl1 = new SortingJooqImpl1(); } @AfterEach void teardDown() { } @Test void emptySortingIsEmpty() { Assertions.assertEquals(true, sortingJooqImpl1.emptySorting().isEmpty()); } @Test void emptySortingIsNotModifiable() { Assertions.assertThrows(UnsupportedOperationException.class, () -> sortingJooqImpl1.emptySorting().add(DSL.field("any", Integer.class).asc())); } @Test void buildOrderByWithEmptySort() { final Collection<SortField<?>> sortFields = sortingJooqImpl1.buildOrderBy(Sort.unsorted()); Assertions.assertNotNull(sortFields); Assertions.assertTrue(sortFields.isEmpty()); } @Test void buildOrderByThrowsWhenNotFoundSortKey() {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/sort/SortingJooqTest.java import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.jooq.SortField; import org.jooq.SortOrder; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Sort; import java.sql.Timestamp; import java.util.Collection; package org.blackdread.filtersortjooqapi.sort; /** * Created by Yoann CAPLAIN on 2017/10/23. */ class SortingJooqTest { private SortingJooqImpl1 sortingJooqImpl1; @BeforeEach void setUp() { sortingJooqImpl1 = new SortingJooqImpl1(); } @AfterEach void teardDown() { } @Test void emptySortingIsEmpty() { Assertions.assertEquals(true, sortingJooqImpl1.emptySorting().isEmpty()); } @Test void emptySortingIsNotModifiable() { Assertions.assertThrows(UnsupportedOperationException.class, () -> sortingJooqImpl1.emptySorting().add(DSL.field("any", Integer.class).asc())); } @Test void buildOrderByWithEmptySort() { final Collection<SortField<?>> sortFields = sortingJooqImpl1.buildOrderBy(Sort.unsorted()); Assertions.assertNotNull(sortFields); Assertions.assertTrue(sortFields.isEmpty()); } @Test void buildOrderByThrowsWhenNotFoundSortKey() {
Assertions.assertThrows(SortingApiException.class, () -> sortingJooqImpl1.buildOrderBy(Sort.by(Sort.Order.asc("id"), Sort.Order.desc("asdas"), Sort.Order.asc("dwadw"))));
Blackdread/filter-sort-jooq-api
src/main/java/org/blackdread/filtersortjooqapi/sort/SortingJooq.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.jooq.SortField; import org.jooq.SortOrder; import org.springframework.data.domain.Sort; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map;
package org.blackdread.filtersortjooqapi.sort; /** * <p>Interface to be implemented by repository that wants to provide sorting</p> * <p>It allows to be consistent through the app for sorting</p> * <p>Interface defines default methods to limit copy/paste code while still providing a way to override * default behavior. Using an abstract class would allow to hide internal methods but wait * for Java 9 private methods :)</p> * Created by Yoann CAPLAIN on 2017/8/25. */ public interface SortingJooq { /** * Empty immutable list for sorting * * @return an empty immutable sort list */ @NotNull default Collection<SortField<?>> emptySorting() { return Collections.emptyList(); } /** * TODO Change to List for return value * * @param sortSpecification Sort from Spring Data * @return Collection of fields to sort (can be empty if {@code sortSpecification} is null or no sort values) * @throws SortingApiException if any sort field given cannot be found (it should result in a 400 error message) or sort contains duplicate keys */ @NotNull default Collection<SortField<?>> buildOrderBy(@Nullable final Sort sortSpecification) { Collection<SortField<?>> querySortFields = new ArrayList<>(10); if (sortSpecification == null) { return getDefaultSorting(); } List<String> usedSortKey = new ArrayList<>(10); for (final Sort.Order specifiedField : sortSpecification) { String sortFieldName = specifiedField.getProperty(); Sort.Direction sortDirection = specifiedField.getDirection(); if (usedSortKey.contains(sortFieldName))
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // } // Path: src/main/java/org/blackdread/filtersortjooqapi/sort/SortingJooq.java import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.jooq.SortField; import org.jooq.SortOrder; import org.springframework.data.domain.Sort; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; package org.blackdread.filtersortjooqapi.sort; /** * <p>Interface to be implemented by repository that wants to provide sorting</p> * <p>It allows to be consistent through the app for sorting</p> * <p>Interface defines default methods to limit copy/paste code while still providing a way to override * default behavior. Using an abstract class would allow to hide internal methods but wait * for Java 9 private methods :)</p> * Created by Yoann CAPLAIN on 2017/8/25. */ public interface SortingJooq { /** * Empty immutable list for sorting * * @return an empty immutable sort list */ @NotNull default Collection<SortField<?>> emptySorting() { return Collections.emptyList(); } /** * TODO Change to List for return value * * @param sortSpecification Sort from Spring Data * @return Collection of fields to sort (can be empty if {@code sortSpecification} is null or no sort values) * @throws SortingApiException if any sort field given cannot be found (it should result in a 400 error message) or sort contains duplicate keys */ @NotNull default Collection<SortField<?>> buildOrderBy(@Nullable final Sort sortSpecification) { Collection<SortField<?>> querySortFields = new ArrayList<>(10); if (sortSpecification == null) { return getDefaultSorting(); } List<String> usedSortKey = new ArrayList<>(10); for (final Sort.Order specifiedField : sortSpecification) { String sortFieldName = specifiedField.getProperty(); Sort.Direction sortDirection = specifiedField.getDirection(); if (usedSortKey.contains(sortFieldName))
throw new SortingApiException("Cannot sort on duplicate keys");
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserDateTimeTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserDateTimeTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "2017-04-04", "2017-04-04 12:12:12", "2017-04-04T12:OO:O0", "2017", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("2017-04-04T12:12:12", Collections.singletonList(LocalDateTime.of(2017, 4, 4, 12, 12, 12))), Arguments.of("2017-04-04T12:12:12,2017-05-04T12:17:12,2017-12-25T12:15", Arrays.asList( LocalDateTime.of(2017, 4, 4, 12, 12, 12), LocalDateTime.of(2017, 5, 4, 12, 17, 12), LocalDateTime.of(2017, 12, 25, 12, 15) )) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<LocalDateTime> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofDateTime().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofDateTime().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofDateTime().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserDateTimeTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserDateTimeTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "2017-04-04", "2017-04-04 12:12:12", "2017-04-04T12:OO:O0", "2017", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("2017-04-04T12:12:12", Collections.singletonList(LocalDateTime.of(2017, 4, 4, 12, 12, 12))), Arguments.of("2017-04-04T12:12:12,2017-05-04T12:17:12,2017-12-25T12:15", Arrays.asList( LocalDateTime.of(2017, 4, 4, 12, 12, 12), LocalDateTime.of(2017, 5, 4, 12, 17, 12), LocalDateTime.of(2017, 12, 25, 12, 15) )) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<LocalDateTime> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofDateTime().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofDateTime().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofDateTime().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterMultipleValueParser.ofDateTime().parse(argument));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserIntTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterParserIntTest { static Stream<String> badStringValuesToParse() { return Stream.of("foo", "poiuytd", "Odwdw0", "O", " 5", " 6", "--4"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of(Arguments.of("5", 5), Arguments.of("-5", -5), Arguments.of("0", 0), Arguments.of("006", 6), Arguments.of("3132324", 3132324)); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final int expected) { Assertions.assertEquals(expected, (int) FilterParser.ofInt().parse(argument)); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) { Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofInt().parse(argument)); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parseWithApiException(final String argument, final int expected) { Assertions.assertEquals(expected, (int) FilterParser.ofInt().parseWithApiException(argument)); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseWithApiExceptionThrows(final String argument) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserIntTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterParserIntTest { static Stream<String> badStringValuesToParse() { return Stream.of("foo", "poiuytd", "Odwdw0", "O", " 5", " 6", "--4"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of(Arguments.of("5", 5), Arguments.of("-5", -5), Arguments.of("0", 0), Arguments.of("006", 6), Arguments.of("3132324", 3132324)); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final int expected) { Assertions.assertEquals(expected, (int) FilterParser.ofInt().parse(argument)); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) { Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofInt().parse(argument)); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parseWithApiException(final String argument, final int expected) { Assertions.assertEquals(expected, (int) FilterParser.ofInt().parseWithApiException(argument)); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseWithApiExceptionThrows(final String argument) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterParser.ofInt().parseWithApiException(argument));
Blackdread/filter-sort-jooq-api
src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserAbstract.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
package org.blackdread.filtersortjooqapi.filter.parser; /** * Created by Yoann CAPLAIN on 2017/8/29. */ abstract class FilterMultipleValueParserAbstract<R> implements FilterMultipleValueParser<R> { FilterMultipleValueParserAbstract() { } @Override public List<R> parse(final String value, final String token) { final List<R> parsedValues = Arrays.stream(value.split(token)) // .map(this::prepareValueForParsing) .map(getParser()::parseWithApiException) .collect(Collectors.toList()); // This is a must have as we filter on values so minimum one has to be given/found if (parsedValues.isEmpty())
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserAbstract.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; package org.blackdread.filtersortjooqapi.filter.parser; /** * Created by Yoann CAPLAIN on 2017/8/29. */ abstract class FilterMultipleValueParserAbstract<R> implements FilterMultipleValueParser<R> { FilterMultipleValueParserAbstract() { } @Override public List<R> parse(final String value, final String token) { final List<R> parsedValues = Arrays.stream(value.split(token)) // .map(this::prepareValueForParsing) .map(getParser()::parseWithApiException) .collect(Collectors.toList()); // This is a must have as we filter on values so minimum one has to be given/found if (parsedValues.isEmpty())
throw new FilteringApiException("Parser of value (" + value + ") resulted in no value. Should result in at least one");
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserByteTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterParserByteTest { @Test void parse() { Assertions.assertEquals(10, (byte) FilterParser.ofByte().parse("10")); Assertions.assertEquals(0x0F, (byte) FilterParser.ofByte().parse("15")); Assertions.assertEquals(127, (byte) FilterParser.ofByte().parse("127")); Assertions.assertEquals(0, (byte) FilterParser.ofByte().parse("0")); Assertions.assertEquals(1, (byte) FilterParser.ofByte().parse("1")); } @Test void parseThrows() { Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("0xFF")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("0xF")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("AFA")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("Odwdw0")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("OxFFFF")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(5, (byte) FilterParser.ofByte().parseWithApiException("5")); Assertions.assertEquals(-5, (byte) FilterParser.ofByte().parseWithApiException("-5")); Assertions.assertEquals(0, (byte) FilterParser.ofByte().parseWithApiException("0")); Assertions.assertEquals(66, (byte) FilterParser.ofByte().parseWithApiException("066")); Assertions.assertEquals(1, (byte) FilterParser.ofByte().parseWithApiException("000001")); } @Test void parseWithApiExceptionThrows() {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserByteTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; package org.blackdread.filtersortjooqapi.filter.parser; class FilterParserByteTest { @Test void parse() { Assertions.assertEquals(10, (byte) FilterParser.ofByte().parse("10")); Assertions.assertEquals(0x0F, (byte) FilterParser.ofByte().parse("15")); Assertions.assertEquals(127, (byte) FilterParser.ofByte().parse("127")); Assertions.assertEquals(0, (byte) FilterParser.ofByte().parse("0")); Assertions.assertEquals(1, (byte) FilterParser.ofByte().parse("1")); } @Test void parseThrows() { Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("0xFF")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("0xF")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("AFA")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("Odwdw0")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse("OxFFFF")); Assertions.assertThrows(NumberFormatException.class, () -> FilterParser.ofByte().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(5, (byte) FilterParser.ofByte().parseWithApiException("5")); Assertions.assertEquals(-5, (byte) FilterParser.ofByte().parseWithApiException("-5")); Assertions.assertEquals(0, (byte) FilterParser.ofByte().parseWithApiException("0")); Assertions.assertEquals(66, (byte) FilterParser.ofByte().parseWithApiException("066")); Assertions.assertEquals(1, (byte) FilterParser.ofByte().parseWithApiException("000001")); } @Test void parseWithApiExceptionThrows() {
Assertions.assertThrows(FilteringApiException.class, () -> FilterParser.ofByte().parseWithApiException("AFA"));
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserLocalDateTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.format.DateTimeParseException;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterParserLocalDateTest { private static final LocalDate now = LocalDate.now(); private static final LocalDate date1 = LocalDate.of(2017, 10, 25); private static final LocalDate date2 = LocalDate.of(2010, 12, 01); private static final String correctFormatDate1 = "2017-10-25"; private static final String correctFormatDate2 = "2010-12-01"; @Test void parse() { Assertions.assertEquals(date1, FilterParser.ofDate().parse(correctFormatDate1)); Assertions.assertEquals(date2, FilterParser.ofDate().parse(correctFormatDate2)); } @Test void parseThrows() { Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("2017-04-06 ")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("2017-04")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("2017")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("O")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(date1, FilterParser.ofDate().parseWithApiException(correctFormatDate1)); Assertions.assertEquals(date2, FilterParser.ofDate().parseWithApiException(correctFormatDate2)); } @Test void parseWithApiExceptionThrows() {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterParserLocalDateTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.format.DateTimeParseException; package org.blackdread.filtersortjooqapi.filter.parser; class FilterParserLocalDateTest { private static final LocalDate now = LocalDate.now(); private static final LocalDate date1 = LocalDate.of(2017, 10, 25); private static final LocalDate date2 = LocalDate.of(2010, 12, 01); private static final String correctFormatDate1 = "2017-10-25"; private static final String correctFormatDate2 = "2010-12-01"; @Test void parse() { Assertions.assertEquals(date1, FilterParser.ofDate().parse(correctFormatDate1)); Assertions.assertEquals(date2, FilterParser.ofDate().parse(correctFormatDate2)); } @Test void parseThrows() { Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("2017-04-06 ")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("2017-04")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("2017")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse("O")); Assertions.assertThrows(DateTimeParseException.class, () -> FilterParser.ofDate().parse(" 5 ")); } @Test void parseWithApiException() { Assertions.assertEquals(date1, FilterParser.ofDate().parseWithApiException(correctFormatDate1)); Assertions.assertEquals(date2, FilterParser.ofDate().parseWithApiException(correctFormatDate2)); } @Test void parseWithApiExceptionThrows() {
Assertions.assertThrows(FilteringApiException.class, () -> FilterParser.ofDate().parseWithApiException("2017-04-06 "));
Blackdread/filter-sort-jooq-api
src/main/java/org/blackdread/filtersortjooqapi/filter/FilteringJooq.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.jooq.Condition; import org.jooq.impl.DSL; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function;
package org.blackdread.filtersortjooqapi.filter; /** * <p>Interface to be implemented by repository that wants to provide filtering</p> * <p>It allows to be consistent through the app for filtering</p> * Created by Yoann CAPLAIN on 2017/8/25. */ public interface FilteringJooq { // TODO Idea for Filter chaining AND/OR -> so kind of strategy pattern -> default on is all are AND, if overridden then it follow the one given (done via default method and overrides), we pass the whole context -> all values that matched and are ready to be filtered // See Operator from jOOQ static final List<String> DEFAULT_IGNORED_KEY_FOR_FILTERING = ImmutableList.of("sort", "page", "size"); /** * @param requestParams Keys and values to filter on * @return Fully constructed condition chaining (with nested conditions if implementation has) * @throws FilteringApiException if any filter field given cannot be found (it should result in a 400 error message) */ @NotNull default Condition buildConditions(final Map<String, String> requestParams) { final List<Condition> conditions = new ArrayList<>(requestParams.size()); // final List<String> usedKeys = new ArrayList<>(requestParams.size()); final List<String> usedKeys = new ArrayList<>(getFilterValues().stream() .mapToInt(FilterValue::size) .sum()); for (Map.Entry<String, String> entry : requestParams.entrySet()) { if (getIgnoredKeys().contains(entry.getKey())) continue; if (usedKeys.contains(entry.getKey())) continue; final FilterValue filterValue = getFilter(entry.getKey())
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/FilteringJooq.java import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.jooq.Condition; import org.jooq.impl.DSL; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; package org.blackdread.filtersortjooqapi.filter; /** * <p>Interface to be implemented by repository that wants to provide filtering</p> * <p>It allows to be consistent through the app for filtering</p> * Created by Yoann CAPLAIN on 2017/8/25. */ public interface FilteringJooq { // TODO Idea for Filter chaining AND/OR -> so kind of strategy pattern -> default on is all are AND, if overridden then it follow the one given (done via default method and overrides), we pass the whole context -> all values that matched and are ready to be filtered // See Operator from jOOQ static final List<String> DEFAULT_IGNORED_KEY_FOR_FILTERING = ImmutableList.of("sort", "page", "size"); /** * @param requestParams Keys and values to filter on * @return Fully constructed condition chaining (with nested conditions if implementation has) * @throws FilteringApiException if any filter field given cannot be found (it should result in a 400 error message) */ @NotNull default Condition buildConditions(final Map<String, String> requestParams) { final List<Condition> conditions = new ArrayList<>(requestParams.size()); // final List<String> usedKeys = new ArrayList<>(requestParams.size()); final List<String> usedKeys = new ArrayList<>(getFilterValues().stream() .mapToInt(FilterValue::size) .sum()); for (Map.Entry<String, String> entry : requestParams.entrySet()) { if (getIgnoredKeys().contains(entry.getKey())) continue; if (usedKeys.contains(entry.getKey())) continue; final FilterValue filterValue = getFilter(entry.getKey())
.orElseThrow(() -> new FilteringApiException("No filter found with key (" + entry.getKey() + ")"));
Blackdread/filter-sort-jooq-api
examples/fullOne/ExceptionTranslator.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/BadUsageApiException.java // public class BadUsageApiException extends RuntimeException { // // public BadUsageApiException(String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.BadUsageApiException; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus;
package fullOne; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class);
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/BadUsageApiException.java // public class BadUsageApiException extends RuntimeException { // // public BadUsageApiException(String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // } // Path: examples/fullOne/ExceptionTranslator.java import org.blackdread.filtersortjooqapi.exception.BadUsageApiException; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; package fullOne; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class);
@ExceptionHandler(FilteringApiException.class)
Blackdread/filter-sort-jooq-api
examples/fullOne/ExceptionTranslator.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/BadUsageApiException.java // public class BadUsageApiException extends RuntimeException { // // public BadUsageApiException(String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.BadUsageApiException; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus;
package fullOne; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class); @ExceptionHandler(FilteringApiException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processFilteringApiError(FilteringApiException ex) { // See jHipster for ErrorVM return new ErrorVM(ErrorConstants.ERR_API_FILTERING, ex.getMessage()); }
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/BadUsageApiException.java // public class BadUsageApiException extends RuntimeException { // // public BadUsageApiException(String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // } // Path: examples/fullOne/ExceptionTranslator.java import org.blackdread.filtersortjooqapi.exception.BadUsageApiException; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; package fullOne; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class); @ExceptionHandler(FilteringApiException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processFilteringApiError(FilteringApiException ex) { // See jHipster for ErrorVM return new ErrorVM(ErrorConstants.ERR_API_FILTERING, ex.getMessage()); }
@ExceptionHandler(SortingApiException.class)
Blackdread/filter-sort-jooq-api
examples/fullOne/ExceptionTranslator.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/BadUsageApiException.java // public class BadUsageApiException extends RuntimeException { // // public BadUsageApiException(String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.BadUsageApiException; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus;
package fullOne; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class); @ExceptionHandler(FilteringApiException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processFilteringApiError(FilteringApiException ex) { // See jHipster for ErrorVM return new ErrorVM(ErrorConstants.ERR_API_FILTERING, ex.getMessage()); } @ExceptionHandler(SortingApiException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processSortingApiError(SortingApiException ex) { // See jHipster for ErrorVM return new ErrorVM(ErrorConstants.ERR_API_SORTING, ex.getMessage()); }
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/BadUsageApiException.java // public class BadUsageApiException extends RuntimeException { // // public BadUsageApiException(String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // // Path: src/main/java/org/blackdread/filtersortjooqapi/exception/SortingApiException.java // public class SortingApiException extends BadUsageApiException { // // public SortingApiException(final String message) { // super(message); // } // } // Path: examples/fullOne/ExceptionTranslator.java import org.blackdread.filtersortjooqapi.exception.BadUsageApiException; import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.blackdread.filtersortjooqapi.exception.SortingApiException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; package fullOne; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class); @ExceptionHandler(FilteringApiException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processFilteringApiError(FilteringApiException ex) { // See jHipster for ErrorVM return new ErrorVM(ErrorConstants.ERR_API_FILTERING, ex.getMessage()); } @ExceptionHandler(SortingApiException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processSortingApiError(SortingApiException ex) { // See jHipster for ErrorVM return new ErrorVM(ErrorConstants.ERR_API_SORTING, ex.getMessage()); }
@ExceptionHandler(BadUsageApiException.class)
Blackdread/filter-sort-jooq-api
src/main/java/org/blackdread/filtersortjooqapi/filter/FilterValue.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/filter/keyparser/KeyParser.java // public interface KeyParser { // // /** // * Get the number of keys to be filtered (there are as many parsers) // * // * @return Number of keys to be filtered // */ // int size(); // // /** // * @return Keys list // */ // List<String> keys(); // // /** // * @return Keys as array // */ // String[] getKeys(); // // /** // * @return Parsers that take a {@link String} and return an {@link Object} // */ // Function<String, ?>[] getParsers(); // }
import org.blackdread.filtersortjooqapi.filter.keyparser.KeyParser; import org.jooq.Condition; import javax.validation.constraints.NotNull; import java.util.List;
package org.blackdread.filtersortjooqapi.filter; /** * Created by Yoann CAPLAIN on 2017/9/7. */ public interface FilterValue { /** * Get the number of keys/values to be filtered (there are as many parsers) * * @return Number of keys/values to be filtered */ int size(); /** * @return {@link KeyParser} that will be used to get keys and parse values from keys */ @NotNull
// Path: src/main/java/org/blackdread/filtersortjooqapi/filter/keyparser/KeyParser.java // public interface KeyParser { // // /** // * Get the number of keys to be filtered (there are as many parsers) // * // * @return Number of keys to be filtered // */ // int size(); // // /** // * @return Keys list // */ // List<String> keys(); // // /** // * @return Keys as array // */ // String[] getKeys(); // // /** // * @return Parsers that take a {@link String} and return an {@link Object} // */ // Function<String, ?>[] getParsers(); // } // Path: src/main/java/org/blackdread/filtersortjooqapi/filter/FilterValue.java import org.blackdread.filtersortjooqapi.filter.keyparser.KeyParser; import org.jooq.Condition; import javax.validation.constraints.NotNull; import java.util.List; package org.blackdread.filtersortjooqapi.filter; /** * Created by Yoann CAPLAIN on 2017/9/7. */ public interface FilterValue { /** * Get the number of keys/values to be filtered (there are as many parsers) * * @return Number of keys/values to be filtered */ int size(); /** * @return {@link KeyParser} that will be used to get keys and parse values from keys */ @NotNull
KeyParser getKeyParser();
Blackdread/filter-sort-jooq-api
src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserTimeTest.java
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // }
import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream;
package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserTimeTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "2017-04-04", "2017-04-04 12:12:12", "2017-04-04T12:OO:O0", "12:12:12 ", "12:12 ", "12:68:12", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("12:12:12", Collections.singletonList(LocalTime.of(12, 12, 12))), Arguments.of("12:12:12,12:17:12.000000113,12:15", Arrays.asList( LocalTime.of(12, 12, 12), LocalTime.of(12, 17, 12, 113), LocalTime.of(12, 15) )) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<LocalTime> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofTime().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofTime().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofTime().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
// Path: src/main/java/org/blackdread/filtersortjooqapi/exception/FilteringApiException.java // public class FilteringApiException extends BadUsageApiException { // // public FilteringApiException(final String message) { // super(message); // } // } // Path: src/test/java/org/blackdread/filtersortjooqapi/filter/parser/FilterMultipleValueParserTimeTest.java import org.blackdread.filtersortjooqapi.exception.FilteringApiException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; package org.blackdread.filtersortjooqapi.filter.parser; class FilterMultipleValueParserTimeTest { static Stream<String> badStringValuesToParse() { return Stream.of("", "2017-04-04", "2017-04-04 12:12:12", "2017-04-04T12:OO:O0", "12:12:12 ", "12:12 ", "12:68:12", "O", " 5", " 6", "--4", "bla,asdasd,9287,dadas,-5,--3,998"); } static Stream<Arguments> goodStringParsableAndResult() { return Stream.of( Arguments.of("12:12:12", Collections.singletonList(LocalTime.of(12, 12, 12))), Arguments.of("12:12:12,12:17:12.000000113,12:15", Arrays.asList( LocalTime.of(12, 12, 12), LocalTime.of(12, 17, 12, 113), LocalTime.of(12, 15) )) ); } @ParameterizedTest @MethodSource("goodStringParsableAndResult") void parse(final String argument, final List<LocalTime> expected) { Assertions.assertEquals(expected, FilterMultipleValueParser.ofTime().parse(argument)); Assertions.assertEquals(expected.size(), FilterMultipleValueParser.ofTime().parse(argument).size()); Assertions.assertEquals(expected, FilterMultipleValueParser.ofTime().parse(argument, ",")); } @ParameterizedTest @MethodSource("badStringValuesToParse") void parseThrows(final String argument) {
Assertions.assertThrows(FilteringApiException.class, () -> FilterMultipleValueParser.ofTime().parse(argument));
abuchanan920/historybook
src/main/java/com/difference/historybook/server/ManagedProxy.java
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // }
import java.util.function.Predicate; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.dropwizard.lifecycle.Managed;
/* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.server; /** * Wrapper to make @Proxy implement @Managed * * Would not need this if Java had something like duck-typing, but such is life. * Did not want Proxy to be dependent on the particular web service framework used. */ public class ManagedProxy implements Proxy, Managed { private final Proxy proxy; public ManagedProxy(Proxy proxy) { this.proxy = proxy; } @Override public void start() throws Exception { proxy.start(); } @Override public void stop() throws Exception { proxy.stop(); } @Override public Proxy setPort(int port) { return proxy.setPort(port); } @Override
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/difference/historybook/server/ManagedProxy.java import java.util.function.Predicate; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.dropwizard.lifecycle.Managed; /* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.server; /** * Wrapper to make @Proxy implement @Managed * * Would not need this if Java had something like duck-typing, but such is life. * Did not want Proxy to be dependent on the particular web service framework used. */ public class ManagedProxy implements Proxy, Managed { private final Proxy proxy; public ManagedProxy(Proxy proxy) { this.proxy = proxy; } @Override public void start() throws Exception { proxy.start(); } @Override public void stop() throws Exception { proxy.stop(); } @Override public Proxy setPort(int port) { return proxy.setPort(port); } @Override
public Proxy setFilterFactory(ProxyFilterFactory factory) {
abuchanan920/historybook
src/main/java/com/difference/historybook/server/ManagedProxy.java
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // }
import java.util.function.Predicate; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.dropwizard.lifecycle.Managed;
/* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.server; /** * Wrapper to make @Proxy implement @Managed * * Would not need this if Java had something like duck-typing, but such is life. * Did not want Proxy to be dependent on the particular web service framework used. */ public class ManagedProxy implements Proxy, Managed { private final Proxy proxy; public ManagedProxy(Proxy proxy) { this.proxy = proxy; } @Override public void start() throws Exception { proxy.start(); } @Override public void stop() throws Exception { proxy.stop(); } @Override public Proxy setPort(int port) { return proxy.setPort(port); } @Override public Proxy setFilterFactory(ProxyFilterFactory factory) { proxy.setFilterFactory(factory); return this; } @Override
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/difference/historybook/server/ManagedProxy.java import java.util.function.Predicate; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.dropwizard.lifecycle.Managed; /* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.server; /** * Wrapper to make @Proxy implement @Managed * * Would not need this if Java had something like duck-typing, but such is life. * Did not want Proxy to be dependent on the particular web service framework used. */ public class ManagedProxy implements Proxy, Managed { private final Proxy proxy; public ManagedProxy(Proxy proxy) { this.proxy = proxy; } @Override public void start() throws Exception { proxy.start(); } @Override public void stop() throws Exception { proxy.stop(); } @Override public Proxy setPort(int port) { return proxy.setPort(port); } @Override public Proxy setFilterFactory(ProxyFilterFactory factory) { proxy.setFilterFactory(factory); return this; } @Override
public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector) {
abuchanan920/historybook
src/main/java/com/difference/historybook/proxy/littleproxy/LittleProxy.java
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // }
import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.LastHttpContent;
/* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.proxy.littleproxy; /** * An implementation of @Proxy using LittleProxy which is based on a Netty core */ public class LittleProxy implements Proxy { private static final Logger LOG = LoggerFactory.getLogger(LittleProxy.class);
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/difference/historybook/proxy/littleproxy/LittleProxy.java import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.LastHttpContent; /* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.proxy.littleproxy; /** * An implementation of @Proxy using LittleProxy which is based on a Netty core */ public class LittleProxy implements Proxy { private static final Logger LOG = LoggerFactory.getLogger(LittleProxy.class);
private ProxyFilterFactory filterFactory;
abuchanan920/historybook
src/main/java/com/difference/historybook/proxy/littleproxy/LittleProxy.java
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // }
import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.LastHttpContent;
/* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.proxy.littleproxy; /** * An implementation of @Proxy using LittleProxy which is based on a Netty core */ public class LittleProxy implements Proxy { private static final Logger LOG = LoggerFactory.getLogger(LittleProxy.class); private ProxyFilterFactory filterFactory;
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/difference/historybook/proxy/littleproxy/LittleProxy.java import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.LastHttpContent; /* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.proxy.littleproxy; /** * An implementation of @Proxy using LittleProxy which is based on a Netty core */ public class LittleProxy implements Proxy { private static final Logger LOG = LoggerFactory.getLogger(LittleProxy.class); private ProxyFilterFactory filterFactory;
private Predicate<ProxyTransactionInfo> selector;
abuchanan920/historybook
src/main/java/com/difference/historybook/proxy/littleproxy/LittleProxy.java
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // }
import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.LastHttpContent;
public LittleProxy setMaxBufferSize(int size) { this.maxBufferSize = size; return this; } @Override public void start() { if (proxy == null) { proxy = DefaultHttpProxyServer.bootstrap() .withPort(port) .withFiltersSource(getFiltersSource()) .start(); } } @Override public void stop() { if (proxy != null) { LOG.info("Stopping proxy"); proxy.stop(); proxy = null; } } private HttpFiltersSource getFiltersSource() { return new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new HttpFiltersAdapter(originalRequest) {
// Path: src/main/java/com/difference/historybook/proxy/Proxy.java // public interface Proxy { // // /** // * Start the web proxy service // * // * @throws Exception // */ // public void start() throws Exception; // // /** // * Stop the web proxy service // * // * @throws Exception // */ // public void stop() throws Exception; // // /** // * Specify the port to run the proxy server on. May not take affect until next start. // * @param port port to run the proxy server on // * @return this for method chaining // */ // public Proxy setPort(int port); // // /** // * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response // * @return this for method call chaining // */ // public Proxy setFilterFactory(ProxyFilterFactory factory); // // /** // * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. // * This is done early in the streaming of a response by peeking at the headers to determine // * whether the content will need to be buffered and decompressed for use. // * // * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. // * @return this for method call chaining // */ // public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/difference/historybook/proxy/littleproxy/LittleProxy.java import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.difference.historybook.proxy.Proxy; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; import com.difference.historybook.proxy.ProxyTransactionInfo; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.LastHttpContent; public LittleProxy setMaxBufferSize(int size) { this.maxBufferSize = size; return this; } @Override public void start() { if (proxy == null) { proxy = DefaultHttpProxyServer.bootstrap() .withPort(port) .withFiltersSource(getFiltersSource()) .start(); } } @Override public void stop() { if (proxy != null) { LOG.info("Stopping proxy"); proxy.stop(); proxy = null; } } private HttpFiltersSource getFiltersSource() { return new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new HttpFiltersAdapter(originalRequest) {
private final ProxyFilter filter = filterFactory != null ? filterFactory.getInstance() : null;
abuchanan920/historybook
src/main/java/com/difference/historybook/proxyfilter/IndexingProxyFilterFactory.java
// Path: src/main/java/com/difference/historybook/index/Index.java // public interface Index extends AutoCloseable { // /** // * Adds a given page to an index collection // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param url the url of the page being indexed // * @param timestamp the timestamp representing when the page was retrieved // * @param body the textual content of the page (binaries are unsupported) // * @throws IndexException // */ // public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException; // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // default public SearchResultWrapper search(String collection, String query, int offset, int size) throws IndexException { // return search(collection, query, offset, size, false); // } // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @param includeDebug include implementation dependent debug information for search result // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // public SearchResultWrapper search(String collection, String query, int offset, int size, boolean includeDebug) throws IndexException; // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // }
import com.difference.historybook.index.Index; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory;
/* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.proxyfilter; /** * Implementation of @ProxyFilterFactory that returns IndexingProxyFilters */ public class IndexingProxyFilterFactory implements ProxyFilterFactory { private final Index index; private final String defaultCollection; /** * Constructor for IndexingProxyFilterFactory * * @param index the @Index to submit the indexing request to * @param defaultCollection The collection namespace to use for indexing requests */ public IndexingProxyFilterFactory(Index index, String defaultCollection) { this.index = index; this.defaultCollection = defaultCollection; } @Override
// Path: src/main/java/com/difference/historybook/index/Index.java // public interface Index extends AutoCloseable { // /** // * Adds a given page to an index collection // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param url the url of the page being indexed // * @param timestamp the timestamp representing when the page was retrieved // * @param body the textual content of the page (binaries are unsupported) // * @throws IndexException // */ // public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException; // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // default public SearchResultWrapper search(String collection, String query, int offset, int size) throws IndexException { // return search(collection, query, offset, size, false); // } // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @param includeDebug include implementation dependent debug information for search result // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // public SearchResultWrapper search(String collection, String query, int offset, int size, boolean includeDebug) throws IndexException; // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // // Path: src/main/java/com/difference/historybook/proxy/ProxyFilterFactory.java // public interface ProxyFilterFactory { // /** // * Return a new @ProxyFilter for use with a new request/response pair. // * @return @ProxyFilter Note that this should be a new object with each call unless the given proxy filter is stateless. // */ // public ProxyFilter getInstance(); // } // Path: src/main/java/com/difference/historybook/proxyfilter/IndexingProxyFilterFactory.java import com.difference.historybook.index.Index; import com.difference.historybook.proxy.ProxyFilter; import com.difference.historybook.proxy.ProxyFilterFactory; /* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.proxyfilter; /** * Implementation of @ProxyFilterFactory that returns IndexingProxyFilters */ public class IndexingProxyFilterFactory implements ProxyFilterFactory { private final Index index; private final String defaultCollection; /** * Constructor for IndexingProxyFilterFactory * * @param index the @Index to submit the indexing request to * @param defaultCollection The collection namespace to use for indexing requests */ public IndexingProxyFilterFactory(Index index, String defaultCollection) { this.index = index; this.defaultCollection = defaultCollection; } @Override
public ProxyFilter getInstance() {
abuchanan920/historybook
src/main/java/com/difference/historybook/resources/CollectionResource.java
// Path: src/main/java/com/difference/historybook/index/Index.java // public interface Index extends AutoCloseable { // /** // * Adds a given page to an index collection // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param url the url of the page being indexed // * @param timestamp the timestamp representing when the page was retrieved // * @param body the textual content of the page (binaries are unsupported) // * @throws IndexException // */ // public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException; // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // default public SearchResultWrapper search(String collection, String query, int offset, int size) throws IndexException { // return search(collection, query, offset, size, false); // } // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @param includeDebug include implementation dependent debug information for search result // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // public SearchResultWrapper search(String collection, String query, int offset, int size, boolean includeDebug) throws IndexException; // } // // Path: src/main/java/com/difference/historybook/index/IndexException.java // public class IndexException extends Exception { // private static final long serialVersionUID = -1660541057609982084L; // // public IndexException(String msg) { // super(msg); // } // // public IndexException(Exception e) { // super(e); // } // } // // Path: src/main/java/com/difference/historybook/index/SearchResultWrapper.java // public class SearchResultWrapper { // private String query; // private int offset; // private int maxResultsRequested; // private int resultCount; // private String debugInfo; // private List<SearchResult> results; // // public String getQuery() { // return query; // } // // public SearchResultWrapper setQuery(String query) { // this.query = query; // return this; // } // // public int getOffset() { // return offset; // } // // public SearchResultWrapper setOffset(int offset) { // this.offset = offset; // return this; // } // // public int getMaxResultsRequested() { // return maxResultsRequested; // } // // public SearchResultWrapper setMaxResultsRequested(int maxResultsRequested) { // this.maxResultsRequested = maxResultsRequested; // return this; // } // // public int getResultCount() { // return resultCount; // } // // public SearchResultWrapper setResultCount(int resultCount) { // this.resultCount = resultCount; // return this; // } // // public List<SearchResult> getResults() { // return results; // } // // public SearchResultWrapper setResults(List<SearchResult> results) { // this.results = results; // return this; // } // // public String getDebugInfo() { // return debugInfo; // } // // public SearchResultWrapper setDebugInfo(String debugInfo) { // this.debugInfo = debugInfo; // return this; // } // // }
import com.difference.historybook.index.Index; import com.difference.historybook.index.IndexException; import com.difference.historybook.index.SearchResultWrapper; import java.time.Instant; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.resources; /** * A resource for interacting with an index collection */ @Path("/collections/{collection}") public class CollectionResource { private static final Logger LOG = LoggerFactory.getLogger(CollectionResource.class);
// Path: src/main/java/com/difference/historybook/index/Index.java // public interface Index extends AutoCloseable { // /** // * Adds a given page to an index collection // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param url the url of the page being indexed // * @param timestamp the timestamp representing when the page was retrieved // * @param body the textual content of the page (binaries are unsupported) // * @throws IndexException // */ // public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException; // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // default public SearchResultWrapper search(String collection, String query, int offset, int size) throws IndexException { // return search(collection, query, offset, size, false); // } // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @param includeDebug include implementation dependent debug information for search result // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // public SearchResultWrapper search(String collection, String query, int offset, int size, boolean includeDebug) throws IndexException; // } // // Path: src/main/java/com/difference/historybook/index/IndexException.java // public class IndexException extends Exception { // private static final long serialVersionUID = -1660541057609982084L; // // public IndexException(String msg) { // super(msg); // } // // public IndexException(Exception e) { // super(e); // } // } // // Path: src/main/java/com/difference/historybook/index/SearchResultWrapper.java // public class SearchResultWrapper { // private String query; // private int offset; // private int maxResultsRequested; // private int resultCount; // private String debugInfo; // private List<SearchResult> results; // // public String getQuery() { // return query; // } // // public SearchResultWrapper setQuery(String query) { // this.query = query; // return this; // } // // public int getOffset() { // return offset; // } // // public SearchResultWrapper setOffset(int offset) { // this.offset = offset; // return this; // } // // public int getMaxResultsRequested() { // return maxResultsRequested; // } // // public SearchResultWrapper setMaxResultsRequested(int maxResultsRequested) { // this.maxResultsRequested = maxResultsRequested; // return this; // } // // public int getResultCount() { // return resultCount; // } // // public SearchResultWrapper setResultCount(int resultCount) { // this.resultCount = resultCount; // return this; // } // // public List<SearchResult> getResults() { // return results; // } // // public SearchResultWrapper setResults(List<SearchResult> results) { // this.results = results; // return this; // } // // public String getDebugInfo() { // return debugInfo; // } // // public SearchResultWrapper setDebugInfo(String debugInfo) { // this.debugInfo = debugInfo; // return this; // } // // } // Path: src/main/java/com/difference/historybook/resources/CollectionResource.java import com.difference.historybook.index.Index; import com.difference.historybook.index.IndexException; import com.difference.historybook.index.SearchResultWrapper; import java.time.Instant; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2016 Andrew W. Buchanan (buchanan@difference.com) * * 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 com.difference.historybook.resources; /** * A resource for interacting with an index collection */ @Path("/collections/{collection}") public class CollectionResource { private static final Logger LOG = LoggerFactory.getLogger(CollectionResource.class);
private final Index index;
abuchanan920/historybook
src/main/java/com/difference/historybook/resources/CollectionResource.java
// Path: src/main/java/com/difference/historybook/index/Index.java // public interface Index extends AutoCloseable { // /** // * Adds a given page to an index collection // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param url the url of the page being indexed // * @param timestamp the timestamp representing when the page was retrieved // * @param body the textual content of the page (binaries are unsupported) // * @throws IndexException // */ // public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException; // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // default public SearchResultWrapper search(String collection, String query, int offset, int size) throws IndexException { // return search(collection, query, offset, size, false); // } // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @param includeDebug include implementation dependent debug information for search result // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // public SearchResultWrapper search(String collection, String query, int offset, int size, boolean includeDebug) throws IndexException; // } // // Path: src/main/java/com/difference/historybook/index/IndexException.java // public class IndexException extends Exception { // private static final long serialVersionUID = -1660541057609982084L; // // public IndexException(String msg) { // super(msg); // } // // public IndexException(Exception e) { // super(e); // } // } // // Path: src/main/java/com/difference/historybook/index/SearchResultWrapper.java // public class SearchResultWrapper { // private String query; // private int offset; // private int maxResultsRequested; // private int resultCount; // private String debugInfo; // private List<SearchResult> results; // // public String getQuery() { // return query; // } // // public SearchResultWrapper setQuery(String query) { // this.query = query; // return this; // } // // public int getOffset() { // return offset; // } // // public SearchResultWrapper setOffset(int offset) { // this.offset = offset; // return this; // } // // public int getMaxResultsRequested() { // return maxResultsRequested; // } // // public SearchResultWrapper setMaxResultsRequested(int maxResultsRequested) { // this.maxResultsRequested = maxResultsRequested; // return this; // } // // public int getResultCount() { // return resultCount; // } // // public SearchResultWrapper setResultCount(int resultCount) { // this.resultCount = resultCount; // return this; // } // // public List<SearchResult> getResults() { // return results; // } // // public SearchResultWrapper setResults(List<SearchResult> results) { // this.results = results; // return this; // } // // public String getDebugInfo() { // return debugInfo; // } // // public SearchResultWrapper setDebugInfo(String debugInfo) { // this.debugInfo = debugInfo; // return this; // } // // }
import com.difference.historybook.index.Index; import com.difference.historybook.index.IndexException; import com.difference.historybook.index.SearchResultWrapper; import java.time.Instant; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
) throws IndexException { LOG.debug("Received: {} {} {}", collection, url, timestamp.toString()); index.indexPage(collection, url, timestamp, body); return Response.accepted().build(); //TODO: What is the correct response code? } //TODO: support date range queries /** * Execute a search against the index * * @param collection the namespaced collection to search within * @param query the query to pass to the index * @param offsetString 0 based offset within the search results (used for paging) * @param sizeString maximum number of results to return * @return the search results within a metadata wrapper * @see Response * @throws NumberFormatException * @throws IndexException */ @GET @Produces("application/json") public Response getSearchResult( @PathParam("collection") String collection, @QueryParam("q") String query, @QueryParam("offset") @DefaultValue("0") String offsetString, @QueryParam("size") @DefaultValue("10") String sizeString, @QueryParam("debug") @DefaultValue("false") boolean debugFlag ) throws NumberFormatException, IndexException { LOG.debug("Query: {} query:{} offset:{} size:{} debug:{}", collection, query, offsetString, sizeString, debugFlag);
// Path: src/main/java/com/difference/historybook/index/Index.java // public interface Index extends AutoCloseable { // /** // * Adds a given page to an index collection // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param url the url of the page being indexed // * @param timestamp the timestamp representing when the page was retrieved // * @param body the textual content of the page (binaries are unsupported) // * @throws IndexException // */ // public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException; // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // default public SearchResultWrapper search(String collection, String query, int offset, int size) throws IndexException { // return search(collection, query, offset, size, false); // } // // /** // * Executes a given query against the index in the specified collection namespace and returns up to the requested page size of results. // * // * @param collection a namespace for an index. Allows storing multiple indexes within the same backing store. // * @param query the search query to execute. The supported syntax of this is determined by the underlying @Index implementation // * @param offset the 0-based offset to begin retrieving results from. Specifying an offset greater than the actual number of results will result in an empty result. // * @param size the maximum number of results to return. The actual number of results returned may be fewer. // * @param includeDebug include implementation dependent debug information for search result // * @return the search results for the specified query along with relevant metadata. // * @see SearchResultWrapper // * @throws IndexException // */ // public SearchResultWrapper search(String collection, String query, int offset, int size, boolean includeDebug) throws IndexException; // } // // Path: src/main/java/com/difference/historybook/index/IndexException.java // public class IndexException extends Exception { // private static final long serialVersionUID = -1660541057609982084L; // // public IndexException(String msg) { // super(msg); // } // // public IndexException(Exception e) { // super(e); // } // } // // Path: src/main/java/com/difference/historybook/index/SearchResultWrapper.java // public class SearchResultWrapper { // private String query; // private int offset; // private int maxResultsRequested; // private int resultCount; // private String debugInfo; // private List<SearchResult> results; // // public String getQuery() { // return query; // } // // public SearchResultWrapper setQuery(String query) { // this.query = query; // return this; // } // // public int getOffset() { // return offset; // } // // public SearchResultWrapper setOffset(int offset) { // this.offset = offset; // return this; // } // // public int getMaxResultsRequested() { // return maxResultsRequested; // } // // public SearchResultWrapper setMaxResultsRequested(int maxResultsRequested) { // this.maxResultsRequested = maxResultsRequested; // return this; // } // // public int getResultCount() { // return resultCount; // } // // public SearchResultWrapper setResultCount(int resultCount) { // this.resultCount = resultCount; // return this; // } // // public List<SearchResult> getResults() { // return results; // } // // public SearchResultWrapper setResults(List<SearchResult> results) { // this.results = results; // return this; // } // // public String getDebugInfo() { // return debugInfo; // } // // public SearchResultWrapper setDebugInfo(String debugInfo) { // this.debugInfo = debugInfo; // return this; // } // // } // Path: src/main/java/com/difference/historybook/resources/CollectionResource.java import com.difference.historybook.index.Index; import com.difference.historybook.index.IndexException; import com.difference.historybook.index.SearchResultWrapper; import java.time.Instant; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ) throws IndexException { LOG.debug("Received: {} {} {}", collection, url, timestamp.toString()); index.indexPage(collection, url, timestamp, body); return Response.accepted().build(); //TODO: What is the correct response code? } //TODO: support date range queries /** * Execute a search against the index * * @param collection the namespaced collection to search within * @param query the query to pass to the index * @param offsetString 0 based offset within the search results (used for paging) * @param sizeString maximum number of results to return * @return the search results within a metadata wrapper * @see Response * @throws NumberFormatException * @throws IndexException */ @GET @Produces("application/json") public Response getSearchResult( @PathParam("collection") String collection, @QueryParam("q") String query, @QueryParam("offset") @DefaultValue("0") String offsetString, @QueryParam("size") @DefaultValue("10") String sizeString, @QueryParam("debug") @DefaultValue("false") boolean debugFlag ) throws NumberFormatException, IndexException { LOG.debug("Query: {} query:{} offset:{} size:{} debug:{}", collection, query, offsetString, sizeString, debugFlag);
SearchResultWrapper results = index.search(
abuchanan920/historybook
src/test/java/com/difference/historybook/proxy/ProxyTest.java
// Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // }
import org.apache.commons.io.IOUtils; import org.junit.Rule; import static com.github.tomakehurst.wiremock.client.WireMock.*; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.common.base.Charsets; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.junit.Test; import com.difference.historybook.proxy.ProxyFilter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths;
assertEquals("chunked", connection.getHeaderField("Transfer-Encoding")); byte[] fetchedContent = IOUtils.toByteArray(connection.getInputStream()); assertArrayEquals(body, fetchedContent); proxy.stop(); } catch (Exception e) { fail(e.getLocalizedMessage()); } } @Test public void testSelector() { String body = "<html><head></head><body>Hello World!</body></html>"; stubFor(get(urlEqualTo("/some/page")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/html") .withBody(body))); stubFor(get(urlEqualTo("/some/other/page")) .willReturn(aResponse() .withStatus(201) .withHeader("Content-Type", "text/html") .withBody(body))); Proxy proxy = getProxy().setPort(PROXY_PORT);
// Path: src/main/java/com/difference/historybook/proxy/ProxyFilter.java // public interface ProxyFilter { // /** // * Perform arbitrary processing based on a given @ProxyRequest // * @param request // */ // public void processRequest(ProxyRequest request); // // /** // * Perform arbitrary processing based on a given @ProxyResponse // * @param response // */ // public void processResponse(ProxyResponse response); // } // Path: src/test/java/com/difference/historybook/proxy/ProxyTest.java import org.apache.commons.io.IOUtils; import org.junit.Rule; import static com.github.tomakehurst.wiremock.client.WireMock.*; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.common.base.Charsets; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.junit.Test; import com.difference.historybook.proxy.ProxyFilter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; assertEquals("chunked", connection.getHeaderField("Transfer-Encoding")); byte[] fetchedContent = IOUtils.toByteArray(connection.getInputStream()); assertArrayEquals(body, fetchedContent); proxy.stop(); } catch (Exception e) { fail(e.getLocalizedMessage()); } } @Test public void testSelector() { String body = "<html><head></head><body>Hello World!</body></html>"; stubFor(get(urlEqualTo("/some/page")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/html") .withBody(body))); stubFor(get(urlEqualTo("/some/other/page")) .willReturn(aResponse() .withStatus(201) .withHeader("Content-Type", "text/html") .withBody(body))); Proxy proxy = getProxy().setPort(PROXY_PORT);
ProxyFilter filter = mock(ProxyFilter.class);
abuchanan920/historybook
src/test/java/com/difference/historybook/proxyfilter/IndexingProxyResponseInfoSelectorTest.java
// Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.difference.historybook.proxy.ProxyTransactionInfo;
package com.difference.historybook.proxyfilter; public class IndexingProxyResponseInfoSelectorTest { @Test public void testStatus() { Map<String,String> headers = new HashMap<>(); headers.put("Content-Type", "text/html"); IndexingProxyResponseInfoSelector selector = new IndexingProxyResponseInfoSelector();
// Path: src/main/java/com/difference/historybook/proxy/ProxyTransactionInfo.java // public class ProxyTransactionInfo { // private final String url; // private final int status; // private final Map<String,String> headers; // // public ProxyTransactionInfo(String url, int status, Map<String,String> headers) { // this.url = url; // this.status = status; // this.headers = headers; // } // // /** // * @return return the URL of the page being fetched // */ // public String getUrl() { // return url; // } // // /** // * @return the numeric HTTP response code for the response // */ // public int getStatus() { // return status; // } // // /** // * @return a @Map of the HTTP headers associated with the response // */ // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/test/java/com/difference/historybook/proxyfilter/IndexingProxyResponseInfoSelectorTest.java import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.difference.historybook.proxy.ProxyTransactionInfo; package com.difference.historybook.proxyfilter; public class IndexingProxyResponseInfoSelectorTest { @Test public void testStatus() { Map<String,String> headers = new HashMap<>(); headers.put("Content-Type", "text/html"); IndexingProxyResponseInfoSelector selector = new IndexingProxyResponseInfoSelector();
ProxyTransactionInfo info1 = new ProxyTransactionInfo("http://does.not.exist", 200, headers);
evant/sres
sres/src/main/java/me/tatarka/sres/property/Property.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. * * @param <T> the property type */ public class Property<T> extends AbstractTrackable { private T value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public Property(T value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(T value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public T get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/Property.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. * * @param <T> the property type */ public class Property<T> extends AbstractTrackable { private T value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public Property(T value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(T value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public T get() {
ChangeTracker.track(this);
evant/sres
sres-compile/src/main/java/me/tatarka/sres/SourceInfo.java
// Path: sres-compile/src/main/java/me/tatarka/sres/util/PathTransformer.java // public class PathTransformer { // private Path path; // // public PathTransformer(Path path) { // this.path = path; // } // // public static PathTransformer of(Path path) { // return new PathTransformer(path); // } // // public static PathTransformer of(File file) { // return new PathTransformer(file.toPath()); // } // // public static PathTransformer of(String fileName) { // return new PathTransformer(new File(fileName).toPath()); // } // // public PathTransformer mirror(Path inputDir, Path outputDir) { // return PathTransformer.of(outputDir.resolve(inputDir.relativize(path))); // } // // public PathTransformer mirror(File inputDir, File outputDir) { // return mirror(inputDir.toPath(), outputDir.toPath()); // } // // public PathTransformer mirror(String inputDir, String outputDir) { // return mirror(new File(inputDir), new File(outputDir)); // } // // public PathTransformer extension(String extension) { // String name = path.getFileName().toString(); // int extensionIndex = FilenameUtils.indexOfExtension(name); // String newName = name.substring(0, extensionIndex < 0 ? name.length() : extensionIndex) + // (extension.length() > 0 ? "." : "") + extension; // return PathTransformer.of(path.getParent() == null ? Paths.get(newName) : path.getParent().resolve(newName)); // } // // public PathTransformer changeNameCase(CaseFormat fromFormat, CaseFormat toFormat) { // String name = path.getFileName().toString(); // String extension = FilenameUtils.getExtension(name); // int extensionIndex = FilenameUtils.indexOfExtension(name); // String bareName = extensionIndex < 0 ? name : name.substring(0, extensionIndex); // String newName = fromFormat.to(toFormat, bareName) + "." + extension; // return PathTransformer.of(path.getParent() == null ? Paths.get(newName) : path.getParent().resolve(newName)); // } // // public Path toPath() { // return path; // } // // @Override // public String toString() { // return path.toString(); // } // }
import me.tatarka.sres.util.PathTransformer; import java.nio.file.Path;
package me.tatarka.sres; /** * Created by evan on 3/8/14. */ public class SourceInfo { private Path path; private String codePackageName; private String appPackageName; public SourceInfo(Path path, String codePackageName, String appPackageName) { this.path = path; this.codePackageName = codePackageName; this.appPackageName = appPackageName; } public String getPackageName() { return codePackageName; } public String getAppPackageName() { return appPackageName; } public String getName() {
// Path: sres-compile/src/main/java/me/tatarka/sres/util/PathTransformer.java // public class PathTransformer { // private Path path; // // public PathTransformer(Path path) { // this.path = path; // } // // public static PathTransformer of(Path path) { // return new PathTransformer(path); // } // // public static PathTransformer of(File file) { // return new PathTransformer(file.toPath()); // } // // public static PathTransformer of(String fileName) { // return new PathTransformer(new File(fileName).toPath()); // } // // public PathTransformer mirror(Path inputDir, Path outputDir) { // return PathTransformer.of(outputDir.resolve(inputDir.relativize(path))); // } // // public PathTransformer mirror(File inputDir, File outputDir) { // return mirror(inputDir.toPath(), outputDir.toPath()); // } // // public PathTransformer mirror(String inputDir, String outputDir) { // return mirror(new File(inputDir), new File(outputDir)); // } // // public PathTransformer extension(String extension) { // String name = path.getFileName().toString(); // int extensionIndex = FilenameUtils.indexOfExtension(name); // String newName = name.substring(0, extensionIndex < 0 ? name.length() : extensionIndex) + // (extension.length() > 0 ? "." : "") + extension; // return PathTransformer.of(path.getParent() == null ? Paths.get(newName) : path.getParent().resolve(newName)); // } // // public PathTransformer changeNameCase(CaseFormat fromFormat, CaseFormat toFormat) { // String name = path.getFileName().toString(); // String extension = FilenameUtils.getExtension(name); // int extensionIndex = FilenameUtils.indexOfExtension(name); // String bareName = extensionIndex < 0 ? name : name.substring(0, extensionIndex); // String newName = fromFormat.to(toFormat, bareName) + "." + extension; // return PathTransformer.of(path.getParent() == null ? Paths.get(newName) : path.getParent().resolve(newName)); // } // // public Path toPath() { // return path; // } // // @Override // public String toString() { // return path.toString(); // } // } // Path: sres-compile/src/main/java/me/tatarka/sres/SourceInfo.java import me.tatarka.sres.util.PathTransformer; import java.nio.file.Path; package me.tatarka.sres; /** * Created by evan on 3/8/14. */ public class SourceInfo { private Path path; private String codePackageName; private String appPackageName; public SourceInfo(Path path, String codePackageName, String appPackageName) { this.path = path; this.codePackageName = codePackageName; this.appPackageName = appPackageName; } public String getPackageName() { return codePackageName; } public String getAppPackageName() { return appPackageName; } public String getName() {
return PathTransformer.of(path.getFileName()).extension("").toString();
evant/sres
sres/src/main/java/me/tatarka/sres/property/BooleanProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class BooleanProperty extends AbstractTrackable { private boolean value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public BooleanProperty(boolean value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(boolean value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public boolean get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/BooleanProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class BooleanProperty extends AbstractTrackable { private boolean value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public BooleanProperty(boolean value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(boolean value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public boolean get() {
ChangeTracker.track(this);
evant/sres
sres/src/main/java/me/tatarka/sres/property/LongProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class LongProperty extends AbstractTrackable { private long value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public LongProperty(long value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(long value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public long get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/LongProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class LongProperty extends AbstractTrackable { private long value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public LongProperty(long value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(long value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public long get() {
ChangeTracker.track(this);
evant/sres
idea-sres/src/me/tatarka/sres/idea/psi/SResTokenType.java
// Path: idea-sres/src/me/tatarka/sres/idea/SResLanguage.java // public class SResLanguage extends Language { // public static final SResLanguage INSTANCE = new SResLanguage(); // // protected SResLanguage() { // super("SRes"); // } // }
import com.intellij.psi.tree.IElementType; import me.tatarka.sres.idea.SResLanguage; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull;
package me.tatarka.sres.idea.psi; /** * Created by evan on 3/2/14. */ public class SResTokenType extends IElementType { public SResTokenType(@NotNull @NonNls String debugName) {
// Path: idea-sres/src/me/tatarka/sres/idea/SResLanguage.java // public class SResLanguage extends Language { // public static final SResLanguage INSTANCE = new SResLanguage(); // // protected SResLanguage() { // super("SRes"); // } // } // Path: idea-sres/src/me/tatarka/sres/idea/psi/SResTokenType.java import com.intellij.psi.tree.IElementType; import me.tatarka.sres.idea.SResLanguage; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; package me.tatarka.sres.idea.psi; /** * Created by evan on 3/2/14. */ public class SResTokenType extends IElementType { public SResTokenType(@NotNull @NonNls String debugName) {
super(debugName, SResLanguage.INSTANCE);
evant/sres
sres/src/main/java/me/tatarka/sres/property/ByteProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class ByteProperty extends AbstractTrackable { private byte value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public ByteProperty(byte value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(byte value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public byte get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/ByteProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class ByteProperty extends AbstractTrackable { private byte value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public ByteProperty(byte value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(byte value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public byte get() {
ChangeTracker.track(this);
evant/sres
sres/src/main/java/me/tatarka/sres/property/IntProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class IntProperty extends AbstractTrackable { private int value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public IntProperty(int value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(int value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public int get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/IntProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class IntProperty extends AbstractTrackable { private int value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public IntProperty(int value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(int value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public int get() {
ChangeTracker.track(this);
evant/sres
sres-compile/src/main/java/me/tatarka/sres/impl/SResXmlLayoutGenerator.java
// Path: sres/src/main/java/me/tatarka/sres/Bindable.java // public interface Bindable<T> { // public static final String NAMESPACE = "http://schemas.android.com/apk/lib/me.tatarka.sres"; // // void bind(T model); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/LayoutGenerator.java // public interface LayoutGenerator { // void generate(RootView rootView, SResOutput output); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/SResOutput.java // public class SResOutput { // public final SourceInfo sourceInfo; // public final Writer writer; // // public SResOutput(SourceInfo sourceInfo, Writer writer) { // this.sourceInfo = sourceInfo; // this.writer = writer; // } // }
import com.google.common.base.CaseFormat; import com.jamesmurty.utils.XMLBuilder; import me.tatarka.sres.Bindable; import me.tatarka.sres.LayoutGenerator; import me.tatarka.sres.SResOutput; import me.tatarka.sres.ast.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerException; import java.util.Properties;
package me.tatarka.sres.impl; /** * Created by evan on 3/1/14. */ public class SResXmlLayoutGenerator implements LayoutGenerator { public static final String NS_ANDROID = "http://schemas.android.com/apk/res/android"; public static final String NS_APP = "http://schemas.android.com/apk/res-auto"; @Override
// Path: sres/src/main/java/me/tatarka/sres/Bindable.java // public interface Bindable<T> { // public static final String NAMESPACE = "http://schemas.android.com/apk/lib/me.tatarka.sres"; // // void bind(T model); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/LayoutGenerator.java // public interface LayoutGenerator { // void generate(RootView rootView, SResOutput output); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/SResOutput.java // public class SResOutput { // public final SourceInfo sourceInfo; // public final Writer writer; // // public SResOutput(SourceInfo sourceInfo, Writer writer) { // this.sourceInfo = sourceInfo; // this.writer = writer; // } // } // Path: sres-compile/src/main/java/me/tatarka/sres/impl/SResXmlLayoutGenerator.java import com.google.common.base.CaseFormat; import com.jamesmurty.utils.XMLBuilder; import me.tatarka.sres.Bindable; import me.tatarka.sres.LayoutGenerator; import me.tatarka.sres.SResOutput; import me.tatarka.sres.ast.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerException; import java.util.Properties; package me.tatarka.sres.impl; /** * Created by evan on 3/1/14. */ public class SResXmlLayoutGenerator implements LayoutGenerator { public static final String NS_ANDROID = "http://schemas.android.com/apk/res/android"; public static final String NS_APP = "http://schemas.android.com/apk/res-auto"; @Override
public void generate(RootView rootView, SResOutput output) {
evant/sres
sres-compile/src/main/java/me/tatarka/sres/impl/SResXmlLayoutGenerator.java
// Path: sres/src/main/java/me/tatarka/sres/Bindable.java // public interface Bindable<T> { // public static final String NAMESPACE = "http://schemas.android.com/apk/lib/me.tatarka.sres"; // // void bind(T model); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/LayoutGenerator.java // public interface LayoutGenerator { // void generate(RootView rootView, SResOutput output); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/SResOutput.java // public class SResOutput { // public final SourceInfo sourceInfo; // public final Writer writer; // // public SResOutput(SourceInfo sourceInfo, Writer writer) { // this.sourceInfo = sourceInfo; // this.writer = writer; // } // }
import com.google.common.base.CaseFormat; import com.jamesmurty.utils.XMLBuilder; import me.tatarka.sres.Bindable; import me.tatarka.sres.LayoutGenerator; import me.tatarka.sres.SResOutput; import me.tatarka.sres.ast.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerException; import java.util.Properties;
package me.tatarka.sres.impl; /** * Created by evan on 3/1/14. */ public class SResXmlLayoutGenerator implements LayoutGenerator { public static final String NS_ANDROID = "http://schemas.android.com/apk/res/android"; public static final String NS_APP = "http://schemas.android.com/apk/res-auto"; @Override public void generate(RootView rootView, SResOutput output) { try { String rootClassName = rootView.subclass != null ? rootView.subclass : output.sourceInfo.getPackageName() + "." + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, output.sourceInfo.getName()); XMLBuilder b = XMLBuilder.create(rootClassName); b.namespace("android", NS_ANDROID); b.namespace("app", NS_APP); if (rootView.bindClass != null) {
// Path: sres/src/main/java/me/tatarka/sres/Bindable.java // public interface Bindable<T> { // public static final String NAMESPACE = "http://schemas.android.com/apk/lib/me.tatarka.sres"; // // void bind(T model); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/LayoutGenerator.java // public interface LayoutGenerator { // void generate(RootView rootView, SResOutput output); // } // // Path: sres-compile/src/main/java/me/tatarka/sres/SResOutput.java // public class SResOutput { // public final SourceInfo sourceInfo; // public final Writer writer; // // public SResOutput(SourceInfo sourceInfo, Writer writer) { // this.sourceInfo = sourceInfo; // this.writer = writer; // } // } // Path: sres-compile/src/main/java/me/tatarka/sres/impl/SResXmlLayoutGenerator.java import com.google.common.base.CaseFormat; import com.jamesmurty.utils.XMLBuilder; import me.tatarka.sres.Bindable; import me.tatarka.sres.LayoutGenerator; import me.tatarka.sres.SResOutput; import me.tatarka.sres.ast.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerException; import java.util.Properties; package me.tatarka.sres.impl; /** * Created by evan on 3/1/14. */ public class SResXmlLayoutGenerator implements LayoutGenerator { public static final String NS_ANDROID = "http://schemas.android.com/apk/res/android"; public static final String NS_APP = "http://schemas.android.com/apk/res-auto"; @Override public void generate(RootView rootView, SResOutput output) { try { String rootClassName = rootView.subclass != null ? rootView.subclass : output.sourceInfo.getPackageName() + "." + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, output.sourceInfo.getName()); XMLBuilder b = XMLBuilder.create(rootClassName); b.namespace("android", NS_ANDROID); b.namespace("app", NS_APP); if (rootView.bindClass != null) {
b.namespace("bind", Bindable.NAMESPACE);
evant/sres
sres/src/main/java/me/tatarka/sres/property/CharProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class CharProperty extends AbstractTrackable { private char value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public CharProperty(char value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(char value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public char get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/CharProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class CharProperty extends AbstractTrackable { private char value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public CharProperty(char value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(char value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public char get() {
ChangeTracker.track(this);
evant/sres
sres/src/main/java/me/tatarka/sres/property/DoubleProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class DoubleProperty extends AbstractTrackable { private double value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public DoubleProperty(double value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(double value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public double get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/DoubleProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class DoubleProperty extends AbstractTrackable { private double value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public DoubleProperty(double value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(double value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public double get() {
ChangeTracker.track(this);
evant/sres
idea-sres/src/me/tatarka/sres/idea/psi/SResElementType.java
// Path: idea-sres/src/me/tatarka/sres/idea/SResLanguage.java // public class SResLanguage extends Language { // public static final SResLanguage INSTANCE = new SResLanguage(); // // protected SResLanguage() { // super("SRes"); // } // }
import com.intellij.psi.tree.IElementType; import me.tatarka.sres.idea.SResLanguage; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull;
package me.tatarka.sres.idea.psi; /** * Created by evan on 3/2/14. */ public class SResElementType extends IElementType { public SResElementType(@NotNull @NonNls String debugName) {
// Path: idea-sres/src/me/tatarka/sres/idea/SResLanguage.java // public class SResLanguage extends Language { // public static final SResLanguage INSTANCE = new SResLanguage(); // // protected SResLanguage() { // super("SRes"); // } // } // Path: idea-sres/src/me/tatarka/sres/idea/psi/SResElementType.java import com.intellij.psi.tree.IElementType; import me.tatarka.sres.idea.SResLanguage; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; package me.tatarka.sres.idea.psi; /** * Created by evan on 3/2/14. */ public class SResElementType extends IElementType { public SResElementType(@NotNull @NonNls String debugName) {
super(debugName, SResLanguage.INSTANCE);
evant/sres
sres/src/main/java/me/tatarka/sres/property/FloatProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class FloatProperty extends AbstractTrackable { private float value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public FloatProperty(float value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(float value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public float get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/FloatProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class FloatProperty extends AbstractTrackable { private float value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public FloatProperty(float value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(float value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public float get() {
ChangeTracker.track(this);
evant/sres
sres/src/main/java/me/tatarka/sres/property/ShortProperty.java
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // }
import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker;
package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class ShortProperty extends AbstractTrackable { private short value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public ShortProperty(short value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(short value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public short get() {
// Path: sres/src/main/java/me/tatarka/sres/AbstractTrackable.java // public abstract class AbstractTrackable implements Trackable { // private Set<Listener> listeners = new LinkedHashSet<Listener>(); // // @Override // public void addListener(Listener listener) { // listeners.add(listener); // } // // @Override // public void removeListener(Listener listener) { // listeners.remove(listener); // } // // protected void notifyChange() { // ThreadHandlerProvider.getDefault().postToMainThread(new Runnable() { // @Override // public void run() { // for (Listener listener : listeners) listener.onChange(); // } // }); // } // } // // Path: sres/src/main/java/me/tatarka/sres/ChangeTracker.java // public class ChangeTracker { // private static ThreadLocal<Boolean> isTracking = new ThreadLocal<Boolean>() { // @Override // protected Boolean initialValue() { // return false; // } // }; // private static ThreadLocal<List<Trackable>> trackedObservables = new ThreadLocal<List<Trackable>>() { // @Override // protected List<Trackable> initialValue() { // return new ArrayList<>(); // } // }; // // private Map<Trackable.Listener, List<Trackable>> observableMap = new HashMap<Trackable.Listener, List<Trackable>>(); // // private static void startTracking() { // isTracking.set(true); // } // // private static List<Trackable> stopTracking() { // isTracking.set(false); // List<Trackable> properties = new ArrayList<Trackable>(trackedObservables.get()); // trackedObservables.get().clear(); // return properties; // } // // /** // * Notifies that the given trackable wants to be tracked. This should be called when a listener // * is registered on #{addListener}. For example, a @{link Property} calls it on @{link // * Property#get}. // * // * @param trackable the trackable to track // */ // public static void track(Trackable trackable) { // if (isTracking.get()) trackedObservables.get().add(trackable); // } // // /** // * Clears all registered listeners so they will no longer be called when the trackable changes. // */ // public void clear() { // ensureMainThread("clear"); // // for (Map.Entry<Trackable.Listener, List<Trackable>> entry : observableMap.entrySet()) { // for (Trackable trackable : entry.getValue()) trackable.removeListener(entry.getKey()); // } // observableMap.clear(); // } // // /** // * Adds the listener. The listener will immediately be called to discover which trackables it // * tracks. Then it will be called every time any of it's trackables change. // * // * @param listener the listener // */ // public void addListener(Trackable.Listener listener) { // ensureMainThread("addListener"); // // startTracking(); // listener.onChange(); // List<Trackable> newEntry = stopTracking(); // List<Trackable> oldEntry = observableMap.put(listener, newEntry); // if (oldEntry != null) { // for (Trackable trackable : oldEntry) trackable.removeListener(listener); // } // for (Trackable trackable : newEntry) trackable.addListener(listener); // } // // /** // * Removes the listener. It will no longer be called when it's trackables change. // * // * @param listener the listener // */ // public void removeListener(Trackable.Listener listener) { // ensureMainThread("removeListener"); // // List<Trackable> entry = observableMap.remove(listener); // if (entry != null) { // for (Trackable trackable : entry) trackable.removeListener(listener); // } // } // // private void ensureMainThread(String name) { // if (!ThreadHandlerProvider.getDefault().isOnMainThread()) { // throw new IllegalStateException("ChangeTracker" + name + "() must be called on the UI thread"); // } // } // } // Path: sres/src/main/java/me/tatarka/sres/property/ShortProperty.java import me.tatarka.sres.AbstractTrackable; import me.tatarka.sres.ChangeTracker; package me.tatarka.sres.property; /** * A Property is a value in which to can track changes. */ public class ShortProperty extends AbstractTrackable { private short value; /** * Constructs a new property with the given initial value. * * @param value the initial value */ public ShortProperty(short value) { this.value = value; } /** * Sets the property's value, notifying all listeners that it has changed. * * @param value the new value */ public void set(short value) { this.value = value; notifyChange(); } /** * Gets the property's value. * * @return the current value */ public short get() {
ChangeTracker.track(this);
stealthcopter/AndroidNetworkTools
library/src/main/java/com/stealthcopter/networktools/PortScan.java
// Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.java // public class PortScanTCP { // // // This class is not to be instantiated // private PortScanTCP() { // } // // /** // * Check if a port is open with TCP // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // Socket s = null; // try { // s = new Socket(); // s.connect(new InetSocketAddress(ia, portNo), timeoutMillis); // return true; // } catch (IOException e) { // // Don't log anything as we are expecting a lot of these from closed ports. // } finally { // if (s != null) { // try { // s.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return false; // } // // } // // Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.java // public class PortScanUDP { // // // This class is not to be instantiated // private PortScanUDP() { // } // // /** // * Check if a port is open with UDP, note that this isn't reliable // * as UDP will does not send ACKs // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // try { // byte[] bytes = new byte[128]; // DatagramPacket dp = new DatagramPacket(bytes, bytes.length); // // DatagramSocket ds = new DatagramSocket(); // ds.setSoTimeout(timeoutMillis); // ds.connect(ia, portNo); // ds.send(dp); // ds.isConnected(); // ds.receive(dp); // ds.close(); // // } catch (SocketTimeoutException e) { // return true; // } catch (Exception ignore) { // // } // // return false; // } // // }
import com.stealthcopter.networktools.portscanning.PortScanTCP; import com.stealthcopter.networktools.portscanning.PortScanUDP; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
} private synchronized void portScanned(int port, boolean open) { if (open) { openPortsFound.add(port); } if (portListener != null) { portListener.onResult(port, open); } } private class PortScanRunnable implements Runnable { private final InetAddress address; private final int portNo; private final int timeOutMillis; private final int method; PortScanRunnable(InetAddress address, int portNo, int timeOutMillis, int method) { this.address = address; this.portNo = portNo; this.timeOutMillis = timeOutMillis; this.method = method; } @Override public void run() { if (cancelled) return; switch (method) { case METHOD_UDP:
// Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.java // public class PortScanTCP { // // // This class is not to be instantiated // private PortScanTCP() { // } // // /** // * Check if a port is open with TCP // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // Socket s = null; // try { // s = new Socket(); // s.connect(new InetSocketAddress(ia, portNo), timeoutMillis); // return true; // } catch (IOException e) { // // Don't log anything as we are expecting a lot of these from closed ports. // } finally { // if (s != null) { // try { // s.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return false; // } // // } // // Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.java // public class PortScanUDP { // // // This class is not to be instantiated // private PortScanUDP() { // } // // /** // * Check if a port is open with UDP, note that this isn't reliable // * as UDP will does not send ACKs // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // try { // byte[] bytes = new byte[128]; // DatagramPacket dp = new DatagramPacket(bytes, bytes.length); // // DatagramSocket ds = new DatagramSocket(); // ds.setSoTimeout(timeoutMillis); // ds.connect(ia, portNo); // ds.send(dp); // ds.isConnected(); // ds.receive(dp); // ds.close(); // // } catch (SocketTimeoutException e) { // return true; // } catch (Exception ignore) { // // } // // return false; // } // // } // Path: library/src/main/java/com/stealthcopter/networktools/PortScan.java import com.stealthcopter.networktools.portscanning.PortScanTCP; import com.stealthcopter.networktools.portscanning.PortScanUDP; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; } private synchronized void portScanned(int port, boolean open) { if (open) { openPortsFound.add(port); } if (portListener != null) { portListener.onResult(port, open); } } private class PortScanRunnable implements Runnable { private final InetAddress address; private final int portNo; private final int timeOutMillis; private final int method; PortScanRunnable(InetAddress address, int portNo, int timeOutMillis, int method) { this.address = address; this.portNo = portNo; this.timeOutMillis = timeOutMillis; this.method = method; } @Override public void run() { if (cancelled) return; switch (method) { case METHOD_UDP:
portScanned(portNo, PortScanUDP.scanAddress(address, portNo, timeOutMillis));
stealthcopter/AndroidNetworkTools
library/src/main/java/com/stealthcopter/networktools/PortScan.java
// Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.java // public class PortScanTCP { // // // This class is not to be instantiated // private PortScanTCP() { // } // // /** // * Check if a port is open with TCP // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // Socket s = null; // try { // s = new Socket(); // s.connect(new InetSocketAddress(ia, portNo), timeoutMillis); // return true; // } catch (IOException e) { // // Don't log anything as we are expecting a lot of these from closed ports. // } finally { // if (s != null) { // try { // s.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return false; // } // // } // // Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.java // public class PortScanUDP { // // // This class is not to be instantiated // private PortScanUDP() { // } // // /** // * Check if a port is open with UDP, note that this isn't reliable // * as UDP will does not send ACKs // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // try { // byte[] bytes = new byte[128]; // DatagramPacket dp = new DatagramPacket(bytes, bytes.length); // // DatagramSocket ds = new DatagramSocket(); // ds.setSoTimeout(timeoutMillis); // ds.connect(ia, portNo); // ds.send(dp); // ds.isConnected(); // ds.receive(dp); // ds.close(); // // } catch (SocketTimeoutException e) { // return true; // } catch (Exception ignore) { // // } // // return false; // } // // }
import com.stealthcopter.networktools.portscanning.PortScanTCP; import com.stealthcopter.networktools.portscanning.PortScanUDP; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
if (open) { openPortsFound.add(port); } if (portListener != null) { portListener.onResult(port, open); } } private class PortScanRunnable implements Runnable { private final InetAddress address; private final int portNo; private final int timeOutMillis; private final int method; PortScanRunnable(InetAddress address, int portNo, int timeOutMillis, int method) { this.address = address; this.portNo = portNo; this.timeOutMillis = timeOutMillis; this.method = method; } @Override public void run() { if (cancelled) return; switch (method) { case METHOD_UDP: portScanned(portNo, PortScanUDP.scanAddress(address, portNo, timeOutMillis)); break; case METHOD_TCP:
// Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.java // public class PortScanTCP { // // // This class is not to be instantiated // private PortScanTCP() { // } // // /** // * Check if a port is open with TCP // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // Socket s = null; // try { // s = new Socket(); // s.connect(new InetSocketAddress(ia, portNo), timeoutMillis); // return true; // } catch (IOException e) { // // Don't log anything as we are expecting a lot of these from closed ports. // } finally { // if (s != null) { // try { // s.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return false; // } // // } // // Path: library/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.java // public class PortScanUDP { // // // This class is not to be instantiated // private PortScanUDP() { // } // // /** // * Check if a port is open with UDP, note that this isn't reliable // * as UDP will does not send ACKs // * // * @param ia - address to scan // * @param portNo - port to scan // * @param timeoutMillis - timeout // * @return - true if port is open, false if not or unknown // */ // public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { // // try { // byte[] bytes = new byte[128]; // DatagramPacket dp = new DatagramPacket(bytes, bytes.length); // // DatagramSocket ds = new DatagramSocket(); // ds.setSoTimeout(timeoutMillis); // ds.connect(ia, portNo); // ds.send(dp); // ds.isConnected(); // ds.receive(dp); // ds.close(); // // } catch (SocketTimeoutException e) { // return true; // } catch (Exception ignore) { // // } // // return false; // } // // } // Path: library/src/main/java/com/stealthcopter/networktools/PortScan.java import com.stealthcopter.networktools.portscanning.PortScanTCP; import com.stealthcopter.networktools.portscanning.PortScanUDP; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; if (open) { openPortsFound.add(port); } if (portListener != null) { portListener.onResult(port, open); } } private class PortScanRunnable implements Runnable { private final InetAddress address; private final int portNo; private final int timeOutMillis; private final int method; PortScanRunnable(InetAddress address, int portNo, int timeOutMillis, int method) { this.address = address; this.portNo = portNo; this.timeOutMillis = timeOutMillis; this.method = method; } @Override public void run() { if (cancelled) return; switch (method) { case METHOD_UDP: portScanned(portNo, PortScanUDP.scanAddress(address, portNo, timeOutMillis)); break; case METHOD_TCP:
portScanned(portNo, PortScanTCP.scanAddress(address, portNo, timeOutMillis));
stealthcopter/AndroidNetworkTools
library/src/main/java/com/stealthcopter/networktools/SubnetDevices.java
// Path: library/src/main/java/com/stealthcopter/networktools/ping/PingResult.java // public class PingResult { // public final InetAddress ia; // public boolean isReachable; // public String error = null; // public float timeTaken; // public String fullString; // public String result; // // public PingResult(InetAddress ia) { // this.ia = ia; // } // // public boolean isReachable() { // return isReachable; // } // // public boolean hasError() { // return error != null; // } // // public float getTimeTaken() { // return timeTaken; // } // // public String getError() { // return error; // } // // public InetAddress getAddress() { // return ia; // } // // @Override // public String toString() { // return "PingResult{" + // "ia=" + ia + // ", isReachable=" + isReachable + // ", error='" + error + '\'' + // ", timeTaken=" + timeTaken + // ", fullString='" + fullString + '\'' + // ", result='" + result + '\'' + // '}'; // } // } // // Path: library/src/main/java/com/stealthcopter/networktools/subnet/Device.java // public class Device { // public String ip; // public String hostname; // public String mac; // public float time = 0; // // public Device(InetAddress ip) { // this.ip = ip.getHostAddress(); // this.hostname = ip.getCanonicalHostName(); // } // // @Override // public String toString() { // return "Device{" + // "ip='" + ip + '\'' + // ", hostname='" + hostname + '\'' + // ", mac='" + mac + '\'' + // ", time=" + time + // '}'; // } // }
import com.stealthcopter.networktools.ping.PingResult; import com.stealthcopter.networktools.subnet.Device; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
package com.stealthcopter.networktools; public class SubnetDevices { private int noThreads = 100; private ArrayList<String> addresses;
// Path: library/src/main/java/com/stealthcopter/networktools/ping/PingResult.java // public class PingResult { // public final InetAddress ia; // public boolean isReachable; // public String error = null; // public float timeTaken; // public String fullString; // public String result; // // public PingResult(InetAddress ia) { // this.ia = ia; // } // // public boolean isReachable() { // return isReachable; // } // // public boolean hasError() { // return error != null; // } // // public float getTimeTaken() { // return timeTaken; // } // // public String getError() { // return error; // } // // public InetAddress getAddress() { // return ia; // } // // @Override // public String toString() { // return "PingResult{" + // "ia=" + ia + // ", isReachable=" + isReachable + // ", error='" + error + '\'' + // ", timeTaken=" + timeTaken + // ", fullString='" + fullString + '\'' + // ", result='" + result + '\'' + // '}'; // } // } // // Path: library/src/main/java/com/stealthcopter/networktools/subnet/Device.java // public class Device { // public String ip; // public String hostname; // public String mac; // public float time = 0; // // public Device(InetAddress ip) { // this.ip = ip.getHostAddress(); // this.hostname = ip.getCanonicalHostName(); // } // // @Override // public String toString() { // return "Device{" + // "ip='" + ip + '\'' + // ", hostname='" + hostname + '\'' + // ", mac='" + mac + '\'' + // ", time=" + time + // '}'; // } // } // Path: library/src/main/java/com/stealthcopter/networktools/SubnetDevices.java import com.stealthcopter.networktools.ping.PingResult; import com.stealthcopter.networktools.subnet.Device; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; package com.stealthcopter.networktools; public class SubnetDevices { private int noThreads = 100; private ArrayList<String> addresses;
private ArrayList<Device> devicesFound;
stealthcopter/AndroidNetworkTools
library/src/main/java/com/stealthcopter/networktools/SubnetDevices.java
// Path: library/src/main/java/com/stealthcopter/networktools/ping/PingResult.java // public class PingResult { // public final InetAddress ia; // public boolean isReachable; // public String error = null; // public float timeTaken; // public String fullString; // public String result; // // public PingResult(InetAddress ia) { // this.ia = ia; // } // // public boolean isReachable() { // return isReachable; // } // // public boolean hasError() { // return error != null; // } // // public float getTimeTaken() { // return timeTaken; // } // // public String getError() { // return error; // } // // public InetAddress getAddress() { // return ia; // } // // @Override // public String toString() { // return "PingResult{" + // "ia=" + ia + // ", isReachable=" + isReachable + // ", error='" + error + '\'' + // ", timeTaken=" + timeTaken + // ", fullString='" + fullString + '\'' + // ", result='" + result + '\'' + // '}'; // } // } // // Path: library/src/main/java/com/stealthcopter/networktools/subnet/Device.java // public class Device { // public String ip; // public String hostname; // public String mac; // public float time = 0; // // public Device(InetAddress ip) { // this.ip = ip.getHostAddress(); // this.hostname = ip.getCanonicalHostName(); // } // // @Override // public String toString() { // return "Device{" + // "ip='" + ip + '\'' + // ", hostname='" + hostname + '\'' + // ", mac='" + mac + '\'' + // ", time=" + time + // '}'; // } // }
import com.stealthcopter.networktools.ping.PingResult; import com.stealthcopter.networktools.subnet.Device; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
} listener.onFinished(devicesFound); } }).start(); return this; } private synchronized void subnetDeviceFound(Device device) { devicesFound.add(device); listener.onDeviceFound(device); } public class SubnetDeviceFinderRunnable implements Runnable { private final String address; SubnetDeviceFinderRunnable(String address) { this.address = address; } @Override public void run() { if (cancelled) return; try { InetAddress ia = InetAddress.getByName(address);
// Path: library/src/main/java/com/stealthcopter/networktools/ping/PingResult.java // public class PingResult { // public final InetAddress ia; // public boolean isReachable; // public String error = null; // public float timeTaken; // public String fullString; // public String result; // // public PingResult(InetAddress ia) { // this.ia = ia; // } // // public boolean isReachable() { // return isReachable; // } // // public boolean hasError() { // return error != null; // } // // public float getTimeTaken() { // return timeTaken; // } // // public String getError() { // return error; // } // // public InetAddress getAddress() { // return ia; // } // // @Override // public String toString() { // return "PingResult{" + // "ia=" + ia + // ", isReachable=" + isReachable + // ", error='" + error + '\'' + // ", timeTaken=" + timeTaken + // ", fullString='" + fullString + '\'' + // ", result='" + result + '\'' + // '}'; // } // } // // Path: library/src/main/java/com/stealthcopter/networktools/subnet/Device.java // public class Device { // public String ip; // public String hostname; // public String mac; // public float time = 0; // // public Device(InetAddress ip) { // this.ip = ip.getHostAddress(); // this.hostname = ip.getCanonicalHostName(); // } // // @Override // public String toString() { // return "Device{" + // "ip='" + ip + '\'' + // ", hostname='" + hostname + '\'' + // ", mac='" + mac + '\'' + // ", time=" + time + // '}'; // } // } // Path: library/src/main/java/com/stealthcopter/networktools/SubnetDevices.java import com.stealthcopter.networktools.ping.PingResult; import com.stealthcopter.networktools.subnet.Device; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; } listener.onFinished(devicesFound); } }).start(); return this; } private synchronized void subnetDeviceFound(Device device) { devicesFound.add(device); listener.onDeviceFound(device); } public class SubnetDeviceFinderRunnable implements Runnable { private final String address; SubnetDeviceFinderRunnable(String address) { this.address = address; } @Override public void run() { if (cancelled) return; try { InetAddress ia = InetAddress.getByName(address);
PingResult pingResult = Ping.onAddress(ia).setTimeOutMillis(timeOutMillis).doPing();
stealthcopter/AndroidNetworkTools
library/src/main/java/com/stealthcopter/networktools/ping/PingNative.java
// Path: library/src/main/java/com/stealthcopter/networktools/IPTools.java // public class IPTools { // // /** // * Ip matching patterns from // * https://examples.javacodegeeks.com/core-java/util/regex/regular-expressions-for-ip-v4-and-ip-v6-addresses/ // * note that these patterns will match most but not all valid ips // */ // // private static final Pattern IPV4_PATTERN = // Pattern.compile( // "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); // // private static final Pattern IPV6_STD_PATTERN = // Pattern.compile( // "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); // // private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = // Pattern.compile( // "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); // // // This class is not to be instantiated // private IPTools() { // } // // public static boolean isIPv4Address(final String address) { // return address != null && IPV4_PATTERN.matcher(address).matches(); // } // // public static boolean isIPv6StdAddress(final String address) { // return address != null && IPV6_STD_PATTERN.matcher(address).matches(); // } // // public static boolean isIPv6HexCompressedAddress(final String address) { // return address != null && IPV6_HEX_COMPRESSED_PATTERN.matcher(address).matches(); // } // // public static boolean isIPv6Address(final String address) { // return address != null && (isIPv6StdAddress(address) || isIPv6HexCompressedAddress(address)); // } // // /** // * @return The first local IPv4 address, or null // */ // public static InetAddress getLocalIPv4Address() { // ArrayList<InetAddress> localAddresses = getLocalIPv4Addresses(); // return localAddresses.size() > 0 ? localAddresses.get(0) : null; // } // // /** // * @return The list of all IPv4 addresses found // */ // public static ArrayList<InetAddress> getLocalIPv4Addresses() { // // ArrayList<InetAddress> foundAddresses = new ArrayList<>(); // // Enumeration<NetworkInterface> ifaces; // try { // ifaces = NetworkInterface.getNetworkInterfaces(); // // while (ifaces.hasMoreElements()) { // NetworkInterface iface = ifaces.nextElement(); // Enumeration<InetAddress> addresses = iface.getInetAddresses(); // // while (addresses.hasMoreElements()) { // InetAddress addr = addresses.nextElement(); // if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) { // foundAddresses.add(addr); // } // } // } // } catch (SocketException e) { // e.printStackTrace(); // } // return foundAddresses; // } // // // /** // * Check if the provided ip address refers to the localhost // * // * https://stackoverflow.com/a/2406819/315998 // * // * @param addr - address to check // * @return - true if ip address is self // */ // public static boolean isIpAddressLocalhost(InetAddress addr) { // if (addr == null) return false; // // // Check if the address is a valid special local or loop back // if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) // return true; // // // Check if the address is defined on any interface // try { // return NetworkInterface.getByInetAddress(addr) != null; // } catch (SocketException e) { // return false; // } // } // // /** // * Check if the provided ip address refers to the localhost // * // * https://stackoverflow.com/a/2406819/315998 // * // * @param addr - address to check // * @return - true if ip address is self // */ // public static boolean isIpAddressLocalNetwork(InetAddress addr) { // return addr != null && addr.isSiteLocalAddress(); // } // // // }
import com.stealthcopter.networktools.IPTools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress;
package com.stealthcopter.networktools.ping; public class PingNative { // This class is not to be instantiated private PingNative() { } public static PingResult ping(InetAddress host, PingOptions pingOptions) throws IOException, InterruptedException { PingResult pingResult = new PingResult(host); if (host == null) { pingResult.isReachable = false; return pingResult; } StringBuilder echo = new StringBuilder(); Runtime runtime = Runtime.getRuntime(); int timeoutSeconds = Math.max(pingOptions.getTimeoutMillis() / 1000, 1); int ttl = Math.max(pingOptions.getTimeToLive(), 1); String address = host.getHostAddress(); String pingCommand = "ping"; if (address != null) {
// Path: library/src/main/java/com/stealthcopter/networktools/IPTools.java // public class IPTools { // // /** // * Ip matching patterns from // * https://examples.javacodegeeks.com/core-java/util/regex/regular-expressions-for-ip-v4-and-ip-v6-addresses/ // * note that these patterns will match most but not all valid ips // */ // // private static final Pattern IPV4_PATTERN = // Pattern.compile( // "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); // // private static final Pattern IPV6_STD_PATTERN = // Pattern.compile( // "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); // // private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = // Pattern.compile( // "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); // // // This class is not to be instantiated // private IPTools() { // } // // public static boolean isIPv4Address(final String address) { // return address != null && IPV4_PATTERN.matcher(address).matches(); // } // // public static boolean isIPv6StdAddress(final String address) { // return address != null && IPV6_STD_PATTERN.matcher(address).matches(); // } // // public static boolean isIPv6HexCompressedAddress(final String address) { // return address != null && IPV6_HEX_COMPRESSED_PATTERN.matcher(address).matches(); // } // // public static boolean isIPv6Address(final String address) { // return address != null && (isIPv6StdAddress(address) || isIPv6HexCompressedAddress(address)); // } // // /** // * @return The first local IPv4 address, or null // */ // public static InetAddress getLocalIPv4Address() { // ArrayList<InetAddress> localAddresses = getLocalIPv4Addresses(); // return localAddresses.size() > 0 ? localAddresses.get(0) : null; // } // // /** // * @return The list of all IPv4 addresses found // */ // public static ArrayList<InetAddress> getLocalIPv4Addresses() { // // ArrayList<InetAddress> foundAddresses = new ArrayList<>(); // // Enumeration<NetworkInterface> ifaces; // try { // ifaces = NetworkInterface.getNetworkInterfaces(); // // while (ifaces.hasMoreElements()) { // NetworkInterface iface = ifaces.nextElement(); // Enumeration<InetAddress> addresses = iface.getInetAddresses(); // // while (addresses.hasMoreElements()) { // InetAddress addr = addresses.nextElement(); // if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) { // foundAddresses.add(addr); // } // } // } // } catch (SocketException e) { // e.printStackTrace(); // } // return foundAddresses; // } // // // /** // * Check if the provided ip address refers to the localhost // * // * https://stackoverflow.com/a/2406819/315998 // * // * @param addr - address to check // * @return - true if ip address is self // */ // public static boolean isIpAddressLocalhost(InetAddress addr) { // if (addr == null) return false; // // // Check if the address is a valid special local or loop back // if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) // return true; // // // Check if the address is defined on any interface // try { // return NetworkInterface.getByInetAddress(addr) != null; // } catch (SocketException e) { // return false; // } // } // // /** // * Check if the provided ip address refers to the localhost // * // * https://stackoverflow.com/a/2406819/315998 // * // * @param addr - address to check // * @return - true if ip address is self // */ // public static boolean isIpAddressLocalNetwork(InetAddress addr) { // return addr != null && addr.isSiteLocalAddress(); // } // // // } // Path: library/src/main/java/com/stealthcopter/networktools/ping/PingNative.java import com.stealthcopter.networktools.IPTools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; package com.stealthcopter.networktools.ping; public class PingNative { // This class is not to be instantiated private PingNative() { } public static PingResult ping(InetAddress host, PingOptions pingOptions) throws IOException, InterruptedException { PingResult pingResult = new PingResult(host); if (host == null) { pingResult.isReachable = false; return pingResult; } StringBuilder echo = new StringBuilder(); Runtime runtime = Runtime.getRuntime(); int timeoutSeconds = Math.max(pingOptions.getTimeoutMillis() / 1000, 1); int ttl = Math.max(pingOptions.getTimeToLive(), 1); String address = host.getHostAddress(); String pingCommand = "ping"; if (address != null) {
if (IPTools.isIPv6Address(address)) {
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ControllableMobs.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // } // // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // }
import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import net.minecraft.server.v1_7_R1.EntityInsentient; import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.PluginClassLoader; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces;
package de.ntcomputer.minecraft.controllablemobs.api; /** * This is a static class which lets you retrieve instances of {@link ControllableMob}. * * @author Cybran * @version v5 * */ public final class ControllableMobs { private static final Map<LivingEntity,ControllableMob<?>> entities = new HashMap<LivingEntity,ControllableMob<?>>(); static { onLoad(); } private static void onLoad() { try { PluginClassLoader cl = (PluginClassLoader) ControllableMobs.class.getClassLoader();
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // } // // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ControllableMobs.java import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import net.minecraft.server.v1_7_R1.EntityInsentient; import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.PluginClassLoader; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces; package de.ntcomputer.minecraft.controllablemobs.api; /** * This is a static class which lets you retrieve instances of {@link ControllableMob}. * * @author Cybran * @version v5 * */ public final class ControllableMobs { private static final Map<LivingEntity,ControllableMob<?>> entities = new HashMap<LivingEntity,ControllableMob<?>>(); static { onLoad(); } private static void onLoad() { try { PluginClassLoader cl = (PluginClassLoader) ControllableMobs.class.getClassLoader();
Plugin[] plugins = NativeInterfaces.JAVAPLUGINLOADER.FIELD_SERVER.get(NativeInterfaces.PLUGINCLASSLOADER.FIELD_LOADER.get(cl)).getPluginManager().getPlugins();
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/ControllableMobHelper.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // }
import org.bukkit.entity.Animals; import org.bukkit.entity.Creature; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces;
package de.ntcomputer.minecraft.controllablemobs.implementation; public class ControllableMobHelper { @SuppressWarnings("deprecation") public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final Class<? extends LivingEntity> entityClass) throws IllegalArgumentException { if(entityClass==null) throw new IllegalArgumentException("entityClass must not be null"); if(entityClass==HumanEntity.class || entityClass==Player.class) return net.minecraft.server.v1_7_R1.EntityHuman.class; if(entityClass==Monster.class) return net.minecraft.server.v1_7_R1.EntityMonster.class; if(entityClass==Creature.class) return net.minecraft.server.v1_7_R1.EntityCreature.class; if(entityClass==Animals.class) return net.minecraft.server.v1_7_R1.EntityAnimal.class; if(entityClass==LivingEntity.class) return net.minecraft.server.v1_7_R1.EntityLiving.class; for(EntityType entityType: EntityType.values()) { if(entityType.getEntityClass()==null || entityType.getTypeId()==-1) continue; if(entityClass.equals(entityType.getEntityClass())) { return getNmsEntityClass(entityType); } } throw new IllegalArgumentException("Class "+entityClass.getSimpleName()+" is not resolvable to an EntityType"); } @SuppressWarnings("deprecation") public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final EntityType entityType) throws IllegalArgumentException { if(entityType==null) throw new IllegalArgumentException("EntityType must not be null"); if(entityType==EntityType.PLAYER) return net.minecraft.server.v1_7_R1.EntityHuman.class; try {
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/ControllableMobHelper.java import org.bukkit.entity.Animals; import org.bukkit.entity.Creature; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces; package de.ntcomputer.minecraft.controllablemobs.implementation; public class ControllableMobHelper { @SuppressWarnings("deprecation") public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final Class<? extends LivingEntity> entityClass) throws IllegalArgumentException { if(entityClass==null) throw new IllegalArgumentException("entityClass must not be null"); if(entityClass==HumanEntity.class || entityClass==Player.class) return net.minecraft.server.v1_7_R1.EntityHuman.class; if(entityClass==Monster.class) return net.minecraft.server.v1_7_R1.EntityMonster.class; if(entityClass==Creature.class) return net.minecraft.server.v1_7_R1.EntityCreature.class; if(entityClass==Animals.class) return net.minecraft.server.v1_7_R1.EntityAnimal.class; if(entityClass==LivingEntity.class) return net.minecraft.server.v1_7_R1.EntityLiving.class; for(EntityType entityType: EntityType.values()) { if(entityType.getEntityClass()==null || entityType.getTypeId()==-1) continue; if(entityClass.equals(entityType.getEntityClass())) { return getNmsEntityClass(entityType); } } throw new IllegalArgumentException("Class "+entityClass.getSimpleName()+" is not resolvable to an EntityType"); } @SuppressWarnings("deprecation") public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final EntityType entityType) throws IllegalArgumentException { if(entityType==null) throw new IllegalArgumentException("EntityType must not be null"); if(entityType==EntityType.PLAYER) return net.minecraft.server.v1_7_R1.EntityHuman.class; try {
final Class<? extends net.minecraft.server.v1_7_R1.Entity> entityClass = NativeInterfaces.ENTITYTYPES.METHOD_GETCLASSBYID.invoke(entityType.getTypeId());
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ai/behaviors/AITargetBehaviorEx.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/ControllableMobHelper.java // public class ControllableMobHelper { // // @SuppressWarnings("deprecation") // public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final Class<? extends LivingEntity> entityClass) throws IllegalArgumentException { // if(entityClass==null) throw new IllegalArgumentException("entityClass must not be null"); // if(entityClass==HumanEntity.class || entityClass==Player.class) return net.minecraft.server.v1_7_R1.EntityHuman.class; // if(entityClass==Monster.class) return net.minecraft.server.v1_7_R1.EntityMonster.class; // if(entityClass==Creature.class) return net.minecraft.server.v1_7_R1.EntityCreature.class; // if(entityClass==Animals.class) return net.minecraft.server.v1_7_R1.EntityAnimal.class; // if(entityClass==LivingEntity.class) return net.minecraft.server.v1_7_R1.EntityLiving.class; // // for(EntityType entityType: EntityType.values()) { // if(entityType.getEntityClass()==null || entityType.getTypeId()==-1) continue; // if(entityClass.equals(entityType.getEntityClass())) { // return getNmsEntityClass(entityType); // } // } // // throw new IllegalArgumentException("Class "+entityClass.getSimpleName()+" is not resolvable to an EntityType"); // } // // @SuppressWarnings("deprecation") // public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final EntityType entityType) throws IllegalArgumentException { // if(entityType==null) throw new IllegalArgumentException("EntityType must not be null"); // if(entityType==EntityType.PLAYER) return net.minecraft.server.v1_7_R1.EntityHuman.class; // // try { // final Class<? extends net.minecraft.server.v1_7_R1.Entity> entityClass = NativeInterfaces.ENTITYTYPES.METHOD_GETCLASSBYID.invoke(entityType.getTypeId()); // if(entityClass==null) throw new IllegalArgumentException("EntityType "+entityType+" is not resolvable to a net.minecraft Class"); // return entityClass; // } catch(Exception e) { // throw new IllegalArgumentException("EntityType "+entityType+" is not resolvable to a net.minecraft Class", e); // } // } // // }
import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.implementation.ControllableMobHelper;
package de.ntcomputer.minecraft.controllablemobs.api.ai.behaviors; /** * Base class for target behavior with extended arguments. * Implementation of these behaviors are using a custom core. * * @author Cybran * @version 53 * */ public abstract class AITargetBehaviorEx extends AITargetBehavior<LivingEntity> { protected final int maximumNoEyeContactTicks; protected final boolean ignoreInvulnerability; protected final double maximumDistance; protected final Class<? extends EntityLiving>[] targetClasses; @SuppressWarnings("unchecked") protected AITargetBehaviorEx(int priority, int maximumNoEyeContactTicks, boolean ignoreInvulnerability, double maximumDistance, Class<? extends LivingEntity>[] targetClasses) throws IllegalArgumentException { super(priority); if(targetClasses==null) throw new IllegalArgumentException("targetClasses must not be null"); if(targetClasses.length==0) throw new IllegalArgumentException("targetClasses must not be empty"); this.maximumNoEyeContactTicks = maximumNoEyeContactTicks; this.ignoreInvulnerability = ignoreInvulnerability; this.maximumDistance = maximumDistance; this.targetClasses = new Class[targetClasses.length]; for(int i=0; i<targetClasses.length; i++) {
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/ControllableMobHelper.java // public class ControllableMobHelper { // // @SuppressWarnings("deprecation") // public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final Class<? extends LivingEntity> entityClass) throws IllegalArgumentException { // if(entityClass==null) throw new IllegalArgumentException("entityClass must not be null"); // if(entityClass==HumanEntity.class || entityClass==Player.class) return net.minecraft.server.v1_7_R1.EntityHuman.class; // if(entityClass==Monster.class) return net.minecraft.server.v1_7_R1.EntityMonster.class; // if(entityClass==Creature.class) return net.minecraft.server.v1_7_R1.EntityCreature.class; // if(entityClass==Animals.class) return net.minecraft.server.v1_7_R1.EntityAnimal.class; // if(entityClass==LivingEntity.class) return net.minecraft.server.v1_7_R1.EntityLiving.class; // // for(EntityType entityType: EntityType.values()) { // if(entityType.getEntityClass()==null || entityType.getTypeId()==-1) continue; // if(entityClass.equals(entityType.getEntityClass())) { // return getNmsEntityClass(entityType); // } // } // // throw new IllegalArgumentException("Class "+entityClass.getSimpleName()+" is not resolvable to an EntityType"); // } // // @SuppressWarnings("deprecation") // public static Class<? extends net.minecraft.server.v1_7_R1.Entity> getNmsEntityClass(final EntityType entityType) throws IllegalArgumentException { // if(entityType==null) throw new IllegalArgumentException("EntityType must not be null"); // if(entityType==EntityType.PLAYER) return net.minecraft.server.v1_7_R1.EntityHuman.class; // // try { // final Class<? extends net.minecraft.server.v1_7_R1.Entity> entityClass = NativeInterfaces.ENTITYTYPES.METHOD_GETCLASSBYID.invoke(entityType.getTypeId()); // if(entityClass==null) throw new IllegalArgumentException("EntityType "+entityType+" is not resolvable to a net.minecraft Class"); // return entityClass; // } catch(Exception e) { // throw new IllegalArgumentException("EntityType "+entityType+" is not resolvable to a net.minecraft Class", e); // } // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ai/behaviors/AITargetBehaviorEx.java import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.implementation.ControllableMobHelper; package de.ntcomputer.minecraft.controllablemobs.api.ai.behaviors; /** * Base class for target behavior with extended arguments. * Implementation of these behaviors are using a custom core. * * @author Cybran * @version 53 * */ public abstract class AITargetBehaviorEx extends AITargetBehavior<LivingEntity> { protected final int maximumNoEyeContactTicks; protected final boolean ignoreInvulnerability; protected final double maximumDistance; protected final Class<? extends EntityLiving>[] targetClasses; @SuppressWarnings("unchecked") protected AITargetBehaviorEx(int priority, int maximumNoEyeContactTicks, boolean ignoreInvulnerability, double maximumDistance, Class<? extends LivingEntity>[] targetClasses) throws IllegalArgumentException { super(priority); if(targetClasses==null) throw new IllegalArgumentException("targetClasses must not be null"); if(targetClasses.length==0) throw new IllegalArgumentException("targetClasses must not be empty"); this.maximumNoEyeContactTicks = maximumNoEyeContactTicks; this.ignoreInvulnerability = ignoreInvulnerability; this.maximumDistance = maximumDistance; this.targetClasses = new Class[targetClasses.length]; for(int i=0; i<targetClasses.length; i++) {
this.targetClasses[i] = (Class<? extends EntityLiving>) ControllableMobHelper.getNmsEntityClass(targetClasses[i]);
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionLookEntity.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // }
import net.minecraft.server.v1_7_R1.World; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftEntity; import org.bukkit.entity.Entity; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob;
package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionLookEntity extends ControllableMobActionLook { private final net.minecraft.server.v1_7_R1.Entity entity;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionLookEntity.java import net.minecraft.server.v1_7_R1.World; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftEntity; import org.bukkit.entity.Entity; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob; package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionLookEntity extends ControllableMobActionLook { private final net.minecraft.server.v1_7_R1.Entity entity;
public ControllableMobActionLookEntity(final CraftControllableMob<?> mob, final Entity entity) {
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionDie.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // }
import net.minecraft.server.v1_7_R1.DamageSource; import net.minecraft.server.v1_7_R1.EntityLiving; import de.ntcomputer.minecraft.controllablemobs.api.actions.ActionType; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob;
package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionDie extends ControllableMobActionBase { private final EntityLiving entity;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionDie.java import net.minecraft.server.v1_7_R1.DamageSource; import net.minecraft.server.v1_7_R1.EntityLiving; import de.ntcomputer.minecraft.controllablemobs.api.actions.ActionType; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob; package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionDie extends ControllableMobActionBase { private final EntityLiving entity;
public ControllableMobActionDie(final CraftControllableMob<?> mob) {
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionTarget.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // }
import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.api.actions.ActionType; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob;
package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionTarget extends ControllableMobActionBase { public final EntityLiving target;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionTarget.java import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.api.actions.ActionType; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob; package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionTarget extends ControllableMobActionBase { public final EntityLiving target;
public ControllableMobActionTarget(final CraftControllableMob<?> mob, final LivingEntity target) throws IllegalArgumentException {
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/ai/CraftAIPart.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ai/AIType.java // public enum AIType { // ATTACK_RANGED(PathfinderGoalArrowAttack.class), // MOVE_AVOIDPLAYER(PathfinderGoalAvoidPlayer.class), // ACTION_BEG(PathfinderGoalBeg.class), // ACTION_DOORBREAK(PathfinderGoalBreakDoor.class), // ACTION_BREED(PathfinderGoalBreed.class), // ACTION_DEFENDVILLAGE(PathfinderGoalDefendVillage.class), // ACTION_EATTILE(PathfinderGoalEatTile.class), // MOVE_FLEESUN(PathfinderGoalFleeSun.class), // MOVE_SWIM(PathfinderGoalFloat.class), // MOVE_FOLLOWONWNER(PathfinderGoalFollowOwner.class), // MOVE_FOLLOWPARENT(PathfinderGoalFollowParent.class), // TARGET_HURTBY(PathfinderGoalHurtByTarget.class), // ACTION_ENTITYINTERACT(PathfinderGoalInteract.class), // MOVE_JUMPONBLOCK(PathfinderGoalJumpOnBlock.class), // ATTACK_LEAP(PathfinderGoalLeapAtTarget.class), // ACTION_ENTITYLOOK(PathfinderGoalLookAtPlayer.class), // ACTION_PLAYERTRADINGLOOK(PathfinderGoalLookAtTradingPlayer.class), // ACTION_LOVE(PathfinderGoalMakeLove.class), // ATTACK_MELEE(PathfinderGoalMeleeAttack.class), // MOVE_INDOORS(PathfinderGoalMoveIndoors.class), // MOVE_VILLAGE(PathfinderGoalMoveThroughVillage.class), // MOVE_RESTRICTED(PathfinderGoalMoveTowardsRestriction.class), // MOVE_TARGET(PathfinderGoalMoveTowardsTarget.class), // TARGET_NEAREST(PathfinderGoalNearestAttackableTarget.class), // ATTACK_OCELOT(PathfinderGoalOcelotAttack.class), // ACTION_FLOWEROFFER(PathfinderGoalOfferFlower.class), // ACTION_DOOROPEN(PathfinderGoalOpenDoor.class), // TARGET_OWNERATTACKER(PathfinderGoalOwnerHurtByTarget.class), // TARGET_OWNERTARGET(PathfinderGoalOwnerHurtTarget.class), // MOVE_PANIC(PathfinderGoalPanic.class), // MOVE_FOLLOWCARROT(PathfinderGoalPassengerCarrotStick.class), // ACTION_PLAY(PathfinderGoalPlay.class), // ACTION_RANDOMLOOK(PathfinderGoalRandomLookaround.class), // MOVE_RANDOMSTROLL(PathfinderGoalRandomStroll.class), // TARGET_NEARESTNONTAMED(PathfinderGoalRandomTargetNonTamed.class), // MOVE_RESTRICTOPENDOOR(PathfinderGoalRestrictOpenDoor.class), // MOVE_RESTRICTSUN(PathfinderGoalRestrictSun.class), // ACTION_SIT(PathfinderGoalSit.class), // ATTACK_SWELL(PathfinderGoalSwell.class), // ACTION_FLOWERTAKE(PathfinderGoalTakeFlower.class), // ACTION_TAME(PathfinderGoalTame.class), // ACTION_TEMPT(PathfinderGoalTempt.class), // ACTION_PLAYERTRADE(PathfinderGoalTradeWithPlayer.class), // UNKNOWN(null); // // private final Class<? extends PathfinderGoal> nmsPathfinderClass; // // private AIType(Class<? extends PathfinderGoal> pfgClass) { // this.nmsPathfinderClass = pfgClass; // } // // // private static final Map<Class<? extends PathfinderGoal>,AIType> classTypeMap; // // static { // classTypeMap = new HashMap<Class<? extends PathfinderGoal>,AIType>(); // for(AIType type: AIType.values()) { // if(type!=AIType.UNKNOWN) classTypeMap.put(type.nmsPathfinderClass, type); // } // } // // /** // * You won't need this. But the API implementation will. // */ // public static AIType getTypeByInstance(PathfinderGoal goal) { // if(classTypeMap.containsKey(goal.getClass())) return classTypeMap.get(goal.getClass()); // else return AIType.UNKNOWN; // } // // } // // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ai/behaviors/AIBehavior.java // public abstract class AIBehavior<E extends LivingEntity> { // private final int priority; // // public AIBehavior(int priority) { // this.priority = priority; // } // // public final int getPriority(int lastBehaviorPriority) { // return this.priority<=0 ? lastBehaviorPriority+1 : this.priority; // } // // /** // * @return the type of this behavior // */ // public abstract AIType getType(); // // public abstract PathfinderGoal createPathfinderGoal(CraftControllableMob<? extends E> mob); // // }
import net.minecraft.server.v1_7_R1.PathfinderGoal; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.api.ControllableMob; import de.ntcomputer.minecraft.controllablemobs.api.ai.AIPart; import de.ntcomputer.minecraft.controllablemobs.api.ai.AIState; import de.ntcomputer.minecraft.controllablemobs.api.ai.AIType; import de.ntcomputer.minecraft.controllablemobs.api.ai.behaviors.AIBehavior;
package de.ntcomputer.minecraft.controllablemobs.implementation.ai; public class CraftAIPart<E extends LivingEntity, B extends AIBehavior<? super E>> implements AIPart<E,B> { private final B behavior; final int priority;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ai/AIType.java // public enum AIType { // ATTACK_RANGED(PathfinderGoalArrowAttack.class), // MOVE_AVOIDPLAYER(PathfinderGoalAvoidPlayer.class), // ACTION_BEG(PathfinderGoalBeg.class), // ACTION_DOORBREAK(PathfinderGoalBreakDoor.class), // ACTION_BREED(PathfinderGoalBreed.class), // ACTION_DEFENDVILLAGE(PathfinderGoalDefendVillage.class), // ACTION_EATTILE(PathfinderGoalEatTile.class), // MOVE_FLEESUN(PathfinderGoalFleeSun.class), // MOVE_SWIM(PathfinderGoalFloat.class), // MOVE_FOLLOWONWNER(PathfinderGoalFollowOwner.class), // MOVE_FOLLOWPARENT(PathfinderGoalFollowParent.class), // TARGET_HURTBY(PathfinderGoalHurtByTarget.class), // ACTION_ENTITYINTERACT(PathfinderGoalInteract.class), // MOVE_JUMPONBLOCK(PathfinderGoalJumpOnBlock.class), // ATTACK_LEAP(PathfinderGoalLeapAtTarget.class), // ACTION_ENTITYLOOK(PathfinderGoalLookAtPlayer.class), // ACTION_PLAYERTRADINGLOOK(PathfinderGoalLookAtTradingPlayer.class), // ACTION_LOVE(PathfinderGoalMakeLove.class), // ATTACK_MELEE(PathfinderGoalMeleeAttack.class), // MOVE_INDOORS(PathfinderGoalMoveIndoors.class), // MOVE_VILLAGE(PathfinderGoalMoveThroughVillage.class), // MOVE_RESTRICTED(PathfinderGoalMoveTowardsRestriction.class), // MOVE_TARGET(PathfinderGoalMoveTowardsTarget.class), // TARGET_NEAREST(PathfinderGoalNearestAttackableTarget.class), // ATTACK_OCELOT(PathfinderGoalOcelotAttack.class), // ACTION_FLOWEROFFER(PathfinderGoalOfferFlower.class), // ACTION_DOOROPEN(PathfinderGoalOpenDoor.class), // TARGET_OWNERATTACKER(PathfinderGoalOwnerHurtByTarget.class), // TARGET_OWNERTARGET(PathfinderGoalOwnerHurtTarget.class), // MOVE_PANIC(PathfinderGoalPanic.class), // MOVE_FOLLOWCARROT(PathfinderGoalPassengerCarrotStick.class), // ACTION_PLAY(PathfinderGoalPlay.class), // ACTION_RANDOMLOOK(PathfinderGoalRandomLookaround.class), // MOVE_RANDOMSTROLL(PathfinderGoalRandomStroll.class), // TARGET_NEARESTNONTAMED(PathfinderGoalRandomTargetNonTamed.class), // MOVE_RESTRICTOPENDOOR(PathfinderGoalRestrictOpenDoor.class), // MOVE_RESTRICTSUN(PathfinderGoalRestrictSun.class), // ACTION_SIT(PathfinderGoalSit.class), // ATTACK_SWELL(PathfinderGoalSwell.class), // ACTION_FLOWERTAKE(PathfinderGoalTakeFlower.class), // ACTION_TAME(PathfinderGoalTame.class), // ACTION_TEMPT(PathfinderGoalTempt.class), // ACTION_PLAYERTRADE(PathfinderGoalTradeWithPlayer.class), // UNKNOWN(null); // // private final Class<? extends PathfinderGoal> nmsPathfinderClass; // // private AIType(Class<? extends PathfinderGoal> pfgClass) { // this.nmsPathfinderClass = pfgClass; // } // // // private static final Map<Class<? extends PathfinderGoal>,AIType> classTypeMap; // // static { // classTypeMap = new HashMap<Class<? extends PathfinderGoal>,AIType>(); // for(AIType type: AIType.values()) { // if(type!=AIType.UNKNOWN) classTypeMap.put(type.nmsPathfinderClass, type); // } // } // // /** // * You won't need this. But the API implementation will. // */ // public static AIType getTypeByInstance(PathfinderGoal goal) { // if(classTypeMap.containsKey(goal.getClass())) return classTypeMap.get(goal.getClass()); // else return AIType.UNKNOWN; // } // // } // // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/api/ai/behaviors/AIBehavior.java // public abstract class AIBehavior<E extends LivingEntity> { // private final int priority; // // public AIBehavior(int priority) { // this.priority = priority; // } // // public final int getPriority(int lastBehaviorPriority) { // return this.priority<=0 ? lastBehaviorPriority+1 : this.priority; // } // // /** // * @return the type of this behavior // */ // public abstract AIType getType(); // // public abstract PathfinderGoal createPathfinderGoal(CraftControllableMob<? extends E> mob); // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/ai/CraftAIPart.java import net.minecraft.server.v1_7_R1.PathfinderGoal; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.api.ControllableMob; import de.ntcomputer.minecraft.controllablemobs.api.ai.AIPart; import de.ntcomputer.minecraft.controllablemobs.api.ai.AIState; import de.ntcomputer.minecraft.controllablemobs.api.ai.AIType; import de.ntcomputer.minecraft.controllablemobs.api.ai.behaviors.AIBehavior; package de.ntcomputer.minecraft.controllablemobs.implementation.ai; public class CraftAIPart<E extends LivingEntity, B extends AIBehavior<? super E>> implements AIPart<E,B> { private final B behavior; final int priority;
private final AIType type;
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionFollow.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // }
import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.api.actions.ActionType; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob;
package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionFollow extends ControllableMobActionBase { public final EntityLiving target; public final float maximumDistanceSquared; public final float minimumDistanceSquared;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/CraftControllableMob.java // public class CraftControllableMob<E extends LivingEntity> implements ControllableMob<E> { // private E entity; // private CraftControllableMobAttributes attributes; // private CraftControllableMobAI<E> ai; // private CraftControllableMobActions actions; // public EntityInsentient nmsEntity; // // public CraftControllableMob(E entity, EntityInsentient notchEntity) { // this.entity = entity; // this.nmsEntity = notchEntity; // this.attributes = new CraftControllableMobAttributes(this); // this.actions = new CraftControllableMobActions(this); // this.ai = new CraftControllableMobAI<E>(this); // } // // private void disposedCall() throws IllegalStateException { // throw new IllegalStateException("[ControllableMobsAPI] the ControllableMob is unassigned"); // } // // public void unassign(boolean resetAttributes) { // if(this.entity==null) this.disposedCall(); // // // component dispose // this.actions.dispose(); // this.ai.dispose(); // this.attributes.dispose(resetAttributes); // // // component disposal // this.actions = null; // this.ai = null; // this.attributes = null; // // // entity unassign // this.nmsEntity = null; // this.entity = null; // } // // public ControllableMobActionManager getActionManager() { // return this.actions.actionManager; // } // // public void adjustMaximumNavigationDistance(double forDistance) { // this.attributes.adjustMaximumNavigationDistance(forDistance); // } // // // @Override // public E getEntity() { // return entity; // } // // @Override // public ControllableMobAI<E> getAI() { // if(this.ai==null) this.disposedCall(); // return this.ai; // } // // @Override // public ControllableMobActions getActions() { // if(this.actions==null) this.disposedCall(); // return this.actions; // } // // @Override // public String toString() { // if(this.entity==null) return "ControllableMob<[unassigned]>"; // else return "ControllableMob<"+this.entity.toString()+">"; // } // // @Override // public ControllableMobAttributes getAttributes() { // if(this.attributes==null) this.disposedCall(); // return this.attributes; // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/actions/ControllableMobActionFollow.java import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import de.ntcomputer.minecraft.controllablemobs.api.actions.ActionType; import de.ntcomputer.minecraft.controllablemobs.implementation.CraftControllableMob; package de.ntcomputer.minecraft.controllablemobs.implementation.actions; public class ControllableMobActionFollow extends ControllableMobActionBase { public final EntityLiving target; public final float maximumDistanceSquared; public final float minimumDistanceSquared;
public ControllableMobActionFollow(final CraftControllableMob<?> mob, final LivingEntity target, final float maximumDistance, final float minimumDistance) throws IllegalArgumentException {
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/attributes/CraftAttributeModifier.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // }
import java.util.HashSet; import java.util.Set; import java.util.UUID; import de.ntcomputer.minecraft.controllablemobs.api.attributes.Attribute; import de.ntcomputer.minecraft.controllablemobs.api.attributes.AttributeModifier; import de.ntcomputer.minecraft.controllablemobs.api.attributes.ModifyOperation; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces;
package de.ntcomputer.minecraft.controllablemobs.implementation.attributes; public class CraftAttributeModifier implements AttributeModifier { private final UUID uniqueID; private final String name; private final double value; private final ModifyOperation operation; private net.minecraft.server.v1_7_R1.AttributeModifier nativeModifier = null; private final Set<CraftAttribute> attachedAttributes = new HashSet<CraftAttribute>(); private final boolean custom; public CraftAttributeModifier(UUID uniqueID, String name, double modifierValue, ModifyOperation operation) { this.uniqueID = uniqueID; this.name = name; this.value = modifierValue; this.operation = operation; this.custom = true; } public CraftAttributeModifier(UUID uuid, net.minecraft.server.v1_7_R1.AttributeModifier nativeModifier) { this.uniqueID = uuid; this.nativeModifier = nativeModifier;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/attributes/CraftAttributeModifier.java import java.util.HashSet; import java.util.Set; import java.util.UUID; import de.ntcomputer.minecraft.controllablemobs.api.attributes.Attribute; import de.ntcomputer.minecraft.controllablemobs.api.attributes.AttributeModifier; import de.ntcomputer.minecraft.controllablemobs.api.attributes.ModifyOperation; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces; package de.ntcomputer.minecraft.controllablemobs.implementation.attributes; public class CraftAttributeModifier implements AttributeModifier { private final UUID uniqueID; private final String name; private final double value; private final ModifyOperation operation; private net.minecraft.server.v1_7_R1.AttributeModifier nativeModifier = null; private final Set<CraftAttribute> attachedAttributes = new HashSet<CraftAttribute>(); private final boolean custom; public CraftAttributeModifier(UUID uniqueID, String name, double modifierValue, ModifyOperation operation) { this.uniqueID = uniqueID; this.name = name; this.value = modifierValue; this.operation = operation; this.custom = true; } public CraftAttributeModifier(UUID uuid, net.minecraft.server.v1_7_R1.AttributeModifier nativeModifier) { this.uniqueID = uuid; this.nativeModifier = nativeModifier;
this.name = NativeInterfaces.ATTRIBUTEMODIFIER.METHOD_GETNAME.invoke(nativeModifier);
DevCybran/Controllable-Mobs-API
src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/attributes/CraftAttribute.java
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // }
import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import net.minecraft.server.v1_7_R1.AttributeModifiable; import net.minecraft.server.v1_7_R1.AttributeRanged; import de.ntcomputer.minecraft.controllablemobs.api.attributes.Attribute; import de.ntcomputer.minecraft.controllablemobs.api.attributes.AttributeModifier; import de.ntcomputer.minecraft.controllablemobs.api.attributes.ModifyOperation; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces;
package de.ntcomputer.minecraft.controllablemobs.implementation.attributes; public final class CraftAttribute implements Attribute { private static final Set<CraftAttribute> attributes = new HashSet<CraftAttribute>(); private static final Map<UUID,CraftAttributeModifier> modifierMap = new HashMap<UUID,CraftAttributeModifier>(); private AttributeModifiable nativeAttribute; private AttributeRanged nativeAttributeTemplate; private final double defaultBasisValue; public static void registerCustomModifier(CraftAttributeModifier modifier) { modifierMap.put(modifier.getUniqueID(), modifier); for(CraftAttribute attribute: attributes) { if(attribute.hasModifierAttached(modifier)) { modifier.setAttributeAttached(attribute); } } } public CraftAttribute(AttributeModifiable nativeAttribute) { this.nativeAttribute = nativeAttribute;
// Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/nativeinterfaces/NativeInterfaces.java // public final class NativeInterfaces { // public static final NmsControllerJump CONTROLLERJUMP = new NmsControllerJump(); // public static final NmsControllerLook CONTROLLERLOOK = new NmsControllerLook(); // public static final NmsEntity ENTITY = new NmsEntity(); // public static final CBInterfaceJavaPluginLoader JAVAPLUGINLOADER = new CBInterfaceJavaPluginLoader(); // public static final NmsNavigation NAVIGATION = new NmsNavigation(); // public static final NmsInterfacePathfinderGoal PATHFINDERGOAL = new NmsInterfacePathfinderGoal(); // public static final NmsPathfinderGoalSelector PATHFINDERGOALSELECTOR = new NmsPathfinderGoalSelector(); // public static final NmsPathfinderGoalSelectorItem PATHFINDERGOALSELECTORITEM = new NmsPathfinderGoalSelectorItem(); // public static final CBInterfacePluginClassLoader PLUGINCLASSLOADER = new CBInterfacePluginClassLoader(); // public static final NmsWorld WORLD = new NmsWorld(); // public static final NmsIAttribute IATTRIBUTE = new NmsIAttribute(); // public static final NmsAttributeRanged ATTRIBUTERANGED = new NmsAttributeRanged(); // public static final NmsAttributeModifiable ATTRIBUTEMODIFIABLE = new NmsAttributeModifiable(); // public static final NmsAttributeModifier ATTRIBUTEMODIFIER = new NmsAttributeModifier(); // public static final NmsGenericAttributes GENERICATTRIBUTES = new NmsGenericAttributes(); // public static final NmsEntityInsentient ENTITYINSENTIENT = new NmsEntityInsentient(); // public static final NmsEntityTypes ENTITYTYPES = new NmsEntityTypes(); // // private NativeInterfaces() { // throw new AssertionError(); // } // // } // Path: src/main/java/de/ntcomputer/minecraft/controllablemobs/implementation/attributes/CraftAttribute.java import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import net.minecraft.server.v1_7_R1.AttributeModifiable; import net.minecraft.server.v1_7_R1.AttributeRanged; import de.ntcomputer.minecraft.controllablemobs.api.attributes.Attribute; import de.ntcomputer.minecraft.controllablemobs.api.attributes.AttributeModifier; import de.ntcomputer.minecraft.controllablemobs.api.attributes.ModifyOperation; import de.ntcomputer.minecraft.controllablemobs.implementation.nativeinterfaces.NativeInterfaces; package de.ntcomputer.minecraft.controllablemobs.implementation.attributes; public final class CraftAttribute implements Attribute { private static final Set<CraftAttribute> attributes = new HashSet<CraftAttribute>(); private static final Map<UUID,CraftAttributeModifier> modifierMap = new HashMap<UUID,CraftAttributeModifier>(); private AttributeModifiable nativeAttribute; private AttributeRanged nativeAttributeTemplate; private final double defaultBasisValue; public static void registerCustomModifier(CraftAttributeModifier modifier) { modifierMap.put(modifier.getUniqueID(), modifier); for(CraftAttribute attribute: attributes) { if(attribute.hasModifierAttached(modifier)) { modifier.setAttributeAttached(attribute); } } } public CraftAttribute(AttributeModifiable nativeAttribute) { this.nativeAttribute = nativeAttribute;
this.nativeAttributeTemplate = (AttributeRanged) NativeInterfaces.ATTRIBUTEMODIFIABLE.METHOD_GETATTRIBUTETEMPLATE.invoke(nativeAttribute);
spinnaker/fiat
fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java // public enum Authorization { // READ, // WRITE, // EXECUTE, // CREATE; // // public static final Set<Authorization> ALL = // Collections.unmodifiableSet(EnumSet.allOf(Authorization.class)); // }
import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.spinnaker.fiat.model.Authorization; import java.util.HashMap; import java.util.Map; import java.util.Set; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component;
/* * Copyright 2016 Google, Inc. * * 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 com.netflix.spinnaker.fiat.model.resources; @Component @Data @EqualsAndHashCode(callSuper = false) public class Application extends BaseAccessControlled<Application> implements Viewable { final ResourceType resourceType = ResourceType.APPLICATION; private String name; private Permissions permissions = Permissions.EMPTY; private Map<String, Object> details = new HashMap<>(); @JsonAnySetter public void setDetails(String name, Object value) { this.details.put(name, value); } @JsonIgnore public View getView(Set<Role> userRoles, boolean isAdmin) { return new View(this, userRoles, isAdmin); } @Data @EqualsAndHashCode(callSuper = false) @NoArgsConstructor public static class View extends BaseView implements Authorizable { String name;
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java // public enum Authorization { // READ, // WRITE, // EXECUTE, // CREATE; // // public static final Set<Authorization> ALL = // Collections.unmodifiableSet(EnumSet.allOf(Authorization.class)); // } // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.spinnaker.fiat.model.Authorization; import java.util.HashMap; import java.util.Map; import java.util.Set; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; /* * Copyright 2016 Google, Inc. * * 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 com.netflix.spinnaker.fiat.model.resources; @Component @Data @EqualsAndHashCode(callSuper = false) public class Application extends BaseAccessControlled<Application> implements Viewable { final ResourceType resourceType = ResourceType.APPLICATION; private String name; private Permissions permissions = Permissions.EMPTY; private Map<String, Object> details = new HashMap<>(); @JsonAnySetter public void setDetails(String name, Object value) { this.details.put(name, value); } @JsonIgnore public View getView(Set<Role> userRoles, boolean isAdmin) { return new View(this, userRoles, isAdmin); } @Data @EqualsAndHashCode(callSuper = false) @NoArgsConstructor public static class View extends BaseView implements Authorizable { String name;
Set<Authorization> authorizations;
spinnaker/fiat
fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/FiatServerConfigurationProperties.java
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java // public enum Authorization { // READ, // WRITE, // EXECUTE, // CREATE; // // public static final Set<Authorization> ALL = // Collections.unmodifiableSet(EnumSet.allOf(Authorization.class)); // }
import com.netflix.spinnaker.fiat.model.Authorization; import java.util.ArrayList; import java.util.List; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty;
/* * Copyright 2016 Google, Inc. * * 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 com.netflix.spinnaker.fiat.config; @Data @ConfigurationProperties("fiat") public class FiatServerConfigurationProperties { /** True if the /authorize endpoint should be available to dump all users in the repo. */ private boolean getAllEnabled = false; private boolean defaultToUnrestrictedUser = false; /** * If a request for user permissions comes through `/authorize` and fails to find stored * permissions, enable this flag to fallback to looking up user permissions from the underlying * {@link com.netflix.spinnaker.fiat.permissions.PermissionsResolver} implementation. */ private boolean allowPermissionResolverFallback = false; private boolean allowAccessToUnknownApplications = false;
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java // public enum Authorization { // READ, // WRITE, // EXECUTE, // CREATE; // // public static final Set<Authorization> ALL = // Collections.unmodifiableSet(EnumSet.allOf(Authorization.class)); // } // Path: fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/FiatServerConfigurationProperties.java import com.netflix.spinnaker.fiat.model.Authorization; import java.util.ArrayList; import java.util.List; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /* * Copyright 2016 Google, Inc. * * 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 com.netflix.spinnaker.fiat.config; @Data @ConfigurationProperties("fiat") public class FiatServerConfigurationProperties { /** True if the /authorize endpoint should be available to dump all users in the repo. */ private boolean getAllEnabled = false; private boolean defaultToUnrestrictedUser = false; /** * If a request for user permissions comes through `/authorize` and fails to find stored * permissions, enable this flag to fallback to looking up user permissions from the underlying * {@link com.netflix.spinnaker.fiat.permissions.PermissionsResolver} implementation. */ private boolean allowPermissionResolverFallback = false; private boolean allowAccessToUnknownApplications = false;
private Authorization executeFallback = Authorization.READ;
spinnaker/fiat
fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ResourcePermissionSource.java
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java // @ToString // @EqualsAndHashCode // public class Permissions { // // public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap()); // // private final Map<Authorization, List<String>> permissions; // // private Permissions(Map<Authorization, List<String>> p) { // this.permissions = Collections.unmodifiableMap(p); // } // // /** // * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order // * to sanitize the input data (just in case). // */ // @JsonCreator // public static Permissions factory(Map<Authorization, List<String>> data) { // return new Builder().set(data).build(); // } // // /** Here specifically for Jackson serialization. */ // @JsonValue // private Map<Authorization, List<String>> getPermissions() { // return permissions; // } // // public Set<String> allGroups() { // return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); // } // // /** // * Determines whether this Permissions has any Authorizations with associated roles. // * // * @return whether this Permissions has any Authorizations with associated roles // * @deprecated check {@code !isRestricted()} instead // */ // @Deprecated // public boolean isEmpty() { // return !isRestricted(); // } // // public boolean isRestricted() { // return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty()); // } // // public boolean isAuthorized(Set<Role> userRoles) { // return !getAuthorizations(userRoles).isEmpty(); // } // // public Set<Authorization> getAuthorizations(Set<Role> userRoles) { // val r = userRoles.stream().map(Role::getName).collect(Collectors.toList()); // return getAuthorizations(r); // } // // public Set<Authorization> getAuthorizations(List<String> userRoles) { // if (!isRestricted()) { // return Authorization.ALL; // } // // return this.permissions.entrySet().stream() // .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles)) // .map(Map.Entry::getKey) // .collect(Collectors.toSet()); // } // // public List<String> get(Authorization a) { // return permissions.getOrDefault(a, new ArrayList<>()); // } // // public Map<Authorization, List<String>> unpack() { // return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get)); // } // // /** // * This is a helper class for setting up an immutable Permissions object. It also acts as the // * target Java Object for Spring's ConfigurationProperties deserialization. // * // * <p>Objects should be defined on the account config like: // * // * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1 // * // * <p>Group/Role names are trimmed of whitespace and lowercased. // */ // public static class Builder extends LinkedHashMap<Authorization, List<String>> { // // private static Permissions fromMap(Map<Authorization, List<String>> authConfig) { // final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class); // for (Authorization auth : Authorization.values()) { // Optional.ofNullable(authConfig.get(auth)) // .map( // groups -> // groups.stream() // .map(String::trim) // .filter(s -> !s.isEmpty()) // .map(String::toLowerCase) // .collect(Collectors.toList())) // .filter(g -> !g.isEmpty()) // .map(Collections::unmodifiableList) // .ifPresent(roles -> perms.put(auth, roles)); // } // return new Permissions(perms); // } // // @JsonCreator // public static Builder factory(Map<Authorization, List<String>> data) { // return new Builder().set(data); // } // // public Builder set(Map<Authorization, List<String>> p) { // this.clear(); // this.putAll(p); // return this; // } // // public Builder add(Authorization a, String group) { // this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group); // return this; // } // // public Builder add(Authorization a, List<String> groups) { // groups.forEach(group -> add(a, group)); // return this; // } // // public Permissions build() { // final Permissions result = fromMap(this); // if (!result.isRestricted()) { // return Permissions.EMPTY; // } // return result; // } // } // }
import com.netflix.spinnaker.fiat.model.resources.Permissions; import com.netflix.spinnaker.fiat.model.resources.Resource; import javax.annotation.Nonnull;
/* * Copyright 2019 Netflix, Inc. * * 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 com.netflix.spinnaker.fiat.providers; /** * A ResourcePermissionSource is capable of resolving the Permissions for a specified Resource from * a specified single source. * * <p>Note that while the API signature matches ResourcePermissionProvider the intent of * ResourcePermissionSource is to model a single source of Permissions (for example CloudDriver as a * source of Account permissions), while ResourcePermissionProvider is responsible for supplying the * computed Permission considering all available ResourcePermissionSources. * * @param <T> the type of Resource this ResourcePermissionSource will supply Permissions for */ public interface ResourcePermissionSource<T extends Resource> { /** * Retrieves Permissions for the supplied resource. * * @param resource the resource for which to get permissions (never null) * @return the Permissions for the resource (never null - use Permissions.EMPTY or apply some * restriction) */ @Nonnull
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java // @ToString // @EqualsAndHashCode // public class Permissions { // // public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap()); // // private final Map<Authorization, List<String>> permissions; // // private Permissions(Map<Authorization, List<String>> p) { // this.permissions = Collections.unmodifiableMap(p); // } // // /** // * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order // * to sanitize the input data (just in case). // */ // @JsonCreator // public static Permissions factory(Map<Authorization, List<String>> data) { // return new Builder().set(data).build(); // } // // /** Here specifically for Jackson serialization. */ // @JsonValue // private Map<Authorization, List<String>> getPermissions() { // return permissions; // } // // public Set<String> allGroups() { // return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); // } // // /** // * Determines whether this Permissions has any Authorizations with associated roles. // * // * @return whether this Permissions has any Authorizations with associated roles // * @deprecated check {@code !isRestricted()} instead // */ // @Deprecated // public boolean isEmpty() { // return !isRestricted(); // } // // public boolean isRestricted() { // return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty()); // } // // public boolean isAuthorized(Set<Role> userRoles) { // return !getAuthorizations(userRoles).isEmpty(); // } // // public Set<Authorization> getAuthorizations(Set<Role> userRoles) { // val r = userRoles.stream().map(Role::getName).collect(Collectors.toList()); // return getAuthorizations(r); // } // // public Set<Authorization> getAuthorizations(List<String> userRoles) { // if (!isRestricted()) { // return Authorization.ALL; // } // // return this.permissions.entrySet().stream() // .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles)) // .map(Map.Entry::getKey) // .collect(Collectors.toSet()); // } // // public List<String> get(Authorization a) { // return permissions.getOrDefault(a, new ArrayList<>()); // } // // public Map<Authorization, List<String>> unpack() { // return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get)); // } // // /** // * This is a helper class for setting up an immutable Permissions object. It also acts as the // * target Java Object for Spring's ConfigurationProperties deserialization. // * // * <p>Objects should be defined on the account config like: // * // * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1 // * // * <p>Group/Role names are trimmed of whitespace and lowercased. // */ // public static class Builder extends LinkedHashMap<Authorization, List<String>> { // // private static Permissions fromMap(Map<Authorization, List<String>> authConfig) { // final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class); // for (Authorization auth : Authorization.values()) { // Optional.ofNullable(authConfig.get(auth)) // .map( // groups -> // groups.stream() // .map(String::trim) // .filter(s -> !s.isEmpty()) // .map(String::toLowerCase) // .collect(Collectors.toList())) // .filter(g -> !g.isEmpty()) // .map(Collections::unmodifiableList) // .ifPresent(roles -> perms.put(auth, roles)); // } // return new Permissions(perms); // } // // @JsonCreator // public static Builder factory(Map<Authorization, List<String>> data) { // return new Builder().set(data); // } // // public Builder set(Map<Authorization, List<String>> p) { // this.clear(); // this.putAll(p); // return this; // } // // public Builder add(Authorization a, String group) { // this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group); // return this; // } // // public Builder add(Authorization a, List<String> groups) { // groups.forEach(group -> add(a, group)); // return this; // } // // public Permissions build() { // final Permissions result = fromMap(this); // if (!result.isRestricted()) { // return Permissions.EMPTY; // } // return result; // } // } // } // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ResourcePermissionSource.java import com.netflix.spinnaker.fiat.model.resources.Permissions; import com.netflix.spinnaker.fiat.model.resources.Resource; import javax.annotation.Nonnull; /* * Copyright 2019 Netflix, Inc. * * 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 com.netflix.spinnaker.fiat.providers; /** * A ResourcePermissionSource is capable of resolving the Permissions for a specified Resource from * a specified single source. * * <p>Note that while the API signature matches ResourcePermissionProvider the intent of * ResourcePermissionSource is to model a single source of Permissions (for example CloudDriver as a * source of Account permissions), while ResourcePermissionProvider is responsible for supplying the * computed Permission considering all available ResourcePermissionSources. * * @param <T> the type of Resource this ResourcePermissionSource will supply Permissions for */ public interface ResourcePermissionSource<T extends Resource> { /** * Retrieves Permissions for the supplied resource. * * @param resource the resource for which to get permissions (never null) * @return the Permissions for the resource (never null - use Permissions.EMPTY or apply some * restriction) */ @Nonnull
Permissions getPermissions(@Nonnull T resource);
spinnaker/fiat
fiat-api/src/main/java/com/netflix/spinnaker/fiat/shared/FiatService.java
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/UserPermission.java // @Data // public class UserPermission { // private String id; // // private Set<Account> accounts = new LinkedHashSet<>(); // private Set<Application> applications = new LinkedHashSet<>(); // private Set<ServiceAccount> serviceAccounts = new LinkedHashSet<>(); // private Set<Role> roles = new LinkedHashSet<>(); // private Set<BuildService> buildServices = new LinkedHashSet<>(); // private Set<Resource> extensionResources = new LinkedHashSet<>(); // private boolean admin = false; // // /** // * Custom setter to normalize the input. lombok.accessors.chain is enabled, so setters must return // * {@code this}. // */ // public UserPermission setId(String id) { // this.id = id.toLowerCase(); // return this; // } // // /** Custom getter to normalize the output. */ // public String getId() { // return this.id.toLowerCase(); // } // // public void addResource(Resource resource) { // addResources(Collections.singleton(resource)); // } // // public UserPermission addResources(Collection<Resource> resources) { // if (resources == null) { // return this; // } // // resources.forEach( // resource -> { // if (resource instanceof Account) { // accounts.add((Account) resource); // } else if (resource instanceof Application) { // applications.add((Application) resource); // } else if (resource instanceof ServiceAccount) { // serviceAccounts.add((ServiceAccount) resource); // } else if (resource instanceof Role) { // roles.add((Role) resource); // } else if (resource instanceof BuildService) { // buildServices.add((BuildService) resource); // } else { // extensionResources.add(resource); // } // }); // // return this; // } // // @JsonIgnore // public Set<Resource> getAllResources() { // Set<Resource> retVal = new HashSet<>(); // retVal.addAll(accounts); // retVal.addAll(applications); // retVal.addAll(serviceAccounts); // retVal.addAll(roles); // retVal.addAll(buildServices); // retVal.addAll(extensionResources); // return retVal; // } // // /** // * This method adds all of other's resources to this one. // * // * @param other // */ // public UserPermission merge(UserPermission other) { // this.addResources(other.getAllResources()); // return this; // } // // @JsonIgnore // public View getView() { // return new View(this); // } // // @Data // @EqualsAndHashCode(callSuper = false) // @NoArgsConstructor // @SuppressWarnings("unchecked") // public static class View extends Viewable.BaseView { // String name; // Set<Account.View> accounts; // Set<Application.View> applications; // Set<ServiceAccount.View> serviceAccounts; // Set<Role.View> roles; // Set<BuildService.View> buildServices; // HashMap<ResourceType, Set<Authorizable>> extensionResources; // boolean admin; // boolean legacyFallback = false; // boolean allowAccessToUnknownApplications = false; // // public View(UserPermission permission) { // this.name = permission.id; // // Function<Set<? extends Viewable>, Set<? extends Viewable.BaseView>> toViews = // sourceSet -> // sourceSet.stream() // .map(viewable -> viewable.getView(permission.getRoles(), permission.isAdmin())) // .collect(Collectors.toSet()); // // this.accounts = (Set<Account.View>) toViews.apply(permission.getAccounts()); // this.applications = (Set<Application.View>) toViews.apply(permission.getApplications()); // this.serviceAccounts = // (Set<ServiceAccount.View>) toViews.apply(permission.getServiceAccounts()); // this.roles = (Set<Role.View>) toViews.apply(permission.getRoles()); // this.buildServices = (Set<BuildService.View>) toViews.apply(permission.getBuildServices()); // // this.extensionResources = new HashMap<>(); // for (val resource : permission.extensionResources) { // val set = // this.extensionResources.computeIfAbsent( // resource.getResourceType(), (ignore) -> new HashSet<>()); // val view = ((Viewable) resource).getView(permission.getRoles(), permission.isAdmin()); // if (view instanceof Authorizable) { // set.add((Authorizable) view); // } // } // // this.admin = permission.isAdmin(); // } // } // }
import com.netflix.spinnaker.fiat.model.UserPermission; import java.util.Collection; import java.util.List; import retrofit.client.Response; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path;
/* * Copyright 2016 Netflix, Inc. * * 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 com.netflix.spinnaker.fiat.shared; public interface FiatService { /** * @param userId The username of the user * @return The full UserPermission of the user. */ @GET("/authorize/{userId}")
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/UserPermission.java // @Data // public class UserPermission { // private String id; // // private Set<Account> accounts = new LinkedHashSet<>(); // private Set<Application> applications = new LinkedHashSet<>(); // private Set<ServiceAccount> serviceAccounts = new LinkedHashSet<>(); // private Set<Role> roles = new LinkedHashSet<>(); // private Set<BuildService> buildServices = new LinkedHashSet<>(); // private Set<Resource> extensionResources = new LinkedHashSet<>(); // private boolean admin = false; // // /** // * Custom setter to normalize the input. lombok.accessors.chain is enabled, so setters must return // * {@code this}. // */ // public UserPermission setId(String id) { // this.id = id.toLowerCase(); // return this; // } // // /** Custom getter to normalize the output. */ // public String getId() { // return this.id.toLowerCase(); // } // // public void addResource(Resource resource) { // addResources(Collections.singleton(resource)); // } // // public UserPermission addResources(Collection<Resource> resources) { // if (resources == null) { // return this; // } // // resources.forEach( // resource -> { // if (resource instanceof Account) { // accounts.add((Account) resource); // } else if (resource instanceof Application) { // applications.add((Application) resource); // } else if (resource instanceof ServiceAccount) { // serviceAccounts.add((ServiceAccount) resource); // } else if (resource instanceof Role) { // roles.add((Role) resource); // } else if (resource instanceof BuildService) { // buildServices.add((BuildService) resource); // } else { // extensionResources.add(resource); // } // }); // // return this; // } // // @JsonIgnore // public Set<Resource> getAllResources() { // Set<Resource> retVal = new HashSet<>(); // retVal.addAll(accounts); // retVal.addAll(applications); // retVal.addAll(serviceAccounts); // retVal.addAll(roles); // retVal.addAll(buildServices); // retVal.addAll(extensionResources); // return retVal; // } // // /** // * This method adds all of other's resources to this one. // * // * @param other // */ // public UserPermission merge(UserPermission other) { // this.addResources(other.getAllResources()); // return this; // } // // @JsonIgnore // public View getView() { // return new View(this); // } // // @Data // @EqualsAndHashCode(callSuper = false) // @NoArgsConstructor // @SuppressWarnings("unchecked") // public static class View extends Viewable.BaseView { // String name; // Set<Account.View> accounts; // Set<Application.View> applications; // Set<ServiceAccount.View> serviceAccounts; // Set<Role.View> roles; // Set<BuildService.View> buildServices; // HashMap<ResourceType, Set<Authorizable>> extensionResources; // boolean admin; // boolean legacyFallback = false; // boolean allowAccessToUnknownApplications = false; // // public View(UserPermission permission) { // this.name = permission.id; // // Function<Set<? extends Viewable>, Set<? extends Viewable.BaseView>> toViews = // sourceSet -> // sourceSet.stream() // .map(viewable -> viewable.getView(permission.getRoles(), permission.isAdmin())) // .collect(Collectors.toSet()); // // this.accounts = (Set<Account.View>) toViews.apply(permission.getAccounts()); // this.applications = (Set<Application.View>) toViews.apply(permission.getApplications()); // this.serviceAccounts = // (Set<ServiceAccount.View>) toViews.apply(permission.getServiceAccounts()); // this.roles = (Set<Role.View>) toViews.apply(permission.getRoles()); // this.buildServices = (Set<BuildService.View>) toViews.apply(permission.getBuildServices()); // // this.extensionResources = new HashMap<>(); // for (val resource : permission.extensionResources) { // val set = // this.extensionResources.computeIfAbsent( // resource.getResourceType(), (ignore) -> new HashSet<>()); // val view = ((Viewable) resource).getView(permission.getRoles(), permission.isAdmin()); // if (view instanceof Authorizable) { // set.add((Authorizable) view); // } // } // // this.admin = permission.isAdmin(); // } // } // } // Path: fiat-api/src/main/java/com/netflix/spinnaker/fiat/shared/FiatService.java import com.netflix.spinnaker.fiat.model.UserPermission; import java.util.Collection; import java.util.List; import retrofit.client.Response; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; /* * Copyright 2016 Netflix, Inc. * * 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 com.netflix.spinnaker.fiat.shared; public interface FiatService { /** * @param userId The username of the user * @return The full UserPermission of the user. */ @GET("/authorize/{userId}")
UserPermission.View getUserPermission(@Path("userId") String userId);