index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/TransportSettings.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; public class TransportSettings extends MadaraJNI { private native long jni_Settings(); private native long jni_Settings(long cptr); private static native void jni_freeSettings(long cptr); public TransportSettings() { setCPtr(jni_Settings()); } public TransportSettings(TransportSettings transportSettings) { setCPtr(jni_Settings(transportSettings.getCPtr())); } private native void jni_setWriteDomain(long cptr, String domains); private native String jni_getWriteDomain(long cptr); private native void jni_setQueueLength(long cptr, int queue_length); private native int jni_getQueueLength(long cptr); private native void jni_setResendAttempts(long cptr, int resends); private native int jni_getResendAttempts(long cptr); private native void jni_setDeadline(long cptr, int deadline); private native int jni_getDeadline(long cptr); private native void jni_setType(long cptr, int type); private native int jni_getType(long cptr); private native void jni_setReliability(long cptr, int reliability); private native int jni_getReliability(long cptr); private native void jni_setId(long cptr, int id); private native int jni_getId(long cptr); private native void jni_setProcesses(long cptr, int id); private native int jni_getProcesses(long cptr); private native void jni_setOnDataReceivedLogic(long cptr, String onDataReceivedLogic); private native String jni_getOnDataReceivedLogic(long cptr); private native void jni_setHosts(long cptr, String[] hosts); private native String[] jni_getHosts(long cptr); private native void jni_save(long cptr, java.lang.String filenmae); private native void jni_load(long cptr, java.lang.String filename); /** * Saves the transport settings as a KnowledgeBase to a file * * @param filename * the file to save the knowledge base to * @throws MadaraDeadObjectException * */ public void save(String filename) throws MadaraDeadObjectException { jni_save(getCPtr(), filename); } /** * Loads the transport settings from a KnowledgeBase context file * * @param filename * the file to save the knowledge base to * @throws MadaraDeadObjectException * */ public void load(String filename) throws MadaraDeadObjectException { jni_load(getCPtr(), filename); } public void setWriteDomain(String domains) throws MadaraDeadObjectException { jni_setWriteDomain(getCPtr(), domains); } public String getWriteDomain() throws MadaraDeadObjectException { return jni_getWriteDomain(getCPtr()); } public void setQueueLength(int queueLength) throws MadaraDeadObjectException { jni_setQueueLength(getCPtr(), queueLength); } public int getQueueLength() throws MadaraDeadObjectException { return jni_getQueueLength(getCPtr()); } public void setResendAttempts(int resends) throws MadaraDeadObjectException { jni_setResendAttempts(getCPtr(), resends); } public int getResendAttempts() throws MadaraDeadObjectException { return jni_getResendAttempts(getCPtr()); } public void setDeadline(int deadline) throws MadaraDeadObjectException { jni_setDeadline(getCPtr(), deadline); } public int getDeadline() throws MadaraDeadObjectException { return jni_getDeadline(getCPtr()); } public void setType(TransportType transport) throws MadaraDeadObjectException { jni_setType(getCPtr(), transport.value()); } public TransportType getType() throws MadaraDeadObjectException { return TransportType.getType(jni_getType(getCPtr())); } public void setReliability(TransportReliability r) throws MadaraDeadObjectException { jni_setReliability(getCPtr(), r.value()); } public TransportReliability getReliability() throws MadaraDeadObjectException { return TransportReliability.getReliability(jni_getReliability(getCPtr())); } public void setId(int id) throws MadaraDeadObjectException { jni_setId(getCPtr(), id); } public int getId() throws MadaraDeadObjectException { return jni_getId(getCPtr()); } public void setProcesses(int processes) throws MadaraDeadObjectException { jni_setProcesses(getCPtr(), processes); } public int getProcesses() throws MadaraDeadObjectException { return jni_getProcesses(getCPtr()); } public void setOnDataReceivedLogic(String onDataReceivedLogic) throws MadaraDeadObjectException { jni_setOnDataReceivedLogic(getCPtr(), onDataReceivedLogic); } public String getOnDataReceivedLogic() throws MadaraDeadObjectException { return jni_getOnDataReceivedLogic(getCPtr()); } public void setHosts(String[] hosts) throws MadaraDeadObjectException { jni_setHosts(getCPtr(), hosts); } public String[] getHosts() throws MadaraDeadObjectException { return jni_getHosts(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance of WaitSettings gets garbage collected */ public void free() { jni_freeSettings(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * * @throws Throwable * necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/TransportType.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport; public enum TransportType { NO_TRANSPORT(0), SPLICE_TRANSPORT(1), NDSS_TRANSPORT(2), TCP_TRANSPORT(3), UDP_TRANSPORT(4), MULTICAST_TRANSPORT(5), BROADCAST_TRANSPORT(6), REGISTRY_SERVER(7), REGISTRY_CLIENT(8), ZMQ_TRANSPORT(9), INCONSISTENT_TRANSPORT(100); private int num; private TransportType(int num) { this.num = num; } /** * Get the integer value of this enum * * @return value of the enum */ public int value() { return num; } public static TransportType getType(int val) { for (TransportType t : values()) { if (t.value() == val) return t; } return null; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/transport
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/filters/AggregateFilter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport.filters; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.Variables; import ai.madara.transport.TransportContext; public interface AggregateFilter { /** * Java implementation of a MADARA Aggregate Filter. <b>DO NOT</b> invoke methods on an instance of * {@link ai.madara.knowledge.KnowledgeBase KnowledgeBase} in this method * @param packet a map of all variable names to values * @param context information about current state of transport layer * @param variables facade for current knowledge base * @throws MadaraDeadObjectException **/ public void filter(Packet packet, TransportContext context, Variables variables) throws MadaraDeadObjectException; }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/transport
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/filters/EraseRecord.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport.filters; import ai.madara.knowledge.EvalSettings; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeList; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.KnowledgeType; import ai.madara.knowledge.Variables; import ai.madara.transport.QoSTransportSettings; import ai.madara.transport.TransportType; public class EraseRecord implements RecordFilter { /** * Removes the record from the packet * @param args {@link java.util.List List&lt;KnowledgeRecord&gt;} of * arguments passed to the function. args[0] is the value, * args[1] is name of record, args[2] is type of operation, * args[3] is send bandwidth used, args[4] is total bandwidth used, * args[5] is the send timestamp, args[6] is current timestamp, * args[7] is the knowledge domain * @param variables Local access to evaluate and compile methods * @return the unaltered record */ public KnowledgeRecord filter(KnowledgeList args, Variables variables) { return new KnowledgeRecord(); } public static void main (String [] args) throws InterruptedException, Exception { QoSTransportSettings settings = new QoSTransportSettings(); settings.setHosts(new String[]{"239.255.0.1:4150"}); settings.setType(TransportType.MULTICAST_TRANSPORT); System.out.println ("Adding individual erase record filter to receive."); settings.addReceiveFilter(KnowledgeType.ALL_TYPES, new LogRecord()); settings.addReceiveFilter(KnowledgeType.INTEGER, new EraseRecord()); settings.addReceiveFilter(new LogAggregate()); System.out.println ("Adding individual erase record filter to send."); settings.addSendFilter(KnowledgeType.ALL_TYPES, new LogRecord()); settings.addSendFilter(KnowledgeType.INTEGER, new EraseRecord()); settings.addSendFilter(new LogAggregate()); KnowledgeBase knowledge = new KnowledgeBase("", settings); EvalSettings delaySending = new EvalSettings(); delaySending.setDelaySendingModifieds(true); System.out.println ("Beginning to loop."); for(int i = 0; i < 10; ++i) { System.out.println("Sending an update."); if(args.length == 1 && args[0].equals("1")) { System.out.println("Agent is James Bond. Writing info."); knowledge.set("name1", "James Bond", delaySending); knowledge.set("age1", 45, delaySending); knowledge.set("weight1", 190.0); //knowledge.evaluate("name0=\"James Bond\"; age0=45; weight0=190.0"); } else { System.out.println("Agent is Alfred Bond. Writing info."); knowledge.set("name0", "Alfred Bond", delaySending); knowledge.set("age0", 20, delaySending); knowledge.set("weight0", 220.0); //knowledge.evaluate("name0=\"Alfred Bond\"; age0=20; weight0=220.0"); } java.lang.Thread.sleep(1000); } // print all knowledge knowledge.print(); if(args.length == 1 && args[0].equals("1")) { if(knowledge.exists("age0")) { System.out.println("FAIL: we received age0."); } else if(!knowledge.exists("name0")) { System.out.println("FAIL: did not receive info from agent 0."); } else { System.out.println("SUCCESS: we did not receive age0."); } } else { if(knowledge.exists("age1")) { System.out.println("FAIL: we received age0."); } else if(!knowledge.exists("name1")) { System.out.println("FAIL: did not receive info from agent 1."); } else { System.out.println("SUCCESS: we did not receive age1."); } } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/transport
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/filters/LogAggregate.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport.filters; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.Variables; import ai.madara.transport.TransportContext; public class LogAggregate implements AggregateFilter { /** * Types of operations **/ public String[] opTypes = { "IDLE_OPERATION", "SEND_OPERATION", "RECEIVE_OPERATION", "REBROADCAST_OPERATION" }; /** * Logger of all information * @param packet a collection of variable keys and values in the packet * @param context information about current state of transport layer * @param variables facade for current knowledge base * @throws MadaraDeadObjectException **/ public void filter(Packet packet, TransportContext context, Variables variables) throws MadaraDeadObjectException { StringBuffer buffer = new StringBuffer(); buffer.append("Aggregate Filter args:\n"); buffer.append(" Operation Type:"); int index = (int) context.getOperation(); if (index < opTypes.length) { buffer.append(opTypes[index]); } buffer.append("\n"); buffer.append(" Send bandwidth:"); buffer.append(context.getSendBandwidth()); buffer.append(" B/s\n"); buffer.append(" Recv bandwidth:"); buffer.append(context.getReceiveBandwidth()); buffer.append(" B/s\n"); buffer.append(" Update Time:"); buffer.append(context.getMessageTime()); buffer.append("\n"); buffer.append(" Current Time:"); buffer.append(context.getCurrentTime()); buffer.append("\n"); buffer.append(" Domain:"); buffer.append(context.getDomain()); buffer.append("\n"); buffer.append(" Updates:\n"); String [] keys = packet.getKeys(); for(int i = 0; i < keys.length; ++i) { buffer.append(" "); buffer.append(keys[i]); buffer.append("="); buffer.append(packet.get(keys[i])); buffer.append("\n"); } buffer.append("\n"); System.out.println(buffer.toString()); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/transport
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/filters/LogRecord.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport.filters; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeList; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.Variables; public class LogRecord implements RecordFilter { /** * Types of operations **/ public String[] opTypes = { "IDLE_OPERATION", "SEND_OPERATION", "RECEIVE_OPERATION", "REBROADCAST_OPERATION" }; /** * Filters a single knowledge update. * @param args {@link java.util.List List&lt;KnowledgeRecord&gt;} of * arguments passed to the function. args[0] is the value, * args[1] is name of record, args[2] is type of operation, * args[3] is send bandwidth used, args[4] is total bandwidth used, * args[5] is the send timestamp, args[6] is current timestamp, * args[7] is the knowledge domain * @param variables Local access to evaluate and compile methods * @return the unaltered record * @throws MadaraDeadObjectException */ public KnowledgeRecord filter(KnowledgeList args, Variables variables) throws MadaraDeadObjectException { StringBuffer buffer = new StringBuffer(); buffer.append("Filter args:\n"); buffer.append(" [0:Record]: "); buffer.append(args.get(0).toString()); buffer.append("\n"); buffer.append(" [1:Record Name]: "); buffer.append(args.get(1).toString()); buffer.append("\n"); buffer.append(" [2:Operation Type]: "); int index = (int) args.get(2).toLong(); if (index < opTypes.length) { buffer.append(opTypes[index]); } buffer.append("\n"); buffer.append(" [3:Send Bandwidth]: "); buffer.append(args.get(3).toString()); buffer.append(" B/s\n"); buffer.append(" [4:Recv Bandwidth]: "); buffer.append(args.get(4).toString()); buffer.append(" B/s\n"); buffer.append(" [5:Update Time]: "); buffer.append(args.get(5).toString()); buffer.append("\n"); buffer.append(" [6:Current Time]: "); buffer.append(args.get(6).toString()); buffer.append("\n"); buffer.append(" [7:Domain]: "); buffer.append(args.get(7).toString()); buffer.append("\n"); buffer.append(" [8:Originator]: "); buffer.append(args.get(8).toString()); buffer.append("\n"); System.out.println(buffer.toString()); return args.get(0); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/transport
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/filters/Packet.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport.filters; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeRecord; public class Packet extends MadaraJNI { private native long jni_get(long cptr, java.lang.String index); private native void jni_set(long cptr, java.lang.String index, long record); private native java.lang.String[] jni_get_keys(long cptr); private native boolean jni_exists(long cptr, java.lang.String index); private native void jni_clear(long cptr); private native void jni_erase(long cptr, java.lang.String index); /** * Only constructor comes from the JNI side **/ private Packet() { } /** * Creates a {@link ai.madara.knowledge.Variables Variables} from a pointer * * @param cptr C pointer to a Variables object * @return new {@link ai.madara.knowledge.Variables Variables} */ public static Packet fromPointer(long cptr) { Packet ret = new Packet(); ret.setCPtr(cptr); return ret; } /** * Gets the record at the specified index * @param index the index of the record * @return the record at the index **/ public KnowledgeRecord get(java.lang.String index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_get(getCPtr(),index)); } /** * Clears all records from the packet **/ public void clear() throws MadaraDeadObjectException { jni_clear(getCPtr()); } /** * Erases the record at the specified index * @param index the index of the record **/ public void erase(java.lang.String index) throws MadaraDeadObjectException { jni_erase(getCPtr(),index); } /** * Checks if there is a record at the specified index * @param index the index of the record * @return true if the index exists in the packet **/ public boolean exists(java.lang.String index) throws MadaraDeadObjectException { return jni_exists(getCPtr(),index); } /** * Sets the record at the specified index * @param index the index of the record * @param record the record to set at the index **/ public void set(java.lang.String index, KnowledgeRecord record) throws MadaraDeadObjectException { jni_set(getCPtr(), index, record.getCPtr()); } /** * Gets all keys in the packet * @return the array of all keys in the packet **/ public String[] getKeys() throws MadaraDeadObjectException { return jni_get_keys(getCPtr()); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/transport
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/filters/RecordFilter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport.filters; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeList; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.Variables; public interface RecordFilter { /** * Filters a single knowledge update. * @param args {@link java.util.List List&lt;KnowledgeRecord&gt;} of * arguments passed to the function. args[0] is the value, * args[1] is name of record, args[2] is type of operation, * args[3] is send bandwidth used, args[4] is total bandwidth used, * args[5] is the send timestamp, args[6] is current timestamp, * args[7] is the knowledge domain * @param variables Local access to evaluate and compile methods * @return A {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecord} containing the result of the function * @throws MadaraDeadObjectException */ public KnowledgeRecord filter(KnowledgeList args, Variables variables) throws MadaraDeadObjectException; }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/util/JNILoader.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.util; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.security.CodeSource; import java.security.MessageDigest; import java.util.Properties; /** * JNILoader is used to load native libraries at runtime when they exist * inside a jar file. On android, it assumes the files are in libs/armeabi */ public class JNILoader { //We use the OS name and arch in a few places private static final String OS_NAME; private static final String OS_ARCH; private static final String CHECKSUM; //Everything gets ignored if we are on Android private static final boolean IS_ANDROID; static { Properties props = System.getProperties(); OS_NAME = props.getProperty("os.name").toLowerCase().replace(" ", ""); OS_ARCH = props.getProperty("os.arch"); String vmName = System.getProperty("java.vm.name"); IS_ANDROID = vmName != null && vmName.contains("Dalvik"); String checksumResult = null; try { CodeSource src = JNILoader.class.getProtectionDomain().getCodeSource(); if (src.getLocation().toString().endsWith(".jar")) { InputStream in = src.getLocation().openStream(); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[1024]; int count = 0; while ((count = in.read(buffer)) > 0) md.update(buffer, 0, count); byte[] checksum = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : checksum) sb.append(Integer.toHexString(b & 0xFF)); checksumResult = sb.toString(); if (checksumResult != null && checksumResult.length() == 0) checksumResult = null; } } catch (Exception e) { e.printStackTrace(); } finally { CHECKSUM = checksumResult; } } /** * Loads a library by name as long as the preconditions are met. * <br> * The library is in lib/os_name/os_arch inside the jar file * <br> * the os_name folder is lower case and has spaces removed * <br> * The library follows proper naming (ie. libTest.so, libTest.dylib, Test.dll) * * @param library The name of the library to load */ @Deprecated public static void load(String library) { System.loadLibrary(library); if (true) return; //If it is android, we have to assume library files are already in libs/armeabi if (IS_ANDROID) { System.loadLibrary(library); return; } //Resolve the library Lib lib = resolve(library); if (lib == null) return; //Extract the library String extractedPath = extract(lib); System.out.println("Loading: " + extractedPath); //If it extracted properly, load it if (extractedPath != null) System.load(extractedPath); } /** * Resolves a library's and opens an input stream to it * * @param library The library to resolve * @return Lib object containing name and input stream */ private static Lib resolve(String library) { //Get the properly formated name. This will return libTest.so/libTest.dylib/Test.dll etc String libName = System.mapLibraryName(library); //Create the file path: /lib/os_name/os_arch/lib_name StringBuilder filePath = new StringBuilder(); filePath.append(File.separatorChar); filePath.append("lib").append(File.separatorChar); filePath.append(OS_NAME).append(File.separatorChar); filePath.append(OS_ARCH).append(File.separatorChar); filePath.append(libName); InputStream in = JNILoader.class.getResourceAsStream(filePath.toString()); //If we fail to open the stream, return null if (in != null) return new Lib(libName, in); return null; } /** * Extrat a lib to the local temp directory * * @param lib Lib object containing lib name and a valid input stream * @return path to the extracted library */ private static String extract(Lib lib) { if (lib == null) return null; //Create the temp directory name StringBuilder tempDirName = new StringBuilder(); //tempDirName.append (System.getProperty ("java.io.tmpdir")); tempDirName.append("jniloader").append(File.separator); tempDirName.append(OS_NAME).append(File.separator); tempDirName.append(OS_ARCH).append(File.separator); if (CHECKSUM != null) tempDirName.append(CHECKSUM).append(File.separator); //Make sure the directories exist File tempDir = new File(System.getProperty("java.io.tmpdir"), tempDirName.toString()); tempDir.mkdirs(); //If this file is already extracted, just return the absolute path File outFile = new File(tempDir, lib.name); if (outFile.exists()) return outFile.getAbsolutePath(); //Write the library file, 2048 bytes at a time. try { FileOutputStream out = new FileOutputStream(outFile); byte[] buffer = new byte[2048]; int count = 0; while ((count = lib.in.read(buffer)) > 0) out.write(buffer, 0, count); lib.in.close(); out.flush(); out.close(); return outFile.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); } return null; } private static class Lib { private String name; private InputStream in; private Lib(String name, InputStream in) { this.name = name; this.in = in; } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/util/Utility.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.madara.util; import ai.madara.MadaraJNI; /** * Utility methods provided by MADARA */ public class Utility extends MadaraJNI { //Native Methods private static native String jni_getVersion(); private static native long jni_getTime(); private static native void jni_sleep(double sleepTime); /** * Returns the current MADARA version * @return the version in "major.minor.revision compiled on {date} at {time}" * format */ public static String getVersion() { return jni_getVersion(); } /** * Returns the time in nanoseconds * @return the current timestamp in nanoseconds */ public static long getTime() { return jni_getTime(); } /** * Sleeps for a number of seconds in double format. Partial time (e.g. * 4.5s) is encouraged. * @param sleepTime the current timestamp in nanoseconds */ public static void sleep(double sleepTime) { jni_sleep(sleepTime); } }
0
java-sources/ai/mantik/testutils_2.12/0.3.1-rc2/ai/mantik/testutils
java-sources/ai/mantik/testutils_2.12/0.3.1-rc2/ai/mantik/testutils/tags/IntegrationTest.java
package ai.mantik.testutils.tags; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation to mark Integration Tests. * They are excluded from running by default. * * See http://www.scalatest.org/user_guide/tagging_your_tests */ @org.scalatest.TagAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface IntegrationTest {}
0
java-sources/ai/marsview/extension/2.0.2/agoramarketplace/marsview
java-sources/ai/marsview/extension/2.0.2/agoramarketplace/marsview/extension/ExtensionManager.java
package agoramarketplace.marsview.extension; import androidx.annotation.Keep; @Keep public class ExtensionManager { public static final String EXTENSION_NAME = "agora-marsview"; // Name of target link library used in CMakeLists.txt public static final String EXTENSION_VENDOR_NAME = "Marsview"; // Provider name used for registering in agora-marsview.cpp public static final String EXTENSION_AUDIO_FILTER_NAME = "TranscriptProvider"; // Audio filter name defined in ExtensionProvider.h }
0
java-sources/ai/marsview/extension/2.0.2/agoramarketplace/marsview
java-sources/ai/marsview/extension/2.0.2/agoramarketplace/marsview/extension/MarsviewRequestHelper.java
package agoramarketplace.marsview.extension; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.ExecutionException; import androidx.annotation.Keep; @Keep public class MarsviewRequestHelper { private String projectApiKey; private String projectApiSecret; private String apiKey; private String apiSecret; private String userId; private String projectId; // public MarsviewRequestHelper(String apiKey, String apiSecret, String userId, String projectId){ // this.apiKey = apiKey; // this.apiSecret = apiSecret; // this.userId = userId; // this.projectId = projectId; // } public MarsviewRequestHelper(String projectApiKey, String projectApiSecret){ this.projectApiKey = projectApiKey; this.projectApiSecret = projectApiSecret; String out; JSONObject object = new JSONObject(); try { object.put("apiKey", this.projectApiKey); object.put("apiSecret", this.projectApiSecret); // out = new PostTask().execute("http://localhost:3001", object.toString()).get(); out = new PostTask().execute("https://agorasockets.marsview.ai/helpers/authenticate_user_project", object.toString()).get(); JSONObject outJson = new JSONObject(out); JSONObject data = outJson.getJSONObject("data"); this.apiKey = data.getString("api_key"); this.apiSecret = data.getString("api_secret"); this.projectId = data.getString("project_id"); this.userId = data.getString("user_id"); Log.d("Agora_Marsview_Java", outJson.toString()); } catch (JSONException | ExecutionException | InterruptedException e) { e.printStackTrace(); } } private JSONObject getAccessToken(){ PostTask postTask = new PostTask(); JSONObject outJson; String out; try{ JSONObject object = new JSONObject(); object.put("apiKey", this.apiKey); object.put("apiSecret", this.apiSecret); object.put("userId", this.userId); out = postTask.execute("https://api.marsview.ai/cb/v1/auth/create_access_token", object.toString()).get(); return new JSONObject(out); }catch(Exception err){ Log.e("Agora_Marsview_Java", err.toString()); return null; } } public String postComputeDataRequest(String txnId, JSONArray enableModels){ JSONObject accessTokenResponse = getAccessToken(); String accessToken = null; try{ if(accessTokenResponse.getBoolean("status")){ JSONObject data = accessTokenResponse.getJSONObject("data"); accessToken = data.getString("accessToken"); JSONObject postData = new JSONObject(); postData.put("userId", this.userId); postData.put("txnId", txnId); postData.put("enableModels",enableModels); String url = "https://api.marsview.ai/cb/v1/conversation/compute"; String postComputeDataResponse = new PostTask().execute(url, "Bearer "+ accessToken, postData.toString()).get(); return postComputeDataResponse; } else{ return accessTokenResponse.getString("error"); } }catch(Exception e){ Log.e("Agora_Marsview_Java", e.toString()); return null; } } public String getProcessingState(String txnId){ JSONObject accessTokenResponse = getAccessToken(); String accessToken = null; try{ if(accessTokenResponse.getBoolean("status")){ JSONObject data = accessTokenResponse.getJSONObject("data"); accessToken = data.getString("accessToken"); JSONObject postData = new JSONObject(); postData.put("userId", this.userId); postData.put("txnId", txnId); String url = "https://api.marsview.ai/cb/v1/conversation/get_txn/"+ txnId; String getProcessingStateResponse = new GetTask().execute(url,"Bearer "+ accessToken, postData.toString()).get(); return getProcessingStateResponse; } else{ return accessTokenResponse.toString(); } }catch(Exception e){ Log.e("Agora_Marsview_Java", e.toString()); return null; } } public String getRequestMetadata(String txnId){ JSONObject accessTokenResponse = getAccessToken(); String accessToken = null; try{ if(accessTokenResponse.getBoolean("status")){ JSONObject data = accessTokenResponse.getJSONObject("data"); accessToken = data.getString("accessToken"); JSONObject postData = new JSONObject(); postData.put("userId", this.userId); postData.put("txnId", txnId); String url = "https://api.marsview.ai/cb/v1/conversation/fetch_metadata/" + txnId; String getRequestMetadataResponse = new GetTask().execute(url,"Bearer " +accessToken, postData.toString()).get(); return getRequestMetadataResponse; } else{ return accessTokenResponse.toString(); } }catch(Exception e){ Log.e("Agora_Marsview_Java", e.toString()); return null; } } private class PostTask extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... strings) { HttpURLConnection conn = null; String urlString = strings[0]; try{ switch(strings.length){ case 2:{ String postData = strings[1]; URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Language", "en-US"); conn.setDoOutput(true); conn.setUseCaches(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postData); wr.close(); break; } case 3:{ String accessToken = strings[1]; String postData = strings[2]; URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Language", "en-US"); conn.setRequestProperty("Authorization", accessToken); conn.setDoOutput(true); conn.setUseCaches(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postData); wr.close(); break; } } InputStream is = conn.getInputStream(); BufferedReader rd = new BufferedReader((new InputStreamReader(is))); StringBuilder response = new StringBuilder(); String line; while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch(Exception e){ Log.e("Agora_Marsview_Java", e.toString()); return null; } finally { if(conn != null){ conn.disconnect(); } } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); //Do anything with response.. } } private class GetTask extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... strings) { HttpURLConnection conn = null; String urlString = strings[0]; try{ URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); if(strings.length >= 2){ String accessToken = strings[1]; conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", accessToken); } int responseCode = conn.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ InputStream is = conn.getInputStream(); BufferedReader rd = new BufferedReader((new InputStreamReader(is))); StringBuilder response = new StringBuilder(); String line; while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } else{ return null; } } catch(Exception e){ Log.e("Agora_Marsview_Java", e.toString()); return null; } finally { if(conn != null){ conn.disconnect(); } } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); //Do anything with response.. } } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/AbstractMasonsSDK.java
package ai.mrs; import ai.mrs.cli.Debugger; import ai.mrs.connection.models.KnockResult; import ai.mrs.session.CalleeSession; import ai.mrs.session.CallerSession; import ai.mrs.connection.MasonsConnection; import java.util.HashMap; import java.util.Map; import ai.mrs.session.models.*; public abstract class AbstractMasonsSDK { private Map<String, CallerSession> accountKey2CallerSessionMapping = new HashMap<String, CallerSession>(); private Map<String, CallerSession> sessionID2CallerSessionMapping = new HashMap<String, CallerSession>(); private Map<String, CalleeSession> accountKey2CalleeSessionMapping = new HashMap<String, CalleeSession>(); private Map<String, CalleeSession> sessionID2CalleeSessionMapping = new HashMap<String, CalleeSession>(); private MasonsSDKConfig config; private MasonsConnection connection; protected AbstractMasonsSDK(MasonsSDKConfig config) { this.config = config; this.connection = new MasonsConnection(this, config); } public void start() { if (config.getDebug()) { new Debugger(this).run(); return; } this.connection.start(); } public void startInThread() { new Thread(() -> { connection.start(); }).start(); } public void stop() { this.connection.stop(); } public KnockResult broadcastKnock(String accountKey, String text, Map<String, Object> data) { Map<String, Object> req = new HashMap<>(); req.put("account_key", accountKey); req.put("text", text); req.put("data", data); Map resp = this.connection.callKnockEvent(req); if (resp == null) { return new KnockResult(); } boolean success = (Boolean) resp.get("success"); KnockResult result = new KnockResult(); if (success) { String sessionID = (String) resp.get("session_id"); String respText = (String) resp.get("text"); result.setSuccess(true); result.setText(respText); result.setSessionID(sessionID); this.createCallerSession(sessionID, accountKey); } return result; } public CallerSession getCallerSessionByAccountKey(String accountKey) { return this.accountKey2CallerSessionMapping.get(accountKey); } public CallerSession getCallerSessionBySessionID(String sessionID) { return this.sessionID2CallerSessionMapping.get(sessionID); } public CalleeSession getCalleeSessionByAccountKey(String accountKey) { return this.accountKey2CalleeSessionMapping.get(accountKey); } public CalleeSession getCalleeSessionBySessionID(String accountKey) { return this.sessionID2CalleeSessionMapping.get(accountKey); } public void createCallerSession(String sessionID, String accountKey) { CallerSession session = new CallerSession(); session.setSessionID(sessionID); session.setAccountKey(accountKey); session.setConnection(this.connection); this.accountKey2CallerSessionMapping.put(accountKey, session); this.sessionID2CallerSessionMapping.put(sessionID, session); } public void createCalleeSession(String sessionID, String accountKey) { CalleeSession session = new CalleeSession(); session.setSessionID(sessionID); session.setAccountKey(accountKey); session.setConnection(this.connection); this.accountKey2CalleeSessionMapping.put(accountKey, session); this.sessionID2CalleeSessionMapping.put(sessionID, session); } public void removeCallerSession(String sessionID, String accountKey) { CallerSession session = this.accountKey2CallerSessionMapping.get(accountKey); if (sessionID.equals(session.getSessionID())) { this.accountKey2CallerSessionMapping.remove(accountKey); } this.sessionID2CallerSessionMapping.remove(accountKey); } public void removeCalleeSession(String sessionID, String accountKey) { CalleeSession session = this.accountKey2CalleeSessionMapping.get(accountKey); if (sessionID.equals(session.getSessionID())) { this.accountKey2CalleeSessionMapping.remove(accountKey); } this.sessionID2CalleeSessionMapping.remove(accountKey); } public abstract ReplyToCaller onReceivingUtteranceFromCaller(UtteranceFromCaller utterance); public abstract void onReceivingReplyFromCallee(ReplyFromCallee reply); public abstract void onExitingSessionOfCaller(ExitingSessionOfCaller session); public abstract void onCreatingSessionOfCallee(CreatingSessionOfCallee session); public abstract KnockResultToCaller handleKnockFromCaller(KnockFromCaller knock); }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/MasonsSDKConfig.java
package ai.mrs; import java.net.Proxy; import java.util.Arrays; import java.util.Base64; import java.util.Map; public class MasonsSDKConfig { private String wsUrl = "ws://svc.masons.mrs.ai/api/v1/masons"; private String nodeUrl = "https://svc.masons.mrs.ai/api/v1/masons/nodes"; private String agentToken; private Boolean debug = false; private long rpcTimeout = 1000L; private int connectTimeout = 1000; private Map<String, String> connectHeaders = null; private Proxy proxy = null; private String proxyAuthorization = null; public MasonsSDKConfig(String agentToken) { this.agentToken = agentToken; } public MasonsSDKConfig(String agentToken, String wsUrl, String nodeUrl) { this.agentToken = agentToken; this.wsUrl = wsUrl; this.nodeUrl = nodeUrl; } public MasonsSDKConfig(String agentToken, String wsUrl, String nodeUrl, long rpcTimeout, int connectTimeout) { this.agentToken = agentToken; this.wsUrl = wsUrl; this.nodeUrl = nodeUrl; this.rpcTimeout = rpcTimeout; this.connectTimeout = connectTimeout; } public String getWsUrl() { return this.wsUrl; } public String getNodeUrl() { return this.nodeUrl; } public String getAgentToken() { return this.agentToken; } public long getRpcTimeout() { return rpcTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setWsUrl(String wsUrl) { this.wsUrl = wsUrl; } public void setNodeUrl(String nodeUrl) { this.nodeUrl = nodeUrl; } public void setAgentToken(String agentToken) { this.agentToken = agentToken; } public void setRpcTimeout(long rpcTimeout) { this.rpcTimeout = rpcTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public Boolean getDebug() { return debug; } public void setDebug(Boolean debug) { this.debug = debug; } public Proxy getProxy() { return proxy; } public void setProxy(Proxy proxy) { this.proxy = proxy; } public Map<String, String> getConnectHeaders() { return connectHeaders; } public void setConnectHeaders(Map<String, String> connectHeaders) { this.connectHeaders = connectHeaders; } public String getProxyAuthorization() { return proxyAuthorization; } public void setProxyAuthorization(String username, String password) { Base64.Encoder encoder = Base64.getEncoder(); String encryptAuth = encoder.encodeToString((username + ":" + password).getBytes()); this.proxyAuthorization = "Basic " + encryptAuth.substring(0, 12); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/cli/Debugger.java
package ai.mrs.cli; import ai.mrs.AbstractMasonsSDK; import ai.mrs.session.CalleeSession; import ai.mrs.session.CallerSession; import ai.mrs.session.models.*; import ai.mrs.utils.JsonUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.UUID; public class Debugger { private AbstractMasonsSDK sdkRef; private String sessionIdRef; public Debugger(AbstractMasonsSDK sdkRef) { this.sdkRef = sdkRef; } public void run() { System.out.println("[Debug] Start"); try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line; System.out.println("Commands:\n" + " exit\n" + " knock <Text>\n" + " send <Text>\n" + " reply <Text>\n" + ""); boolean flag = true; while (flag) { line = reader.readLine().trim(); String[] argv = line.split(" ", 2); String cmd = argv[0]; if (cmd.isEmpty()) { continue; } switch (cmd) { case "knock": { String text = argv[1]; String accountKey = ""; KnockFromCaller knock = new KnockFromCaller(); knock.setAccountKey(accountKey); knock.setText(text); KnockResultToCaller result = sdkRef.handleKnockFromCaller(knock); if (null == result) { System.out.println("[Debug] " + "Knock Response: " + "null"); } else { System.out.println("[Debug] " + "Knock Response: " + JsonUtil.objToJson(result)); if (result.getSuccess()) { createCalleeSession(text); } } break; } case "send": { String text = argv[1]; CalleeSession session = sdkRef.getCalleeSessionBySessionID(sessionIdRef); UtteranceFromCaller utterance = new UtteranceFromCaller(session, text); ReplyToCaller reply = sdkRef.onReceivingUtteranceFromCaller(utterance); if (null != reply && null != reply.getText() && !reply.getText().isEmpty()) { System.out.println("[Reply] " + reply.getText()); if (reply.getIsEnd()) { System.out.println("[Debug] " + "Session ended, " + sessionIdRef); } } else { System.out.println("[Reply] " + "null"); } break; } case "reply": { String text = argv[1]; CalleeSession session = sdkRef.getCalleeSessionBySessionID(sessionIdRef); if (null == session) { createCalleeSession(text); session = sdkRef.getCalleeSessionBySessionID(sessionIdRef); } UtteranceFromCaller utterance = new UtteranceFromCaller(session, text); ReplyToCaller reply = sdkRef.onReceivingUtteranceFromCaller(utterance); if (null != reply) { System.out.println("[Reply] " + reply.getText()); } else { System.out.println("[Reply] " + "null"); } break; } case "end": { String text; if (argv.length > 1) { text = argv[1]; } else { text = null; } CallerSession callerSession = sdkRef.getCallerSessionBySessionID(sessionIdRef); if (null != callerSession) { System.out.println("[Debug] " + "Session ended, " + sessionIdRef); } CalleeSession calleeSession = sdkRef.getCalleeSessionBySessionID(sessionIdRef); if (null != calleeSession) { calleeSession.exit(text); System.out.println("[Debug] " + "Session ended, " + sessionIdRef); } sessionIdRef = null; break; } case "exit": { sdkRef.stop(); flag = false; break; } default: { System.out.println("[Debug] " + "Wrong command"); } } } } catch (IOException e) { e.printStackTrace(); } } private void createCalleeSession(String text) { sessionIdRef = UUID.randomUUID().toString(); System.out.println("[Debug] " + "Session ID: " + sessionIdRef); CreatingSessionOfCallee creatingSessionOfCallee = new CreatingSessionOfCallee(); String accountKeyRef = "tester"; creatingSessionOfCallee.setAccountKey(accountKeyRef); creatingSessionOfCallee.setText(text); sdkRef.onCreatingSessionOfCallee(creatingSessionOfCallee); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/cli/Sample.java
package ai.mrs.cli; import ai.mrs.MasonsSDKConfig; public class Sample { public static void main(String[] args) { MasonsSDKConfig config = new MasonsSDKConfig("3ec0c016-846b-4836-aa9b-b671d448f4e8"); config.setDebug(true); SampleMasons masons = new SampleMasons(config); masons.start(); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/cli/SampleMasons.java
package ai.mrs.cli; import ai.mrs.AbstractMasonsSDK; import ai.mrs.MasonsSDKConfig; import ai.mrs.session.models.*; public class SampleMasons extends AbstractMasonsSDK { public SampleMasons(MasonsSDKConfig config) { super(config); } @Override public ReplyToCaller onReceivingUtteranceFromCaller(UtteranceFromCaller utterance) { ReplyToCaller reply = new ReplyToCaller(); reply.setText("You said: "+ utterance.getText()); reply.setIsEnd(false); return reply; } @Override public void onReceivingReplyFromCallee(ReplyFromCallee reply) { } @Override public void onExitingSessionOfCaller(ExitingSessionOfCaller session) { } @Override public void onCreatingSessionOfCallee(CreatingSessionOfCallee session) { } @Override public KnockResultToCaller handleKnockFromCaller(KnockFromCaller knock) { KnockResultToCaller result = new KnockResultToCaller(); if (knock.getText().equals("echo")) { result.setSuccess(true); result.setText("Hello, this is echo bot"); } else { result.setSuccess(false); } return result; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection/MasonsConnection.java
package ai.mrs.connection; import ai.mrs.AbstractMasonsSDK; import ai.mrs.connection.models.UtteranceResponse; import ai.mrs.connection.utils.HTTPUtil; import ai.mrs.mdp.MDPClient; import ai.mrs.mdp.MDPHandler; import ai.mrs.session.CalleeSession; import ai.mrs.session.CallerSession; import ai.mrs.session.models.*; import ai.mrs.MasonsSDKConfig; import ai.mrs.utils.JsonUtil; import java.net.Proxy; import java.util.HashMap; import java.util.Map; public class MasonsConnection implements MDPHandler { private String nodeID; private MDPClient mdpClient; private AbstractMasonsSDK sdk; private MasonsSDKConfig config; public MasonsConnection(AbstractMasonsSDK sdk, MasonsSDKConfig config) { this.config = config; this.sdk = sdk; } private void createNode(Map<String, String> headers, Proxy proxy) { String nodeUrl = this.config.getNodeUrl(); String resp = HTTPUtil.post(nodeUrl, "", headers, proxy); Map respMap = JsonUtil.jsonToMap(resp); this.nodeID = (String) respMap.get("node_id"); } public void start() { Map<String, String> headers = new HashMap<>(); headers.put("Access-Token", config.getAgentToken()); Proxy proxy = this.config.getProxy(); String proxyAuthorization = this.config.getProxyAuthorization(); if (null != proxyAuthorization) { headers.put("Proxy-Authorization", proxyAuthorization); } Map<String, String> connectHeaders = this.config.getConnectHeaders(); if (null != connectHeaders) { for (Map.Entry<String, String> entry : connectHeaders.entrySet()) { headers.put(entry.getKey(), entry.getValue()); } } this.createNode(headers, proxy); headers.put("Sec-WebSocket-Protocol", "Duplex"); headers.put("Node-ID", this.nodeID); this.mdpClient = new MDPClient( this.config.getWsUrl(), this, headers, this.config.getConnectTimeout(), this.config.getRpcTimeout(), proxy ); this.mdpClient.connect(); } public void stop() { this.mdpClient.close(); } public Map callKnockEvent(Map data) { return this.mdpClient.callRPC("knock", data); } public UtteranceResponse callUtteranceEvent(String sessionID, String text) { Map<String, Object> req = new HashMap<>(); req.put("session_id", sessionID); req.put("text", text); Map resp = this.mdpClient.callRPC("utterance", req); return JsonUtil.mapToObj(resp, UtteranceResponse.class); } public void sendReplyEvent(String sessionID, String text, boolean isEnd) { Map<String, Object> data = new HashMap<>(); data.put("session_id", sessionID); data.put("text", text); data.put("isEnd", isEnd); this.mdpClient.sendEvent("reply", data); } public void sendExitEvent(String sessionID, String text) { Map<String, Object> data = new HashMap<>(); data.put("session_id", sessionID); data.put("text", text); this.mdpClient.sendEvent("exit", data); } @Override public void processEventMessage(String event, Map data) { String sessionID = (String) data.get("session_id"); switch (event) { case "reply": String replyText = (String) data.get("text"); Boolean isEnd = (Boolean) data.get("is_end"); ReplyFromCallee replyFromCallee = new ReplyFromCallee(); replyFromCallee.setText(replyText); replyFromCallee.setIsEnd(isEnd); this.sdk.onReceivingReplyFromCallee(replyFromCallee); break; case "create": { String accountKey = (String) data.get("account_key"); this.sdk.createCalleeSession(sessionID, accountKey); CreatingSessionOfCallee sessionWrapper = new CreatingSessionOfCallee(); sessionWrapper.setAccountKey(accountKey); this.sdk.onCreatingSessionOfCallee(sessionWrapper); break; } case "exit": { CallerSession session = this.sdk.getCallerSessionBySessionID(sessionID); String accountKey = session.getAccountKey(); this.sdk.removeCallerSession(sessionID, accountKey); ExitingSessionOfCaller sessionWrapper = new ExitingSessionOfCaller(); sessionWrapper.setAccountKey(accountKey); this.sdk.onExitingSessionOfCaller(sessionWrapper); break; } default: this.mdpClient.sendError("This event is not supported"); } } @Override public Map processRPCRequest(String event, Map data) { String sessionID = (String) data.get("session_id"); Map ret = new HashMap(); switch (event) { case "knock": { KnockFromCaller knock = JsonUtil.mapToObj(data, KnockFromCaller.class); KnockResultToCaller result = this.sdk.handleKnockFromCaller(knock); ret = JsonUtil.objToMap(result); break; } case "utterance": { String text = (String) data.get("text"); CalleeSession calleeSession = this.sdk.getCalleeSessionBySessionID(sessionID); UtteranceFromCaller utterance = new UtteranceFromCaller(calleeSession, text); ReplyToCaller reply = this.sdk.onReceivingUtteranceFromCaller(utterance); if (null != reply) { ret = JsonUtil.objToMap(reply); } break; } default: { this.mdpClient.sendError("This event is not supported"); } } return ret; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection/models/KnockData.java
package ai.mrs.connection.models; import com.google.gson.annotations.SerializedName; import java.util.Map; public class KnockData { @SerializedName("account_key") private String accountKey; private Map<String, Object> data; public String getAccountKey() { return accountKey; } public Map<String, Object> getData() { return data; } public void setAccountKey(String accountKey) { this.accountKey = accountKey; } public void setData(Map<String, Object> data) { this.data = data; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection/models/KnockResult.java
package ai.mrs.connection.models; public class KnockResult { private boolean success = false; private String text = null; private String sessionID = null; public boolean getSuccess() { return this.success; } public String getText() { return text; } public String getSessionID() { return sessionID; } public void setSuccess(boolean success) { this.success = success; } public void setText(String text) { this.text = text; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection/models/UtteranceResponse.java
package ai.mrs.connection.models; import com.google.gson.annotations.SerializedName; public class UtteranceResponse { private String text; @SerializedName("is_end") private boolean isEnd; public UtteranceResponse(String text, boolean isEnd) { this.text = text; this.isEnd = isEnd; } public String getText() { return text; } public boolean getIsEnd() { return isEnd; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/connection/utils/HTTPUtil.java
package ai.mrs.connection.utils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.util.Map; public class HTTPUtil { private static String dispatchRequest( String method, String urlStr, String body, Map<String, String> headers, Proxy proxy ) { String result = null; HttpURLConnection connection = null; InputStreamReader in = null; try { // local pc host: 10.0.2.2 URL url = new URL(urlStr); if (null != proxy) { connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Charset", "utf-8"); for (Map.Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } DataOutputStream dop = new DataOutputStream(connection.getOutputStream()); dop.writeBytes(body); dop.flush(); dop.close(); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static String post(String url, String body, Map<String, String> headers, Proxy proxy) { return HTTPUtil.dispatchRequest("POST", url, body, headers, proxy); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/exceptions/MDPEventException.java
package ai.mrs.exceptions; public class MDPEventException extends Exception { public MDPEventException() { super(); } public MDPEventException(String message) { super(message); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/mdp/MDPClient.java
package ai.mrs.mdp; import ai.mrs.utils.JsonUtil; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft_6455; import java.net.Proxy; import java.net.URI; import java.net.URISyntaxException; import java.nio.channels.NotYetConnectedException; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; public class MDPClient implements MDPProtocol { private boolean connected = false; private MDPHandler handler; private Map<String, RPCWaiter> rpcWaiters = new HashMap<>(); // private Map<String, JSONObject> expectedAckMessages = new HashMap<String, JSONObject>(); private long rpcTimeout; private int connectTimeout; private URI uri; private Timer reconnectController = null; private ConcurrentLinkedQueue<String> messageQueue = new ConcurrentLinkedQueue<String>(); private Map<String, String> httpHeaders; private WebSocketEndpoint ws = null; private Proxy proxy = null; public MDPClient(String uriStr, MDPHandler handler, Map<String, String> httpHeaders, int connectTimeout, long rpcTimeout, Proxy proxy) { try { this.uri = new URI(uriStr); } catch (URISyntaxException e) { e.printStackTrace(); } this.handler = handler; this.httpHeaders = httpHeaders; this.rpcTimeout = rpcTimeout; this.connectTimeout = connectTimeout; this.proxy = proxy; } @Override public void sendMessage(Map<String, Object> msg) { String msgID = this.generateUniID(); msg.put("msg_id", msgID); this.send(JsonUtil.mapToJson(msg)); } @Override public void sendEvent(String event, Map data) { Map<String, Object> map = new HashMap<>(); map.put("event", event); map.put("data", data); this.sendMessage(map); } @Override public Map callRPC(String event, Map data) { Map<String, Object> msg = new HashMap<>(); String rpcID = this.generateUniID(); msg.put("rpc_id", rpcID); msg.put("event", event); msg.put("data", data); this.sendMessage(msg); return this.waitForRpcResponse(rpcID); } @Override public void sendError(String err) { Map<String, Object> obj = new HashMap<>(); obj.put("error", err); this.send(JsonUtil.mapToJson(obj)); } @Override public void connect() { if (null != this.ws) { if (this.webSocketIsOpen() || this.webSocketIsConnecting()) { return; } this.ws.close(); this.ws = null; } this.ws = new WebSocketEndpoint( this.uri, new Draft_6455(), this.httpHeaders, this.connectTimeout, this, this.proxy ); this.ws.connect(); } @Override public void close() { this.reconnectController.cancel(); this.messageQueue.clear(); this.ws.close(); } @Override public void onOpen() { this.connected = true; this.reconnectController.cancel(); if (this.messageQueue.size() > 0) { // Drain any messages that came in while the channel was not open. Iterator<String> iter = this.messageQueue.iterator(); for (; iter.hasNext(); ) { this.send(iter.next()); } this.messageQueue.clear(); } } @Override public void onClose(int code, String reason, boolean remote) { this.reconnect(); } @Override public void onError(Exception ex) { } @Override public void onMessage(String message) { if (message.equals("ping")) { this.send("pong"); return; } if (message.equals("pong")) { return; } try { Map jsonObject = JsonUtil.jsonToMap(message); if (jsonObject.containsKey("error")) { return; } if (jsonObject.containsKey("ack")) { String msgID = (String) jsonObject.get("ack"); // this.expectedAckMessages.remove(msgID); return; } if (!jsonObject.containsKey("msg_id")) { this.sendError("'msg_id' is missing"); return; } String msgID = (String) jsonObject.get("msg_id"); this.replyAck(msgID); if (jsonObject.containsKey("rpc_id")) { String rpcID = (String) jsonObject.get("rpc_id"); if (jsonObject.containsKey("echo")) { Map data = (Map) jsonObject.get("echo"); this.processRpcResponse(rpcID, data); } else { String event = (String) jsonObject.get("event"); Map data = (Map) jsonObject.get("data"); this.processRpcRequest(rpcID, event, data); } return; } if (jsonObject.containsKey("event")) { String event = (String) jsonObject.get("event"); Map data = (Map) jsonObject.get("data"); this.processEventMessage(event, data); } else { this.sendError("'event' is missing"); } } catch (Exception e) { this.sendError("Error occurred in parsing message:" + e.toString()); } } private void replyAck(String msgID) { Map<String, String> ack = new HashMap<>(); ack.put("ack", msgID); this.send(JsonUtil.mapToJson(ack)); } public void send(String msg) { try { if (null == this.ws) { throw new NotYetConnectedException(); } this.ws.send(msg); } catch (NotYetConnectedException e) { this.reconnect(); this.messageQueue.add(msg); } } private void reconnect() { if (null != this.ws) { this.ws.close(); this.ws = null; } this.connected = false; if (null != this.reconnectController) { this.reconnectController.cancel(); } this.reconnectController = new Timer(); this.reconnectController.schedule( new TimerTask() { @Override public void run() { doReconnect(); } }, 0L, 2000L ); } private synchronized void doReconnect() { if (this.connected) { this.reconnectController.cancel(); return; } this.connect(); } private boolean webSocketIsOpen() { return this.ws.getReadyState() == WebSocket.READYSTATE.OPEN; } private boolean webSocketIsConnecting() { return this.ws.getReadyState() == WebSocket.READYSTATE.CONNECTING; } private Map waitForRpcResponse(String rpcID) { RPCWaiter waiter = new RPCWaiter(this.rpcTimeout); this.rpcWaiters.put(rpcID, waiter); waiter.acquire(); Map result = waiter.getResult(); this.rpcWaiters.remove(rpcID); return result; } private void processRpcRequest(String rpcID, String event, Map req) { Map respData = this.handler.processRPCRequest(event, req); Map<String, Object> resp = new HashMap<>(); resp.put("rpc_id", rpcID); resp.put("event", event); resp.put("data", respData); this.sendMessage(resp); } private void processRpcResponse(String rpcID, Map data) { RPCWaiter waiter = this.rpcWaiters.get(rpcID); if (null != waiter) { waiter.setResult(data); waiter.release(); } } private void processEventMessage(String event, Map data) { this.handler.processEventMessage(event, data); } private String generateUniID() { return UUID.randomUUID().toString(); } // private void expectAck() { // // TODO: use thread pool // new Thread(() -> { // try { // Thread.sleep(1000); // if (expectedAckMessages.containsKey(msgID)) { // JSONObject msg = expectedAckMessages.get(msgID); // send(msg.toString()); // } // } catch (InterruptedException e) { // e.printStackTrace(); // } // }).start(); // } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/mdp/MDPHandler.java
package ai.mrs.mdp; import java.util.Map; public interface MDPHandler { void processEventMessage(String event, Map data); Map processRPCRequest(String event, Map data); }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/mdp/MDPProtocol.java
package ai.mrs.mdp; import java.util.Map; public interface MDPProtocol { void sendMessage(Map<String, Object> msg); void sendEvent(String event, Map data); Map callRPC(String event, Map data); void sendError(String err); void connect(); void close(); void onOpen(); void onError(Exception e); void onClose(int code, String reason, boolean remote); void onMessage(String message); }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/mdp/RPCWaiter.java
package ai.mrs.mdp; import java.util.Map; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class RPCWaiter { private Map result = null; private Semaphore lock = new Semaphore(0); private long timeout; public RPCWaiter(long timeout) { this.timeout = timeout; } public void acquire() { try { this.lock.tryAcquire(this.timeout, TimeUnit.MILLISECONDS); // this.lock.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.release(); } } public void release() { this.lock.release(); } public Map getResult() { return result; } public void setResult(Map result) { this.result = result; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/mdp/WebSocketEndpoint.java
package ai.mrs.mdp; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ServerHandshake; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.Proxy; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map; public class WebSocketEndpoint extends WebSocketClient { private MDPClient mdpClient; public WebSocketEndpoint(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout, MDPClient mdpClient, Proxy proxy) { super(serverUri, protocolDraft, httpHeaders, connectTimeout); this.mdpClient = mdpClient; if (serverUri.toString().startsWith("wss")) { this.initSSL(); } if (null != proxy) { this.setProxy(proxy); } } private void initSSL() { try { TrustManager[] tm = {new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); this.setSocket(ssf.createSocket()); } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyManagementException | IOException e ) { e.printStackTrace(); } } @Override public void onOpen(ServerHandshake serverHandshake) { this.mdpClient.onOpen(); } @Override public void onMessage(String s) { this.mdpClient.onMessage(s); } @Override public void onClose(int i, String s, boolean b) { this.mdpClient.onClose(i, s, b); } @Override public void onError(Exception e) { this.mdpClient.onError(e); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/CalleeSession.java
package ai.mrs.session; public class CalleeSession extends Session { public void reply(String text, boolean isEnd) { this.connection.sendReplyEvent(this.sessionID, text, isEnd); } public void exit(String text) { this.connection.sendExitEvent(sessionID, text); } public void exit() { this.connection.sendExitEvent(sessionID, null); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/CallerSession.java
package ai.mrs.session; import ai.mrs.connection.models.UtteranceResponse; public class CallerSession extends Session { public UtteranceResponse utter(String text){ return this.connection.callUtteranceEvent(this.sessionID, text); } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/Session.java
package ai.mrs.session; import ai.mrs.connection.MasonsConnection; public abstract class Session { protected String sessionID; protected String accountKey; protected MasonsConnection connection; public String getSessionID() { return this.sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public String getAccountKey() { return accountKey; } public void setAccountKey(String accountKey) { this.accountKey = accountKey; } public void setConnection(MasonsConnection connection) { this.connection = connection; } public MasonsConnection getConnection() { return connection; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/CreatingSessionOfCallee.java
package ai.mrs.session.models; public class CreatingSessionOfCallee { private String accountKey; private String text; public void setAccountKey(String accountKey) { this.accountKey = accountKey; } public String getAccountKey() { return accountKey; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/CreatingSessionOfCaller.java
package ai.mrs.session.models; public class CreatingSessionOfCaller { }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/ExitingSessionOfCaller.java
package ai.mrs.session.models; public class ExitingSessionOfCaller { private String accountKey; public void setAccountKey(String accountKey) { this.accountKey = accountKey; } public String getAccountKey() { return accountKey; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/KnockFromCaller.java
package ai.mrs.session.models; import com.google.gson.annotations.SerializedName; import java.util.Map; public class KnockFromCaller { @SerializedName("account_key") private String accountKey; private String text; private Map data = null; public String getAccountKey() { return accountKey; } public void setAccountKey(String accountKey) { this.accountKey = accountKey; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Map getData() { return data; } public void setData(Map data) { this.data = data; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/KnockResultToCaller.java
package ai.mrs.session.models; public class KnockResultToCaller { private Boolean success; private String text = null; public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/ReplyFromCallee.java
package ai.mrs.session.models; public class ReplyFromCallee { private String text; private Boolean isEnd; public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean getIsEnd() { return isEnd; } public void setIsEnd(Boolean end) { isEnd = end; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/ReplyToCaller.java
package ai.mrs.session.models; import com.google.gson.annotations.SerializedName; public class ReplyToCaller { private String text; @SerializedName("is_end") private Boolean isEnd; public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean getIsEnd() { return isEnd; } public void setIsEnd(Boolean end) { isEnd = end; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/session/models/UtteranceFromCaller.java
package ai.mrs.session.models; import ai.mrs.session.CalleeSession; public class UtteranceFromCaller { private CalleeSession session; private String text; public UtteranceFromCaller(CalleeSession session, String text) { this.session = session; this.text = text; } public void reply(String text, boolean isEnd) { this.session.reply(text, isEnd); } public CalleeSession getSession() { return session; } public String getText() { return text; } public void setSession(CalleeSession session) { this.session = session; } public void setText(String text) { this.text = text; } }
0
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs
java-sources/ai/mrs/masons-java-sdk/1.2.3/ai/mrs/utils/JsonUtil.java
package ai.mrs.utils; import com.google.gson.Gson; import java.util.HashMap; import java.util.Map; public class JsonUtil { public static String mapToJson(Map map) { Gson gson = new Gson(); return gson.toJson(map); } public static Map jsonToMap(String json) { Gson gson = new Gson(); return gson.fromJson(json, HashMap.class); } public static <T> T mapToObj(Map map, Class<T> respClass) { Gson gson = new Gson(); return gson.fromJson(gson.toJson(map), respClass); } public static String objToJson(Object obj) { Gson gson = new Gson(); return gson.toJson(obj); } public static Map objToMap(Object obj) { Gson gson = new Gson(); return gson.fromJson(gson.toJson(obj), HashMap.class); } }
0
java-sources/ai/mykg/mytool/0.0.5/ai/mykg
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool/IdUtil.java
package ai.mykg.mytool; import ai.mykg.mytool.convert.AbvConverter; import ai.mykg.mytool.convert.BaseConverter; import ai.mykg.mytool.convert.ConvertException; import java.nio.ByteBuffer; import java.util.UUID; import org.apache.commons.codec.binary.Base64; /** * @author Goddy [goddy@mykg.ai] 2021/3/5 * @since 0.0.1 */ public class IdUtil { private static BaseConverter shortConverter; /** * generate uuid * * @return uuid string * @since 0.0.1 */ public static String newUuid() { return UUID.randomUUID().toString(); } /** * generate short uuid * * @return short uuid * @since 0.0.1 */ public static String shortUuid() { String uuid = newUuid(); return shortUuid(uuid); } /** * generate short uuid from uuid * * @param uuid uuid * @return short uuid * @since 0.0.1 */ public static String shortUuid(String uuid) { return shortConverter.convert( uuid.toLowerCase().replaceAll("-", "")); } /** * revert short uuid to normal uuid * * @param shortUuid short uuid * @return uuid * @since 0.0.1 */ public static String fromShortUuid(String shortUuid) { String uuid = shortConverter.revert(shortUuid); for (int i = 0, len = 32 - uuid.length(); i < len; i++) { uuid = "0".concat(uuid); } return uuid.replaceFirst( "([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5"); } /** * revert short uuid from base64 * * @return short uuid * @since 0.0.5 */ public static String uuid2base64() { String uuid = newUuid(); return uuid2base64(uuid); } /** * generate short uuid from base64 * * @param str uuid string * @return short uuid * @since 0.0.5 */ public static String uuid2base64(String str) { UUID uuid = UUID.fromString(str); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return Base64.encodeBase64URLSafeString(bb.array()); } /** * revert short uuid from base64 * * @param str short uuid * @return uuid string * @since 0.0.5 */ public static String uuidFromBase64(String str) { byte[] bytes = Base64.decodeBase64(str); ByteBuffer bb = ByteBuffer.wrap(bytes); UUID uuid = new UUID(bb.getLong(), bb.getLong()); return uuid.toString(); } /** * generate bv * * @param av av id * @return bv str * @since 0.0.5 */ public static String av2bv(long av) { return AbvConverter.av2bv(av); } /** * revert bv to av * @param bv bv string * @return av id */ public static long bv2av(String bv) { return AbvConverter.bv2av(bv); } // === private === static { try { shortConverter = new BaseConverter(BaseConverter.HEX, BaseConverter.BASE58); } catch (ConvertException e) { e.printStackTrace(); } } }
0
java-sources/ai/mykg/mytool/0.0.5/ai/mykg
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool/StringUtil.java
package ai.mykg.mytool; /** * @author Goddy [goddy@mykg.ai] 2021/3/6 * @since 0.0.1 */ public class StringUtil { /** * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return true if the CharSequence is null, empty or whitespace only * @since 0.0.1 */ public static boolean isBlank(final CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return true if the CharSequence is not empty and not null and not whitespace only * @since 0.0.1 */ public static boolean isNotBlank(final CharSequence cs) { return !isBlank(cs); } /** * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return true if the CharSequence is empty or null * @since 0.0.1 */ public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } /** * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty("") = false * StringUtils.isNotEmpty(" ") = true * StringUtils.isNotEmpty("bob") = true * StringUtils.isNotEmpty(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return true if the CharSequence is not empty and not null * @since 0.0.1 */ public static boolean isNotEmpty(final CharSequence cs) { return !isEmpty(cs); } }
0
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool/convert/AbvConverter.java
package ai.mykg.mytool.convert; import java.util.HashMap; /** * @author Goddy [goddy@mykg.ai] 2021/4/7 * * <pre> * av: * bv: * </pre> * * <pre> * reference: * - @see <a href="https://www.bilibili.com/blackboard/activity-BV-PC.html">bilibili-announcement</a> * - @see <a href="https://github.com/Goodjooy/BilibiliAV2BV/blob/master/src/net/augcloud/BilibiliA2B.java">github-BilibiliA2B.java</a> * - @see <a href="https://blog.csdn.net/weixin_44735156/article/details/107580637">csdn-av_BV</a> * </pre> * @since 0.0.5 */ public class AbvConverter { private static final String alphabet = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"; private static final String[] wordList = alphabet.split(""); private static final int[] s = {11, 10, 3, 8, 4, 6}; private static final int xor = 177451812; private static final long add = 8728348608L; private static final HashMap<String, Integer> number2wordMap; static { number2wordMap = new HashMap<String, Integer>(); for (int i = 0; i < wordList.length; i++) { number2wordMap.put(wordList[i], i); } } /** * @param av av * @return bv */ public static String av2bv(long av) { av = (av ^ xor) + add; String r = "BV1 4 1 7 "; for (int i = 0; i < 6; i++) { int updatedIndex = (int) ((av / Math.pow(58, i)) % 58); r = topOffIndex(r, wordList[updatedIndex], s[i]); } return r.replace("BV", ""); } /** * @param str bv * @return av */ public static long bv2av(String str) { str = "BV" + str; long r = 0; String[] wordList = str.split(""); for (int i = 0; i < 6; i++) { r += number2wordMap.get(wordList[s[i]]) * (long)Math.pow(58, i); } return (r - add) ^ xor; } // === private === private static String topOffIndex(String before, String updated, int index) { return String.format("%s%s%s", before.substring(0, index), updated, before.substring(index + 1)); } }
0
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool/convert/BaseConverter.java
package ai.mykg.mytool.convert; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * @author Goddy [goddy@mykg.ai] 2021/3/5 * @since 0.0.1 */ public class BaseConverter implements Serializable { private static final long serialVersionUID = -343663115496966264L; // BINARY public static final String BIN = "01"; // OCTAL public static final String OCT = "01234567"; // DECIMAL public static final String DEC = "0123456789"; // HEXADECIMAL public static final String HEX = "0123456789abcdef"; // delete 0, l, I, O public static final String BASE58 = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; private final String srcAlphabet; private final String distAlphabet; private final Boolean isSameAlphabet; public BaseConverter(String srcAlphabet, String distAlphabet) throws ConvertException { checkAlphabet(srcAlphabet); checkAlphabet(distAlphabet); this.srcAlphabet = srcAlphabet; this.distAlphabet = distAlphabet; this.isSameAlphabet = srcAlphabet.equals(distAlphabet); } /** * convert str from srcAlphabet to distAlphabet * * @param str words from srcAlphabet * @return words from distAlphabet */ public String convert(String str) { if (this.isSameAlphabet) { return str; } return convert(this.srcAlphabet, this.distAlphabet, str); } public String revert(String str) { if (this.isSameAlphabet) { return str; } return convert(this.distAlphabet, this.srcAlphabet, str); } // === private === private static String convert(String srcAlphabet, String distAlphabet, String str) { int fromBase = srcAlphabet.length(); int toBase = distAlphabet.length(); int len = str.length(); Integer[] numArray = new Integer[str.length()]; for (int i = 0; i < len; i++) { numArray[i] = srcAlphabet.indexOf(str.charAt(i)); } int divide; int newLen; String result = ""; do { divide = 0; newLen = 0; for (int i = 0; i < len; i++) { divide = divide * fromBase + numArray[i]; if (divide >= toBase) { numArray[newLen] = divide / toBase; newLen++; divide = divide % toBase; } else if (newLen > 0) { numArray[newLen] = 0; newLen++; } } len = newLen; result = distAlphabet.substring(divide, divide + 1).concat(result); } while (newLen != 0); return result; } /** * @param alphabet string without blank or duplicate char */ private void checkAlphabet(String alphabet) throws ConvertException { int strLen; if (alphabet == null || (strLen = alphabet.length()) == 0) { throw new ConvertException("Empty alphabet!"); } Set<Character> chars = new HashSet<Character>(); for (int i = 0; i < strLen; i++) { Character c = alphabet.charAt(i); if (Character.isWhitespace(c) || chars.contains(c)) { throw new ConvertException("Bad alphabet!"); } else { chars.add(c); } } } }
0
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool
java-sources/ai/mykg/mytool/0.0.5/ai/mykg/mytool/convert/ConvertException.java
package ai.mykg.mytool.convert; /** * @author Goddy [goddy@mykg.ai] 2021/3/6 * @since 0.0.1 */ public class ConvertException extends Exception { private static final long serialVersionUID = -8712740708963245612L; public ConvertException(String message) { super(message); } }
0
java-sources/ai/nextbillion/gradle/0.2.2/ai/nextbillion
java-sources/ai/nextbillion/gradle/0.2.2/ai/nextbillion/nexbillionmaven/FileUtils.java
package ai.nextbillion.nexbillionmaven; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class FileUtils { public static void saveFileToFolder(File folderFile, String fileName, String fileContentData) { if (folderFile != null && !folderFile.exists()) { folderFile.mkdirs(); } File createFile = new File(folderFile, fileName); if (createFile.exists()) { boolean delete = createFile.delete(); } try { boolean create = createFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (createFile.exists()) { FileOutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; BufferedWriter writer = null; try { outputStream = new FileOutputStream(createFile); outputStreamWriter = new OutputStreamWriter(outputStream); writer = new BufferedWriter(outputStreamWriter); writer.write(fileContentData); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } if (outputStreamWriter != null) { outputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } public static void deleteFileByIO(String filePath) { File file = new File(filePath); File[] list = file.listFiles(); if (list != null) { for (File temp : list) { deleteFileByIO(temp.getAbsolutePath()); } } file.delete(); } }
0
java-sources/ai/nextbillion/gradle/0.2.2/ai/nextbillion
java-sources/ai/nextbillion/gradle/0.2.2/ai/nextbillion/nexbillionmaven/UploadInfo.java
package ai.nextbillion.nexbillionmaven; public class UploadInfo { public String groupId; public String artifactId; public String version; public String codeReportUrl; public String sdkName; public String sdkDescription; public boolean release; // maven2 user name public String userName; // maven2 user password public String password; // maven2 user email public String email = ""; public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getCodeReportUrl() { return codeReportUrl; } public void setCodeReportUrl(String codeReportUrl) { this.codeReportUrl = codeReportUrl; } public String getSdkName() { return sdkName; } public void setSdkName(String sdkName) { this.sdkName = sdkName; } public String getSdkDescription() { return sdkDescription; } public void setSdkDescription(String sdkDescription) { this.sdkDescription = sdkDescription; } public boolean isRelease() { return release; } public void setRelease(boolean release) { this.release = release; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "UploadInfo{" + "groupId='" + groupId + '\'' + ", artifactId='" + artifactId + '\'' + ", version='" + version + '\'' + ", codeReportUrl='" + codeReportUrl + '\'' + ", sdkName='" + sdkName + '\'' + ", sdkDescription='" + sdkDescription + '\'' + ", release=" + release + '}'; } }
0
java-sources/ai/nextbillion/gradle/0.2.2/ai/nextbillion
java-sources/ai/nextbillion/gradle/0.2.2/ai/nextbillion/nexbillionmaven/UploadInfoParser.java
package ai.nextbillion.nexbillionmaven; public class UploadInfoParser { public static UploadInfo getPublish(String buildContent) { if (!buildContent.contains("upload {") && !buildContent.contains("upload{")) { return null; } int startIndex = buildContent.indexOf("upload{"); if (startIndex == -1) { startIndex = buildContent.indexOf("upload {"); } if (startIndex == -1) { return null; } String upload = buildContent.substring(startIndex, buildContent.indexOf("}",startIndex)); UploadInfo publish = new UploadInfo(); String[] lines = upload.split("\n"); for (String line : lines) { if (line.trim().isEmpty()) { continue; } String[] parts = line.trim().split("="); if (parts.length != 2) { continue; } String key = parts[0].trim(); String value = parts[1].trim().replaceAll("\"|'", ""); switch (key) { case "groupId": publish.setGroupId(value); break; case "artifactId": publish.setArtifactId(value); break; case "version": publish.setVersion(value); break; case "codeReportUrl": publish.setCodeReportUrl(value); break; case "sdkName": publish.setSdkName(value); break; case "sdkDescription": publish.setSdkDescription(value); break; case "userName": publish.setUserName(value); break; case "password": publish.setPassword(value); break; case "email": publish.setEmail(value); case "release": publish.setRelease(Boolean.getBoolean(value)); break; default: throw new IllegalArgumentException("Invalid key: " + key); } } return publish; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/AndroidGesturesManager.java
package com.nbmap.android.gestures; import android.content.Context; import android.os.Build; import androidx.annotation.IntDef; import androidx.annotation.UiThread; import android.view.MotionEvent; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Entry point for all of the detectors. Set listener for gestures you'd like to be notified about * and pass all of the {@link MotionEvent}s through {@link #onTouchEvent(MotionEvent)} to start processing gestures. */ @UiThread public class AndroidGesturesManager { @Retention(RetentionPolicy.SOURCE) @IntDef( {GESTURE_TYPE_SCROLL, GESTURE_TYPE_SCALE, GESTURE_TYPE_ROTATE, GESTURE_TYPE_SHOVE, GESTURE_TYPE_MULTI_FINGER_TAP, GESTURE_TYPE_SINGLE_TAP_UP, GESTURE_TYPE_LONG_PRESS, GESTURE_TYPE_FLING, GESTURE_TYPE_SHOW_PRESS, GESTURE_TYPE_DOWN, GESTURE_TYPE_DOUBLE_TAP, GESTURE_TYPE_DOUBLE_TAP_EVENT, GESTURE_TYPE_SINGLE_TAP_CONFIRMED, GESTURE_TYPE_MOVE, GESTURE_TYPE_SIDEWAYS_SHOVE, GESTURE_TYPE_QUICK_SCALE }) public @interface GestureType { } public static final int GESTURE_TYPE_SCROLL = 0; public static final int GESTURE_TYPE_SCALE = 1; public static final int GESTURE_TYPE_ROTATE = 2; public static final int GESTURE_TYPE_SHOVE = 3; public static final int GESTURE_TYPE_MULTI_FINGER_TAP = 4; public static final int GESTURE_TYPE_SINGLE_TAP_UP = 5; public static final int GESTURE_TYPE_LONG_PRESS = 6; public static final int GESTURE_TYPE_FLING = 7; public static final int GESTURE_TYPE_SHOW_PRESS = 8; public static final int GESTURE_TYPE_DOWN = 9; public static final int GESTURE_TYPE_DOUBLE_TAP = 10; public static final int GESTURE_TYPE_DOUBLE_TAP_EVENT = 11; public static final int GESTURE_TYPE_SINGLE_TAP_CONFIRMED = 12; public static final int GESTURE_TYPE_MOVE = 13; public static final int GESTURE_TYPE_SIDEWAYS_SHOVE = 14; public static final int GESTURE_TYPE_QUICK_SCALE = 15; private final List<Set<Integer>> mutuallyExclusiveGestures = new ArrayList<>(); private final List<BaseGesture> detectors = new ArrayList<>(); private final StandardGestureDetector standardGestureDetector; private final StandardScaleGestureDetector standardScaleGestureDetector; private final RotateGestureDetector rotateGestureDetector; private final ShoveGestureDetector shoveGestureDetector; private final MultiFingerTapGestureDetector multiFingerTapGestureDetector; private final MoveGestureDetector moveGestureDetector; private final SidewaysShoveGestureDetector sidewaysShoveGestureDetector; /** * Creates a new instance of the {@link AndroidGesturesManager}. * * @param context activity's context */ public AndroidGesturesManager(Context context) { this(context, true); } /** * Creates a new instance of the {@link AndroidGesturesManager}. * * @param context activity's context * @param applyDefaultThresholds if true, default gestures thresholds and adjustments will be applied */ public AndroidGesturesManager(Context context, boolean applyDefaultThresholds) { this(context, new ArrayList<Set<Integer>>(), applyDefaultThresholds); } /** * Creates a new instance of the {@link AndroidGesturesManager}. * * @param context Activity's context * @param exclusiveGestures a number of sets of {@link GestureType}s that <b>should not</b> be invoked at the same. * This means that when a set contains a {@link ProgressiveGesture} and this gestures * is in progress no other gestures from the set will be invoked. * <p> * At the moment {@link #GESTURE_TYPE_SCROLL} is not interpreted as a progressive gesture * because it is not implemented this way by the * {@link androidx.core.view.GestureDetectorCompat}. */ @SafeVarargs public AndroidGesturesManager(Context context, Set<Integer>... exclusiveGestures) { this(context, Arrays.asList(exclusiveGestures), true); } /** * Creates a new instance of the {@link AndroidGesturesManager}. * * @param context Activity's context * @param exclusiveGestures a list of sets of {@link GestureType}s that <b>should not</b> be invoked at the same. * This means that when a set contains a {@link ProgressiveGesture} and this gestures * is in progress no other gestures from the set will be invoked. * <p> * At the moment {@link #GESTURE_TYPE_SCROLL} is not interpreted as * a progressive gesture because it is not implemented this way by the * {@link androidx.core.view.GestureDetectorCompat}. * @param applyDefaultThresholds if true, default gestures thresholds and adjustments will be applied */ public AndroidGesturesManager(Context context, List<Set<Integer>> exclusiveGestures, boolean applyDefaultThresholds) { this.mutuallyExclusiveGestures.addAll(exclusiveGestures); rotateGestureDetector = new RotateGestureDetector(context, this); standardScaleGestureDetector = new StandardScaleGestureDetector(context, this); shoveGestureDetector = new ShoveGestureDetector(context, this); sidewaysShoveGestureDetector = new SidewaysShoveGestureDetector(context, this); multiFingerTapGestureDetector = new MultiFingerTapGestureDetector(context, this); moveGestureDetector = new MoveGestureDetector(context, this); standardGestureDetector = new StandardGestureDetector(context, this); detectors.add(rotateGestureDetector); detectors.add(standardScaleGestureDetector); detectors.add(shoveGestureDetector); detectors.add(sidewaysShoveGestureDetector); detectors.add(multiFingerTapGestureDetector); detectors.add(moveGestureDetector); detectors.add(standardGestureDetector); if (applyDefaultThresholds) { initDefaultThresholds(); } } private void initDefaultThresholds() { for (BaseGesture detector : detectors) { if (detector instanceof MultiFingerGesture) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { ((MultiFingerGesture) detector).setSpanThresholdResource(R.dimen.nbmap_internalMinSpan23); } else { ((MultiFingerGesture) detector).setSpanThresholdResource(R.dimen.nbmap_internalMinSpan24); } } if (detector instanceof StandardScaleGestureDetector) { ((StandardScaleGestureDetector) detector).setSpanSinceStartThresholdResource( R.dimen.nbmap_defaultScaleSpanSinceStartThreshold); } if (detector instanceof ShoveGestureDetector) { ((ShoveGestureDetector) detector).setPixelDeltaThresholdResource(R.dimen.nbmap_defaultShovePixelThreshold); ((ShoveGestureDetector) detector).setMaxShoveAngle(Constants.DEFAULT_SHOVE_MAX_ANGLE); } if (detector instanceof SidewaysShoveGestureDetector) { ((SidewaysShoveGestureDetector) detector).setPixelDeltaThresholdResource( R.dimen.nbmap_defaultShovePixelThreshold); ((SidewaysShoveGestureDetector) detector).setMaxShoveAngle(Constants.DEFAULT_SHOVE_MAX_ANGLE); } if (detector instanceof MultiFingerTapGestureDetector) { ((MultiFingerTapGestureDetector) detector).setMultiFingerTapMovementThresholdResource( R.dimen.nbmap_defaultMultiTapMovementThreshold); ((MultiFingerTapGestureDetector) detector).setMultiFingerTapTimeThreshold( Constants.DEFAULT_MULTI_TAP_TIME_THRESHOLD); } if (detector instanceof RotateGestureDetector) { ((RotateGestureDetector) detector).setAngleThreshold(Constants.DEFAULT_ROTATE_ANGLE_THRESHOLD); } } } /** * Passes motion events to all gesture detectors. * * @param motionEvent event provided by the Android OS. * @return true if the touch event is handled by any gesture, false otherwise. */ public boolean onTouchEvent(MotionEvent motionEvent) { boolean isHandled = false; for (BaseGesture detector : detectors) { if (detector.onTouchEvent(motionEvent)) { isHandled = true; } } return isHandled; } /** * Sets a listener for all the events normally returned by the {@link androidx.core.view.GestureDetectorCompat}. * * @param listener your gestures listener * @see <a href="https://developer.android.com/training/gestures/index.html">Using Touch Gestures</a> * @see <a href="https://developer.android.com/reference/android/support/v4/view/GestureDetectorCompat.html">GestureDetectorCompat</a> */ public void setStandardGestureListener(StandardGestureDetector.StandardOnGestureListener listener) { standardGestureDetector.setListener(listener); } /** * Removes a listener for all the events normally returned by the * {@link androidx.core.view.GestureDetectorCompat}. */ public void removeStandardGestureListener() { standardGestureDetector.removeListener(); } /** * Sets a listener for scale gestures. * * @param listener your gestures listener */ public void setStandardScaleGestureListener(StandardScaleGestureDetector.StandardOnScaleGestureListener listener) { standardScaleGestureDetector.setListener(listener); } /** * Removes a listener for scale gestures. */ public void removeStandardScaleGestureListener() { standardScaleGestureDetector.removeListener(); } /** * Sets a listener for rotate gestures. * * @param listener your gestures listener */ public void setRotateGestureListener(RotateGestureDetector.OnRotateGestureListener listener) { rotateGestureDetector.setListener(listener); } /** * Removes a listener for rotate gestures. */ public void removeRotateGestureListener() { rotateGestureDetector.removeListener(); } /** * Sets a listener for shove gestures. * * @param listener your gestures listener */ public void setShoveGestureListener(ShoveGestureDetector.OnShoveGestureListener listener) { shoveGestureDetector.setListener(listener); } /** * Removes a listener for shove gestures. */ public void removeShoveGestureListener() { shoveGestureDetector.removeListener(); } /** * Sets a listener for multi finger tap gestures. * * @param listener your gestures listener */ public void setMultiFingerTapGestureListener(MultiFingerTapGestureDetector.OnMultiFingerTapGestureListener listener) { multiFingerTapGestureDetector.setListener(listener); } /** * Removes a listener for multi finger tap gestures. */ public void removeMultiFingerTapGestureListener() { multiFingerTapGestureDetector.removeListener(); } /** * Sets a listener for move gestures. * <p> * {@link MoveGestureDetector} serves similar purpose to * {@link com.nbmap.android.gestures.StandardGestureDetector.StandardOnGestureListener * #onScroll(MotionEvent, MotionEvent, float, float)}, however, it's a {@link ProgressiveGesture} that * introduces {@link MoveGestureDetector.OnMoveGestureListener#onMoveBegin(MoveGestureDetector)}, * {@link MoveGestureDetector.OnMoveGestureListener#onMoveEnd(MoveGestureDetector, float, float)}, * threshold with {@link MoveGestureDetector#setMoveThreshold(float)} and multi finger support thanks to * {@link MoveDistancesObject}. * * @param listener your gestures listener */ public void setMoveGestureListener(MoveGestureDetector.OnMoveGestureListener listener) { moveGestureDetector.setListener(listener); } /** * Removes a listener for move gestures. */ public void removeMoveGestureListener() { moveGestureDetector.removeListener(); } /** * Sets a listener for sideways shove gestures. * * @param listener your gestures listener */ public void setSidewaysShoveGestureListener(SidewaysShoveGestureDetector.OnSidewaysShoveGestureListener listener) { sidewaysShoveGestureDetector.setListener(listener); } /** * Removes a listener for sideways shove gestures. */ public void removeSidewaysShoveGestureListener() { sidewaysShoveGestureDetector.removeListener(); } /** * Get a list of all active gesture detectors. * * @return list of all gesture detectors */ public List<BaseGesture> getDetectors() { return detectors; } /** * Get gesture detector that wraps {@link androidx.core.view.GestureDetectorCompat}. * * @return gesture detector */ public StandardGestureDetector getStandardGestureDetector() { return standardGestureDetector; } /** * Get scale gesture detector. * * @return gesture detector */ public StandardScaleGestureDetector getStandardScaleGestureDetector() { return standardScaleGestureDetector; } /** * Get rotate gesture detector. * * @return gesture detector */ public RotateGestureDetector getRotateGestureDetector() { return rotateGestureDetector; } /** * Get shove gesture detector. * * @return gesture detector */ public ShoveGestureDetector getShoveGestureDetector() { return shoveGestureDetector; } /** * Get multi finger tap gesture detector. * * @return gesture detector */ public MultiFingerTapGestureDetector getMultiFingerTapGestureDetector() { return multiFingerTapGestureDetector; } /** * Get move gesture detector. * * @return gesture detector */ public MoveGestureDetector getMoveGestureDetector() { return moveGestureDetector; } /** * Get sideways shove gesture detector. * * @return gesture detector */ public SidewaysShoveGestureDetector getSidewaysShoveGestureDetector() { return sidewaysShoveGestureDetector; } /** * Sets a number of sets containing mutually exclusive gestures. * * @param exclusiveGestures a number of sets of {@link GestureType}s that <b>should not</b> be invoked at the same. * This means that when a set contains a {@link ProgressiveGesture} and this gestures * is in progress no other gestures from the set will be invoked. * <p> * At the moment {@link #GESTURE_TYPE_SCROLL} is not interpreted as a progressive gesture * because it is not interpreted this way by the * {@link androidx.core.view.GestureDetectorCompat}. */ @SafeVarargs public final void setMutuallyExclusiveGestures(Set<Integer>... exclusiveGestures) { setMutuallyExclusiveGestures(Arrays.asList(exclusiveGestures)); } /** * Sets a list of sets containing mutually exclusive gestures. * * @param exclusiveGestures a list of sets of {@link GestureType}s that <b>should not</b> be invoked at the same. * This means that when a set contains a {@link ProgressiveGesture} and this gestures * is in progress no other gestures from the set will be invoked. * <p> * At the moment {@link #GESTURE_TYPE_SCROLL} is not interpreted as a progressive gesture * because it is not interpreted this way by the * {@link androidx.core.view.GestureDetectorCompat}. */ public void setMutuallyExclusiveGestures(List<Set<Integer>> exclusiveGestures) { this.mutuallyExclusiveGestures.clear(); this.mutuallyExclusiveGestures.addAll(exclusiveGestures); } /** * Returns a list of sets containing mutually exclusive gestures. * * @return mutually exclusive gestures * @see #setMutuallyExclusiveGestures(List) */ public List<Set<Integer>> getMutuallyExclusiveGestures() { return mutuallyExclusiveGestures; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/BaseGesture.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.UiThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.MotionEvent; import android.view.WindowManager; import java.util.Set; /** * Base class for all of the gesture detectors. * * @param <L> listener that will be called with gesture events/updates. */ @UiThread public abstract class BaseGesture<L> { protected final Context context; protected final WindowManager windowManager; private final AndroidGesturesManager gesturesManager; private MotionEvent currentEvent; private MotionEvent previousEvent; private long gestureDuration; private boolean isEnabled = true; /** * Listener that will be called with gesture events/updates. */ protected L listener; public BaseGesture(Context context, AndroidGesturesManager gesturesManager) { this.context = context; this.windowManager = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)); this.gesturesManager = gesturesManager; } protected boolean onTouchEvent(MotionEvent motionEvent) { return analyze(motionEvent); } private boolean analyze(@Nullable MotionEvent motionEvent) { if (motionEvent == null) { return false; } if (previousEvent != null) { previousEvent.recycle(); previousEvent = null; } if (currentEvent != null) { previousEvent = MotionEvent.obtain(currentEvent); currentEvent.recycle(); currentEvent = null; } currentEvent = MotionEvent.obtain(motionEvent); gestureDuration = currentEvent.getEventTime() - currentEvent.getDownTime(); return analyzeEvent(motionEvent); } protected abstract boolean analyzeEvent(@NonNull MotionEvent motionEvent); protected boolean canExecute(@AndroidGesturesManager.GestureType int invokedGestureType) { if (listener == null || !isEnabled) { return false; } for (Set<Integer> exclusives : gesturesManager.getMutuallyExclusiveGestures()) { if (exclusives.contains(invokedGestureType)) { for (@AndroidGesturesManager.GestureType int gestureType : exclusives) { for (BaseGesture detector : gesturesManager.getDetectors()) { if (detector instanceof ProgressiveGesture) { ProgressiveGesture progressiveDetector = (ProgressiveGesture) detector; if (progressiveDetector.getHandledTypes().contains(gestureType) && progressiveDetector.isInProgress()) { return false; } } } } } } return true; } protected void setListener(L listener) { this.listener = listener; } protected void removeListener() { listener = null; } /** * Returns a difference in millis between {@link MotionEvent#getDownTime()} and {@link MotionEvent#getEventTime()} * (most recent event's time) associated with this gesture. * <p> * This is a duration of the user's total interaction with the touch screen, * accounting for the time before the gesture was recognized by the detector. * * @return duration of the gesture in millis. */ public long getGestureDuration() { return gestureDuration; } /** * Returns most recent event in this gesture chain. * * @return most recent event */ public MotionEvent getCurrentEvent() { return currentEvent; } /** * Returns previous event in this gesture chain. * * @return previous event */ public MotionEvent getPreviousEvent() { return previousEvent; } /** * Check whether this detector accepts and analyzes motion events. Default is true. * * @return true if it analyzes, false otherwise */ public boolean isEnabled() { return isEnabled; } /** * Set whether this detector should accept and analyze motion events. Default is true. * * @param enabled true if it should analyze, false otherwise */ public void setEnabled(boolean enabled) { isEnabled = enabled; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/Constants.java
package com.nbmap.android.gestures; public final class Constants { /** * Default angle change required in rotation movement to register rotate gesture./ */ public static final float DEFAULT_ROTATE_ANGLE_THRESHOLD = 15.3f; /** * Default angle between pointers (starting from horizontal line) required to abort shove gesture. */ public static final float DEFAULT_SHOVE_MAX_ANGLE = 20f; /** * Default time within which pointers need to leave the screen to register tap gesture. */ public static final long DEFAULT_MULTI_TAP_TIME_THRESHOLD = 150L; /*Private constants*/ static final String internal_scaleGestureDetectorMinSpanField = "mMinSpan"; static final String internal_scaleGestureDetectorSpanSlopField = "mSpanSlop"; }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/MoveDistancesObject.java
package com.nbmap.android.gestures; /** * Class that holds initial, previous and current X and Y on-screen coordinates for active pointers. */ public final class MoveDistancesObject { private final float initialX; private final float initialY; private float prevX; private float prevY; private float currX; private float currY; private float distanceXSinceLast; private float distanceYSinceLast; private float distanceXSinceStart; private float distanceYSinceStart; public MoveDistancesObject(float initialX, float initialY) { this.initialX = initialX; this.initialY = initialY; } /** * Add a new position of this pointer and recalculate distances. * @param x new X coordinate * @param y new Y coordinate */ public void addNewPosition(float x, float y) { prevX = currX; prevY = currY; currX = x; currY = y; distanceXSinceLast = prevX - currX; distanceYSinceLast = prevY - currY; distanceXSinceStart = initialX - currX; distanceYSinceStart = initialY - currY; } /** * Get X coordinate of this pointer when it was first register. * @return X coordinate */ public float getInitialX() { return initialX; } /** * Get Y coordinate of this pointer when it was first register. * @return Y coordinate */ public float getInitialY() { return initialY; } /** * Get previous X coordinate of this pointer. * @return X coordinate */ public float getPreviousX() { return prevX; } /** * Get previous Y coordinate of this pointer. * @return Y coordinate */ public float getPreviousY() { return prevY; } /** * Get current X coordinate of this pointer. * @return X coordinate */ public float getCurrentX() { return currX; } /** * Get current Y coordinate of this pointer. * @return Y coordinate */ public float getCurrentY() { return currY; } /** * Get X distance covered by this pointer since previous position. * @return X distance */ public float getDistanceXSinceLast() { return distanceXSinceLast; } /** * Get Y distance covered by this pointer since previous position. * @return Y distance */ public float getDistanceYSinceLast() { return distanceYSinceLast; } /** * Get X distance covered by this pointer since start position. * @return X distance */ public float getDistanceXSinceStart() { return distanceXSinceStart; } /** * Get Y distance covered by this pointer since start position. * @return Y distance */ public float getDistanceYSinceStart() { return distanceYSinceStart; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/MoveGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import android.graphics.PointF; import android.graphics.RectF; import android.view.MotionEvent; import androidx.annotation.DimenRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_MOVE; /** * Gesture detector handling move gesture. * <p> * {@link MoveGestureDetector} serves similar purpose to * {@link com.nbmap.android.gestures.StandardGestureDetector.StandardOnGestureListener * #onScroll(MotionEvent, MotionEvent, float, float)}, however, it's a {@link ProgressiveGesture} that * introduces {@link OnMoveGestureListener#onMoveBegin(MoveGestureDetector)}, * {@link OnMoveGestureListener#onMoveEnd(MoveGestureDetector, float, float)}, * threshold with {@link MoveGestureDetector#setMoveThreshold(float)} and multi finger support thanks to * {@link MoveDistancesObject}. */ @UiThread public class MoveGestureDetector extends ProgressiveGesture<MoveGestureDetector.OnMoveGestureListener> { private static final int MOVE_REQUIRED_POINTERS_COUNT = 1; private static final Set<Integer> handledTypes = new HashSet<>(); private PointF previousFocalPoint; private boolean resetFocal; float lastDistanceX; float lastDistanceY; static { handledTypes.add(GESTURE_TYPE_MOVE); } @Nullable private RectF moveThresholdRect; private float moveThreshold; private final Map<Integer, MoveDistancesObject> moveDistancesObjectMap = new HashMap<>(); public MoveGestureDetector(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); } @NonNull @Override protected Set<Integer> provideHandledTypes() { return handledTypes; } public interface OnMoveGestureListener { /** * Indicates that the move gesture started. * * @param detector this detector * @return true if you want to receive subsequent {@link #onMove(MoveGestureDetector, float, float)} callbacks, * false if you want to ignore this gesture. */ boolean onMoveBegin(@NonNull MoveGestureDetector detector); /** * Called for every move change during the gesture. * * @param detector this detector * @param distanceX X distance of the focal point in pixel since last call * @param distanceY Y distance of the focal point in pixel since last call * @return true if the gesture was handled, false otherwise */ boolean onMove(@NonNull MoveGestureDetector detector, float distanceX, float distanceY); /** * Indicates that the move gesture ended. * * @param velocityX velocityX of the gesture in the moment of lifting the fingers * @param velocityY velocityY of the gesture in the moment of lifting the fingers * @param detector this detector */ void onMoveEnd(@NonNull MoveGestureDetector detector, float velocityX, float velocityY); } public static class SimpleOnMoveGestureListener implements OnMoveGestureListener { @Override public boolean onMoveBegin(@NonNull MoveGestureDetector detector) { return true; } @Override public boolean onMove(@NonNull MoveGestureDetector detector, float distanceX, float distanceY) { return false; } @Override public void onMoveEnd(@NonNull MoveGestureDetector detector, float velocityX, float velocityY) { // No implementation } } @Override protected boolean analyzeEvent(@NonNull MotionEvent motionEvent) { switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: resetFocal = true; //recalculating focal point float x = motionEvent.getX(motionEvent.getActionIndex()); float y = motionEvent.getY(motionEvent.getActionIndex()); moveDistancesObjectMap.put( motionEvent.getPointerId(motionEvent.getActionIndex()), new MoveDistancesObject(x, y) ); break; case MotionEvent.ACTION_UP: moveDistancesObjectMap.clear(); break; case MotionEvent.ACTION_POINTER_UP: resetFocal = true; //recalculating focal point moveDistancesObjectMap.remove(motionEvent.getPointerId(motionEvent.getActionIndex())); break; case MotionEvent.ACTION_CANCEL: moveDistancesObjectMap.clear(); break; default: break; } return super.analyzeEvent(motionEvent); } @Override protected boolean analyzeMovement() { super.analyzeMovement(); updateMoveDistancesObjects(); if (isInProgress()) { PointF currentFocalPoint = getFocalPoint(); lastDistanceX = previousFocalPoint.x - currentFocalPoint.x; lastDistanceY = previousFocalPoint.y - currentFocalPoint.y; previousFocalPoint = currentFocalPoint; if (resetFocal) { resetFocal = false; return listener.onMove(this, 0, 0); } return listener.onMove(this, lastDistanceX, lastDistanceY); } else if (canExecute(GESTURE_TYPE_MOVE)) { if (listener.onMoveBegin(this)) { gestureStarted(); previousFocalPoint = getFocalPoint(); resetFocal = false; return true; } } return false; } private void updateMoveDistancesObjects() { for (int pointerId : pointerIdList) { moveDistancesObjectMap.get(pointerId).addNewPosition( getCurrentEvent().getX(getCurrentEvent().findPointerIndex(pointerId)), getCurrentEvent().getY(getCurrentEvent().findPointerIndex(pointerId)) ); } } boolean checkAnyMoveAboveThreshold() { for (MoveDistancesObject moveDistancesObject : moveDistancesObjectMap.values()) { boolean thresholdExceeded = Math.abs(moveDistancesObject.getDistanceXSinceStart()) >= moveThreshold || Math.abs(moveDistancesObject.getDistanceYSinceStart()) >= moveThreshold; boolean isInRect = moveThresholdRect != null && moveThresholdRect.contains(getFocalPoint().x, getFocalPoint().y); return !isInRect && thresholdExceeded; } return false; } @Override protected boolean canExecute(int invokedGestureType) { return super.canExecute(invokedGestureType) && checkAnyMoveAboveThreshold(); } @Override protected void reset() { super.reset(); } @Override protected void gestureStopped() { super.gestureStopped(); listener.onMoveEnd(this, velocityX, velocityY); } @Override protected int getRequiredPointersCount() { return MOVE_REQUIRED_POINTERS_COUNT; } /** * Get the delta pixel threshold required to qualify it as a move gesture. * * @return delta pixel threshold * @see #getMoveThresholdRect() */ public float getMoveThreshold() { return moveThreshold; } /** * Set the delta pixel threshold required to qualify it as a move gesture. * <p> * We encourage to set those values from dimens to accommodate for various screen sizes. * * @param moveThreshold delta threshold * @see #setMoveThresholdRect(RectF) */ public void setMoveThreshold(float moveThreshold) { this.moveThreshold = moveThreshold; } /** * Get the screen area in which the move gesture cannot be started. * If the gesture is already in progress, this value is ignored. * This condition is evaluated before {@link #setMoveThreshold(float)}. * * @return the screen area in which the gesture cannot be started */ @Nullable public RectF getMoveThresholdRect() { return moveThresholdRect; } /** * Set the screen area in which the move gesture cannot be started. * If the gesture is already in progress, this value is ignored. * This condition is evaluated before {@link #setMoveThreshold(float)}. * * @param moveThresholdRect the screen area in which the gesture cannot be started */ public void setMoveThresholdRect(@Nullable RectF moveThresholdRect) { this.moveThresholdRect = moveThresholdRect; } /** * Set the delta dp threshold required to qualify it as a move gesture. * * @param moveThresholdDimen delta threshold */ public void setMoveThresholdResource(@DimenRes int moveThresholdDimen) { setMoveThreshold(context.getResources().getDimension(moveThresholdDimen)); } /** * Returns X distance of the focal point in pixels * calculated during the last {@link OnMoveGestureListener#onMove(MoveGestureDetector, float, float)} call. * * @return X distance of the focal point in pixel */ public float getLastDistanceX() { return lastDistanceX; } /** * Returns Y distance of the focal point in pixels * calculated during the last {@link OnMoveGestureListener#onMove(MoveGestureDetector, float, float)} call. * * @return Y distance of the focal point in pixel */ public float getLastDistanceY() { return lastDistanceY; } /** * Returns {@link MoveDistancesObject} referencing the pointer held under passed index. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * * @param pointerIndex pointer's index * @return distances object of the referenced pointer */ public MoveDistancesObject getMoveObject(int pointerIndex) { if (isInProgress()) { if (pointerIndex >= 0 && pointerIndex < getPointersCount()) { return moveDistancesObjectMap.get(pointerIdList.get(pointerIndex)); } } return null; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/MultiFingerDistancesObject.java
package com.nbmap.android.gestures; /** * Object that holds pixel current and previous distances between a pair of fingers. */ public class MultiFingerDistancesObject { private final float prevFingersDiffX; private final float prevFingersDiffY; private final float currFingersDiffX; private final float currFingersDiffY; private final float prevFingersDiffXY; private final float currFingersDiffXY; public MultiFingerDistancesObject(float prevFingersDiffX, float prevFingersDiffY, float currFingersDiffX, float currFingersDiffY) { this.prevFingersDiffX = prevFingersDiffX; this.prevFingersDiffY = prevFingersDiffY; this.currFingersDiffX = currFingersDiffX; this.currFingersDiffY = currFingersDiffY; prevFingersDiffXY = (float) Math.sqrt(prevFingersDiffX * prevFingersDiffX + prevFingersDiffY * prevFingersDiffY); currFingersDiffXY = (float) Math.sqrt(currFingersDiffX * currFingersDiffX + currFingersDiffY * currFingersDiffY); } public float getPrevFingersDiffX() { return prevFingersDiffX; } public float getPrevFingersDiffY() { return prevFingersDiffY; } public float getCurrFingersDiffX() { return currFingersDiffX; } public float getCurrFingersDiffY() { return currFingersDiffY; } public float getPrevFingersDiffXY() { return prevFingersDiffXY; } public float getCurrFingersDiffXY() { return currFingersDiffXY; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/MultiFingerGesture.java
package com.nbmap.android.gestures; import android.content.Context; import android.graphics.PointF; import android.os.Build; import androidx.annotation.DimenRes; import androidx.annotation.UiThread; import androidx.annotation.NonNull; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.ViewConfiguration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.NoSuchElementException; /** * Base class for all multi finger gesture detectors. * * @param <L> listener that will be called with gesture events/updates. */ @UiThread public abstract class MultiFingerGesture<L> extends BaseGesture<L> { /** * This value is the threshold ratio between the previous combined pressure * and the current combined pressure. When pressure decreases rapidly * between events the position values can often be imprecise, as it usually * indicates that the user is in the process of lifting a pointer off of the * device. This value was tuned experimentally. * <p> * Thanks to Almer Thie (code.almeros.com). */ private static final float PRESSURE_THRESHOLD = 0.67f; private static final int DEFAULT_REQUIRED_FINGERS_COUNT = 2; private final float edgeSlop; private float spanThreshold; private final PermittedActionsGuard permittedActionsGuard = new PermittedActionsGuard(); /** * A list that holds IDs of currently active pointers in an order of activation. * First element is the oldest active pointer and last element is the most recently activated pointer. */ final List<Integer> pointerIdList = new ArrayList<>(); final HashMap<PointerDistancePair, MultiFingerDistancesObject> pointersDistanceMap = new HashMap<>(); private PointF focalPoint = new PointF(); private DisplayMetrics displayMetrics; public MultiFingerGesture(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); ViewConfiguration config = ViewConfiguration.get(context); edgeSlop = config.getScaledEdgeSlop(); queryDisplayMetrics(); } @Override protected boolean analyzeEvent(@NonNull MotionEvent motionEvent) { int action = motionEvent.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { // As orientation can change, query the metrics in touch down queryDisplayMetrics(); } boolean isMissingEvents = permittedActionsGuard.isMissingActions(action, motionEvent.getPointerCount(), pointerIdList.size()) || (action == MotionEvent.ACTION_MOVE && isMissingPointers(motionEvent)); if (isMissingEvents) { // stopping ProgressiveGestures and clearing pointers if (this instanceof ProgressiveGesture && ((ProgressiveGesture) this).isInProgress()) { ((ProgressiveGesture) this).gestureStopped(); } pointerIdList.clear(); pointersDistanceMap.clear(); } if (!isMissingEvents || action == MotionEvent.ACTION_DOWN) { // if we are not missing any actions or the invalid one happens // to be ACTION_DOWN (therefore, we can start over immediately), then update pointers updatePointerList(motionEvent); } focalPoint = Utils.determineFocalPoint(motionEvent); if (isMissingEvents) { Log.w("MultiFingerGesture", "Some MotionEvents were not passed to the library " + "or events from different view trees are merged."); return false; } else { if (action == MotionEvent.ACTION_MOVE) { if (pointerIdList.size() >= getRequiredPointersCount() && checkPressure()) { calculateDistances(); if (!isSloppyGesture()) { return analyzeMovement(); } } } } return false; } private void queryDisplayMetrics() { if (windowManager != null) { displayMetrics = new DisplayMetrics(); Display display = windowManager.getDefaultDisplay(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // get real metrics to take into account multi-window where application's visible bounds might be offset, // but we still need to operate on raw values display.getRealMetrics(displayMetrics); } else { // this method is relative to the applications visible bounds and will not return raw values display.getMetrics(displayMetrics); } } else { // this method is relative to the applications visible bounds and will not return raw values displayMetrics = context.getResources().getDisplayMetrics(); } } private void updatePointerList(MotionEvent motionEvent) { int action = motionEvent.getActionMasked(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) { pointerIdList.add(motionEvent.getPointerId(motionEvent.getActionIndex())); } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { pointerIdList.remove(Integer.valueOf(motionEvent.getPointerId(motionEvent.getActionIndex()))); } } private boolean isMissingPointers(MotionEvent motionEvent) { for (int pointerId : pointerIdList) { boolean hasPointer = motionEvent.findPointerIndex(pointerId) != -1; if (!hasPointer) { return true; } } return false; } boolean checkPressure() { float currentPressure = getCurrentEvent().getPressure(); float previousPressure = getPreviousEvent().getPressure(); return currentPressure / previousPressure > PRESSURE_THRESHOLD; } private boolean checkSpanBelowThreshold() { for (MultiFingerDistancesObject distancesObject : pointersDistanceMap.values()) { if (distancesObject.getCurrFingersDiffXY() < spanThreshold) { return true; } } return false; } protected int getRequiredPointersCount() { return DEFAULT_REQUIRED_FINGERS_COUNT; } protected boolean analyzeMovement() { return false; } /** * Check if we have a sloppy gesture. Sloppy gestures can happen if the edge * of the user's hand is touching the screen, for example. * <p> * Thanks to Almer Thie (code.almeros.com). * * @return true if we detect sloppy gesture, false otherwise */ protected boolean isSloppyGesture() { float rightSlopEdge = displayMetrics.widthPixels - edgeSlop; float bottomSlopEdge = displayMetrics.heightPixels - edgeSlop; final float edgeSlop = this.edgeSlop; for (int pointerId : pointerIdList) { int pointerIndex = getCurrentEvent().findPointerIndex(pointerId); float x = Utils.getRawX(getCurrentEvent(), pointerIndex); float y = Utils.getRawY(getCurrentEvent(), pointerIndex); boolean isSloppy = x < edgeSlop || y < edgeSlop || x > rightSlopEdge || y > bottomSlopEdge; if (isSloppy) { return true; } } return checkSpanBelowThreshold(); } @Override protected boolean canExecute(int invokedGestureType) { return super.canExecute(invokedGestureType) && !isSloppyGesture(); } protected void reset() { } private void calculateDistances() { pointersDistanceMap.clear(); for (int i = 0; i < pointerIdList.size() - 1; i++) { for (int j = i + 1; j < pointerIdList.size(); j++) { int primaryPointerId = pointerIdList.get(i); int secondaryPointerId = pointerIdList.get(j); float px0 = getPreviousEvent().getX(getPreviousEvent().findPointerIndex(primaryPointerId)); float py0 = getPreviousEvent().getY(getPreviousEvent().findPointerIndex(primaryPointerId)); float px1 = getPreviousEvent().getX(getPreviousEvent().findPointerIndex(secondaryPointerId)); float py1 = getPreviousEvent().getY(getPreviousEvent().findPointerIndex(secondaryPointerId)); float prevFingersDiffX = px1 - px0; float prevFingersDiffY = py1 - py0; float cx0 = getCurrentEvent().getX(getCurrentEvent().findPointerIndex(primaryPointerId)); float cy0 = getCurrentEvent().getY(getCurrentEvent().findPointerIndex(primaryPointerId)); float cx1 = getCurrentEvent().getX(getCurrentEvent().findPointerIndex(secondaryPointerId)); float cy1 = getCurrentEvent().getY(getCurrentEvent().findPointerIndex(secondaryPointerId)); float currFingersDiffX = cx1 - cx0; float currFingersDiffY = cy1 - cy0; pointersDistanceMap.put(new PointerDistancePair(primaryPointerId, secondaryPointerId), new MultiFingerDistancesObject( prevFingersDiffX, prevFingersDiffY, currFingersDiffX, currFingersDiffY) ); } } } /** * Returns the current distance between the two pointers forming the * gesture in progress. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * The order of parameters is irrelevant. * * @param firstPointerIndex one of pointers indexes * @param secondPointerIndex one of pointers indexes * @return Distance between pointers in pixels. * @see #pointerIdList */ public float getCurrentSpan(int firstPointerIndex, int secondPointerIndex) { if (!verifyPointers(firstPointerIndex, secondPointerIndex)) { throw new NoSuchElementException("There is no such pair of pointers!"); } MultiFingerDistancesObject distancesObject = pointersDistanceMap.get( new PointerDistancePair(pointerIdList.get(firstPointerIndex), pointerIdList.get(secondPointerIndex))); return distancesObject.getCurrFingersDiffXY(); } /** * Returns the previous distance between the two pointers forming the * gesture in progress. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * The order of parameters is irrelevant. * * @param firstPointerIndex one of pointers indexes * @param secondPointerIndex one of pointers indexes * @return Previous distance between pointers in pixels. * @see #pointerIdList */ public float getPreviousSpan(int firstPointerIndex, int secondPointerIndex) { if (!verifyPointers(firstPointerIndex, secondPointerIndex)) { throw new NoSuchElementException("There is no such pair of pointers!"); } MultiFingerDistancesObject distancesObject = pointersDistanceMap.get( new PointerDistancePair(pointerIdList.get(firstPointerIndex), pointerIdList.get(secondPointerIndex))); return distancesObject.getPrevFingersDiffXY(); } /** * Returns current X distance between pointers in pixels. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * The order of parameters is irrelevant. * * @param firstPointerIndex one of pointers indexes * @param secondPointerIndex one of pointers indexes * @return Current X distance between pointers in pixels. * @see #pointerIdList */ public float getCurrentSpanX(int firstPointerIndex, int secondPointerIndex) { if (!verifyPointers(firstPointerIndex, secondPointerIndex)) { throw new NoSuchElementException("There is no such pair of pointers!"); } MultiFingerDistancesObject distancesObject = pointersDistanceMap.get( new PointerDistancePair(pointerIdList.get(firstPointerIndex), pointerIdList.get(secondPointerIndex))); return Math.abs(distancesObject.getCurrFingersDiffX()); } /** * Returns current Y distance between pointers in pixels. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * The order of parameters is irrelevant. * * @param firstPointerIndex one of pointers indexes * @param secondPointerIndex one of pointers indexes * @return Current Y distance between pointers in pixels. * @see #pointerIdList */ public float getCurrentSpanY(int firstPointerIndex, int secondPointerIndex) { if (!verifyPointers(firstPointerIndex, secondPointerIndex)) { throw new NoSuchElementException("There is no such pair of pointers!"); } MultiFingerDistancesObject distancesObject = pointersDistanceMap.get( new PointerDistancePair(pointerIdList.get(firstPointerIndex), pointerIdList.get(secondPointerIndex))); return Math.abs(distancesObject.getCurrFingersDiffY()); } /** * Returns previous X distance between pointers in pixels. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * The order of parameters is irrelevant. * * @param firstPointerIndex one of pointers indexes * @param secondPointerIndex one of pointers indexes * @return Previous X distance between pointers in pixels. * @see #pointerIdList */ public float getPreviousSpanX(int firstPointerIndex, int secondPointerIndex) { if (!verifyPointers(firstPointerIndex, secondPointerIndex)) { throw new NoSuchElementException("There is no such pair of pointers!"); } MultiFingerDistancesObject distancesObject = pointersDistanceMap.get( new PointerDistancePair(pointerIdList.get(firstPointerIndex), pointerIdList.get(secondPointerIndex))); return Math.abs(distancesObject.getPrevFingersDiffX()); } /** * Returns previous Y distance between pointers in pixels. * <p> * Pointers are sorted by the time they were placed on the screen until lifted up. * This means that index 0 will reflect the oldest added, still active pointer * and index ({@link #getPointersCount()} - 1) will reflect the latest added, still active pointer. * <p> * The order of parameters is irrelevant. * * @param firstPointerIndex one of pointers indexes * @param secondPointerIndex one of pointers indexes * @return Previous Y distance between pointers in pixels. * @see #pointerIdList */ public float getPreviousSpanY(int firstPointerIndex, int secondPointerIndex) { if (!verifyPointers(firstPointerIndex, secondPointerIndex)) { throw new NoSuchElementException("There is no such pair of pointers!"); } MultiFingerDistancesObject distancesObject = pointersDistanceMap.get( new PointerDistancePair(pointerIdList.get(firstPointerIndex), pointerIdList.get(secondPointerIndex))); return Math.abs(distancesObject.getPrevFingersDiffY()); } private boolean verifyPointers(int firstPointerIndex, int secondPointerIndex) { return firstPointerIndex != secondPointerIndex && firstPointerIndex >= 0 && secondPointerIndex >= 0 && firstPointerIndex < getPointersCount() && secondPointerIndex < getPointersCount(); } /** * Returns the number of active pointers. * * @return number of active pointers. */ public int getPointersCount() { return pointerIdList.size(); } /** * Returns a center point of this gesture. * * @return center point of this gesture. */ public PointF getFocalPoint() { return focalPoint; } /** * Get minimum span between any pair of finger that is required to pass motion events to this detector. * * @return minimum span */ public float getSpanThreshold() { return spanThreshold; } /** * Set minimum span in pixels between any pair of finger that is required to pass motion events to this detector. * <p> * We encourage to set those values from dimens to accommodate for various screen sizes. * * @param spanThreshold minimum span */ public void setSpanThreshold(float spanThreshold) { this.spanThreshold = spanThreshold; } /** * Set minimum span in dp between any pair of finger that is required to pass motion events to this detector. * * @param spanThresholdDimen minimum span */ public void setSpanThresholdResource(@DimenRes int spanThresholdDimen) { setSpanThreshold(context.getResources().getDimension(spanThresholdDimen)); } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/MultiFingerTapGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.DimenRes; import androidx.annotation.UiThread; import androidx.annotation.NonNull; import android.view.MotionEvent; import java.util.HashMap; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_MULTI_FINGER_TAP; /** * Gesture detector handling multi tap gesture. */ @UiThread public class MultiFingerTapGestureDetector extends MultiFingerGesture<MultiFingerTapGestureDetector.OnMultiFingerTapGestureListener> { /** * Maximum time in millis to lift the fingers to register a tap event. */ private long multiFingerTapTimeThreshold; /** * Maximum movement in pixels allowed for any finger before rejecting this gesture. */ private float multiFingerTapMovementThreshold; private boolean invalidMovement; private boolean pointerLifted; private int lastPointersDownCount; public MultiFingerTapGestureDetector(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); } public interface OnMultiFingerTapGestureListener { boolean onMultiFingerTap(@NonNull MultiFingerTapGestureDetector detector, int pointersCount); } @Override protected boolean analyzeEvent(@NonNull MotionEvent motionEvent) { super.analyzeEvent(motionEvent); int action = motionEvent.getActionMasked(); switch (action) { case MotionEvent.ACTION_POINTER_DOWN: if (pointerLifted) { invalidMovement = true; } lastPointersDownCount = pointerIdList.size(); break; case MotionEvent.ACTION_POINTER_UP: pointerLifted = true; break; case MotionEvent.ACTION_UP: boolean canExecute = canExecute(GESTURE_TYPE_MULTI_FINGER_TAP); boolean handled = false; if (canExecute) { handled = listener.onMultiFingerTap(this, lastPointersDownCount); } reset(); return handled; case MotionEvent.ACTION_MOVE: if (invalidMovement) { break; } invalidMovement = exceededMovementThreshold(pointersDistanceMap); break; default: break; } return false; } boolean exceededMovementThreshold(HashMap<PointerDistancePair, MultiFingerDistancesObject> map) { for (MultiFingerDistancesObject distancesObject : map.values()) { float diffX = Math.abs(distancesObject.getCurrFingersDiffX() - distancesObject.getPrevFingersDiffX()); float diffY = Math.abs(distancesObject.getCurrFingersDiffY() - distancesObject.getPrevFingersDiffY()); invalidMovement = diffX > multiFingerTapMovementThreshold || diffY > multiFingerTapMovementThreshold; if (invalidMovement) { return true; } } return false; } @Override protected boolean canExecute(int invokedGestureType) { return lastPointersDownCount > 1 && !invalidMovement && getGestureDuration() < multiFingerTapTimeThreshold && super.canExecute(invokedGestureType); } @Override protected void reset() { super.reset(); lastPointersDownCount = 0; invalidMovement = false; pointerLifted = false; } /** * Get maximum time in millis that fingers can have a contact with the screen before rejecting this gesture. * * @return maximum touch time for tap gesture. */ public long getMultiFingerTapTimeThreshold() { return multiFingerTapTimeThreshold; } /** * Set maximum time in millis that fingers can have a contact with the screen before rejecting this gesture. * * @param multiFingerTapTimeThreshold maximum touch time for tap gesture. */ public void setMultiFingerTapTimeThreshold(long multiFingerTapTimeThreshold) { this.multiFingerTapTimeThreshold = multiFingerTapTimeThreshold; } /** * Get maximum movement allowed for any finger before rejecting this gesture. * * @return movement threshold in pixels. */ public float getMultiFingerTapMovementThreshold() { return multiFingerTapMovementThreshold; } /** * Set maximum movement allowed in pixels for any finger before rejecting this gesture. * <p> * We encourage to set those values from dimens to accommodate for various screen sizes. * * @param multiFingerTapMovementThreshold movement threshold. */ public void setMultiFingerTapMovementThreshold(float multiFingerTapMovementThreshold) { this.multiFingerTapMovementThreshold = multiFingerTapMovementThreshold; } /** * Set maximum movement allowed in dp for any finger before rejecting this gesture. * * @param multiFingerTapMovementThresholdDimen movement threshold. */ public void setMultiFingerTapMovementThresholdResource(@DimenRes int multiFingerTapMovementThresholdDimen) { setMultiFingerTapMovementThreshold(context.getResources().getDimension(multiFingerTapMovementThresholdDimen)); } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/PermittedActionsGuard.java
package com.nbmap.android.gestures; import androidx.annotation.IntRange; import android.view.MotionEvent; class PermittedActionsGuard { /** * Enables to store up to 8 permitted actions in the long type (64 bits / 8 bits per action). */ private static final int BITS_PER_PERMITTED_ACTION = 8; private static final int PERMITTED_ACTION_MASK = ((1 << BITS_PER_PERMITTED_ACTION) - 1); private static final int NO_ACTION_PERMITTED = 0b11111111; boolean isMissingActions(int action, @IntRange(from = 0) int eventPointerCount, @IntRange(from = 0) int internalPointerCount) { long permittedActions = updatePermittedActions(eventPointerCount, internalPointerCount); if (action == permittedActions) { // this will only happen for action == permittedActions == ACTION_DOWN return false; } while (permittedActions != 0) { // get one of actions, the one on the first BITS_PER_PERMITTED_ACTION bits long testCase = permittedActions & PERMITTED_ACTION_MASK; if (action == testCase) { // we got a match, all good return false; } // remove the one we just checked and iterate permittedActions = permittedActions >> BITS_PER_PERMITTED_ACTION; } // no available matching actions, we are missing some! return true; } /** * Returns all acceptable at this point MotionEvent actions based on the pointers state. * Each one of them is written on {@link #BITS_PER_PERMITTED_ACTION} successive bits. */ private long updatePermittedActions(@IntRange(from = 0) int eventPointerCount, @IntRange(from = 0) int internalPointerCount) { long permittedActions = MotionEvent.ACTION_DOWN; if (internalPointerCount == 0) { // only ACTION_DOWN available when no other pointers registered permittedActions = permittedActions << BITS_PER_PERMITTED_ACTION; permittedActions += MotionEvent.ACTION_DOWN; } else { if (Math.abs(eventPointerCount - internalPointerCount) > 1) { // missing a pointer up/down event, required to start over return NO_ACTION_PERMITTED; } else { if (eventPointerCount > internalPointerCount) { // event holds one more pointer than we have locally permittedActions = permittedActions << BITS_PER_PERMITTED_ACTION; permittedActions += MotionEvent.ACTION_POINTER_DOWN; } else if (eventPointerCount < internalPointerCount) { // event holds one less pointer than we have locally. This indicates that we are missing events, // because ACTION_UP and ACTION_POINTER_UP events still return not decremented pointer count return NO_ACTION_PERMITTED; } else { // event holds an equal number of pointers compared to the local count if (eventPointerCount == 1) { permittedActions = permittedActions << BITS_PER_PERMITTED_ACTION; permittedActions += MotionEvent.ACTION_UP; } else { permittedActions = permittedActions << BITS_PER_PERMITTED_ACTION; permittedActions += MotionEvent.ACTION_POINTER_UP; } permittedActions = permittedActions << BITS_PER_PERMITTED_ACTION; permittedActions += MotionEvent.ACTION_MOVE; } } } return permittedActions; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/PointerDistancePair.java
package com.nbmap.android.gestures; import android.util.Pair; public class PointerDistancePair extends Pair<Integer, Integer> { public PointerDistancePair(Integer first, Integer second) { super(first, second); } @Override public boolean equals(Object o) { if (o instanceof PointerDistancePair) { PointerDistancePair otherPair = (PointerDistancePair) o; if ((this.first.equals(otherPair.first) && this.second.equals(otherPair.second)) || (this.first.equals(otherPair.second) && this.second.equals(otherPair.first))) { return true; } } return false; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/ProgressiveGesture.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.UiThread; import android.view.MotionEvent; import android.view.VelocityTracker; import java.util.Set; /** * Base class for all progressive gesture detectors. * * @param <L> listener that will be called with gesture events/updates. */ @UiThread public abstract class ProgressiveGesture<L> extends MultiFingerGesture<L> { private final Set<Integer> handledTypes = provideHandledTypes(); private boolean isInProgress; private boolean interrupted; VelocityTracker velocityTracker; float velocityX; float velocityY; public ProgressiveGesture(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); } @NonNull protected abstract Set<Integer> provideHandledTypes(); @Override protected boolean analyzeEvent(@NonNull MotionEvent motionEvent) { int action = motionEvent.getActionMasked(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN || action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_CANCEL) { // configuration changed, reset data reset(); } if (interrupted) { interrupted = false; reset(); gestureStopped(); } if (velocityTracker != null) { velocityTracker.addMovement(getCurrentEvent()); } boolean movementHandled = super.analyzeEvent(motionEvent); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { if (pointerIdList.size() < getRequiredPointersCount() && isInProgress) { gestureStopped(); return true; } } else if (action == MotionEvent.ACTION_CANCEL) { if (isInProgress) { gestureStopped(); return true; } } return movementHandled; } protected void gestureStarted() { isInProgress = true; if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } } protected void gestureStopped() { isInProgress = false; if (velocityTracker != null) { velocityTracker.computeCurrentVelocity(1000); velocityX = velocityTracker.getXVelocity(); velocityY = velocityTracker.getYVelocity(); velocityTracker.recycle(); velocityTracker = null; } reset(); } Set<Integer> getHandledTypes() { return handledTypes; } /** * Check whether a gesture has started and is in progress. * * @return true if gesture is in progress, false otherwise. */ public boolean isInProgress() { return isInProgress; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (!enabled) { interrupt(); } } /** * Interrupt a gesture by stopping it's execution immediately. * Forces gesture detector to meet start conditions again in order to resume. */ public void interrupt() { if (isInProgress()) { this.interrupted = true; } } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/RotateGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.UiThread; import java.util.HashSet; import java.util.Set; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_ROTATE; /** * Gesture detector handling rotation gesture. */ @UiThread public class RotateGestureDetector extends ProgressiveGesture<RotateGestureDetector.OnRotateGestureListener> { private static final Set<Integer> handledTypes = new HashSet<>(); static { handledTypes.add(GESTURE_TYPE_ROTATE); } private float angleThreshold; float deltaSinceStart; float deltaSinceLast; public RotateGestureDetector(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); } @NonNull @Override protected Set<Integer> provideHandledTypes() { return handledTypes; } /** * Listener for rotate gesture callbacks. */ public interface OnRotateGestureListener { /** * Indicates that the rotation gesture started. * * @param detector this detector * @return true if you want to receive subsequent {@link #onRotate(RotateGestureDetector, float, float)} callbacks, * false if you want to ignore this gesture. */ boolean onRotateBegin(@NonNull RotateGestureDetector detector); /** * Called for every rotation change during the gesture. * * @param detector this detector * @param rotationDegreesSinceLast rotation change since the last call * @param rotationDegreesSinceFirst rotation change since the start of the gesture * @return true if the gesture was handled, false otherwise */ boolean onRotate(@NonNull RotateGestureDetector detector, float rotationDegreesSinceLast, float rotationDegreesSinceFirst); /** * Indicates that the rotation gesture ended. * * @param velocityX velocityX of the gesture in the moment of lifting the fingers * @param velocityY velocityY of the gesture in the moment of lifting the fingers * @param angularVelocity angularVelocity of the gesture in the moment of lifting the fingers * @param detector this detector */ void onRotateEnd(@NonNull RotateGestureDetector detector, float velocityX, float velocityY, float angularVelocity); } public static class SimpleOnRotateGestureListener implements OnRotateGestureListener { @Override public boolean onRotateBegin(@NonNull RotateGestureDetector detector) { return true; } @Override public boolean onRotate(@NonNull RotateGestureDetector detector, float rotationDegreesSinceLast, float rotationDegreesSinceFirst) { return true; } @Override public void onRotateEnd(@NonNull RotateGestureDetector detector, float velocityX, float velocityY, float angularVelocity) { // No implementation } } @Override protected boolean analyzeMovement() { super.analyzeMovement(); deltaSinceLast = getRotationDegreesSinceLast(); deltaSinceStart += deltaSinceLast; if (isInProgress() && deltaSinceLast != 0) { return listener.onRotate(this, deltaSinceLast, deltaSinceStart); } else if (canExecute(GESTURE_TYPE_ROTATE)) { if (listener.onRotateBegin(this)) { gestureStarted(); return true; } } return false; } @Override protected boolean canExecute(int invokedGestureType) { return Math.abs(deltaSinceStart) >= angleThreshold && super.canExecute(invokedGestureType); } @Override protected void gestureStopped() { super.gestureStopped(); if (deltaSinceLast == 0) { velocityX = 0; velocityY = 0; } float angularVelocity = calculateAngularVelocityVector(velocityX, velocityY); listener.onRotateEnd(this, velocityX, velocityY, angularVelocity); } @Override protected void reset() { super.reset(); deltaSinceStart = 0f; } float getRotationDegreesSinceLast() { MultiFingerDistancesObject distancesObject = pointersDistanceMap.get(new PointerDistancePair(pointerIdList.get(0), pointerIdList.get(1))); double diffRadians = Math.atan2(distancesObject.getPrevFingersDiffY(), distancesObject.getPrevFingersDiffX()) - Math.atan2( distancesObject.getCurrFingersDiffY(), distancesObject.getCurrFingersDiffX()); return (float) Math.toDegrees(diffRadians); } float calculateAngularVelocityVector(float velocityX, float velocityY) { float angularVelocity = Math.abs((float) ((getFocalPoint().x * velocityY + getFocalPoint().y * velocityX) / (Math.pow(getFocalPoint().x, 2.0) + Math.pow(getFocalPoint().y, 2.0)))); if (deltaSinceLast < 0) { angularVelocity = -angularVelocity; } return angularVelocity; } /** * Returns rotation change in degrees since the start of the gesture. * * @return rotation change since the start of the gesture */ public float getDeltaSinceStart() { return deltaSinceStart; } /** * Returns last rotation change difference in degrees * calculated in {@link OnRotateGestureListener#onRotate(RotateGestureDetector, float, float)} * * @return rotation change since last callback */ public float getDeltaSinceLast() { return deltaSinceLast; } /** * Get the threshold angle between first and current fingers position * for this detector to actually qualify it as a rotation gesture. * * @return Angle threshold for rotation gesture */ public float getAngleThreshold() { return angleThreshold; } /** * Set the threshold angle between first and current fingers position * for this detector to actually qualify it as a rotation gesture. * * @param angleThreshold angle threshold for rotation gesture */ public void setAngleThreshold(float angleThreshold) { this.angleThreshold = angleThreshold; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/ShoveGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.DimenRes; import androidx.annotation.NonNull; import androidx.annotation.UiThread; import java.util.HashSet; import java.util.Set; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SHOVE; /** * Gesture detector handling shove gesture. */ @UiThread public class ShoveGestureDetector extends ProgressiveGesture<ShoveGestureDetector.OnShoveGestureListener> { private static final Set<Integer> handledTypes = new HashSet<>(); static { handledTypes.add(GESTURE_TYPE_SHOVE); } private float maxShoveAngle; private float pixelDeltaThreshold; float deltaPixelsSinceStart; float deltaPixelSinceLast; public ShoveGestureDetector(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); } @NonNull @Override protected Set<Integer> provideHandledTypes() { return handledTypes; } /** * Listener for shove callbacks. */ public interface OnShoveGestureListener { /** * Indicates that the shove gesture started. * * @param detector this detector * @return true if you want to receive subsequent {@link #onShove(ShoveGestureDetector, float, float)} callbacks, * false if you want to ignore this gesture. */ boolean onShoveBegin(@NonNull ShoveGestureDetector detector); /** * Called for every shove change during the gesture. * * @param detector this detector * @param deltaPixelsSinceLast pixels delta change since the last call * @param deltaPixelsSinceStart pixels delta change since the start of the gesture * @return true if the gesture was handled, false otherwise */ boolean onShove(@NonNull ShoveGestureDetector detector, float deltaPixelsSinceLast, float deltaPixelsSinceStart); /** * Indicates that the shove gesture ended. * * @param velocityX velocityX of the gesture in the moment of lifting the fingers * @param velocityY velocityY of the gesture in the moment of lifting the fingers * @param detector this detector */ void onShoveEnd(@NonNull ShoveGestureDetector detector, float velocityX, float velocityY); } public static class SimpleOnShoveGestureListener implements OnShoveGestureListener { @Override public boolean onShoveBegin(@NonNull ShoveGestureDetector detector) { return true; } @Override public boolean onShove(@NonNull ShoveGestureDetector detector, float deltaPixelsSinceLast, float deltaPixelsSinceStart) { return false; } @Override public void onShoveEnd(@NonNull ShoveGestureDetector detector, float velocityX, float velocityY) { // No Implementation } } @Override protected boolean analyzeMovement() { super.analyzeMovement(); deltaPixelSinceLast = calculateDeltaPixelsSinceLast(); deltaPixelsSinceStart += deltaPixelSinceLast; if (isInProgress() && deltaPixelSinceLast != 0) { return listener.onShove(this, deltaPixelSinceLast, deltaPixelsSinceStart); } else if (canExecute(GESTURE_TYPE_SHOVE)) { if (listener.onShoveBegin(this)) { gestureStarted(); return true; } } return false; } @Override protected boolean canExecute(int invokedGestureType) { return Math.abs(deltaPixelsSinceStart) >= pixelDeltaThreshold && super.canExecute(invokedGestureType); } @Override protected boolean isSloppyGesture() { return super.isSloppyGesture() || !isAngleAcceptable(); } @Override protected void gestureStopped() { super.gestureStopped(); listener.onShoveEnd(this, velocityX, velocityY); } @Override protected void reset() { super.reset(); deltaPixelsSinceStart = 0; } boolean isAngleAcceptable() { MultiFingerDistancesObject distancesObject = pointersDistanceMap.get(new PointerDistancePair(pointerIdList.get(0), pointerIdList.get(1))); // Takes values from 0 to 180 double angle = Math.toDegrees(Math.abs(Math.atan2( distancesObject.getCurrFingersDiffY(), distancesObject.getCurrFingersDiffX()))); return angle <= maxShoveAngle || 180f - angle <= maxShoveAngle; } float calculateDeltaPixelsSinceLast() { float py0 = getPreviousEvent().getY(getPreviousEvent().findPointerIndex(pointerIdList.get(0))); float py1 = getPreviousEvent().getY(getPreviousEvent().findPointerIndex(pointerIdList.get(1))); float prevAverageY = (py0 + py1) / 2.0f; float cy0 = getCurrentEvent().getY(getCurrentEvent().findPointerIndex(pointerIdList.get(0))); float cy1 = getCurrentEvent().getY(getCurrentEvent().findPointerIndex(pointerIdList.get(1))); float currAverageY = (cy0 + cy1) / 2.0f; return currAverageY - prevAverageY; } /** * Returns vertical pixel delta change since the start of the gesture. * * @return pixels delta change since the start of the gesture */ public float getDeltaPixelsSinceStart() { return deltaPixelsSinceStart; } /** * Returns last vertical pixel delta change * calculated in {@link OnShoveGestureListener#onShove(ShoveGestureDetector, float, float)}. * * @return pixels delta change since the last call */ public float getDeltaPixelSinceLast() { return deltaPixelSinceLast; } /** * Get the delta pixel threshold required to qualify it as a shove gesture. * * @return delta pixel threshold */ public float getPixelDeltaThreshold() { return pixelDeltaThreshold; } /** * Set the delta pixel threshold required to qualify it as a shove gesture. * <p> * We encourage to set those values from dimens to accommodate for various screen sizes. * * @param pixelDeltaThreshold delta threshold */ public void setPixelDeltaThreshold(float pixelDeltaThreshold) { this.pixelDeltaThreshold = pixelDeltaThreshold; } /** * Set the delta dp threshold required to qualify it as a shove gesture. * * @param pixelDeltaThresholdDimen delta threshold */ public void setPixelDeltaThresholdResource(@DimenRes int pixelDeltaThresholdDimen) { setPixelDeltaThreshold(context.getResources().getDimension(pixelDeltaThresholdDimen)); } /** * Get the maximum allowed angle between fingers, measured from the horizontal line, to qualify it as a shove gesture. * * @return maximum allowed angle */ public float getMaxShoveAngle() { return maxShoveAngle; } /** * Set the maximum allowed angle between fingers, measured from the horizontal line, to qualify it as a shove gesture. * * @param maxShoveAngle maximum allowed angle */ public void setMaxShoveAngle(float maxShoveAngle) { this.maxShoveAngle = maxShoveAngle; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/SidewaysShoveGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.DimenRes; import androidx.annotation.NonNull; import androidx.annotation.UiThread; import java.util.HashSet; import java.util.Set; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SIDEWAYS_SHOVE; /** * Gesture detector handling sideways shove gesture. */ @UiThread public class SidewaysShoveGestureDetector extends ProgressiveGesture<SidewaysShoveGestureDetector.OnSidewaysShoveGestureListener> { private static final Set<Integer> handledTypes = new HashSet<>(); static { handledTypes.add(GESTURE_TYPE_SIDEWAYS_SHOVE); } private float maxShoveAngle; private float pixelDeltaThreshold; float deltaPixelsSinceStart; float deltaPixelSinceLast; public SidewaysShoveGestureDetector(Context context, AndroidGesturesManager gesturesManager) { super(context, gesturesManager); } @NonNull @Override protected Set<Integer> provideHandledTypes() { return handledTypes; } /** * Listener for sideways shove gesture callbacks. */ public interface OnSidewaysShoveGestureListener { /** * Indicates that the sideways shove gesture started. * * @param detector this detector * @return true if you want to receive subsequent * {@link #onSidewaysShove(SidewaysShoveGestureDetector, float, float)} callbacks, * false if you want to ignore this gesture. */ boolean onSidewaysShoveBegin(@NonNull SidewaysShoveGestureDetector detector); /** * Called for every sideways shove change during the gesture. * * @param detector this detector * @param deltaPixelsSinceLast pixels delta change since the last call * @param deltaPixelsSinceStart pixels delta change since the start of the gesture * @return true if the gesture was handled, false otherwise */ boolean onSidewaysShove(@NonNull SidewaysShoveGestureDetector detector, float deltaPixelsSinceLast, float deltaPixelsSinceStart); /** * Indicates that the sideways shove gesture ended. * * @param velocityX velocityX of the gesture in the moment of lifting the fingers * @param velocityY velocityY of the gesture in the moment of lifting the fingers * @param detector this detector */ void onSidewaysShoveEnd(@NonNull SidewaysShoveGestureDetector detector, float velocityX, float velocityY); } public static class SimpleOnSidewaysShoveGestureListener implements OnSidewaysShoveGestureListener { @Override public boolean onSidewaysShoveBegin(@NonNull SidewaysShoveGestureDetector detector) { return true; } @Override public boolean onSidewaysShove(@NonNull SidewaysShoveGestureDetector detector, float deltaPixelsSinceLast, float deltaPixelsSinceStart) { return false; } @Override public void onSidewaysShoveEnd(@NonNull SidewaysShoveGestureDetector detector, float velocityX, float velocityY) { // No Implementation } } @Override protected boolean analyzeMovement() { super.analyzeMovement(); deltaPixelSinceLast = calculateDeltaPixelsSinceLast(); deltaPixelsSinceStart += deltaPixelSinceLast; if (isInProgress() && deltaPixelSinceLast != 0) { return listener.onSidewaysShove(this, deltaPixelSinceLast, deltaPixelsSinceStart); } else if (canExecute(GESTURE_TYPE_SIDEWAYS_SHOVE)) { if (listener.onSidewaysShoveBegin(this)) { gestureStarted(); return true; } } return false; } @Override protected boolean canExecute(int invokedGestureType) { return Math.abs(deltaPixelsSinceStart) >= pixelDeltaThreshold && super.canExecute(invokedGestureType); } @Override protected boolean isSloppyGesture() { return super.isSloppyGesture() || !isAngleAcceptable(); } @Override protected void gestureStopped() { super.gestureStopped(); listener.onSidewaysShoveEnd(this, velocityX, velocityY); } @Override protected void reset() { super.reset(); deltaPixelsSinceStart = 0; } boolean isAngleAcceptable() { MultiFingerDistancesObject distancesObject = pointersDistanceMap.get(new PointerDistancePair(pointerIdList.get(0), pointerIdList.get(1))); // Takes values from 0 to 180 double angle = Math.toDegrees(Math.abs(Math.atan2( distancesObject.getCurrFingersDiffY(), distancesObject.getCurrFingersDiffX()))); // Making the axis vertical angle = Math.abs(angle - 90); return angle <= maxShoveAngle; } float calculateDeltaPixelsSinceLast() { float px0 = getPreviousEvent().getX(getPreviousEvent().findPointerIndex(pointerIdList.get(0))); float px1 = getPreviousEvent().getX(getPreviousEvent().findPointerIndex(pointerIdList.get(1))); float prevAverageX = (px0 + px1) / 2.0f; float cx0 = getCurrentEvent().getX(getCurrentEvent().findPointerIndex(pointerIdList.get(0))); float cx1 = getCurrentEvent().getX(getCurrentEvent().findPointerIndex(pointerIdList.get(1))); float currAverageX = (cx0 + cx1) / 2.0f; return currAverageX - prevAverageX; } /** * Returns horizontal pixel delta change since the start of the gesture. * * @return pixels delta change since the start of the gesture */ public float getDeltaPixelsSinceStart() { return deltaPixelsSinceStart; } /** * Returns last horizontal pixel delta change * calculated in {@link OnSidewaysShoveGestureListener#onSidewaysShove(SidewaysShoveGestureDetector, float, float)}. * * @return pixels delta change since the last call */ public float getDeltaPixelSinceLast() { return deltaPixelSinceLast; } /** * Get the delta pixel threshold required to qualify it as a sideways shove gesture. * * @return delta pixel threshold */ public float getPixelDeltaThreshold() { return pixelDeltaThreshold; } /** * Set the delta pixel threshold required to qualify it as a sideways shove gesture. * <p> * We encourage to set those values from dimens to accommodate for various screen sizes. * * @param pixelDeltaThreshold delta threshold */ public void setPixelDeltaThreshold(float pixelDeltaThreshold) { this.pixelDeltaThreshold = pixelDeltaThreshold; } /** * Set the delta dp threshold required to qualify it as a sideways shove gesture. * * @param pixelDeltaThresholdDimen delta threshold */ public void setPixelDeltaThresholdResource(@DimenRes int pixelDeltaThresholdDimen) { setPixelDeltaThreshold(context.getResources().getDimension(pixelDeltaThresholdDimen)); } /** * Get the maximum allowed angle between fingers, measured from the vertical line, * to qualify it as a sideways shove gesture. * * @return maximum allowed angle */ public float getMaxShoveAngle() { return maxShoveAngle; } /** * Set the maximum allowed angle between fingers, measured from the vertical line, * to qualify it as a sideways shove gesture. * * @param maxShoveAngle maximum allowed angle */ public void setMaxShoveAngle(float maxShoveAngle) { this.maxShoveAngle = maxShoveAngle; } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/StandardGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import androidx.annotation.UiThread; import androidx.annotation.NonNull; import androidx.core.view.GestureDetectorCompat; import android.view.GestureDetector; import android.view.MotionEvent; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_DOUBLE_TAP; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_DOUBLE_TAP_EVENT; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_DOWN; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_FLING; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_LONG_PRESS; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SCROLL; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SHOW_PRESS; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SINGLE_TAP_CONFIRMED; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SINGLE_TAP_UP; /** * Detector that wraps {@link GestureDetectorCompat}. */ @UiThread public class StandardGestureDetector extends BaseGesture<StandardGestureDetector.StandardOnGestureListener> { private final GestureDetectorCompat gestureDetector; public StandardGestureDetector(Context context, AndroidGesturesManager androidGesturesManager) { super(context, androidGesturesManager); this.gestureDetector = new GestureDetectorCompat(context, innerListener); } final StandardOnGestureListener innerListener = new StandardOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return canExecute(GESTURE_TYPE_SINGLE_TAP_UP) && listener.onSingleTapUp(e); } @Override public void onLongPress(MotionEvent e) { if (canExecute(GESTURE_TYPE_LONG_PRESS)) { listener.onLongPress(e); } } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return canExecute(GESTURE_TYPE_SCROLL) && listener.onScroll(e1, e2, distanceX, distanceY); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return canExecute(GESTURE_TYPE_FLING) && listener.onFling(e1, e2, velocityX, velocityY); } @Override public void onShowPress(MotionEvent e) { if (canExecute(GESTURE_TYPE_SHOW_PRESS)) { listener.onShowPress(e); } } @Override public boolean onDown(MotionEvent e) { return canExecute(GESTURE_TYPE_DOWN) && listener.onDown(e); } @Override public boolean onDoubleTap(MotionEvent e) { return canExecute(GESTURE_TYPE_DOUBLE_TAP) && listener.onDoubleTap(e); } @Override public boolean onDoubleTapEvent(MotionEvent e) { return canExecute(GESTURE_TYPE_DOUBLE_TAP_EVENT) && listener.onDoubleTapEvent(e); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { return canExecute(GESTURE_TYPE_SINGLE_TAP_CONFIRMED) && listener.onSingleTapConfirmed(e); } }; /** * Listener that merges {@link android.view.GestureDetector.OnGestureListener} * and {@link android.view.GestureDetector.OnDoubleTapListener}. */ public interface StandardOnGestureListener extends GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { } /** * Listener that mirrors {@link android.view.GestureDetector.SimpleOnGestureListener}. */ public static class SimpleStandardOnGestureListener implements StandardOnGestureListener { @Override public boolean onSingleTapConfirmed(@NonNull MotionEvent e) { return false; } @Override public boolean onDoubleTap(@NonNull MotionEvent e) { return false; } @Override public boolean onDoubleTapEvent(@NonNull MotionEvent e) { return false; } @Override public boolean onDown(@NonNull MotionEvent e) { return false; } @Override public void onShowPress(@NonNull MotionEvent e) { } @Override public boolean onSingleTapUp(@NonNull MotionEvent e) { return false; } @Override public boolean onScroll(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(@NonNull MotionEvent e) { } @Override public boolean onFling(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) { return false; } } @Override protected boolean analyzeEvent(@NonNull MotionEvent motionEvent) { return gestureDetector.onTouchEvent(motionEvent); } /** * @return True if longpress in enabled, false otherwise. * @see GestureDetectorCompat#isLongpressEnabled() */ public boolean isLongpressEnabled() { return gestureDetector.isLongpressEnabled(); } /** * @param enabled True if longpress should be enabled, false otherwise. * @see GestureDetectorCompat#setIsLongpressEnabled(boolean) */ public void setIsLongpressEnabled(boolean enabled) { gestureDetector.setIsLongpressEnabled(enabled); } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/StandardScaleGestureDetector.java
package com.nbmap.android.gestures; import android.content.Context; import android.graphics.PointF; import androidx.annotation.DimenRes; import androidx.annotation.NonNull; import androidx.annotation.UiThread; import androidx.core.view.GestureDetectorCompat; import android.view.GestureDetector; import android.view.MotionEvent; import java.util.HashSet; import java.util.Set; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_QUICK_SCALE; import static com.nbmap.android.gestures.AndroidGesturesManager.GESTURE_TYPE_SCALE; /** * Gesture detector handling scale gesture. */ @UiThread public class StandardScaleGestureDetector extends ProgressiveGesture<StandardScaleGestureDetector.StandardOnScaleGestureListener> { private static final Set<Integer> handledTypes = new HashSet<>(); static { handledTypes.add(GESTURE_TYPE_SCALE); handledTypes.add(GESTURE_TYPE_QUICK_SCALE); } private static final float QUICK_SCALE_MULTIPLIER = 0.5f; private final GestureDetectorCompat innerGestureDetector; private boolean quickScale; private PointF quickScaleFocalPoint; private float startSpan; private float startSpanX; private float startSpanY; private float currentSpan; private float currentSpanX; private float currentSpanY; private float previousSpan; private float previousSpanX; private float previousSpanY; private float spanDeltaSinceStart; private float spanSinceStartThreshold; private boolean isScalingOut; private float scaleFactor; public StandardScaleGestureDetector(Context context, AndroidGesturesManager androidGesturesManager) { super(context, androidGesturesManager); GestureDetector.OnGestureListener doubleTapEventListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTapEvent(MotionEvent event) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { quickScale = true; quickScaleFocalPoint = new PointF(event.getX(), event.getY()); } return true; } }; innerGestureDetector = new GestureDetectorCompat(context, doubleTapEventListener); } @Override protected boolean analyzeMovement() { super.analyzeMovement(); if (isInProgress() && quickScale && getPointersCount() > 1) { // additional pointer has been placed during quick scale // abort and start a traditional pinch next gestureStopped(); return false; } PointF focal = quickScale ? quickScaleFocalPoint : getFocalPoint(); currentSpanX = 0; currentSpanY = 0; for (int i = 0; i < getPointersCount(); i++) { currentSpanX += Math.abs(getCurrentEvent().getX(i) - focal.x); currentSpanY += Math.abs(getCurrentEvent().getY(i) - focal.y); } currentSpanX *= 2; currentSpanY *= 2; if (quickScale) { currentSpan = currentSpanY; } else { currentSpan = (float) Math.hypot(currentSpanX, currentSpanY); } if (startSpan == 0) { startSpan = currentSpan; startSpanX = currentSpanX; startSpanY = currentSpanY; } spanDeltaSinceStart = Math.abs(startSpan - currentSpan); scaleFactor = calculateScaleFactor(); isScalingOut = scaleFactor < 1f; boolean handled = false; if (isInProgress() && currentSpan > 0) { handled = listener.onScale(this); } else if (canExecute(quickScale ? GESTURE_TYPE_QUICK_SCALE : GESTURE_TYPE_SCALE) && (spanDeltaSinceStart >= spanSinceStartThreshold)) { handled = listener.onScaleBegin(this); if (handled) { gestureStarted(); } } previousSpan = currentSpan; previousSpanX = currentSpanX; previousSpanY = currentSpanY; return handled; } @Override protected void gestureStopped() { super.gestureStopped(); listener.onScaleEnd(StandardScaleGestureDetector.this, velocityX, velocityY); quickScale = false; } @Override protected void reset() { super.reset(); startSpan = 0; spanDeltaSinceStart = 0; currentSpan = 0; previousSpan = 0; scaleFactor = 1f; } @Override protected boolean analyzeEvent(@NonNull MotionEvent motionEvent) { int action = motionEvent.getActionMasked(); if (quickScale) { if (action == MotionEvent.ACTION_POINTER_DOWN || action == MotionEvent.ACTION_CANCEL) { if (isInProgress()) { interrupt(); } else { // since the double tap has been registered and canceled but the gesture wasn't started, // we need to mark it manually quickScale = false; } } else if (!isInProgress() && action == MotionEvent.ACTION_UP) { // if double tap has been registered but the threshold was not met and gesture is not in progress, // we need to manually mark the finish of a double tap quickScale = false; } } boolean handled = super.analyzeEvent(motionEvent); return handled | innerGestureDetector.onTouchEvent(motionEvent); } @Override protected int getRequiredPointersCount() { if (isInProgress()) { return quickScale ? 1 : 2; } else { return 1; } } @Override protected boolean isSloppyGesture() { // do not accept move events if there are less than 2 pointers and we are not quick scaling return super.isSloppyGesture() || (!quickScale && getPointersCount() < 2); } @NonNull @Override protected Set<Integer> provideHandledTypes() { return handledTypes; } /** * Listener for scale gesture callbacks. */ public interface StandardOnScaleGestureListener { /** * Indicates that the scale gesture started. * * @param detector this detector * @return true if you want to receive subsequent {@link #onScale(StandardScaleGestureDetector)} callbacks, * false if you want to ignore this gesture. */ boolean onScaleBegin(@NonNull StandardScaleGestureDetector detector); /** * Called for every scale change during the gesture. * * @param detector this detector * @return Whether or not the detector should consider this event as handled. */ boolean onScale(@NonNull StandardScaleGestureDetector detector); /** * Indicates that the scale gesture ended. * * @param detector this detector * @param velocityX velocityX of the gesture in the moment of lifting the fingers * @param velocityY velocityY of the gesture in the moment of lifting the fingers */ void onScaleEnd(@NonNull StandardScaleGestureDetector detector, float velocityX, float velocityY); } public static class SimpleStandardOnScaleGestureListener implements StandardOnScaleGestureListener { @Override public boolean onScaleBegin(@NonNull StandardScaleGestureDetector detector) { return true; } @Override public boolean onScale(@NonNull StandardScaleGestureDetector detector) { return false; } @Override public void onScaleEnd(@NonNull StandardScaleGestureDetector detector, float velocityX, float velocityY) { // No implementation } } /** * Check whether user is scaling out. * * @return true if user is scaling out, false if user is scaling in */ public boolean isScalingOut() { return isScalingOut; } /** * Get the threshold span in pixels between initial fingers position and current needed * for this detector to qualify it as a scale gesture. * * @return span threshold */ public float getSpanSinceStartThreshold() { return spanSinceStartThreshold; } /** * Set the threshold span in pixels between initial fingers position and current needed * for this detector to qualify it as a scale gesture. * <p> * We encourage to set those values from dimens to accommodate for various screen sizes. * * @param spanSinceStartThreshold delta span threshold */ public void setSpanSinceStartThreshold(float spanSinceStartThreshold) { this.spanSinceStartThreshold = spanSinceStartThreshold; } /** * Set the threshold span in dp between initial fingers position and current needed * for this detector to qualify it as a scale gesture. * * @param spanSinceStartThresholdDimen delta span threshold */ public void setSpanSinceStartThresholdResource(@DimenRes int spanSinceStartThresholdDimen) { setSpanSinceStartThreshold(context.getResources().getDimension(spanSinceStartThresholdDimen)); } /** * @return Scale factor. */ public float getScaleFactor() { return scaleFactor; } /** * Return the average distance between each of the pointers forming the * gesture in progress through the focal point, when the gesture was started. * * @return Distance between pointers in pixels. */ public float getStartSpan() { return startSpan; } /** * Return the average X distance between each of the pointers forming the * gesture in progress through the focal point, when the gesture was started. * * @return Distance between pointers in pixels. */ public float getStartSpanX() { return startSpanX; } /** * Return the average Y distance between each of the pointers forming the * gesture in progress through the focal point, when the gesture was started. * * @return Distance between pointers in pixels. */ public float getStartSpanY() { return startSpanY; } /** * Return the average distance between each of the pointers forming the * gesture in progress through the focal point. * * @return Distance between pointers in pixels. */ public float getCurrentSpan() { return currentSpan; } /** * Return the average X distance between each of the pointers forming the * gesture in progress through the focal point. * * @return Distance between pointers in pixels. */ public float getCurrentSpanX() { return currentSpanX; } /** * Return the average Y distance between each of the pointers forming the * gesture in progress through the focal point. * * @return Distance between pointers in pixels. */ public float getCurrentSpanY() { return currentSpanY; } /** * Return the previous average distance between each of the pointers forming the * gesture in progress through the focal point. * * @return Previous distance between pointers in pixels. */ public float getPreviousSpan() { return previousSpan; } /** * Return the previous average X distance between each of the pointers forming the * gesture in progress through the focal point. * * @return Previous distance between pointers in pixels. */ public float getPreviousSpanX() { return previousSpanX; } /** * Return the previous average Y distance between each of the pointers forming the * gesture in progress through the focal point. * * @return Previous distance between pointers in pixels. */ public float getPreviousSpanY() { return previousSpanY; } private float calculateScaleFactor() { if (quickScale) { final boolean scaleOut = // below focal point moving up getCurrentEvent().getY() < quickScaleFocalPoint.y && currentSpan < previousSpan // above focal point moving up || getCurrentEvent().getY() > quickScaleFocalPoint.y && currentSpan > previousSpan; final float spanDiff = Math.abs(1 - (currentSpan / previousSpan)) * QUICK_SCALE_MULTIPLIER; return previousSpan <= 0 ? 1 : scaleOut ? (1 + spanDiff) : (1 - spanDiff); } else { return previousSpan > 0 ? currentSpan / previousSpan : 1; } } }
0
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android
java-sources/ai/nextbillion/nb-gestures/0.1.0/com/nbmap/android/gestures/Utils.java
package com.nbmap.android.gestures; import android.content.Context; import android.content.res.Resources; import android.graphics.PointF; import androidx.annotation.NonNull; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.MotionEvent; public class Utils { /** * Calculates the center point of the multi finger gesture. * * @param motionEvent event * @return center point of the gesture */ public static PointF determineFocalPoint(@NonNull MotionEvent motionEvent) { int pointersCount = motionEvent.getPointerCount(); float x = 0; float y = 0; for (int i = 0; i < pointersCount; i++) { x += motionEvent.getX(i); y += motionEvent.getY(i); } return new PointF(x / pointersCount, y / pointersCount); } /** * @param event motion event * @param pointerIndex pointer's index * @return rawY for a pointer * @author Almer Thie (code.almeros.com) * <p> * MotionEvent has no getRawY(int) method; simulate it pending future API approval. */ public static float getRawX(MotionEvent event, int pointerIndex) { float offset = event.getRawX() - event.getX(); if (pointerIndex < event.getPointerCount()) { return event.getX(pointerIndex) + offset; } return 0.0f; } /** * @param event motion event * @param pointerIndex pointer's index * @return rawX for a pointer * @author Almer Thie (code.almeros.com) * <p> * MotionEvent has no getRawX(int) method; simulate it pending future API approval. */ public static float getRawY(MotionEvent event, int pointerIndex) { float offset = event.getRawY() - event.getY(); if (pointerIndex < event.getPointerCount()) { return event.getY(pointerIndex) + offset; } return 0.0f; } /** * Converts DIP to PX. * * @param dp initial value * @return converted value */ public static float dpToPx(float dp) { return dp * Resources.getSystem().getDisplayMetrics().density; } /** * Converts PX to DIP. * * @param px initial value * @return converted value */ public static float pxToDp(float px) { return px / Resources.getSystem().getDisplayMetrics().density; } /** * Converts PX to MM (millimeters). * * @param px initial value * @param context context * @return converted value */ public static float pxToMm(final float px, final Context context) { final DisplayMetrics dm = context.getResources().getDisplayMetrics(); return px / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1, dm); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/NBMapAPI.java
package ai.nextbillion.api; import java.io.IOException; import java.util.List; import ai.nextbillion.api.directions.NBDirections; import ai.nextbillion.api.directions.NBDirectionsResponse; import ai.nextbillion.api.distancematrix.NBDistanceMatrix; import ai.nextbillion.api.distancematrix.NBDistanceMatrixResponse; import ai.nextbillion.api.models.NBLocation; import ai.nextbillion.api.snaptoroad.NBSnapToRoad; import ai.nextbillion.api.snaptoroad.NBSnapToRoadResponse; import retrofit2.Callback; import retrofit2.Response; public class NBMapAPI { private String key; private String mode; private String baseUrl; private String routingService = "directions"; private boolean debug = false; private String avoid; private String overview = "full"; private String approaches; private String truckSize; private int truckWeight; private static class BillPughSingleton { private static final NBMapAPI INSTANCE = new NBMapAPI(); } public static NBMapAPI getInstance() { return BillPughSingleton.INSTANCE; } public static NBMapAPI getInstance(String key, String baseUrl) { NBMapAPI instance = BillPughSingleton.INSTANCE; instance.setKey(key); instance.setBaseUrl(baseUrl); instance.setOverview("full"); instance.setApproaches(""); instance.setTruckWeight(0); instance.setTruckSize(""); instance.setAvoid(""); return instance; } public static NBMapAPI getDebugInstance() { NBMapAPI instance = BillPughSingleton.INSTANCE; instance.setKey("plaintesting"); instance.setMode("4w"); instance.setBaseUrl("https://api.nextbillion.io"); instance.setOverview("full"); instance.setApproaches(""); instance.setTruckWeight(0); instance.setTruckSize(""); instance.setAvoid(""); return instance; } private NBMapAPI() { } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public void setRoutingService(String service) { this.routingService = service; } public void setOverview(String overview) { this.overview = overview; } public String getOverview() { return overview; } public void setApproaches(String approaches) { this.approaches = approaches; } public String getApproaches() { return approaches; } public void setTruckSize(String truckSize) { this.truckSize = truckSize; } public String getTruckSize() { return truckSize; } public void setTruckWeight(int truckWeight) { this.truckWeight = truckWeight; } public int getTruckWeight() { return truckWeight; } public void setAvoid(String avoid) { this.avoid = avoid; } public String getAvoid() { return avoid; } /////////////////////////////////////////////////////////////////////////// // Directions /////////////////////////////////////////////////////////////////////////// public Response<NBDirectionsResponse> getDirections(NBLocation origin, NBLocation destination) throws IOException { NBDirections nbDirections = getDirectionsBuilder() .origin(origin) .destination(destination) .steps(true) .build(); nbDirections.enableDebug(debug); return nbDirections.executeCall(); } public void enqueueGetDirections(NBLocation origin, NBLocation destination, Callback<NBDirectionsResponse> callback) { NBDirections nbDirections = getDirectionsBuilder() .origin(origin) .destination(destination) .steps(true) .build(); nbDirections.enableDebug(debug); nbDirections.enqueueCall(callback); } public NBDirections.Builder getDirectionsBuilder() { int departureTime = (int) System.currentTimeMillis() / 1000; return NBDirections.builder() .service(routingService) .alternativeCount(1) .alternatives(true) .departureTime(departureTime) .baseUrl(baseUrl) .key(key) .mode(mode) .debug(debug) .steps(true) .avoid(avoid) .overview(overview) .approaches(approaches) .truckSize(truckSize) .truckWeight(truckWeight); } /////////////////////////////////////////////////////////////////////////// // Distance Matrix /////////////////////////////////////////////////////////////////////////// public Response<NBDistanceMatrixResponse> getDistanceMatrix(List<NBLocation> origins, List<NBLocation> destinations) throws IOException { NBDistanceMatrix distanceMatrix = getDistanceMatrixBuilder() .origins(origins) .destinations(destinations) .departureTime((int) System.currentTimeMillis() / 1000) .build(); distanceMatrix.enableDebug(debug); return distanceMatrix.executeCall(); } public void enqueueGetDistanceMatrix(List<NBLocation> origins, List<NBLocation> destinations, Callback<NBDistanceMatrixResponse> callback) { NBDistanceMatrix distanceMatrix = getDistanceMatrixBuilder() .origins(origins) .destinations(destinations) .departureTime((int) System.currentTimeMillis() / 1000) .build(); distanceMatrix.enableDebug(debug); distanceMatrix.enqueueCall(callback); } public NBDistanceMatrix.Builder getDistanceMatrixBuilder() { return NBDistanceMatrix.builder() .baseUrl(baseUrl) .mode(mode) .debug(debug) .key(key); } /////////////////////////////////////////////////////////////////////////// // Matching / Snap To Roads /////////////////////////////////////////////////////////////////////////// public Response<NBSnapToRoadResponse> getSnapToRoad(List<NBLocation> pointsOnPath) throws IOException { NBSnapToRoad snapToRoad = getSnapToRoadBuilder() .path(pointsOnPath) .build(); snapToRoad.enableDebug(debug); return snapToRoad.executeCall(); } public void enqueueGetSnapToRoads(List<NBLocation> pointsOnPath, Callback<NBSnapToRoadResponse> callback) { NBSnapToRoad snapToRoad = getSnapToRoadBuilder() .path(pointsOnPath) .build(); snapToRoad.enableDebug(debug); snapToRoad.enqueueCall(callback); } public NBSnapToRoad.Builder getSnapToRoadBuilder() { return NBSnapToRoad.builder() .baseUrl(baseUrl) .key(key) .interpolate(true) .tolerateOutlier(false); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/directions/NBDirections.java
package ai.nextbillion.api.directions; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import ai.nextbillion.kits.core.NBService; import ai.nextbillion.kits.core.constants.Constants; import ai.nextbillion.api.models.NBLocation; import retrofit2.Call; @AutoValue public abstract class NBDirections extends NBService<NBDirectionsResponse, NBDirectionsService> { public NBDirections() { super(NBDirectionsService.class); } @Override protected abstract String baseUrl(); @Override protected Call<NBDirectionsResponse> initializeCall() { return get(); } /////////////////////////////////////////////////////////////////////////// // HTTP /////////////////////////////////////////////////////////////////////////// private Call<NBDirectionsResponse> get() { String origin = origin() != null ? origin().toString() : null; String dest = destination() != null ? destination().toString() : null; return getService().getDirections( service(), alternativeCount(), alternatives(), debug(), departureTime(), dest, geometry(), geometry_type(), key(), mode(), lang(), origin, session(), steps(), wayPoints(), avoid(), overview(), approaches(), truckSize(), truckWeight(), bearings() ); } /////////////////////////////////////////////////////////////////////////// // Params /////////////////////////////////////////////////////////////////////////// abstract String service(); abstract int alternativeCount(); abstract boolean alternatives(); abstract boolean debug(); abstract int departureTime(); @Nullable abstract NBLocation destination(); @Nullable abstract String geometry(); @Nullable abstract String geometry_type(); abstract String key(); abstract String mode(); @Nullable abstract String lang(); @Nullable abstract NBLocation origin(); @Nullable abstract String session(); abstract boolean steps(); @Nullable abstract String wayPoints(); @Nullable abstract String avoid(); @Nullable abstract String overview(); @Nullable abstract String approaches(); @Nullable abstract String truckSize(); abstract int truckWeight(); @Nullable abstract String bearings(); /////////////////////////////////////////////////////////////////////////// // Builder /////////////////////////////////////////////////////////////////////////// @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder().registerTypeAdapterFactory(NBDirectionAdapterFactory.create()); } public static Builder builder() { return new AutoValue_NBDirections.Builder().baseUrl(Constants.BASE_API_URL); } @AutoValue.Builder public abstract static class Builder { public abstract Builder baseUrl(String baseUrl); public abstract Builder service(String service); public abstract Builder alternativeCount(int alternativeCount); public abstract Builder alternatives(boolean alternatives); public abstract Builder debug(boolean debug); public abstract Builder departureTime(int departureTime); public abstract Builder destination(NBLocation destination); public abstract Builder geometry(String geometry); public abstract Builder geometry_type(String geometry_type); public abstract Builder key(String key); public abstract Builder mode(String mode); public abstract Builder lang(String lang); public abstract Builder origin(NBLocation origin); public abstract Builder session(String session); public abstract Builder steps(boolean steps); public abstract Builder wayPoints(String wayPoints); public abstract Builder avoid(String avoid); public abstract Builder overview(String overview); public abstract Builder approaches(String approaches); public abstract Builder truckSize(String truckSize); public abstract Builder truckWeight(int truckWeight); public abstract Builder bearings(String bearings); public abstract NBDirections build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/directions/NBDirectionsResponse.java
package ai.nextbillion.api.directions; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import java.io.Serializable; import java.util.List; import ai.nextbillion.api.models.directions.NBRoute; @AutoValue public abstract class NBDirectionsResponse implements Serializable { /////////////////////////////////////////////////////////////////////////// // Params /////////////////////////////////////////////////////////////////////////// @Nullable public abstract String errorMessage(); @Nullable public abstract String mode(); @Nullable public abstract String status(); public abstract List<NBRoute> routes(); @Nullable public abstract String country_code(); /////////////////////////////////////////////////////////////////////////// // Params end /////////////////////////////////////////////////////////////////////////// public static Builder builder() { return new AutoValue_NBDirectionsResponse.Builder(); } public abstract Builder toBuilder(); public static TypeAdapter<NBDirectionsResponse> typeAdapter(Gson gson) { return new AutoValue_NBDirectionsResponse.GsonTypeAdapter(gson); } @AutoValue.Builder public abstract static class Builder { public abstract Builder errorMessage(String errorMessage); public abstract Builder mode(String mode); public abstract Builder status(String status); public abstract Builder routes(List<NBRoute> routes); public abstract Builder country_code(String country_code); public abstract NBDirectionsResponse build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/directions/NBDirectionsService.java
package ai.nextbillion.api.directions; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface NBDirectionsService { //context is deprecated //special object types is for L&T only @GET("/{service}/json") Call<NBDirectionsResponse> getDirections( @Path("service") String service, @Query("altcount") int alternativeCount, @Query("alternatives") boolean alternatives, @Query("debug") boolean debug, @Query("departure_time") int departureTime, @Query("destination") String destination, @Query("geometry") String geometry, @Query("geometry_type") String geometryType, @Query("key") String key, @Query("mode") String mode, @Query("lang") String lang, @Query("origin") String origin, @Query("session") String session, @Query("steps") boolean steps, @Query("waypoints") String wayPoints, @Query("avoid") String avoid, @Query("overview") String overview, @Query("approaches") String approaches, @Query("truck_size") String truckSize, @Query("truck_weight") int truckWeight, @Query("bearings") String bearings ); }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/distancematrix/NBDistanceMatrix.java
package ai.nextbillion.api.distancematrix; import androidx.annotation.NonNull; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import ai.nextbillion.kits.core.NBService; import ai.nextbillion.kits.core.constants.Constants; import java.util.List; import ai.nextbillion.api.models.NBLocation; import ai.nextbillion.api.utils.FormatUtils; import retrofit2.Call; @AutoValue public abstract class NBDistanceMatrix extends NBService<NBDistanceMatrixResponse, NBDistanceMatrixService> { public NBDistanceMatrix() { super(NBDistanceMatrixService.class); } @Override protected abstract String baseUrl(); @Override protected Call<NBDistanceMatrixResponse> initializeCall() { return getService().getDistanceMatrix( debug(), departureTime(), locationsToString(destinations()), key(), mode(), locationsToString(origins()) ); } /////////////////////////////////////////////////////////////////////////// // Params converter /////////////////////////////////////////////////////////////////////////// private String locationsToString(@NonNull List<NBLocation> locations) { return FormatUtils.join("|", locations); } /////////////////////////////////////////////////////////////////////////// // Params /////////////////////////////////////////////////////////////////////////// abstract boolean debug(); abstract int departureTime(); abstract List<NBLocation> destinations(); abstract String key(); abstract String mode(); abstract List<NBLocation> origins(); /////////////////////////////////////////////////////////////////////////// // Builder /////////////////////////////////////////////////////////////////////////// @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder().registerTypeAdapterFactory(NBDistanceMatrixAdapterFactory.create()); } public static Builder builder() { return new AutoValue_NBDistanceMatrix.Builder().baseUrl(Constants.BASE_API_URL); } @AutoValue.Builder public abstract static class Builder { public abstract Builder baseUrl(String baseUrl); public abstract Builder debug(boolean debug); public abstract Builder departureTime(int departureTime); public abstract Builder destinations(List<NBLocation> destinations); public abstract Builder key(String accessToken); public abstract Builder mode(String mode); public abstract Builder origins(List<NBLocation> origins); public abstract NBDistanceMatrix build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/NBLane.java
package ai.nextbillion.api.models.directions; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import java.util.List; @AutoValue public abstract class NBLane { public static final String INDICATION_NONE = "none"; public static final String INDICATION_UTURN = "uturn"; public static final String INDICATION_SHARP_RIGHT = "sharp right"; public static final String INDICATION_RIGHT = "right"; public static final String INDICATION_SLIGHT_RIGHT = "slight right"; public static final String INDICATION_STRAIGHT = "straight"; public static final String INDICATION_SLIGHT_LEFT = "slight left"; public static final String INDICATION_LEFT = "left"; public static final String INDICATION_SHARP_LEFT = "sharp left"; @Nullable @SerializedName("indications") public abstract List<String> indications(); @SerializedName("valid") public abstract boolean valid(); public static TypeAdapter<NBLane> typeAdapter(Gson gson) { return new AutoValue_NBLane.GsonTypeAdapter(gson); } public static Builder builder() { return new AutoValue_NBLane.Builder(); } public abstract Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder indications(List<String> indications); public abstract Builder valid(boolean valid); public abstract NBLane build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/NBLegStep.java
package ai.nextbillion.api.models.directions; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import java.util.List; import ai.nextbillion.api.models.NBDistance; import ai.nextbillion.api.models.NBDuration; import ai.nextbillion.api.models.NBLocation; @AutoValue public abstract class NBLegStep { @Nullable @SerializedName("end_location") public abstract NBLocation endLocation(); @Nullable @SerializedName("start_location") public abstract NBLocation startLocation(); @Nullable @SerializedName("maneuver") public abstract NBStepManeuver maneuver(); @Nullable @SerializedName("intersections") public abstract List<NBStepIntersection> intersections(); public abstract NBDistance distance(); public abstract NBDuration duration(); @Nullable public abstract String geometry(); @Nullable public abstract String name(); @Nullable public abstract String reference(); @Nullable @SerializedName("road_shield_type") public abstract NBRoadShieldType roadShieldType(); public static TypeAdapter<NBLegStep> typeAdapter(Gson gson) { return new AutoValue_NBLegStep.GsonTypeAdapter(gson); } public static Builder builder() { return new AutoValue_NBLegStep.Builder(); } public abstract Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder endLocation(NBLocation endLocation); public abstract Builder startLocation(NBLocation startLocation); public abstract Builder geometry(String geometry); public abstract Builder name(String name); public abstract Builder reference(String reference); public abstract Builder maneuver(NBStepManeuver maneuver); public abstract Builder distance(NBDistance distance); public abstract Builder duration(NBDuration duration); public abstract Builder intersections( List<NBStepIntersection> intersections); public abstract Builder roadShieldType(NBRoadShieldType roadShieldType); public abstract NBLegStep build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/NBRoadShieldType.java
package ai.nextbillion.api.models.directions; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; @AutoValue public abstract class NBRoadShieldType { @Nullable public abstract String label(); @Nullable @SerializedName("image_url") public abstract String imageUrl(); public abstract NBRoadShieldType.Builder toBuilder(); public static TypeAdapter<NBRoadShieldType> typeAdapter(Gson gson) { return new AutoValue_NBRoadShieldType.GsonTypeAdapter(gson); } public static NBRoadShieldType.Builder builder() { return new AutoValue_NBRoadShieldType.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract NBRoadShieldType.Builder imageUrl(String imageUrl); public abstract NBRoadShieldType.Builder label(String label); public abstract NBRoadShieldType build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/NBStepIntersection.java
package ai.nextbillion.api.models.directions; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import java.util.List; import ai.nextbillion.api.models.NBLocation; @AutoValue public abstract class NBStepIntersection { @Nullable @SerializedName("location") public abstract NBLocation location(); @SerializedName("intersection_in") public abstract int in(); @SerializedName("intersection_out") public abstract int out(); @Nullable @SerializedName("bearings") public abstract List<Integer> bearings(); @Nullable @SerializedName("entry") public abstract List<Boolean> entry(); @Nullable @SerializedName("classes") public abstract List<String> classes(); @Nullable @SerializedName("lanes") public abstract List<NBLane> lanes(); public static TypeAdapter<NBStepIntersection> typeAdapter(Gson gson) { return new AutoValue_NBStepIntersection.GsonTypeAdapter(gson); } public static Builder builder() { return new AutoValue_NBStepIntersection.Builder(); } public abstract Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder location(NBLocation location); public abstract Builder in(int in); public abstract Builder out(int out); public abstract Builder bearings(List<Integer> bearings); public abstract Builder entry(List<Boolean> entry); public abstract Builder classes(List<String> classes); public abstract Builder lanes(List<NBLane> lanes); public abstract NBStepIntersection build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/NBStepManeuver.java
package ai.nextbillion.api.models.directions; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import java.util.List; import ai.nextbillion.api.models.NBLocation; import androidx.annotation.Nullable; @AutoValue public abstract class NBStepManeuver { @SerializedName("bearing_after") public abstract int bearingAfter(); @SerializedName("bearing_before") public abstract int bearingBefore(); @SerializedName("coordinate") public abstract NBLocation coordinate(); @SerializedName("maneuver_type") public abstract String type(); @Nullable @SerializedName("modifier") public abstract String modifier(); @Nullable @SerializedName("instruction") public abstract String instruction(); @Nullable @SerializedName("voice_instruction") public abstract List<NBVoiceInstruction> voiceInstructions(); @SerializedName("muted") public abstract boolean muted(); public static TypeAdapter<NBStepManeuver> typeAdapter(Gson gson) { return new AutoValue_NBStepManeuver.GsonTypeAdapter(gson); } public static Builder builder() { return new AutoValue_NBStepManeuver.Builder(); } public abstract NBStepManeuver.Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder bearingAfter(int bearingAfter); public abstract Builder bearingBefore(int bearingBefore); public abstract Builder coordinate(NBLocation coordinate); public abstract Builder type(String type); public abstract Builder modifier(String modifier); public abstract Builder instruction(String instruction); public abstract Builder voiceInstructions(List<NBVoiceInstruction> voiceInstructions); public abstract Builder muted(boolean muted); public abstract NBStepManeuver build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/NBVoiceInstruction.java
package ai.nextbillion.api.models.directions; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; @AutoValue public abstract class NBVoiceInstruction { @SerializedName("distance_along_geometry") public abstract double distanceAlongGeometry(); @SerializedName("unit") public abstract String unit(); @SerializedName("instruction") public abstract String instruction(); public static TypeAdapter<NBVoiceInstruction> typeAdapter(Gson gson) { return new AutoValue_NBVoiceInstruction.GsonTypeAdapter(gson); } public static Builder builder() { return new AutoValue_NBVoiceInstruction.Builder(); } public abstract Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder distanceAlongGeometry(double distanceAlongGeometry); public abstract Builder unit(String unit); public abstract Builder instruction(String instruction); public abstract NBVoiceInstruction build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/models/directions/RoutingBearing.java
package ai.nextbillion.api.models.directions; public class RoutingBearing { public float bearing; public float range; public RoutingBearing(float bearing, float range) { this.bearing = bearing; this.range = range; } @Override public String toString() { return bearing + "," + range ; } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/nearby/NBNearBy.java
package ai.nextbillion.api.nearby; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import ai.nextbillion.kits.core.NBService; import ai.nextbillion.kits.core.constants.Constants; import ai.nextbillion.kits.core.exceptions.ServicesException; import ai.nextbillion.kits.core.utils.NbmapUtils; import retrofit2.Call; @AutoValue public abstract class NBNearBy extends NBService<NBNearByResponse, NBNearByService> { public NBNearBy() { super(NBNearByService.class); } @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder(); } @Override protected Call<NBNearByResponse> initializeCall() { return null; } @Override protected abstract String baseUrl(); ////////////////////Query Params/////////////////////////////////////////// abstract String currentLocation(); abstract int maxCount(); abstract int searchRadius(); abstract String serviceType(); abstract String accessToken(); ////////////////////Query Params Ends////////////////////////////////////// public static Builder builder() { return new AutoValue_NBNearBy.Builder().baseUrl(Constants.BASE_API_URL); } /////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////// @AutoValue.Builder public abstract static class Builder { abstract Builder currentLocation(String currentLocation); abstract Builder maxCount(int maxCount); abstract Builder searchRadius(int radius); abstract Builder serviceType(String serviceType); abstract Builder accessToken(String token); public abstract Builder baseUrl(String baseUrl); abstract NBNearBy autoBuild(); public NBNearBy build() { NBNearBy nearBy = autoBuild(); if (!NbmapUtils.isAccessTokenValid(nearBy.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } return nearBy; } } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/posttriproute/NBPostTripRoute.java
package ai.nextbillion.api.posttriproute; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import ai.nextbillion.kits.core.NBService; import ai.nextbillion.kits.core.constants.Constants; import retrofit2.Call; @AutoValue public abstract class NBPostTripRoute extends NBService<NBPostTripRouteResponse, NBPostTripRouteService> { public NBPostTripRoute() { super(NBPostTripRouteService.class); } /////////////////////////////////////////////////////////////////////////// // Override /////////////////////////////////////////////////////////////////////////// @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder(); } @Override protected Call<NBPostTripRouteResponse> initializeCall() { return null; } @Override protected abstract String baseUrl(); /////////////////////////////////////////////////////////////////////////// // Params /////////////////////////////////////////////////////////////////////////// abstract boolean debug(); abstract String accessToken(); abstract String mode(); abstract String timestamps(); abstract boolean tolerateOutlier(); abstract String wayPoints(); /////////////////////////////////////////////////////////////////////////// // Builder /////////////////////////////////////////////////////////////////////////// public static Builder builder() { return new AutoValue_NBPostTripRoute.Builder().baseUrl(Constants.BASE_API_URL); } @AutoValue.Builder public abstract static class Builder { abstract Builder debug(boolean debug); abstract Builder accessToken(String accessToken); abstract Builder mode(String mode); abstract Builder baseUrl(String baseUrl); abstract Builder timestamps(String timestamps); abstract Builder tolerateOutlier(boolean tolerateOutlier); abstract Builder wayPoints(String wayPoints); abstract NBPostTripRoute build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/snaptoroad/NBSnapToRoad.java
package ai.nextbillion.api.snaptoroad; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import ai.nextbillion.kits.core.NBService; import java.util.List; import ai.nextbillion.api.models.NBLocation; import ai.nextbillion.api.utils.FormatUtils; import retrofit2.Call; @AutoValue public abstract class NBSnapToRoad extends NBService<NBSnapToRoadResponse, NBSnapToRoadService> { protected NBSnapToRoad() { super(NBSnapToRoadService.class); } @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder().registerTypeAdapterFactory(NBSnapToRoadsAdapterFactory.create()); } @Override protected Call<NBSnapToRoadResponse> initializeCall() { return getService().getSnapToRoads( interpolate(), key(), locationsToString(path()), listToString(radiuses()), timestamps(), tolerateOutlier() ); } /////////////////////////////////////////////////////////////////////////// // Params converter /////////////////////////////////////////////////////////////////////////// private String locationsToString(@NonNull List<NBLocation> locations) { return FormatUtils.join("|", locations); } private String listToString(@NonNull List<String> list) { return FormatUtils.join("|", list); } /////////////////////////////////////////////////////////////////////////// // Params /////////////////////////////////////////////////////////////////////////// public abstract boolean interpolate(); @Override public abstract String baseUrl(); public abstract String key(); public abstract List<NBLocation> path(); @Nullable public abstract List<String> radiuses(); @Nullable public abstract String timestamps(); public abstract boolean tolerateOutlier(); /////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////// public static TypeAdapter<NBSnapToRoad> typeAdapter(Gson gson) { return new AutoValue_NBSnapToRoad.GsonTypeAdapter(gson); } public static Builder builder() { return new AutoValue_NBSnapToRoad.Builder(); } public abstract Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder interpolate(boolean interpolate); public abstract Builder key(String accessToken); public abstract Builder path(List<NBLocation> path); public abstract Builder radiuses(List<String> radiuses); public abstract Builder timestamps(String timestamps); public abstract Builder tolerateOutlier(boolean tolerateOutlier); public abstract Builder baseUrl(String baseUrl); public abstract NBSnapToRoad build(); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/utils/FormatUtils.java
package ai.nextbillion.api.utils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import ai.nextbillion.kits.geojson.Point; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Methods to convert models to Strings. */ public class FormatUtils { /** * Returns a string containing the tokens joined by delimiters. Doesn't remove trailing nulls. * * @param delimiter the delimiter on which to split. * @param tokens A list of objects to be joined. Strings will be formed from the objects by * calling object.toString(). * @return {@link String} */ @Nullable public static String join(@NonNull CharSequence delimiter, @Nullable List<?> tokens) { return join(delimiter, tokens, false); } /** * Returns a string containing the tokens joined by delimiters. * * @param delimiter the delimiter on which to split. * @param tokens A list of objects to be joined. Strings will be formed from the objects by * calling object.toString(). * @param removeTrailingNulls true if trailing nulls should be removed. * @return {@link String} */ @Nullable public static String join(@NonNull CharSequence delimiter, @Nullable List<?> tokens, boolean removeTrailingNulls) { if (tokens == null || tokens.size() < 1) { return null; } int lastNonNullToken = tokens.size() - 1; if (removeTrailingNulls) { for (int i = tokens.size() - 1; i >= 0; i--) { Object token = tokens.get(i); if (token != null) { break; } else { lastNonNullToken--; } } } StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (int i = 0; i <= lastNonNullToken; i++) { if (firstTime) { firstTime = false; } else { sb.append(delimiter); } Object token = tokens.get(i); if (token != null) { sb.append(token); } } return sb.toString(); } /** * Useful to remove any trailing zeros and prevent a coordinate being over 7 significant figures. * * @param coordinate a double value representing a coordinate. * @return a formatted string. */ @NonNull public static String formatCoordinate(double coordinate) { DecimalFormat decimalFormat = new DecimalFormat("0.######", new DecimalFormatSymbols(Locale.US)); return String.format(Locale.US, "%s", decimalFormat.format(coordinate)); } /** * Used in various APIs to format the user provided radiuses to a String matching the APIs * format. * * @param radiuses a list of doubles represents the radius values * @return a String ready for being passed into the Retrofit call */ @Nullable public static String formatRadiuses(@Nullable List<Double> radiuses) { if (radiuses == null || radiuses.size() == 0) { return null; } List<String> radiusesToJoin = new ArrayList<>(); for (Double radius : radiuses) { if (radius == null) { radiusesToJoin.add(null); } else if (radius == Double.POSITIVE_INFINITY) { radiusesToJoin.add("unlimited"); } else { radiusesToJoin.add(String.format(Locale.US, "%s", formatCoordinate(radius))); } } return join(";", radiusesToJoin); } /** * Formats the bearing variables from the raw values to a string which can than be used for the * request URL. * * @param bearings a List of list of doubles representing bearing values * @return a string with the bearing values */ @Nullable public static String formatBearings(@Nullable List<List<Double>> bearings) { if (bearings == null || bearings.isEmpty()) { return null; } List<String> bearingsToJoin = new ArrayList<>(); for (List<Double> bearing : bearings) { if (bearing == null) { bearingsToJoin.add(null); } else { if (bearing.size() != 2) { throw new RuntimeException("Bearing size should be 2."); } Double angle = bearing.get(0); Double tolerance = bearing.get(1); if (angle == null || tolerance == null) { bearingsToJoin.add(null); } else { if (angle < 0 || angle > 360 || tolerance < 0 || tolerance > 360) { throw new RuntimeException("Angle and tolerance have to be from 0 to 360."); } bearingsToJoin.add(String.format(Locale.US, "%s,%s", formatCoordinate(angle), formatCoordinate(tolerance))); } } } return join(";", bearingsToJoin); } /** * Converts the list of integer arrays to a string ready for API consumption. * * @param distributions the list of integer arrays representing the distribution * @return a string with the distribution values */ @Nullable public static String formatDistributions(@Nullable List<Integer[]> distributions) { if (distributions == null || distributions.isEmpty()) { return null; } List<String> distributionsToJoin = new ArrayList<>(); for (Integer[] array : distributions) { if (array.length == 0) { distributionsToJoin.add(null); } else { distributionsToJoin.add(String.format(Locale.US, "%s,%s", formatCoordinate(array[0]), formatCoordinate(array[1]))); } } return join(";", distributionsToJoin); } /** * Converts String list with approaches values to a string ready for API consumption. An approach * could be unrestricted, curb or null. * * @param approaches a list representing approaches to each coordinate. * @return a formatted string. */ @Nullable public static String formatApproaches(@Nullable List<String> approaches) { if (approaches == null || approaches.isEmpty()) { return null; } for (String approach : approaches) { if (approach != null && !approach.equals("unrestricted") && !approach.equals("curb") && !approach.isEmpty()) { return null; } } return join(";", approaches); } /** * Converts String list with waypoint_names values to a string ready for API consumption. * * @param waypointNames a string representing approaches to each coordinate. * @return a formatted string. */ @Nullable public static String formatWaypointNames(@Nullable List<String> waypointNames) { if (waypointNames == null || waypointNames.isEmpty()) { return null; } return join(";", waypointNames); } /** * Converts a list of Points to String. * * @param coordinates a list of coordinates. * @return a formatted string. */ @Nullable public static String formatCoordinates(@NonNull List<Point> coordinates) { List<String> coordinatesToJoin = new ArrayList<>(); for (Point point : coordinates) { coordinatesToJoin.add(String.format(Locale.US, "%s,%s", formatCoordinate(point.longitude()), formatCoordinate(point.latitude()))); } return join(";", coordinatesToJoin); } /** * Converts array of Points with waypoint_targets values to a string ready for API consumption. * * @param points a list representing approaches to each coordinate. * @return a formatted string. */ @Nullable public static String formatPointsList(@Nullable List<Point> points) { if (points == null || points.isEmpty()) { return null; } List<String> coordinatesToJoin = new ArrayList<>(); for (Point point : points) { if (point == null) { coordinatesToJoin.add(null); } else { coordinatesToJoin.add(String.format(Locale.US, "%s,%s", formatCoordinate(point.longitude()), formatCoordinate(point.latitude()))); } } return join(";", coordinatesToJoin); } }
0
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api
java-sources/ai/nextbillion/nb-kits-api/0.0.2/ai/nextbillion/api/utils/ParseUtils.java
package ai.nextbillion.api.utils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import ai.nextbillion.kits.geojson.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Methods to convert Strings to Lists of objects. */ public class ParseUtils { private static final String SEMICOLON = ";"; private static final String COMMA = ","; private static final String UNLIMITED = "unlimited"; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Parse a String to a list of Integers. * * @param original an original String. * @return List of Integers */ @Nullable public static List<Integer> parseToIntegers(@Nullable String original) { if (original == null) { return null; } List<Integer> integers = new ArrayList<>(); String[] strings = original.split(SEMICOLON); for (String index : strings) { if (index != null) { if (index.isEmpty()) { integers.add(null); } else { integers.add(Integer.valueOf(index)); } } } return integers; } /** * Parse a String to a list of Strings using ";" as a separator. * * @param original an original String. * @return List of Strings */ @Nullable public static List<String> parseToStrings(@Nullable String original) { return parseToStrings(original, SEMICOLON); } /** * Parse a String to a list of Strings. * * @param original an original String. * @param separator a String used as a separator. * @return List of Strings */ @Nullable public static List<String> parseToStrings(@Nullable String original, @NonNull String separator) { if (original == null) { return null; } List<String> result = new ArrayList<>(); String[] strings = original.split(separator, -1); for (String str : strings) { if (str != null) { if (str.isEmpty()) { result.add(null); } else { result.add(str); } } } return result; } /** * Parse a String to a list of Points. * * @param original an original String. * @return List of Points */ @Nullable public static List<Point> parseToPoints(@Nullable String original) { if (original == null) { return null; } List<Point> points = new ArrayList<>(); String[] targets = original.split(SEMICOLON, -1); for (String target : targets) { if (target != null) { if (target.isEmpty()) { points.add(null); } else { String[] point = target.split(COMMA); points.add(Point.fromLngLat(Double.valueOf(point[0]), Double.valueOf(point[1]))); } } } return points; } /** * Parse a String to a list of Points. * * @param original an original String. * @return List of Doubles */ @Nullable public static List<Double> parseToDoubles(@Nullable String original) { if (original == null) { return null; } List<Double> doubles = new ArrayList<>(); String[] strings = original.split(SEMICOLON, -1); for (String str : strings) { if (str != null) { if (str.isEmpty()) { doubles.add(null); } else if (str.equals(UNLIMITED)) { doubles.add(Double.POSITIVE_INFINITY); } else { doubles.add(Double.valueOf(str)); } } } return doubles; } /** * Parse a String to a list of list of Doubles. * * @param original an original String. * @return List of List of Doubles */ @Nullable public static List<List<Double>> parseToListOfListOfDoubles(@Nullable String original) { if (original == null) { return null; } List<List<Double>> result = new ArrayList<>(); String[] pairs = original.split(SEMICOLON, -1); for (String pair : pairs) { if (pair.isEmpty()) { result.add(null); } else { String[] values = pair.split(COMMA); if (values.length == 2) { result.add(Arrays.asList(Double.valueOf(values[0]), Double.valueOf(values[1]))); } } } return result; } /** * Parse a String to a list of Boolean. * * @param original an original String. * @return List of Booleans */ @Nullable public static List<Boolean> parseToBooleans(@Nullable String original) { if (original == null) { return null; } List<Boolean> booleans = new ArrayList<>(); if (original.isEmpty()) { return booleans; } String[] strings = original.split(SEMICOLON, -1); for (String str : strings) { if (str != null) { if (str.isEmpty()) { booleans.add(null); } else if (str.equalsIgnoreCase(TRUE)) { booleans.add(true); } else if (str.equalsIgnoreCase(FALSE)) { booleans.add(false); } else { booleans.add(null); } } } return booleans; } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/NBService.java
package ai.nextbillion.kits.core; import com.google.gson.GsonBuilder; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Nbmap specific services used internally within the SDK. Subclasses must implement baseUrl and * initializeCall. * * @param <T> Type parameter for response. * @param <S> Type parameter for service interface. * */ public abstract class NBService<T, S> { protected static final int MAX_URL_SIZE = 1024 * 8; private final Class<S> APIServiceType; private boolean enableDebug; protected OkHttpClient okHttpClient; private okhttp3.Call.Factory callFactory; private Retrofit retrofit; private Call<T> call; private S service; /** * Constructor for creating a new NBService setting the service type for use when * initializing retrofit. Subclasses should pass their service class to this constructor. * * @param serviceType for initializing retrofit * */ public NBService(Class<S> serviceType) { this.APIServiceType = serviceType; } /** * Should return base url for retrofit calls. * * @return baseUrl as a string * */ protected abstract String baseUrl(); /** * Abstract method for getting Retrofit {@link Call} from the subclass. Subclasses should override * this method and construct and return the call. * * @return call * */ protected abstract Call<T> initializeCall(); /** * Get call if already created, otherwise get it from subclass implementation. * * @return call * */ protected Call<T> getCall() { if (call == null) { call = initializeCall(); } return call; } /** * Wrapper method for Retrofits {@link Call#execute()} call returning a response specific to the * API implementing this class. * * @return the response once the call completes successfully * @throws IOException Signals that an I/O exception of some sort has occurred * */ public Response<T> executeCall() throws IOException { return getCall().execute(); } /** * Wrapper method for Retrofits {@link Call#enqueue(Callback)} call returning a response specific * to the API implementing this class. Use this method to make a request on the Main Thread. * * @param callback a {@link Callback} which is used once the API response is created. * */ public void enqueueCall(Callback<T> callback) { getCall().enqueue(callback); } /** * Wrapper method for Retrofits {@link Call#cancel()} call, important to manually cancel call if * the user dismisses the calling activity or no longer needs the returned results. * * */ public void cancelCall() { getCall().cancel(); } /** * Wrapper method for Retrofits {@link Call#clone()} call, useful for getting call information. * * @return cloned call * */ public Call<T> cloneCall() { return getCall().clone(); } /** * Creates the Retrofit object and the service if they are not already created. Subclasses can * override getGsonBuilder to add anything to the GsonBuilder. * * @return new service if not already created, otherwise the existing service * */ protected S getService() { // No need to recreate it if (service != null) { return service; } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(baseUrl()) .addConverterFactory(GsonConverterFactory.create(getGsonBuilder().create())); if (getCallFactory() != null) { retrofitBuilder.callFactory(getCallFactory()); } else { retrofitBuilder.client(getOkHttpClient()); } retrofit = retrofitBuilder.build(); service = (S) retrofit.create(APIServiceType); return service; } /** * Returns the retrofit instance. * * @return retrofit, or null if it hasn't been initialized yet. * */ public Retrofit getRetrofit() { return retrofit; } /** * Gets the GsonConverterFactory. Subclasses can override to register TypeAdapterFactories, etc. * * @return GsonBuilder for Retrofit * */ protected GsonBuilder getGsonBuilder() { return new GsonBuilder(); } /** * Returns if debug logging is enabled in Okhttp. * * @return whether enableDebug is true * */ public boolean isEnableDebug() { return enableDebug; } /** * Enable for more verbose log output while making request. * * @param enableDebug true if you'd like Okhttp to log * */ public void enableDebug(boolean enableDebug) { this.enableDebug = enableDebug; } /** * Gets the call factory for creating {@link Call} instances. * * @return the call factory, or the default OkHttp client if it's null. * */ public okhttp3.Call.Factory getCallFactory() { return callFactory; } /** * Specify a custom call factory for creating {@link Call} instances. * * @param callFactory implementation * */ public void setCallFactory(okhttp3.Call.Factory callFactory) { this.callFactory = callFactory; } /** * Used Internally. * * @return OkHttpClient * */ protected synchronized OkHttpClient getOkHttpClient() { if (okHttpClient == null) { if (isEnableDebug()) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(logging); okHttpClient = httpClient.build(); } else { okHttpClient = new OkHttpClient(); } } return okHttpClient; } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/package-info.java
/** * Contains common classes and methods shared between all other service modules. * * */ package ai.nextbillion.kits.core;
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/constants/Constants.java
package ai.nextbillion.kits.core.constants; import ai.nextbillion.kits.core.BuildConfig; import java.util.Locale; /** * Includes common variables used throughout the Nbmap Service modules. * * */ public final class Constants { /** * User agent for HTTP requests. * * */ public static final String HEADER_USER_AGENT = String.format(Locale.US, "NbmapJava/%s (%s)", BuildConfig.VERSION, BuildConfig.GIT_REVISION); /** * Base URL for all API calls, not hardcoded to enable testing. * * */ public static final String BASE_API_URL = "https://api.nextbillion.io"; /** * The default user variable used for all the Nbmap user names. * * */ public static final String NBMAP_USER = "nbmap"; /** * Use a precision of 6 decimal places when encoding or decoding a polyline. * * */ public static final int PRECISION_6 = 6; /** * Use a precision of 5 decimal places when encoding or decoding a polyline. * * */ public static final int PRECISION_5 = 5; private Constants() { // Empty constructor prevents users from initializing this class } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/constants/package-info.java
/** * Contains the core service constant values useful for all other modules. * * */ package ai.nextbillion.kits.core.constants;
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/exceptions/ServicesException.java
package ai.nextbillion.kits.core.exceptions; /** * A form of {@code Throwable} that indicates conditions that a reasonable application might * want to catch. * * */ public class ServicesException extends RuntimeException { /** * A form of {@code Throwable} that indicates conditions that a reasonable application might * want to catch. * * @param message the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * */ public ServicesException(String message) { super(message); } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/exceptions/package-info.java
/** * Contains a simple services runtime exception which can be used throughout the project. * * */ package ai.nextbillion.kits.core.exceptions;
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/internal/Preconditions.java
package ai.nextbillion.kits.core.internal; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import androidx.annotation.RestrictTo; /** * Contains simple precondition checks. * * */ @RestrictTo(LIBRARY_GROUP) public final class Preconditions { /** * Checks if the passed in value is not Null. Throws a NPE if the value is null. * * @param value The object to be checked fo null * @param message The message to be associated with NPE, if value is null * */ public static void checkNotNull(Object value, String message) { if (value == null) { throw new NullPointerException(message); } } private Preconditions() { throw new AssertionError("No instances."); } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/internal/package-info.java
/** * Contains simple precondition checks which can be used throughout the project. * * */ package ai.nextbillion.kits.core.internal;
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/utils/ApiCallHelper.java
package ai.nextbillion.kits.core.utils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import ai.nextbillion.kits.core.constants.Constants; import java.util.Locale; /** * Static class with methods for assisting in making Nbmap API calls. * * */ public final class ApiCallHelper { private static final String ONLY_PRINTABLE_CHARS = "[^\\p{ASCII}]"; private ApiCallHelper() { // Private constructor preventing instances of class } /** * Computes a full user agent header of the form: * {@code NbmapJava/1.2.0 Mac OS X/10.11.5 (x86_64)}. * * @param clientAppName Application Name * @return {@link String} representing the header user agent * */ public static String getHeaderUserAgent(@Nullable String clientAppName) { String osName = System.getProperty("os.name"); String osVersion = System.getProperty("os.version"); String osArch = System.getProperty("os.arch"); if (TextUtils.isEmpty(osName) || TextUtils.isEmpty(osVersion) || TextUtils.isEmpty(osArch)) { return Constants.HEADER_USER_AGENT; } else { return getHeaderUserAgent(clientAppName, osName, osVersion, osArch); } } /** * Computes a full user agent header of the form: * {@code NbmapJava/1.2.0 Mac OS X/10.11.5 (x86_64)}. * * @param clientAppName Application Name * @param osName OS name * @param osVersion OS version * @param osArch OS Achitecture * @return {@link String} representing the header user agent * */ public static String getHeaderUserAgent(@Nullable String clientAppName, @NonNull String osName, @NonNull String osVersion, @NonNull String osArch) { osName = osName.replaceAll(ONLY_PRINTABLE_CHARS, ""); osVersion = osVersion.replaceAll(ONLY_PRINTABLE_CHARS, ""); osArch = osArch.replaceAll(ONLY_PRINTABLE_CHARS, ""); String baseUa = String.format( Locale.US, "%s %s/%s (%s)", Constants.HEADER_USER_AGENT, osName, osVersion, osArch); return TextUtils.isEmpty(clientAppName) ? baseUa : String.format(Locale.US, "%s %s", clientAppName, baseUa); } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/utils/ColorUtils.java
package ai.nextbillion.kits.core.utils; /** * Utils class for assisting with color transformations and other operations being done on colors. * * */ public final class ColorUtils { private ColorUtils() { // No Instance. } /** * Converts red, green, blue values to a hex string that can then be used in a URL when making API * request. Note that this does <b>Not</b> add the hex key before the string. * * @param red the value of the color which needs to be converted * @param green the value of the color which needs to be converted * @param blue the value of the color which needs to be converted * @return the hex color value as a string * */ public static String toHexString(int red, int green, int blue) { String hexColor = String.format("%02X%02X%02X", red, green, blue); if (hexColor.length() < 6) { hexColor = "000000".substring(0, 6 - hexColor.length()) + hexColor; } return hexColor; } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/utils/NbmapUtils.java
package ai.nextbillion.kits.core.utils; /** * Misc utils around Nbmap services. * * */ public final class NbmapUtils { private NbmapUtils() { // Empty private constructor since only static methods are found inside class. } /** * Checks that the provided access token is not empty or null, and that it starts with * the right prefixes. Note that this method does not check Nbmap servers to verify that * it actually belongs to an account. * * @param accessToken A Nbmap access token. * @return true if the provided access token is valid, false otherwise. * */ public static boolean isAccessTokenValid(String accessToken) { return !TextUtils.isEmpty(accessToken); } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/utils/TextUtils.java
package ai.nextbillion.kits.core.utils; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; /** * We avoid including a full library like org.apache.commons:commons-lang3 to avoid an unnecessary * large number of methods, which is inconvenient to Android devs. * * @see <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/TextUtils.java">Some code came from this source.</a> * */ public final class TextUtils { private TextUtils() { // Empty private constructor preventing class from getting initialized } /** * Returns true if the string is null or 0-length. * * @param str the string to be examined * @return true if str is null or zero length * */ public static boolean isEmpty(CharSequence str) { return str == null || str.length() == 0; } /** * Returns a string containing the tokens joined by delimiters. * * @param delimiter the delimeter on which to split. * @param tokens An array objects to be joined. Strings will be formed from the objects by * calling object.toString(). * @return {@link String} * */ public static String join(CharSequence delimiter, Object[] tokens) { if (tokens == null || tokens.length < 1) { return null; } StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (Object token : tokens) { if (firstTime) { firstTime = false; } else { sb.append(delimiter); } sb.append(token); } return sb.toString(); } /** * Useful to remove any trailing zeros and prevent a coordinate being over 7 significant figures. * * @param coordinate a double value representing a coordinate. * @return a formatted string. * */ public static String formatCoordinate(double coordinate) { DecimalFormat decimalFormat = new DecimalFormat("0.######", new DecimalFormatSymbols(Locale.US)); return String.format(Locale.US, "%s", decimalFormat.format(coordinate)); } /** * Allows the specific adjusting of a coordinates precision. * * @param coordinate a double value representing a coordinate. * @param precision an integer value you'd like the precision to be at. * @return a formatted string. * */ public static String formatCoordinate(double coordinate, int precision) { String pattern = "0." + new String(new char[precision]).replace("\0", "0"); DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.US); df.applyPattern(pattern); df.setRoundingMode(RoundingMode.FLOOR); return df.format(coordinate); } /** * Used in various APIs to format the user provided radiuses to a String matching the APIs format. * * @param radiuses a double array which represents the radius values * @return a String ready for being passed into the Retrofit call * * @deprecated use FormatUtils.formatRadiuses(List) */ @Deprecated public static String formatRadiuses(double[] radiuses) { if (radiuses == null || radiuses.length == 0) { return null; } String[] radiusesFormatted = new String[radiuses.length]; for (int i = 0; i < radiuses.length; i++) { if (radiuses[i] == Double.POSITIVE_INFINITY) { radiusesFormatted[i] = "unlimited"; } else { radiusesFormatted[i] = String.format(Locale.US, "%s", TextUtils.formatCoordinate(radiuses[i])); } } return join(";", radiusesFormatted); } /** * Formats the bearing variables from the raw values to a string which can than be used for the * request URL. * * @param bearings a List of doubles representing bearing values * @return a string with the bearing values * * @deprecated use FormatUtils.formatBearing(List) */ @Deprecated public static String formatBearing(List<Double[]> bearings) { if (bearings.isEmpty()) { return null; } String[] bearingFormatted = new String[bearings.size()]; for (int i = 0; i < bearings.size(); i++) { if (bearings.get(i).length == 0) { bearingFormatted[i] = ""; } else { bearingFormatted[i] = String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(bearings.get(i)[0]), TextUtils.formatCoordinate(bearings.get(i)[1])); } } return TextUtils.join(";", bearingFormatted); } /** * converts the list of integer arrays to a string ready for API consumption. * * @param distributions the list of integer arrays representing the distribution * @return a string with the distribution values * * @deprecated use FormatUtils.formatDistributions(List) */ @Deprecated public static String formatDistributions(List<Integer[]> distributions) { if (distributions.isEmpty()) { return null; } String[] distributionsFormatted = new String[distributions.size()]; for (int i = 0; i < distributions.size(); i++) { if (distributions.get(i).length == 0) { distributionsFormatted[i] = ""; } else { distributionsFormatted[i] = String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(distributions.get(i)[0]), TextUtils.formatCoordinate(distributions.get(i)[1])); } } return TextUtils.join(";", distributionsFormatted); } /** * Converts String array with approaches values * to a string ready for API consumption. * An approach could be unrestricted, curb or null. * * @param approaches a string representing approaches to each coordinate. * @return a formatted string. * * @deprecated use FormatUtils.formatApproaches(List) */ @Deprecated public static String formatApproaches(String[] approaches) { for (int i = 0; i < approaches.length; i++) { if (approaches[i] == null) { approaches[i] = ""; } else if (!approaches[i].equals("unrestricted") && !approaches[i].equals("curb") && !approaches[i].isEmpty()) { return null; } } return TextUtils.join(";", approaches); } /** * Converts String array with waypoint_names values * to a string ready for API consumption. * * @param waypointNames a string representing approaches to each coordinate. * @return a formatted string. * * @deprecated use FormatUtils.formatWaypointNames(List) */ @Deprecated public static String formatWaypointNames(String[] waypointNames) { for (int i = 0; i < waypointNames.length; i++) { if (waypointNames[i] == null) { waypointNames[i] = ""; } } return TextUtils.join(";", waypointNames); } }
0
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core
java-sources/ai/nextbillion/nb-kits-core/0.0.2/ai/nextbillion/kits/core/utils/package-info.java
/** * Contains classes with utilities useful throughout the project. * * */ package ai.nextbillion.kits.core.utils;
0
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/BaseCoordinatesTypeAdapter.java
package ai.nextbillion.kits.geojson; import androidx.annotation.Keep; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import ai.nextbillion.kits.geojson.exception.GeoJsonException; import ai.nextbillion.kits.geojson.shifter.CoordinateShifterManager; import ai.nextbillion.kits.geojson.utils.GeoJsonUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Base class for converting {@code T} instance of coordinates to JSON and * JSON to instance of {@code T}. * * @param <T> Type of coordinates */ @Keep abstract class BaseCoordinatesTypeAdapter<T> extends TypeAdapter<T> { protected void writePoint(JsonWriter out, Point point) throws IOException { if (point == null) { return; } writePointList(out, point.coordinates()); } protected Point readPoint(JsonReader in) throws IOException { List<Double> coordinates = readPointList(in); if (coordinates != null && coordinates.size() > 1) { return new Point("Point",null, coordinates); } throw new GeoJsonException(" Point coordinates should be non-null double array"); } protected void writePointList(JsonWriter out, List<Double> value) throws IOException { if (value == null) { return; } out.beginArray(); // Unshift coordinates List<Double> unshiftedCoordinates = CoordinateShifterManager.getCoordinateShifter().unshiftPoint(value); out.value(GeoJsonUtils.trim(unshiftedCoordinates.get(0))); out.value(GeoJsonUtils.trim(unshiftedCoordinates.get(1))); // Includes altitude if (value.size() > 2) { out.value(unshiftedCoordinates.get(2)); } out.endArray(); } protected List<Double> readPointList(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { throw new NullPointerException(); } List<Double> coordinates = new ArrayList<Double>(); in.beginArray(); while (in.hasNext()) { coordinates.add(in.nextDouble()); } in.endArray(); if (coordinates.size() > 2) { return CoordinateShifterManager.getCoordinateShifter() .shiftLonLatAlt(coordinates.get(0), coordinates.get(1), coordinates.get(2)); } return CoordinateShifterManager.getCoordinateShifter() .shiftLonLat(coordinates.get(0), coordinates.get(1)); } }
0
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/BaseGeometryTypeAdapter.java
package ai.nextbillion.kits.geojson; import androidx.annotation.Keep; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import ai.nextbillion.kits.geojson.exception.GeoJsonException; import ai.nextbillion.kits.geojson.gson.BoundingBoxTypeAdapter; import java.io.IOException; /** * Base class for converting {@code Geometry} instances to JSON and * JSON to instances of {@code Geometry}. * * @param <G> Geometry * @param <T> Type of coordinates */ @Keep abstract class BaseGeometryTypeAdapter<G, T> extends TypeAdapter<G> { private volatile TypeAdapter<String> stringAdapter; private volatile TypeAdapter<BoundingBox> boundingBoxAdapter; private volatile TypeAdapter<T> coordinatesAdapter; private final Gson gson; BaseGeometryTypeAdapter(Gson gson, TypeAdapter<T> coordinatesAdapter) { this.gson = gson; this.coordinatesAdapter = coordinatesAdapter; this.boundingBoxAdapter = new BoundingBoxTypeAdapter(); } public void writeCoordinateContainer(JsonWriter jsonWriter, CoordinateContainer<T> object) throws IOException { if (object == null) { jsonWriter.nullValue(); return; } jsonWriter.beginObject(); jsonWriter.name("type"); if (object.type() == null) { jsonWriter.nullValue(); } else { TypeAdapter<String> stringAdapter = this.stringAdapter; if (stringAdapter == null) { stringAdapter = gson.getAdapter(String.class); this.stringAdapter = stringAdapter; } stringAdapter.write(jsonWriter, object.type()); } jsonWriter.name("bbox"); if (object.bbox() == null) { jsonWriter.nullValue(); } else { TypeAdapter<BoundingBox> boundingBoxAdapter = this.boundingBoxAdapter; if (boundingBoxAdapter == null) { boundingBoxAdapter = gson.getAdapter(BoundingBox.class); this.boundingBoxAdapter = boundingBoxAdapter; } boundingBoxAdapter.write(jsonWriter, object.bbox()); } jsonWriter.name("coordinates"); if (object.coordinates() == null) { jsonWriter.nullValue(); } else { TypeAdapter<T> coordinatesAdapter = this.coordinatesAdapter; if (coordinatesAdapter == null) { throw new GeoJsonException("Coordinates type adapter is null"); } coordinatesAdapter.write(jsonWriter, object.coordinates()); } jsonWriter.endObject(); } public CoordinateContainer<T> readCoordinateContainer(JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return null; } jsonReader.beginObject(); String type = null; BoundingBox bbox = null; T coordinates = null; while (jsonReader.hasNext()) { String name = jsonReader.nextName(); if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); continue; } switch (name) { case "type": TypeAdapter<String> stringAdapter = this.stringAdapter; if (stringAdapter == null) { stringAdapter = gson.getAdapter(String.class); this.stringAdapter = stringAdapter; } type = stringAdapter.read(jsonReader); break; case "bbox": TypeAdapter<BoundingBox> boundingBoxAdapter = this.boundingBoxAdapter; if (boundingBoxAdapter == null) { boundingBoxAdapter = gson.getAdapter(BoundingBox.class); this.boundingBoxAdapter = boundingBoxAdapter; } bbox = boundingBoxAdapter.read(jsonReader); break; case "coordinates": TypeAdapter<T> coordinatesAdapter = this.coordinatesAdapter; if (coordinatesAdapter == null) { throw new GeoJsonException("Coordinates type adapter is null"); } coordinates = coordinatesAdapter.read(jsonReader); break; default: jsonReader.skipValue(); } } jsonReader.endObject(); return createCoordinateContainer(type, bbox, coordinates); } abstract CoordinateContainer<T> createCoordinateContainer(String type, BoundingBox bbox, T coordinates); }
0
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/BoundingBox.java
package ai.nextbillion.kits.geojson; import static ai.nextbillion.kits.geojson.constants.GeoJsonConstants.MIN_LATITUDE; import static ai.nextbillion.kits.geojson.constants.GeoJsonConstants.MIN_LONGITUDE; import androidx.annotation.FloatRange; import androidx.annotation.Keep; import androidx.annotation.NonNull; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import ai.nextbillion.kits.geojson.constants.GeoJsonConstants; import ai.nextbillion.kits.geojson.gson.BoundingBoxTypeAdapter; import java.io.Serializable; /** * A GeoJson object MAY have a member named "bbox" to include information on the coordinate range * for its Geometries, Features, or FeatureCollections. * <p> * This class simplifies the build process for creating a bounding box and working with them when * deserialized. specific parameter naming helps define which coordinates belong where when a * bounding box instance is being created. Note that since GeoJson objects only have the option of * including a bounding box JSON element, the {@code bbox} value returned by a GeoJson object might * be null. * <p> * At a minimum, a bounding box will have two {@link Point}s or four coordinates which define the * box. A 3rd dimensional bounding box can be produced if elevation or altitude is defined. * */ @Keep public class BoundingBox implements Serializable { private final Point southwest; private final Point northeast; /** * Create a new instance of this class by passing in a formatted valid JSON String. * * @param json a formatted valid JSON string defining a Bounding Box * @return a new instance of this class defined by the values passed inside this static factory * method */ public static BoundingBox fromJson(String json) { Gson gson = new GsonBuilder() .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .create(); return gson.fromJson(json, BoundingBox.class); } /** * Define a new instance of this class by passing in two {@link Point}s, representing both the * southwest and northwest corners of the bounding box. * * @param southwest represents the bottom left corner of the bounding box when the camera is * pointing due north * @param northeast represents the top right corner of the bounding box when the camera is * pointing due north * @return a new instance of this class defined by the provided points */ public static BoundingBox fromPoints(@NonNull Point southwest, @NonNull Point northeast) { return new BoundingBox(southwest, northeast); } /** * Define a new instance of this class by passing in four coordinates in the same order they would * appear in the serialized GeoJson form. Limits are placed on the minimum and maximum coordinate * values which can exist and comply with the GeoJson spec. * * @param west the left side of the bounding box when the map is facing due north * @param south the bottom side of the bounding box when the map is facing due north * @param east the right side of the bounding box when the map is facing due north * @param north the top side of the bounding box when the map is facing due north * @return a new instance of this class defined by the provided coordinates * @deprecated As of 3.1.0, use {@link #fromLngLats} instead. */ @Deprecated public static BoundingBox fromCoordinates( @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double west, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double south, @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double east, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double north) { return fromLngLats(west, south, east, north); } /** * Define a new instance of this class by passing in four coordinates in the same order they would * appear in the serialized GeoJson form. Limits are placed on the minimum and maximum coordinate * values which can exist and comply with the GeoJson spec. * * @param west the left side of the bounding box when the map is facing due north * @param south the bottom side of the bounding box when the map is facing due north * @param southwestAltitude the southwest corner altitude or elevation when the map is facing due * north * @param east the right side of the bounding box when the map is facing due north * @param north the top side of the bounding box when the map is facing due north * @param northEastAltitude the northeast corner altitude or elevation when the map is facing due * north * @return a new instance of this class defined by the provided coordinates * @deprecated As of 3.1.0, use {@link #fromLngLats} instead. * */ @Deprecated public static BoundingBox fromCoordinates( @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double west, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double south, double southwestAltitude, @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double east, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double north, double northEastAltitude) { return fromLngLats(west, south, southwestAltitude, east, north, northEastAltitude); } /** * Define a new instance of this class by passing in four coordinates in the same order they would * appear in the serialized GeoJson form. Limits are placed on the minimum and maximum coordinate * values which can exist and comply with the GeoJson spec. * * @param west the left side of the bounding box when the map is facing due north * @param south the bottom side of the bounding box when the map is facing due north * @param east the right side of the bounding box when the map is facing due north * @param north the top side of the bounding box when the map is facing due north * @return a new instance of this class defined by the provided coordinates */ public static BoundingBox fromLngLats( @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double west, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double south, @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double east, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double north) { return new BoundingBox(Point.fromLngLat(west, south), Point.fromLngLat(east, north)); } /** * Define a new instance of this class by passing in four coordinates in the same order they would * appear in the serialized GeoJson form. Limits are placed on the minimum and maximum coordinate * values which can exist and comply with the GeoJson spec. * * @param west the left side of the bounding box when the map is facing due north * @param south the bottom side of the bounding box when the map is facing due north * @param southwestAltitude the southwest corner altitude or elevation when the map is facing due * north * @param east the right side of the bounding box when the map is facing due north * @param north the top side of the bounding box when the map is facing due north * @param northEastAltitude the northeast corner altitude or elevation when the map is facing due * north * @return a new instance of this class defined by the provided coordinates */ public static BoundingBox fromLngLats( @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double west, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double south, double southwestAltitude, @FloatRange(from = GeoJsonConstants.MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double east, @FloatRange(from = GeoJsonConstants.MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double north, double northEastAltitude) { return new BoundingBox( Point.fromLngLat(west, south, southwestAltitude), Point.fromLngLat(east, north, northEastAltitude)); } BoundingBox(Point southwest, Point northeast) { if (southwest == null) { throw new NullPointerException("Null southwest"); } this.southwest = southwest; if (northeast == null) { throw new NullPointerException("Null northeast"); } this.northeast = northeast; } /** * Provides the {@link Point} which represents the southwest corner of this bounding box when the * map is facing due north. * * @return a {@link Point} which defines this bounding boxes southwest corner */ @NonNull public Point southwest() { return southwest; } /** * Provides the {@link Point} which represents the northeast corner of this bounding box when the * map is facing due north. * * @return a {@link Point} which defines this bounding boxes northeast corner */ @NonNull public Point northeast() { return northeast; } /** * Convenience method for getting the bounding box most westerly point (longitude) as a double * coordinate. * * @return the most westerly coordinate inside this bounding box */ public final double west() { return southwest().longitude(); } /** * Convenience method for getting the bounding box most southerly point (latitude) as a double * coordinate. * * @return the most southerly coordinate inside this bounding box */ public final double south() { return southwest().latitude(); } /** * Convenience method for getting the bounding box most easterly point (longitude) as a double * coordinate. * * @return the most easterly coordinate inside this bounding box */ public final double east() { return northeast().longitude(); } /** * Convenience method for getting the bounding box most westerly point (longitude) as a double * coordinate. * * @return the most westerly coordinate inside this bounding box */ public final double north() { return northeast().latitude(); } /** * Gson TYPE adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the TYPE adapter for this class */ public static TypeAdapter<BoundingBox> typeAdapter(Gson gson) { return new BoundingBoxTypeAdapter(); } /** * This takes the currently defined values found inside this instance and converts it to a GeoJson * string. * * @return a JSON string which represents this Bounding box */ public final String toJson() { Gson gson = new GsonBuilder() .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .create(); return gson.toJson(this, BoundingBox.class); } @Override public String toString() { return "BoundingBox{" + "southwest=" + southwest + ", " + "northeast=" + northeast + "}"; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof BoundingBox) { BoundingBox that = (BoundingBox) obj; return (this.southwest.equals(that.southwest())) && (this.northeast.equals(that.northeast())); } return false; } @Override public int hashCode() { int hashCode = 1; hashCode *= 1000003; hashCode ^= southwest.hashCode(); hashCode *= 1000003; hashCode ^= northeast.hashCode(); return hashCode; } }
0
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/CoordinateContainer.java
package ai.nextbillion.kits.geojson; import androidx.annotation.Keep; /** * Each of the s geometries which make up GeoJson implement this interface and consume a varying * dimension of {@link Point} list. Since this is varying, each geometry object fulfills the * contract by replacing the generic with a well defined list of Points. * * @param <T> a generic allowing varying dimensions for each GeoJson geometry */ @Keep public interface CoordinateContainer<T> extends Geometry { /** * the coordinates which define the geometry. Typically a list of points but for some geometry * such as polygon this can be a list of a list of points, thus the return is generic here. * * @return the {@link Point}s which make up the coordinates defining the geometry */ T coordinates(); }